]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/client/view.qc
Merge branch 'z411/annce_queue' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / client / view.qc
1 #include "view.qh"
2
3 #include <client/announcer.qh>
4 #include <client/csqcmodel_hooks.qh>
5 #include <client/draw.qh>
6 #include <client/hud/_mod.qh>
7 #include <client/hud/panel/quickmenu.qh>
8 #include <client/hud/panel/scoreboard.qh>
9 #include <client/mapvoting.qh>
10 #include <client/mutators/_mod.qh>
11 #include <client/shownames.qh>
12 #include <common/anim.qh>
13 #include <common/animdecide.qh>
14 #include <common/constants.qh>
15 #include <common/deathtypes/all.qh>
16 #include <common/debug.qh>
17 #include <common/ent_cs.qh>
18 #include <common/gamemodes/_mod.qh>
19 #include <common/mapinfo.qh>
20 #include <common/mapobjects/target/music.qh>
21 #include <common/mapobjects/trigger/viewloc.qh>
22 #include <common/minigames/cl_minigames.qh>
23 #include <common/minigames/cl_minigames_hud.qh>
24 #include <common/mutators/mutator/powerups/_mod.qh>
25 #include <common/mutators/mutator/status_effects/_mod.qh>
26 #include <common/mutators/mutator/waypoints/all.qh>
27 #include <common/net_linked.qh>
28 #include <common/net_notice.qh>
29 #include <common/physics/player.qh>
30 #include <common/stats.qh>
31 #include <common/teams.qh>
32 #include <common/vehicles/all.qh>
33 #include <common/viewloc.qh>
34 #include <common/weapons/_all.qh>
35 #include <common/weapons/weapon/tuba.qh>
36 #include <common/wepent.qh>
37 #include <lib/csqcmodel/cl_model.qh>
38 #include <lib/csqcmodel/cl_player.qh>
39 #include <lib/warpzone/client.qh>
40 #include <lib/warpzone/common.qh>
41
42 float autocvar_cl_viewmodel_scale;
43 float autocvar_cl_viewmodel_alpha = 1;
44
45 bool autocvar_cl_bobmodel;
46 float autocvar_cl_bobmodel_speed;
47 float autocvar_cl_bobmodel_side;
48 float autocvar_cl_bobmodel_up;
49
50 float autocvar_cl_followmodel;
51 float autocvar_cl_followmodel_speed = 0.3;
52 float autocvar_cl_followmodel_limit = 135;
53 float autocvar_cl_followmodel_velocity_lowpass = 0.05;
54 float autocvar_cl_followmodel_highpass = 0.05;
55 float autocvar_cl_followmodel_lowpass = 0.03;
56 bool autocvar_cl_followmodel_velocity_absolute;
57
58 float autocvar_cl_leanmodel;
59 float autocvar_cl_leanmodel_speed = 0.3;
60 float autocvar_cl_leanmodel_limit = 30;
61 float autocvar_cl_leanmodel_highpass1 = 0.2;
62 float autocvar_cl_leanmodel_highpass = 0.2;
63 float autocvar_cl_leanmodel_lowpass = 0.05;
64
65 #define avg_factor(avg_time) (1 - exp(-frametime / max(0.001, avg_time)))
66
67 #define lowpass(value, frac, ref_store, ret) \
68         ret = ref_store = ref_store * (1 - frac) + (value) * frac;
69
70 #define lowpass_limited(value, frac, limit, ref_store, ret) MACRO_BEGIN \
71         float __ignore; lowpass(value, frac, ref_store, __ignore); \
72         ret = ref_store = bound((value) - (limit), ref_store, (value) + (limit)); \
73 MACRO_END
74
75 #define highpass(value, frac, ref_store, ret) MACRO_BEGIN \
76         float __f = 0; lowpass(value, frac, ref_store, __f); \
77         ret = (value) - __f; \
78 MACRO_END
79
80 #define highpass_limited(value, frac, limit, ref_store, ret) MACRO_BEGIN \
81         float __f = 0; lowpass_limited(value, frac, limit, ref_store, __f); \
82         ret = (value) - __f; \
83 MACRO_END
84
85 #define lowpass2(value, frac, ref_store, ref_out) MACRO_BEGIN \
86         lowpass(value.x, frac, ref_store.x, ref_out.x); \
87         lowpass(value.y, frac, ref_store.y, ref_out.y); \
88 MACRO_END
89
90 #define highpass2(value, frac, ref_store, ref_out) MACRO_BEGIN \
91         highpass(value.x, frac, ref_store.x, ref_out.x); \
92         highpass(value.y, frac, ref_store.y, ref_out.y); \
93 MACRO_END
94
95 #define highpass2_limited(value, frac, limit, ref_store, ref_out) MACRO_BEGIN \
96         highpass_limited(value.x, frac, limit, ref_store.x, ref_out.x); \
97         highpass_limited(value.y, frac, limit, ref_store.y, ref_out.y); \
98 MACRO_END
99
100 #define lowpass3(value, frac, ref_store, ref_out) MACRO_BEGIN \
101         lowpass(value.x, frac, ref_store.x, ref_out.x); \
102         lowpass(value.y, frac, ref_store.y, ref_out.y); \
103         lowpass(value.z, frac, ref_store.z, ref_out.z); \
104 MACRO_END
105
106 #define highpass3(value, frac, ref_store, ref_out) MACRO_BEGIN \
107         highpass(value.x, frac, ref_store.x, ref_out.x); \
108         highpass(value.y, frac, ref_store.y, ref_out.y); \
109         highpass(value.z, frac, ref_store.z, ref_out.z); \
110 MACRO_END
111
112 void calc_followmodel_ofs(entity view)
113 {
114         if(cl_followmodel_time == time)
115                 return; // cl_followmodel_ofs already calculated for this frame
116
117         float frac;
118         vector gunorg = '0 0 0';
119         static vector vel_average;
120         static vector gunorg_adjustment_highpass;
121         static vector gunorg_adjustment_lowpass;
122
123         vector vel;
124         if (autocvar_cl_followmodel_velocity_absolute)
125                 vel = view.velocity;
126         else
127         {
128                 vector forward, right, up;
129                 MAKE_VECTORS(view_angles, forward, right, up);
130                 vel.x = view.velocity * forward;
131                 vel.y = view.velocity * right * -1;
132                 vel.z = view.velocity * up;
133         }
134
135         vel.x = bound(vel_average.x - autocvar_cl_followmodel_limit, vel.x, vel_average.x + autocvar_cl_followmodel_limit);
136         vel.y = bound(vel_average.y - autocvar_cl_followmodel_limit, vel.y, vel_average.y + autocvar_cl_followmodel_limit);
137         vel.z = bound(vel_average.z - autocvar_cl_followmodel_limit, vel.z, vel_average.z + autocvar_cl_followmodel_limit);
138
139         frac = avg_factor(autocvar_cl_followmodel_velocity_lowpass);
140         lowpass3(vel, frac, vel_average, gunorg);
141
142         gunorg *= -autocvar_cl_followmodel_speed * 0.042;
143
144         // perform highpass/lowpass on the adjustment vectors (turning velocity into acceleration!)
145         // trick: we must do the lowpass LAST, so the lowpass vector IS the final vector!
146         frac = avg_factor(autocvar_cl_followmodel_highpass);
147         highpass3(gunorg, frac, gunorg_adjustment_highpass, gunorg);
148         frac = avg_factor(autocvar_cl_followmodel_lowpass);
149         lowpass3(gunorg, frac, gunorg_adjustment_lowpass, gunorg);
150
151         if (autocvar_cl_followmodel_velocity_absolute)
152         {
153                 vector fixed_gunorg;
154                 vector forward, right, up;
155                 MAKE_VECTORS(view_angles, forward, right, up);
156                 fixed_gunorg.x = gunorg * forward;
157                 fixed_gunorg.y = gunorg * right * -1;
158                 fixed_gunorg.z = gunorg * up;
159                 gunorg = fixed_gunorg;
160         }
161
162         cl_followmodel_ofs = gunorg;
163         cl_followmodel_time = time;
164 }
165
166 vector leanmodel_ofs(entity view)
167 {
168         float frac;
169         vector gunangles = '0 0 0';
170         static vector gunangles_prev = '0 0 0';
171         static vector gunangles_highpass = '0 0 0';
172         static vector gunangles_adjustment_highpass;
173         static vector gunangles_adjustment_lowpass;
174
175         if (view.csqcmodel_teleported)
176                 gunangles_prev = view_angles;
177
178         // in the highpass, we _store_ the DIFFERENCE to the actual view angles...
179         gunangles_highpass += gunangles_prev;
180         PITCH(gunangles_highpass) += 360 * floor((PITCH(view_angles) - PITCH(gunangles_highpass)) / 360 + 0.5);
181         YAW(gunangles_highpass) += 360 * floor((YAW(view_angles) - YAW(gunangles_highpass)) / 360 + 0.5);
182         ROLL(gunangles_highpass) += 360 * floor((ROLL(view_angles) - ROLL(gunangles_highpass)) / 360 + 0.5);
183         frac = avg_factor(autocvar_cl_leanmodel_highpass1);
184         highpass2_limited(view_angles, frac, autocvar_cl_leanmodel_limit, gunangles_highpass, gunangles);
185         gunangles_prev = view_angles;
186         gunangles_highpass -= gunangles_prev;
187
188         PITCH(gunangles) *= -autocvar_cl_leanmodel_speed;
189         YAW(gunangles) *= -autocvar_cl_leanmodel_speed;
190
191         // we assume here: PITCH = 0, YAW = 1, ROLL = 2
192         frac = avg_factor(autocvar_cl_leanmodel_highpass);
193         highpass2(gunangles, frac, gunangles_adjustment_highpass, gunangles);
194         frac = avg_factor(autocvar_cl_leanmodel_lowpass);
195         lowpass2(gunangles, frac, gunangles_adjustment_lowpass, gunangles);
196
197         gunangles.x = -gunangles.x; // pitch was inverted, now that actually matters
198
199         return gunangles;
200 }
201
202 vector bobmodel_ofs(entity view)
203 {
204         bool clonground = !(view.anim_implicit_state & ANIMIMPLICITSTATE_INAIR);
205         static bool oldonground;
206         static float hitgroundtime;
207         if (clonground)
208         {
209                 float f = time; // cl.movecmd[0].time
210                 if (!oldonground)
211                         hitgroundtime = f;
212         }
213         oldonground = clonground;
214
215         // calculate for swinging gun model
216         // the gun bobs when running on the ground, but doesn't bob when you're in the air.
217         vector gunorg = '0 0 0';
218         static float bobmodel_scale = 0;
219         static float time_ofs = 0; // makes the effect always restart in the same way
220         if (clonground)
221         {
222                 if (time - hitgroundtime > 0.05)
223                         bobmodel_scale = min(1, bobmodel_scale + frametime * 5);
224         }
225         else
226                 bobmodel_scale = max(0, bobmodel_scale - frametime * 5);
227
228         float xyspeed = bound(0, vlen(vec2(view.velocity)), 400);
229         if (bobmodel_scale && xyspeed)
230         {
231                 float bspeed = xyspeed * 0.01 * autocvar_cl_viewmodel_scale * bobmodel_scale;
232                 float s = (time - time_ofs) * autocvar_cl_bobmodel_speed;
233                 gunorg.y = bspeed * autocvar_cl_bobmodel_side * sin(s);
234                 gunorg.z = bspeed * autocvar_cl_bobmodel_up * cos(s * 2);
235         }
236         else
237                 time_ofs = time;
238
239         return gunorg;
240 }
241
242 void viewmodel_animate(entity this)
243 {
244         if (autocvar_chase_active || STAT(HEALTH) <= 0) return;
245
246         entity view = CSQCModel_server2csqc(player_localentnum - 1);
247
248         if (autocvar_cl_followmodel)
249         {
250                 calc_followmodel_ofs(view);
251                 this.origin += cl_followmodel_ofs;
252         }
253
254         if (autocvar_cl_leanmodel)
255                 this.angles += leanmodel_ofs(view);
256
257         // vertical view bobbing code
258         // TODO: cl_bob
259
260         // horizontal view bobbing code
261         // TODO: cl_bob2
262
263         // fall bobbing code
264         // causes the view to swing down and back up when touching the ground
265         // TODO: cl_bobfall
266
267         // gun model bobbing code
268         if (autocvar_cl_bobmodel)
269                 this.origin += bobmodel_ofs(view);
270 }
271
272 .vector viewmodel_origin, viewmodel_angles;
273 .float weapon_nextthink;
274 .float weapon_eta_last;
275 .float weapon_switchdelay;
276
277 .string name_last;
278
279 void viewmodel_draw(entity this)
280 {
281         if(!this.activeweapon || !autocvar_r_drawviewmodel)
282                 return;
283         int mask = (intermission || (STAT(HEALTH) <= 0) || autocvar_chase_active) ? 0 : MASK_NORMAL;
284         float a = ((autocvar_cl_viewmodel_alpha) ? bound(-1, autocvar_cl_viewmodel_alpha, this.m_alpha) : this.m_alpha);
285         int wepskin = this.m_skin;
286         bool invehicle = player_localentnum > maxclients;
287         if (invehicle) a = -1;
288         Weapon wep = this.activeweapon;
289         int c = entcs_GetClientColors(current_player);
290         vector g = weaponentity_glowmod(wep, c, this);
291         entity me = CSQCModel_server2csqc(player_localentnum - 1);
292         int fx = ((me.csqcmodel_effects & EFMASK_CHEAP)
293                 | EF_NODEPTHTEST)
294                 &~ (EF_FULLBRIGHT); // can mask team color, so get rid of it
295         for (entity e = this; e; e = e.weaponchild)
296         {
297                 e.drawmask = mask;
298                 e.alpha = a;
299                 e.skin = wepskin;
300                 e.colormap = 256 + c;  // colormap == 0 is black, c == 0 is white
301                 e.glowmod = g;
302                 e.csqcmodel_effects = fx;
303                 CSQCModel_Effects_Apply(e);
304         }
305         if(a >= 0)
306         {
307                 string name = wep.mdl;
308                 string newname = wep.wr_viewmodel(wep, this);
309                 if(newname)
310                         name = newname;
311                 bool swap = name != this.name_last;
312                 // if (swap)
313                 {
314                         this.name_last = name;
315                         CL_WeaponEntity_SetModel(this, name, swap);
316                         this.viewmodel_origin = this.origin;
317                         this.viewmodel_angles = this.angles;
318                 }
319                 anim_update(this);
320                 if ((!this.animstate_override && !this.animstate_looping) || time > this.animstate_endtime)
321                         anim_set(this, this.anim_idle, true, false, false);
322         }
323         float f = 0; // 0..1; 0: fully active
324         float rate = STAT(WEAPONRATEFACTOR);
325         float eta = rate ? ((this.weapon_nextthink - time) / rate) : 0;
326         if (eta <= 0) f = this.weapon_eta_last;
327         else switch (this.state)
328         {
329                 case WS_RAISE:
330                 {
331                         f = eta / max(eta, this.weapon_switchdelay);
332                         break;
333                 }
334                 case WS_DROP:
335                 {
336                         f = 1 - eta / max(eta, this.weapon_switchdelay);
337                         break;
338                 }
339                 case WS_CLEAR:
340                 {
341                         f = 1;
342                         break;
343                 }
344         }
345         this.weapon_eta_last = f;
346         this.origin = this.viewmodel_origin;
347         this.angles = this.viewmodel_angles;
348         this.angles_x = (-90 * f * f);
349         viewmodel_animate(this);
350         MUTATOR_CALLHOOK(DrawViewModel, this);
351         setorigin(this, this.origin);
352 }
353
354 STATIC_INIT(viewmodel) {
355     for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
356         viewmodels[slot] = new(viewmodel);
357 }
358
359 vector project_3d_to_2d(vector vec)
360 {
361         vec = cs_project(vec);
362         return vec;
363 }
364
365 bool projected_on_screen(vector screen_pos)
366 {
367         return screen_pos.z >= 0
368                 && screen_pos.x >= 0
369                 && screen_pos.y >= 0
370                 && screen_pos.x < vid_conwidth
371                 && screen_pos.y < vid_conheight;
372 }
373
374 void update_mousepos()
375 {
376         mousepos += getmousepos() * autocvar_menu_mouse_speed;
377         mousepos.x = bound(0, mousepos.x, vid_conwidth);
378         mousepos.y = bound(0, mousepos.y, vid_conheight);
379 }
380
381 float showfps_prevfps_time;
382 int showfps_framecounter;
383
384 void fpscounter_update()
385 {
386         if(!STAT(SHOWFPS))
387                 return;
388
389         float currentTime = gettime(GETTIME_FRAMESTART);
390
391         showfps_framecounter += 1;
392         if(currentTime - showfps_prevfps_time > STAT(SHOWFPS))
393         {
394                 float fps = showfps_framecounter / (currentTime - showfps_prevfps_time);
395                 showfps_framecounter = 0;
396                 showfps_prevfps_time = currentTime;
397
398                 int channel = MSG_C2S;
399                 WriteHeader(channel, fpsreport);
400                 WriteShort(channel, bound(0, rint(fps), 32767)); // prevent insane fps values
401         }
402 }
403
404 STATIC_INIT(fpscounter_init)
405 {
406         float currentTime = gettime(GETTIME_FRAMESTART);
407         showfps_prevfps_time = currentTime; // we must initialize it to avoid an instant low frame sending
408 }
409
410 float avgspeed;
411 vector GetCurrentFov(float fov)
412 {
413         float zoomsensitivity, zoomspeed, zoomfactor, zoomdir;
414         float velocityzoom, curspeed;
415         vector v;
416
417         zoomsensitivity = autocvar_cl_zoomsensitivity;
418         zoomfactor = autocvar_cl_zoomfactor;
419         if(zoomfactor < 1 || zoomfactor > 30)
420                 zoomfactor = 2.5;
421         zoomspeed = autocvar_cl_zoomspeed;
422         if (zoomspeed >= 0 && (zoomspeed < 0.5 || zoomspeed > 16))
423                 zoomspeed = 3.5;
424
425         zoomdir = button_zoom;
426
427         if(hud == HUD_NORMAL && !spectatee_status)
428         {
429                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
430                 {
431                         entity wepent = viewmodels[slot];
432                         if(wepent.switchweapon != wepent.activeweapon)
433                                 continue;
434                         Weapon wep = wepent.activeweapon;
435                         if(wep != WEP_Null && wep.wr_zoomdir)
436                         {
437                                 bool do_zoom = wep.wr_zoomdir(wep); // TODO: merge this with wr_zoom?
438                                 zoomdir += do_zoom;
439                         }
440                 }
441         }
442         if(spectatee_status > 0 || isdemo())
443         {
444                 if(spectatorbutton_zoom)
445                 {
446                         if(zoomdir)
447                                 zoomdir = 0;
448                         else
449                                 zoomdir = 1;
450                 }
451                 // fteqcc failed twice here already, don't optimize this
452         }
453
454         if(zoomdir) { zoomin_effect = 0; }
455
456         if (spectatee_status > 0 && STAT(CAMERA_SPECTATOR) == 2)
457         {
458                 current_viewzoom = 1;
459         }
460         else if (camera_active)
461         {
462                 current_viewzoom = min(1, current_viewzoom + drawframetime);
463         }
464         else if(autocvar_cl_spawnzoom && zoomin_effect)
465         {
466                 float spawnzoomfactor = bound(1, autocvar_cl_spawnzoom_factor, 30);
467
468                 current_viewzoom += (autocvar_cl_spawnzoom_speed * (spawnzoomfactor - current_viewzoom) * drawframetime);
469                 current_viewzoom = bound(1 / spawnzoomfactor, current_viewzoom, 1);
470                 if(current_viewzoom == 1) { zoomin_effect = 0; }
471         }
472         else
473         {
474                 if(zoomspeed < 0) // instant zoom
475                 {
476                         if(zoomdir)
477                                 current_viewzoom = 1 / zoomfactor;
478                         else
479                                 current_viewzoom = 1;
480                 }
481                 else
482                 {
483                         if(zoomdir)
484                                 current_viewzoom = 1 / bound(1, 1 / current_viewzoom + drawframetime * zoomspeed * (zoomfactor - 1), zoomfactor);
485                         else
486                                 current_viewzoom = bound(1 / zoomfactor, current_viewzoom + drawframetime * zoomspeed * (1 - 1 / zoomfactor), 1);
487                 }
488         }
489
490         if(almost_equals(current_viewzoom, 1))
491                 current_zoomfraction = 0;
492         else if(almost_equals(current_viewzoom, 1/zoomfactor))
493                 current_zoomfraction = 1;
494         else
495                 current_zoomfraction = (current_viewzoom - 1) / (1/zoomfactor - 1);
496
497         if(zoomsensitivity < 1)
498                 setsensitivityscale(current_viewzoom ** (1 - zoomsensitivity));
499         else
500                 setsensitivityscale(1);
501
502         if(autocvar_cl_velocityzoom_enabled && autocvar_cl_velocityzoom_type && !autocvar_cl_lockview) // _type = 0 disables velocity zoom too
503         {
504                 if (intermission || (spectatee_status > 0 && STAT(CAMERA_SPECTATOR) == 2))
505                         curspeed = 0;
506                 else
507                 {
508                         vector forward, right, up;
509                         MAKE_VECTORS(view_angles, forward, right, up);
510                         v = pmove_vel;
511                         if(csqcplayer)
512                                 v = csqcplayer.velocity;
513
514                         switch(autocvar_cl_velocityzoom_type)
515                         {
516                                 case 3: curspeed = max(0, forward * v); break;
517                                 case 2: curspeed = (forward * v); break;
518                                 case 1: default: curspeed = vlen(v); break;
519                         }
520                 }
521
522                 velocityzoom = bound(0, drawframetime / max(0.000000001, autocvar_cl_velocityzoom_time), 1); // speed at which the zoom adapts to player velocity
523                 avgspeed = avgspeed * (1 - velocityzoom) + (curspeed / autocvar_cl_velocityzoom_speed) * velocityzoom;
524                 velocityzoom = exp(float2range11(avgspeed * -autocvar_cl_velocityzoom_factor / 1) * 1);
525
526                 //print(ftos(avgspeed), " avgspeed, ", ftos(curspeed), " curspeed, ", ftos(velocityzoom), " return\n"); // for debugging
527         }
528         else
529                 velocityzoom = 1;
530
531         float frustumx, frustumy, fovx, fovy;
532         frustumy = tan(fov * M_PI / 360.0) * 0.75 * current_viewzoom * velocityzoom;
533         frustumx = frustumy * vid_width / vid_height / vid_pixelheight;
534         fovx = atan2(frustumx, 1) / M_PI * 360.0;
535         fovy = atan2(frustumy, 1) / M_PI * 360.0;
536
537         return '1 0 0' * fovx + '0 1 0' * fovy;
538 }
539
540 vector GetViewLocationFOV(float fov)
541 {
542         float frustumy = tan(fov * M_PI / 360.0) * 0.75;
543         float frustumx = frustumy * vid_width / vid_height / vid_pixelheight;
544         float fovx = atan2(frustumx, 1) / M_PI * 360.0;
545         float fovy = atan2(frustumy, 1) / M_PI * 360.0;
546         return '1 0 0' * fovx + '0 1 0' * fovy;
547 }
548
549 vector GetOrthoviewFOV(vector ov_worldmin, vector ov_worldmax, vector ov_mid, vector ov_org)
550 {
551         float fovx, fovy;
552         float width = (ov_worldmax.x - ov_worldmin.x);
553         float height = (ov_worldmax.y - ov_worldmin.y);
554         float distance_to_middle_of_world = vlen(ov_mid - ov_org);
555         fovx = atan2(width/2, distance_to_middle_of_world) / M_PI * 360.0;
556         fovy = atan2(height/2, distance_to_middle_of_world) / M_PI * 360.0;
557         return '1 0 0' * fovx + '0 1 0' * fovy;
558 }
559
560 // this function must match W_SetupShot!
561
562 bool minigame_wasactive;
563
564 float camera_mode;
565 const float CAMERA_FREE = 1;
566 const float CAMERA_CHASE = 2;
567 string NextFrameCommand;
568
569 vector freeze_org, freeze_ang;
570 entity nightvision_noise, nightvision_noise2;
571
572 float myhealth, myhealth_prev;
573 float myhealth_flash;
574
575 float old_blurradius, old_bluralpha;
576 float old_sharpen_intensity;
577
578 vector myhealth_gentlergb;
579
580 float contentavgalpha, liquidalpha_prev;
581 vector liquidcolor_prev;
582
583 float eventchase_current_distance;
584 float eventchase_running;
585 int WantEventchase(entity this, bool want_vehiclechase)
586 {
587         if(autocvar_cl_orthoview)
588                 return 0;
589         if(STAT(GAME_STOPPED) || intermission)
590                 return 1;
591         if(this.viewloc)
592                 return 1;
593         if(spectatee_status >= 0)
594         {
595                 if(want_vehiclechase)
596                         return 1;
597                 if(MUTATOR_CALLHOOK(WantEventchase, this))
598                         return 1;
599                 if(autocvar_cl_eventchase_frozen && STAT(FROZEN))
600                         return 1;
601                 if(autocvar_cl_eventchase_death && (STAT(HEALTH) <= 0))
602                 {
603                         if(autocvar_cl_eventchase_death == 2)
604                         {
605                                 // don't stop eventchase once it's started (even if velocity changes afterwards)
606                                 if(this.velocity == '0 0 0' || eventchase_running)
607                                         return 1;
608                         }
609                         else return 1;
610                 }
611                 if (spectatee_status > 0 && autocvar_cl_eventchase_spectated_change)
612                 {
613                         if (time <= spectatee_status_changed_time + min(3, autocvar_cl_eventchase_spectated_change_time))
614                                 return 1;
615                         else if (eventchase_running)
616                                 return -1; // disable chase_active while eventchase is still enabled so to avoid a glicth
617                 }
618         }
619         return 0;
620 }
621
622 void View_EventChase(entity this)
623 {
624         // event chase camera
625         if(autocvar_chase_active <= 0) // greater than 0 means it's enabled manually, and this code is skipped
626         {
627                 if(STAT(CAMERA_SPECTATOR))
628                 {
629                         if(spectatee_status > 0)
630                         {
631                                 if(!autocvar_chase_active)
632                                 {
633                                         cvar_set("chase_active", "-2");
634                                         return;
635                                 }
636                         }
637                         else if(autocvar_chase_active == -2)
638                                 cvar_set("chase_active", "0");
639
640                         if(autocvar_chase_active == -2)
641                                 return;
642                 }
643                 else if(autocvar_chase_active == -2)
644                         cvar_set("chase_active", "0");
645
646                 bool vehicle_chase = (hud != HUD_NORMAL && (autocvar_cl_eventchase_vehicle || spectatee_status > 0));
647
648                 float vehicle_viewdist = 0;
649                 vector vehicle_viewofs = '0 0 0';
650
651                 if(vehicle_chase)
652                 {
653                         if(hud != HUD_BUMBLEBEE_GUN)
654                         {
655                                 Vehicle info = REGISTRY_GET(Vehicles, hud);
656                                 vehicle_viewdist = info.height;
657                                 vehicle_viewofs = info.view_ofs;
658                                 if(vehicle_viewdist < 0) // when set below 0, this vehicle doesn't use third person view (gunner slots)
659                                         vehicle_chase = false;
660                         }
661                         else
662                                 vehicle_chase = false;
663                 }
664
665                 int eventchase = WantEventchase(this, vehicle_chase);
666                 if (eventchase)
667                 {
668                         vector current_view_origin_override = '0 0 0';
669                         vector view_offset_override = '0 0 0';
670                         float chase_distance_override = 0;
671                         bool custom_eventchase = MUTATOR_CALLHOOK(CustomizeEventchase, this);
672                         if(custom_eventchase)
673                         {
674                                 current_view_origin_override = M_ARGV(0, vector);
675                                 view_offset_override = M_ARGV(1, vector);
676                                 chase_distance_override = M_ARGV(0, float);
677                         }
678                         eventchase_running = true;
679
680                         // make special vector since we can't use view_origin (It is one frame old as of this code, it gets set later with the results this code makes.)
681                         vector current_view_origin = (csqcplayer ? csqcplayer.origin : pmove_org);
682                         if (custom_eventchase)
683                                 current_view_origin = current_view_origin_override;
684
685                         // detect maximum viewoffset and use it
686                         vector view_offset = autocvar_cl_eventchase_viewoffset;
687                         if(vehicle_chase)
688                         {
689                                 if(vehicle_viewofs)
690                                         view_offset = vehicle_viewofs;
691                                 else
692                                         view_offset = autocvar_cl_eventchase_vehicle_viewoffset;
693                         }
694                         if (custom_eventchase)
695                                 view_offset = view_offset_override;
696
697                         if(view_offset)
698                         {
699                                 WarpZone_TraceLine(current_view_origin, current_view_origin + view_offset + ('0 0 1' * autocvar_cl_eventchase_maxs.z), MOVE_WORLDONLY, this);
700                                 if(trace_fraction == 1) { current_view_origin += view_offset; }
701                                 else { current_view_origin.z += max(0, (trace_endpos.z - current_view_origin.z) - autocvar_cl_eventchase_maxs.z); }
702                         }
703
704                         // We must enable chase_active to get a third person view (weapon viewmodel hidden and own player model showing).
705                         // Ideally, there should be another way to enable third person cameras, such as through setproperty()
706                         // -1 enables chase_active while marking it as set by this code, and not by the user (which would be 1)
707                         if(!autocvar_chase_active) { cvar_set("chase_active", "-1"); }
708
709                         // make the camera smooth back
710                         float chase_distance = autocvar_cl_eventchase_distance;
711                         if(vehicle_chase)
712                         {
713                                 if(vehicle_viewofs)
714                                         chase_distance = vehicle_viewdist;
715                                 else
716                                         chase_distance = autocvar_cl_eventchase_vehicle_distance;
717                         }
718                         if (custom_eventchase)
719                                 chase_distance = chase_distance_override;
720
721                         if(autocvar_cl_eventchase_speed && eventchase_current_distance < chase_distance)
722                                 eventchase_current_distance += autocvar_cl_eventchase_speed * (chase_distance - eventchase_current_distance) * frametime; // slow down the further we get
723                         else if(eventchase_current_distance != chase_distance)
724                                 eventchase_current_distance = chase_distance;
725
726                         vector forward, right, up;
727                         MAKE_VECTORS(view_angles, forward, right, up);
728
729                         vector eventchase_target_origin = (current_view_origin - (forward * eventchase_current_distance));
730                         WarpZone_TraceBox(current_view_origin, autocvar_cl_eventchase_mins, autocvar_cl_eventchase_maxs, eventchase_target_origin, MOVE_WORLDONLY, this);
731
732                         // If the boxtrace fails, revert back to line tracing.
733                         if(!this.viewloc)
734                         if(trace_startsolid)
735                         {
736                                 eventchase_target_origin = (current_view_origin - (forward * eventchase_current_distance));
737                                 WarpZone_TraceLine(current_view_origin, eventchase_target_origin, MOVE_WORLDONLY, this);
738                                 setproperty(VF_ORIGIN, (trace_endpos - (forward * autocvar_cl_eventchase_mins.z)));
739                         }
740                         else { setproperty(VF_ORIGIN, trace_endpos); }
741
742                         if(!this.viewloc)
743                                 setproperty(VF_ANGLES, WarpZone_TransformVAngles(WarpZone_trace_transform, view_angles));
744                 }
745
746                 if (eventchase <= 0 && autocvar_chase_active < 0) // time to disable chase_active if it was set by this code
747                 {
748                         eventchase_running = false;
749                         cvar_set("chase_active", "0");
750                         eventchase_current_distance = 0; // start from 0 next time
751                 }
752         }
753         // workaround for camera stuck between player's legs when using chase_active 1
754         // because the engine stops updating the chase_active camera when the game ends
755         else if(intermission)
756         {
757                 cvar_settemp("chase_active", "-1");
758                 eventchase_current_distance = 0;
759         }
760 }
761
762 vector damage_blurpostprocess, content_blurpostprocess;
763
764 void UpdateDamage()
765 {
766         // accumulate damage with each stat update
767         static float damage_total_prev = 0;
768         float damage_total = STAT(HITSOUND_DAMAGE_DEALT_TOTAL);
769         float unaccounted_damage_new = COMPARE_INCREASING(damage_total, damage_total_prev);
770         damage_total_prev = damage_total;
771
772         static float damage_dealt_time_prev = 0;
773         float damage_dealt_time = STAT(HIT_TIME);
774         if (damage_dealt_time != damage_dealt_time_prev)
775         {
776                 unaccounted_damage += unaccounted_damage_new;
777                 //LOG_TRACE("dmg total: ", ftos(unaccounted_damage), " (+", ftos(unaccounted_damage_new), ")");
778         }
779         damage_dealt_time_prev = damage_dealt_time;
780
781         // prevent hitsound when switching spectatee
782         static float spectatee_status_prev = 0;
783         if (spectatee_status != spectatee_status_prev)
784                 unaccounted_damage = 0;
785         spectatee_status_prev = spectatee_status;
786 }
787
788 void HitSound()
789 {
790         // varying sound pitch
791
792         bool have_arc = false;
793         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
794         {
795                 entity wepent = viewmodels[slot];
796
797                 if(wepent.activeweapon == WEP_ARC)
798                         have_arc = true;
799         }
800
801         static float hitsound_time_prev = 0;
802         // HACK: the only way to get the arc to sound consistent with pitch shift is to ignore cl_hitsound_antispam_time
803         bool arc_hack = have_arc && autocvar_cl_hitsound >= 2;
804         if (arc_hack || COMPARE_INCREASING(time, hitsound_time_prev) > autocvar_cl_hitsound_antispam_time)
805         {
806                 if (autocvar_cl_hitsound && unaccounted_damage)
807                 {
808                         float pitch_shift = 1;
809                         if (autocvar_cl_hitsound == 2 || autocvar_cl_hitsound == 3)
810                         {
811                                 // customizable gradient function that crosses (0,a), (c,1) and asymptotically approaches b
812                                 float a = autocvar_cl_hitsound_max_pitch;
813                                 float b = autocvar_cl_hitsound_min_pitch;
814                                 float c = autocvar_cl_hitsound_nom_damage;
815                                 float d = unaccounted_damage;
816                                 pitch_shift = (b*d*(a-1) + a*c*(1-b)) / (d*(a-1) + c*(1-b));
817
818                                 // if pitch shift is reversed, mirror in (max-min)/2 + min
819                                 if (autocvar_cl_hitsound == 3)
820                                 {
821                                         float mirror_value = (a-b)/2 + b;
822                                         pitch_shift = mirror_value + (mirror_value - pitch_shift);
823                                 }
824                         }
825
826                         //LOG_TRACE("dmg total (dmg): ", ftos(unaccounted_damage), " , pitch shift: ", ftos(pitch_shift));
827
828                         // todo: avoid very long and very short sounds from wave stretching using different sound files? seems unnecessary
829                         // todo: normalize sound pressure levels? seems unnecessary
830
831                         sound7(NULL, CH_INFO, SND(HIT), VOL_BASE, ATTN_NONE, pitch_shift * 100, 0);
832                 }
833                 unaccounted_damage = 0;
834                 hitsound_time_prev = time;
835         }
836
837         static float typehit_time_prev = 0;
838         float typehit_time = STAT(TYPEHIT_TIME);
839         if (COMPARE_INCREASING(typehit_time, typehit_time_prev) > autocvar_cl_hitsound_antispam_time)
840         {
841                 sound(NULL, CH_INFO, SND_TYPEHIT, VOL_BASE, ATTN_NONE);
842                 typehit_time_prev = typehit_time;
843         }
844
845         static float kill_time_prev = 0;
846         float kill_time = STAT(KILL_TIME);
847         if (COMPARE_INCREASING(kill_time, kill_time_prev) > autocvar_cl_hitsound_antispam_time)
848         {
849                 sound(NULL, CH_INFO, SND_KILL, VOL_BASE, ATTN_NONE);
850                 kill_time_prev = kill_time;
851         }
852 }
853
854 void HUD_Draw(entity this)
855 {
856         // if we don't know gametype and scores yet avoid drawing the scoreboard
857         // also in the very first frames, player state may be inconsistent so avoid drawing the hud at all
858         // e.g. since initial player's health is 0 hud would display the hud_damage effect,
859         // cl_deathscoreboard would show the scoreboard and so on
860         if(!gametype)
861                 return;
862
863         Hud_Dynamic_Frame();
864
865         if(!intermission)
866         {
867                 if (MUTATOR_CALLHOOK(HUD_Draw_overlay))
868                 {
869                         drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), M_ARGV(0, vector), autocvar_hud_colorflash_alpha * M_ARGV(1, float), DRAWFLAG_ADDITIVE);
870                 }
871                 else if(STAT(FROZEN))
872                 {
873                         vector col = '0.25 0.90 1';
874                         float col_fade = max(0, STAT(REVIVE_PROGRESS) * 2 - 1);
875                         float alpha_fade = 0.3 + 0.7 * (1 - max(0, STAT(REVIVE_PROGRESS) * 4 - 3));
876                         if(col_fade)
877                                 col += vec3(col_fade, -col_fade, -col_fade);
878                         drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), col, autocvar_hud_colorflash_alpha * alpha_fade, DRAWFLAG_ADDITIVE);
879                 }
880         }
881
882         HUD_Scale_Enable();
883         if(!intermission)
884         {
885                 if(STAT(NADE_TIMER) && autocvar_cl_nade_timer) // give nade top priority, as it's a matter of life and death
886                 {
887                         vector col = '0.25 0.90 1' + vec3(STAT(NADE_TIMER), -STAT(NADE_TIMER), -STAT(NADE_TIMER));
888                         DrawCircleClippedPic(vec2(0.5 * vid_conwidth, 0.6 * vid_conheight), 0.1 * vid_conheight, "gfx/crosshair_ring", STAT(NADE_TIMER), col, autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
889                         drawstring_aspect(eY * 0.64 * vid_conheight, ((autocvar_cl_nade_timer == 2) ? _("Nade timer") : ""), vec2(vid_conwidth, 0.025 * vid_conheight), '1 1 1', 1, DRAWFLAG_NORMAL);
890                 }
891                 else if(STAT(CAPTURE_PROGRESS))
892                 {
893                         DrawCircleClippedPic(vec2(0.5 * vid_conwidth, 0.6 * vid_conheight), 0.1 * vid_conheight, "gfx/crosshair_ring", STAT(CAPTURE_PROGRESS), '0.25 0.90 1', autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
894                         drawstring_aspect(eY * 0.64 * vid_conheight, _("Capture progress"), vec2(vid_conwidth, 0.025 * vid_conheight), '1 1 1', 1, DRAWFLAG_NORMAL);
895                 }
896                 else if(STAT(REVIVE_PROGRESS))
897                 {
898                         DrawCircleClippedPic(vec2(0.5 * vid_conwidth, 0.6 * vid_conheight), 0.1 * vid_conheight, "gfx/crosshair_ring", STAT(REVIVE_PROGRESS), '0.25 0.90 1', autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
899                         drawstring_aspect(eY * 0.64 * vid_conheight, _("Revival progress"), vec2(vid_conwidth, 0.025 * vid_conheight), '1 1 1', 1, DRAWFLAG_NORMAL);
900                 }
901         }
902         HUD_Scale_Disable();
903
904         if(autocvar_r_letterbox == 0)
905         {
906                 if(autocvar_viewsize < 120)
907                 {
908                         if(!MUTATOR_CALLHOOK(DrawScoreboardAccuracy))
909                                 Accuracy_LoadLevels();
910
911                         HUD_Main();
912                         HUD_Scale_Disable();
913                 }
914         }
915
916         // crosshair goes VERY LAST
917         UpdateDamage();
918         HUD_Crosshair(this);
919         HitSound();
920         Local_Notification_Queue_Process();
921 }
922
923 void ViewLocation_Mouse()
924 {
925         if(spectatee_status)
926                 return; // don't draw it as spectator!
927
928         viewloc_mousepos += getmousepos() * autocvar_menu_mouse_speed;
929         viewloc_mousepos.x = bound(0, viewloc_mousepos.x, vid_conwidth);
930         viewloc_mousepos.y = bound(0, viewloc_mousepos.y, vid_conheight);
931
932         //float cursor_alpha = 1 - autocvar__menu_alpha;
933         //cursor_type = CURSOR_NORMAL;
934         //draw_cursor(viewloc_mousepos, '0.5 0.5 0', "/cursor_move", '1 1 1', cursor_alpha);
935 }
936
937 void HUD_Cursor_Show()
938 {
939         float cursor_alpha = 1 - autocvar__menu_alpha;
940         if(cursor_type == CURSOR_NORMAL)
941                 draw_cursor_normal(mousepos, '1 1 1', cursor_alpha);
942         else if(cursor_type == CURSOR_MOVE)
943                 draw_cursor(mousepos, '0.5 0.5 0', "/cursor_move", '1 1 1', cursor_alpha);
944         else if(cursor_type == CURSOR_RESIZE)
945                 draw_cursor(mousepos, '0.5 0.5 0', "/cursor_resize", '1 1 1', cursor_alpha);
946         else if(cursor_type == CURSOR_RESIZE2)
947                 draw_cursor(mousepos, '0.5 0.5 0', "/cursor_resize2", '1 1 1', cursor_alpha);
948 }
949
950 void HUD_Mouse(entity player)
951 {
952         if(autocvar__menu_alpha == 1)
953                 return;
954
955         if(!cursor_active)
956         {
957                 if(player.viewloc && (player.viewloc.spawnflags & VIEWLOC_FREEAIM))
958                         ViewLocation_Mouse(); // NOTE: doesn't use cursormode
959                 return;
960         }
961
962         if (cursor_active == -1) // starting to display the cursor
963         {
964                 // since HUD_Mouse is called by CSQC_UpdateView before CSQC_InputEvent,
965                 // in the first frame mousepos is the mouse position of the last time
966                 // the cursor was displayed, thus we ignore it to avoid a glictch
967                 cursor_active = 1;
968                 return;
969         }
970
971         if(!autocvar_hud_cursormode)
972                 update_mousepos();
973
974         cursor_type = CURSOR_NORMAL;
975         if(autocvar__hud_configure)
976                 HUD_Panel_Mouse();
977         else
978         {
979                 if (HUD_MinigameMenu_IsOpened())
980                         HUD_Minigame_Mouse();
981                 if (QuickMenu_IsOpened())
982                         QuickMenu_Mouse();
983                 if (HUD_Radar_Clickable())
984                         HUD_Radar_Mouse();
985         }
986
987         prevMouseClicked = mouseClicked;
988
989         HUD_Cursor_Show();
990 }
991
992 void View_NightVision()
993 {
994         if(!(autocvar_r_fakelight >= 2 || autocvar_r_fullbright) || (serverflags & SERVERFLAG_ALLOW_FULLBRIGHT))
995                 return;
996
997         // apply night vision effect
998         vector tc_00, tc_01, tc_10, tc_11;
999         vector rgb = '0 0 0';
1000         float a;
1001
1002         if(!nightvision_noise)
1003         {
1004                 nightvision_noise = new(nightvision_noise);
1005         }
1006         if(!nightvision_noise2)
1007         {
1008                 nightvision_noise2 = new(nightvision_noise2);
1009         }
1010
1011         // color tint in yellow
1012         drawfill('0 0 0', autocvar_vid_conwidth * '1 0 0' + autocvar_vid_conheight * '0 1 0', '0.5 1 0.3', 1, DRAWFLAG_MODULATE);
1013
1014         // draw BG
1015         a = Noise_Pink(nightvision_noise, frametime * 1.5) * 0.05 + 0.15;
1016         rgb = '1 1 1';
1017         tc_00 = '0 0 0' + '0.2 0 0' * sin(time * 0.3) + '0 0.3 0' * cos(time * 0.7);
1018         tc_01 = '0 2.25 0' + '0.6 0 0' * cos(time * 1.2) - '0 0.3 0' * sin(time * 2.2);
1019         tc_10 = '1.5 0 0' - '0.2 0 0' * sin(time * 0.5) + '0 0.5 0' * cos(time * 1.7);
1020         //tc_11 = '1 1 0' + '0.6 0 0' * sin(time * 0.6) + '0 0.3 0' * cos(time * 0.1);
1021         tc_11 = tc_01 + tc_10 - tc_00;
1022         R_BeginPolygon("gfx/nightvision-bg", DRAWFLAG_ADDITIVE, true);
1023         R_PolygonVertex('0 0 0', tc_00, rgb, a);
1024         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0', tc_10, rgb, a);
1025         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0' + autocvar_vid_conheight * '0 1 0', tc_11, rgb, a);
1026         R_PolygonVertex(autocvar_vid_conheight * '0 1 0', tc_01, rgb, a);
1027         R_EndPolygon();
1028
1029         // draw FG
1030         a = Noise_Pink(nightvision_noise2, frametime * 0.1) * 0.05 + 0.12;
1031         rgb = '0.3 0.6 0.4' + '0.1 0.4 0.2' * Noise_White(nightvision_noise2, frametime);
1032         tc_00 = '0 0 0' + '1 0 0' * Noise_White(nightvision_noise2, frametime) + '0 1 0' * Noise_White(nightvision_noise2, frametime);
1033         tc_01 = tc_00 + '0 3 0' * (1 + Noise_White(nightvision_noise2, frametime) * 0.2);
1034         tc_10 = tc_00 + '2 0 0' * (1 + Noise_White(nightvision_noise2, frametime) * 0.3);
1035         tc_11 = tc_01 + tc_10 - tc_00;
1036         R_BeginPolygon("gfx/nightvision-fg", DRAWFLAG_ADDITIVE, true);
1037         R_PolygonVertex('0 0 0', tc_00, rgb, a);
1038         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0', tc_10, rgb, a);
1039         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0' + autocvar_vid_conheight * '0 1 0', tc_11, rgb, a);
1040         R_PolygonVertex(autocvar_vid_conheight * '0 1 0', tc_01, rgb, a);
1041         R_EndPolygon();
1042 }
1043
1044 // visual overlay while in liquids
1045 // provides some effects to the postprocessing function
1046 void HUD_Contents()
1047 {
1048         if(!autocvar_hud_contents || MUTATOR_CALLHOOK(HUD_Contents))
1049                 return;
1050
1051         // improved polyblend
1052         float contentalpha_temp, incontent, liquidalpha, contentfadetime;
1053         vector liquidcolor;
1054
1055         switch(pointcontents(view_origin))
1056         {
1057                 case CONTENT_WATER:
1058                         liquidalpha = autocvar_hud_contents_water_alpha;
1059                         liquidcolor = stov(autocvar_hud_contents_water_color);
1060                         incontent = 1;
1061                         break;
1062
1063                 case CONTENT_LAVA:
1064                         liquidalpha = autocvar_hud_contents_lava_alpha;
1065                         liquidcolor = stov(autocvar_hud_contents_lava_color);
1066                         incontent = 1;
1067                         break;
1068
1069                 case CONTENT_SLIME:
1070                         liquidalpha = autocvar_hud_contents_slime_alpha;
1071                         liquidcolor = stov(autocvar_hud_contents_slime_color);
1072                         incontent = 1;
1073                         break;
1074
1075                 default:
1076                         liquidalpha = 0;
1077                         liquidcolor = '0 0 0';
1078                         incontent = 0;
1079                         break;
1080         }
1081
1082         if(incontent) // fade in/out at different speeds so you can do e.g. instant fade when entering water and slow when leaving it.
1083         { // also lets delcare previous values for blending properties, this way it isn't reset until after you have entered a different content
1084                 contentfadetime = autocvar_hud_contents_fadeintime;
1085                 liquidalpha_prev = liquidalpha;
1086                 liquidcolor_prev = liquidcolor;
1087         }
1088         else
1089                 contentfadetime = autocvar_hud_contents_fadeouttime;
1090
1091         contentalpha_temp = bound(0, drawframetime / max(0.0001, contentfadetime), 1);
1092         contentavgalpha = contentavgalpha * (1 - contentalpha_temp) + incontent * contentalpha_temp;
1093
1094         if(contentavgalpha)
1095                 drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), liquidcolor_prev, contentavgalpha * liquidalpha_prev, DRAWFLAG_NORMAL);
1096
1097         if(autocvar_hud_postprocessing)
1098         {
1099                 if(autocvar_hud_contents_blur && contentavgalpha)
1100                 {
1101                         content_blurpostprocess.x = 1;
1102                         content_blurpostprocess.y = contentavgalpha * autocvar_hud_contents_blur;
1103                         content_blurpostprocess.z = contentavgalpha * autocvar_hud_contents_blur_alpha;
1104                 }
1105                 else
1106                 {
1107                         content_blurpostprocess.x = 0;
1108                         content_blurpostprocess.y = 0;
1109                         content_blurpostprocess.z = 0;
1110                 }
1111         }
1112 }
1113
1114 // visual pain effects on the screen
1115 // provides some effects to the postprocessing function
1116 void HUD_Damage()
1117 {
1118         if(!autocvar_hud_damage || STAT(FROZEN))
1119                 return;
1120
1121         vector splash_pos = '0 0 0', splash_size = '0 0 0';
1122         splash_size.x = max(vid_conwidth, vid_conheight);
1123         splash_size.y = max(vid_conwidth, vid_conheight);
1124         splash_pos.x = (vid_conwidth - splash_size.x) / 2;
1125         splash_pos.y = (vid_conheight - splash_size.y) / 2;
1126
1127         float myhealth_flash_temp;
1128         myhealth = STAT(HEALTH);
1129
1130         // fade out
1131         myhealth_flash = max(0, myhealth_flash - autocvar_hud_damage_fade_rate * frametime);
1132         // add new damage
1133         myhealth_flash = bound(0, myhealth_flash + dmg_take * autocvar_hud_damage_factor, autocvar_hud_damage_maxalpha);
1134
1135         float pain_threshold, pain_threshold_lower, pain_threshold_lower_health;
1136         pain_threshold = autocvar_hud_damage_pain_threshold;
1137         pain_threshold_lower = autocvar_hud_damage_pain_threshold_lower;
1138         pain_threshold_lower_health = autocvar_hud_damage_pain_threshold_lower_health;
1139
1140         if(pain_threshold_lower && myhealth < pain_threshold_lower_health)
1141         {
1142                 pain_threshold = pain_threshold - max(autocvar_hud_damage_pain_threshold_pulsating_min, fabs(sin(M_PI * time / autocvar_hud_damage_pain_threshold_pulsating_period))) * pain_threshold_lower * (1 - max(0, myhealth)/pain_threshold_lower_health);
1143         }
1144
1145         myhealth_flash_temp = bound(0, myhealth_flash - pain_threshold, 1);
1146
1147         if(myhealth_prev < 1)
1148         {
1149                 if(myhealth >= 1)
1150                 {
1151                         myhealth_flash = 0; // just spawned, clear the flash immediately
1152                         myhealth_flash_temp = 0;
1153                 }
1154                 else
1155                 {
1156                         myhealth_flash += autocvar_hud_damage_fade_rate * frametime; // dead
1157                 }
1158         }
1159
1160         if(spectatee_status == -1 || intermission)
1161         {
1162                 myhealth_flash = 0; // observing, or match ended
1163                 myhealth_flash_temp = 0;
1164         }
1165
1166         myhealth_prev = myhealth;
1167
1168         // IDEA: change damage color/picture based on player model for robot/alien species?
1169         // pro: matches model better
1170         // contra: it's not red because blood is red, but because red is an alarming color, so red should stay
1171         // maybe different reddish pics?
1172         if(autocvar_cl_gentle_damage || autocvar_cl_gentle)
1173         {
1174                 if(autocvar_cl_gentle_damage == 2)
1175                 {
1176                         if(myhealth_flash < pain_threshold) // only randomize when the flash is gone
1177                                 myhealth_gentlergb = randomvec();
1178                 }
1179                 else
1180                         myhealth_gentlergb = stov(autocvar_hud_damage_gentle_color);
1181
1182                 if(myhealth_flash_temp > 0)
1183                         drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), myhealth_gentlergb, autocvar_hud_damage_gentle_alpha_multiplier * bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage, DRAWFLAG_NORMAL);
1184         }
1185         else if(myhealth_flash_temp > 0)
1186                 drawpic(splash_pos, "gfx/blood", splash_size, stov(autocvar_hud_damage_color), bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage, DRAWFLAG_NORMAL);
1187
1188         if(autocvar_hud_postprocessing) // we still need to set this anyway even when chase_active is set, this way it doesn't get stuck on.
1189         {
1190                 if(autocvar_hud_damage_blur && myhealth_flash_temp)
1191                 {
1192                         damage_blurpostprocess.x = 1;
1193                         damage_blurpostprocess.y = bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage_blur;
1194                         damage_blurpostprocess.z = bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage_blur_alpha;
1195                 }
1196                 else
1197                 {
1198                         damage_blurpostprocess.x = 0;
1199                         damage_blurpostprocess.y = 0;
1200                         damage_blurpostprocess.z = 0;
1201                 }
1202         }
1203 }
1204
1205 void View_PostProcessing()
1206 {
1207         float e1 = (autocvar_hud_postprocessing_maxbluralpha != 0);
1208         float e2 = (autocvar_hud_powerup != 0);
1209         if(autocvar_hud_postprocessing && (e1 || e2)) // TODO: Remove this code and re-do the postprocess handling in the engine, where it properly belongs.
1210         {
1211                 // enable or disable rendering types if they are used or not
1212                 if(cvar("r_glsl_postprocess_uservec1_enable") != e1) { cvar_set("r_glsl_postprocess_uservec1_enable", ftos(e1)); }
1213                 if(cvar("r_glsl_postprocess_uservec2_enable") != e2) { cvar_set("r_glsl_postprocess_uservec2_enable", ftos(e2)); }
1214
1215                 // blur postprocess handling done first (used by hud_damage and hud_contents)
1216                 if((damage_blurpostprocess.x || content_blurpostprocess.x))
1217                 {
1218                         float blurradius = bound(0, damage_blurpostprocess.y + content_blurpostprocess.y, autocvar_hud_postprocessing_maxblurradius);
1219                         float bluralpha = bound(0, damage_blurpostprocess.z + content_blurpostprocess.z, autocvar_hud_postprocessing_maxbluralpha);
1220                         if(blurradius != old_blurradius || bluralpha != old_bluralpha) // reduce cvar_set spam as much as possible
1221                         {
1222                                 cvar_set("r_glsl_postprocess_uservec1", strcat(ftos(blurradius), " ", ftos(bluralpha), " 0 0"));
1223                                 old_blurradius = blurradius;
1224                                 old_bluralpha = bluralpha;
1225                         }
1226                 }
1227                 else if(cvar_string("r_glsl_postprocess_uservec1") != "0 0 0 0") // reduce cvar_set spam as much as possible
1228                 {
1229                         cvar_set("r_glsl_postprocess_uservec1", "0 0 0 0");
1230                         old_blurradius = 0;
1231                         old_bluralpha = 0;
1232                 }
1233
1234                 // edge detection postprocess handling done second (used by hud_powerup)
1235                 float sharpen_intensity = 0;
1236                 FOREACH(StatusEffect, it.instanceOfPowerups,
1237                 {
1238                         float powerup_finished = StatusEffects_gettime(it, g_statuseffects) - time;
1239                         if(powerup_finished > 0)
1240                                 sharpen_intensity += powerup_finished;
1241                 });
1242
1243                 sharpen_intensity = bound(0, ((STAT(HEALTH) > 0) ? sharpen_intensity : 0), 5); // Check to see if player is alive (if not, set 0) - also bound to fade out starting at 5 seconds.
1244
1245                 if(autocvar_hud_powerup && sharpen_intensity > 0)
1246                 {
1247                         if(sharpen_intensity != old_sharpen_intensity) // reduce cvar_set spam as much as possible
1248                         {
1249                                 cvar_set("r_glsl_postprocess_uservec2", strcat(ftos((sharpen_intensity / 5) * autocvar_hud_powerup), " ", ftos(-sharpen_intensity * autocvar_hud_powerup), " 0 0"));
1250                                 old_sharpen_intensity = sharpen_intensity;
1251                         }
1252                 }
1253                 else if(cvar_string("r_glsl_postprocess_uservec2") != "0 0 0 0") // reduce cvar_set spam as much as possible
1254                 {
1255                         cvar_set("r_glsl_postprocess_uservec2", "0 0 0 0");
1256                         old_sharpen_intensity = 0;
1257                 }
1258
1259                 if(cvar("r_glsl_postprocess") == 0)
1260                         cvar_set("r_glsl_postprocess", "2");
1261         }
1262         else if(cvar("r_glsl_postprocess") == 2)
1263                 cvar_set("r_glsl_postprocess", "0");
1264 }
1265
1266 void View_Lock()
1267 {
1268         int lock_type = autocvar_cl_lockview;
1269
1270         if (!autocvar_hud_cursormode
1271                 && ((autocvar__hud_configure && spectatee_status <= 0)
1272                         || intermission > 1
1273                         || HUD_Radar_Clickable()
1274                         || HUD_MinigameMenu_IsOpened()
1275                         || QuickMenu_IsOpened()
1276                 )
1277         )
1278                 lock_type = 1;
1279
1280         // lock_type 1: lock origin and angles
1281         // lock_type 2: lock only origin
1282         if(lock_type >= 1)
1283                 setproperty(VF_ORIGIN, freeze_org);
1284         else
1285                 freeze_org = getpropertyvec(VF_ORIGIN);
1286         if(lock_type == 1)
1287                 setproperty(VF_ANGLES, freeze_ang);
1288         else
1289                 freeze_ang = getpropertyvec(VF_ANGLES);
1290 }
1291
1292 void View_DemoCamera()
1293 {
1294         if(camera_active) // Camera for demo playback
1295         {
1296                 if(autocvar_camera_enable)
1297                         CSQC_Demo_Camera();
1298                 else
1299                 {
1300                         cvar_set("chase_active", ftos(chase_active_backup));
1301                         cvar_set("cl_demo_mousegrab", "0");
1302                         camera_active = false;
1303                 }
1304         }
1305         else
1306         {
1307 #ifdef CAMERATEST
1308                 if(autocvar_camera_enable)
1309 #else
1310                 if(autocvar_camera_enable && isdemo())
1311 #endif
1312                 {
1313                         // Enable required Darkplaces cvars
1314                         chase_active_backup = autocvar_chase_active;
1315                         cvar_set("chase_active", "2");
1316                         cvar_set("cl_demo_mousegrab", "1");
1317                         camera_active = true;
1318                         camera_mode = false;
1319                 }
1320         }
1321 }
1322
1323 #ifdef BLURTEST
1324 void View_BlurTest()
1325 {
1326         if(time > blurtest_time0 && time < blurtest_time1)
1327         {
1328                 float t = (time - blurtest_time0) / (blurtest_time1 - blurtest_time0);
1329                 float r = t * blurtest_radius;
1330                 float f = 1 / (t ** blurtest_power) - 1;
1331
1332                 cvar_set("r_glsl_postprocess", "1");
1333                 cvar_set("r_glsl_postprocess_uservec1", strcat(ftos(r), " ", ftos(f), " 0 0"));
1334         }
1335         else
1336         {
1337                 cvar_set("r_glsl_postprocess", "0");
1338                 cvar_set("r_glsl_postprocess_uservec1", "0 0 0 0");
1339         }
1340 }
1341 #endif
1342
1343 void View_CheckButtonStatus()
1344 {
1345         float is_dead = (STAT(HEALTH) <= 0);
1346
1347         // FIXME do we need this hack?
1348         if(isdemo())
1349         {
1350                 // in demos, input_buttons do not work
1351                 button_zoom = (autocvar__togglezoom == "-");
1352         }
1353         else if(button_zoom
1354                 && autocvar_cl_unpress_zoom_on_death
1355                 && (spectatee_status >= 0)
1356                 && (is_dead || intermission))
1357         {
1358                 // no zoom while dead or in intermission please
1359                 localcmd("-zoom\n");
1360                 button_zoom = false;
1361         }
1362
1363         if(autocvar_fov <= 59.5)
1364         {
1365                 if(!zoomscript_caught)
1366                 {
1367                         localcmd("+button9\n");
1368                         zoomscript_caught = 1;
1369                 }
1370         }
1371         else
1372         {
1373                 if(zoomscript_caught)
1374                 {
1375                         localcmd("-button9\n");
1376                         zoomscript_caught = 0;
1377                 }
1378         }
1379
1380         if(active_minigame && HUD_MinigameMenu_IsOpened())
1381         {
1382                 if(!minigame_wasactive)
1383                 {
1384                         localcmd("+button12\n");
1385                         minigame_wasactive = true;
1386                 }
1387         }
1388         else if(minigame_wasactive)
1389         {
1390                 localcmd("-button12\n");
1391                 minigame_wasactive = false;
1392         }
1393
1394         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1395         {
1396                 entity wepent = viewmodels[slot];
1397
1398                 if(wepent.last_switchweapon != wepent.switchweapon)
1399                 {
1400                         weapontime = time;
1401                         wepent.last_switchweapon = wepent.switchweapon;
1402                         if(slot == 0 && button_zoom && autocvar_cl_unpress_zoom_on_weapon_switch)
1403                         {
1404                                 localcmd("-zoom\n");
1405                                 button_zoom = false;
1406                         }
1407                         if(slot == 0 && autocvar_cl_unpress_attack_on_weapon_switch)
1408                         {
1409                                 localcmd("-fire\n");
1410                                 localcmd("-fire2\n");
1411                                 button_attack2 = false;
1412                         }
1413                 }
1414                 if(wepent.last_activeweapon != wepent.activeweapon)
1415                 {
1416                         wepent.last_activeweapon = wepent.activeweapon;
1417
1418                         entity e = wepent.activeweapon;
1419                         if(e.netname != "")
1420                                 localcmd(strcat("\ncl_hook_activeweapon ", e.netname), "\n");
1421                         else if(slot == 0)
1422                                 localcmd("\ncl_hook_activeweapon none\n");
1423                 }
1424         }
1425 }
1426
1427 bool ov_enabled;
1428 float oldr_nearclip;
1429 float oldr_farclip_base;
1430 float oldr_farclip_world;
1431 float oldr_novis;
1432 float oldr_useportalculling;
1433 float oldr_useinfinitefarclip;
1434 vector ov_org = '0 0 0';
1435 vector ov_mid = '0 0 0';
1436 vector ov_worldmin = '0 0 0';
1437 vector ov_worldmax = '0 0 0';
1438
1439 void View_Ortho()
1440 {
1441         ov_org = '0 0 0';
1442         ov_mid = '0 0 0';
1443         ov_worldmin = '0 0 0';
1444         ov_worldmax = '0 0 0';
1445         if(autocvar_cl_orthoview)
1446         {
1447                 ov_worldmin = mi_picmin;
1448                 ov_worldmax = mi_picmax;
1449
1450                 float ov_width = (ov_worldmax.x - ov_worldmin.x);
1451                 float ov_height = (ov_worldmax.y - ov_worldmin.y);
1452                 float ov_distance = (max(vid_width, vid_height) * max(ov_width, ov_height));
1453
1454                 ov_mid = ((ov_worldmax + ov_worldmin) * 0.5);
1455                 ov_org = vec3(ov_mid.x, ov_mid.y, (ov_mid.z + ov_distance));
1456
1457                 float ov_nearest = vlen(ov_org - vec3(
1458                         bound(ov_worldmin.x, ov_org.x, ov_worldmax.x),
1459                         bound(ov_worldmin.y, ov_org.y, ov_worldmax.y),
1460                         bound(ov_worldmin.z, ov_org.z, ov_worldmax.z)
1461                 ));
1462
1463                 float ov_furthest = 0;
1464                 float dist = 0;
1465
1466                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmin.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1467                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmin.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1468                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmax.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1469                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmin.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1470                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmax.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1471                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmax.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1472                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmin.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1473                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmax.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1474
1475                 if(!ov_enabled)
1476                 {
1477                         oldr_nearclip = cvar("r_nearclip");
1478                         oldr_farclip_base = cvar("r_farclip_base");
1479                         oldr_farclip_world = cvar("r_farclip_world");
1480                         oldr_novis = cvar("r_novis");
1481                         oldr_useportalculling = cvar("r_useportalculling");
1482                         oldr_useinfinitefarclip = cvar("r_useinfinitefarclip");
1483                 }
1484
1485                 cvar_settemp("r_nearclip", ftos(ov_nearest));
1486                 cvar_settemp("r_farclip_base", ftos(ov_furthest));
1487                 cvar_settemp("r_farclip_world", "0");
1488                 cvar_settemp("r_novis", "1");
1489                 cvar_settemp("r_useportalculling", "0");
1490                 cvar_settemp("r_useinfinitefarclip", "0");
1491
1492                 setproperty(VF_ORIGIN, ov_org);
1493                 setproperty(VF_ANGLES, '90 0 0');
1494
1495                 ov_enabled = true;
1496
1497                 #if 0
1498                 LOG_INFOF("OrthoView: org = %s, angles = %s, distance = %f, nearest = %f, furthest = %f",
1499                         vtos(ov_org),
1500                         vtos(getpropertyvec(VF_ANGLES)),
1501                         ov_distance,
1502                         ov_nearest,
1503                         ov_furthest);
1504                 #endif
1505         }
1506         else
1507         {
1508                 if(ov_enabled)
1509                 {
1510                         cvar_set("r_nearclip", ftos(oldr_nearclip));
1511                         cvar_set("r_farclip_base", ftos(oldr_farclip_base));
1512                         cvar_set("r_farclip_world", ftos(oldr_farclip_world));
1513                         cvar_set("r_novis", ftos(oldr_novis));
1514                         cvar_set("r_useportalculling", ftos(oldr_useportalculling));
1515                         cvar_set("r_useinfinitefarclip", ftos(oldr_useinfinitefarclip));
1516                 }
1517                 ov_enabled = false;
1518         }
1519 }
1520
1521 void View_UpdateFov()
1522 {
1523         vector fov;
1524         if(autocvar_cl_orthoview)
1525                 fov = GetOrthoviewFOV(ov_worldmin, ov_worldmax, ov_mid, ov_org);
1526         else if(csqcplayer.viewloc)
1527                 fov = GetViewLocationFOV(110); // enforce 110 fov, so things don't look odd
1528         else
1529                 fov = GetCurrentFov(autocvar_fov);
1530
1531         setproperty(VF_FOV, fov);
1532 }
1533
1534 void CSQC_UpdateView(entity this, float w, float h)
1535 {
1536         TC(int, w); TC(int, h);
1537
1538         execute_next_frame();
1539
1540         ++framecount;
1541
1542         stats_get();
1543         hud = STAT(HUD);
1544
1545         ReplicateVars(REPLICATEVARS_CHECK);
1546
1547         HUD_Scale_Disable();
1548
1549         if(autocvar__hud_showbinds_reload) // menu can set this one
1550         {
1551                 db_close(binddb);
1552                 binddb = db_create();
1553                 cvar_set("_hud_showbinds_reload", "0");
1554         }
1555
1556         if(checkextension("DP_CSQC_MINFPS_QUALITY"))
1557                 view_quality = getproperty(VF_MINFPS_QUALITY);
1558         else
1559                 view_quality = 1;
1560
1561         button_attack2 = PHYS_INPUT_BUTTON_ATCK2(this);
1562         button_zoom = PHYS_INPUT_BUTTON_ZOOM(this);
1563
1564         vector vf_size = getpropertyvec(VF_SIZE);
1565         vector vf_min = getpropertyvec(VF_MIN);
1566         vid_width = vf_size.x;
1567         vid_height = vf_size.y;
1568
1569         ticrate = STAT(MOVEVARS_TICRATE) * STAT(MOVEVARS_TIMESCALE);
1570
1571         if (autocvar_chase_active)
1572         {
1573                 // in first person view if r_drawviewmodel is off weapon isn't visible
1574                 // and server doesn't throw any casing
1575                 // switching to 3rd person view r_drawviewmodel is set to -1 to let know the server casings
1576                 // can be thrown for self since own weapon model is visible
1577                 if (autocvar_r_drawviewmodel == 0 && STAT(HEALTH) > 0)
1578                         cvar_set("r_drawviewmodel", "-1");
1579         }
1580         else
1581         {
1582                 if (autocvar_r_drawviewmodel < 0)
1583                         cvar_set("r_drawviewmodel", "0");
1584         }
1585
1586         WaypointSprite_Load();
1587
1588         CSQCPlayer_SetCamera();
1589
1590         if(player_localentnum <= maxclients) // is it a client?
1591                 current_player = player_localentnum - 1;
1592         else // then player_localentnum is the vehicle I'm driving
1593                 current_player = player_localnum;
1594         myteam = entcs_GetTeam(current_player);
1595
1596         entity local_player = ((csqcplayer) ? csqcplayer : CSQCModel_server2csqc(player_localentnum - 1));
1597         if(!local_player)
1598                 local_player = this; // fall back!
1599
1600         View_EventChase(local_player);
1601
1602         // do lockview after event chase camera so that it still applies whenever necessary.
1603         View_Lock();
1604
1605         WarpZone_FixView();
1606         //WarpZone_FixPMove();
1607
1608         View_Ortho();
1609
1610         // run viewmodel_draw before updating view_angles to the angles calculated by WarpZone_FixView
1611         // viewmodel_draw needs to use the view_angles set by the engine on every CSQC_UpdateView call
1612         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1613                 viewmodel_draw(viewmodels[slot]);
1614
1615         // Render the Scene
1616         view_origin = getpropertyvec(VF_ORIGIN);
1617         view_angles = getpropertyvec(VF_ANGLES);
1618         MAKE_VECTORS(view_angles, view_forward, view_right, view_up);
1619
1620 #ifdef BLURTEST
1621         View_BlurTest();
1622 #endif
1623
1624         TargetMusic_Advance();
1625         Fog_Force();
1626         fpscounter_update();
1627
1628         if(drawtime == 0)
1629                 drawframetime = 0.01666667; // when we don't know fps yet, we assume 60fps
1630         else
1631                 drawframetime = bound(0.000001, time - drawtime, 1);
1632         drawtime = time;
1633
1634         // watch for gametype changes here...
1635         // in ParseStuffCMD the cmd isn't executed yet :/
1636         // might even be better to add the gametype to TE_CSQC_INIT...?
1637         if(!postinit)
1638                 PostInit();
1639
1640         if(intermission && !intermission_time)
1641                 intermission_time = time;
1642
1643         if(STAT(GAME_STOPPED) && !game_stopped_time)
1644                 game_stopped_time = time;
1645         else if(game_stopped_time && !STAT(GAME_STOPPED))
1646                 game_stopped_time = 0;
1647
1648         if(intermission && !isdemo() && !(calledhooks & HOOK_END))
1649         {
1650                 if(calledhooks & HOOK_START)
1651                 {
1652                         int gamecount = cvar("cl_matchcount");
1653                         localcmd("\ncl_hook_gameend\n");
1654                         // NOTE: using localcmd here to ensure it's executed AFTER cl_hook_gameend
1655                         // earlier versions of the game abuse the hook to set this cvar
1656                         localcmd(strcat("cl_matchcount ", itos(gamecount + 1), "\n"));
1657                         //cvar_set("cl_matchcount", itos(gamecount + 1));
1658                         calledhooks |= HOOK_END;
1659                 }
1660         }
1661
1662         Welcome_Message_Show_Try();
1663
1664         Announcer();
1665
1666         View_CheckButtonStatus();
1667
1668         ColorTranslateMode = autocvar_cl_stripcolorcodes;
1669
1670         // ALWAYS Clear Current Scene First
1671         clearscene();
1672
1673         setproperty(VF_ORIGIN, view_origin);
1674         setproperty(VF_ANGLES, view_angles);
1675
1676         // FIXME engine bug? VF_SIZE and VF_MIN are not restored to sensible values by this
1677         setproperty(VF_SIZE, vf_size);
1678         setproperty(VF_MIN, vf_min);
1679
1680         // Assign Standard Viewflags
1681         // Draw the World (and sky)
1682         setproperty(VF_DRAWWORLD, 1);
1683
1684         vid_conwidth = autocvar_vid_conwidth;
1685         vid_conheight = autocvar_vid_conheight;
1686         vid_pixelheight = autocvar_vid_pixelheight;
1687
1688         View_UpdateFov();
1689
1690         View_DemoCamera();
1691
1692         setproperty(VF_DRAWCROSSHAIR, 0); // hide engine crosshair
1693         setproperty(VF_DRAWENGINESBAR, 0); // hide engine status bar
1694
1695         IL_EACH(g_drawables, it.draw, it.draw(it));
1696
1697         addentities(MASK_NORMAL | MASK_ENGINE | MASK_ENGINEVIEWMODELS); // TODO: .health is used in cl_deathfade (a feature we have turned off currently)
1698         renderscene();
1699
1700         // Now the the scene has been rendered, begin with the 2D drawing functions
1701
1702         View_NightVision();
1703         DrawReticle(local_player);
1704         HUD_Contents();
1705         HUD_Damage();
1706         View_PostProcessing();
1707
1708         // draw 2D entities
1709         IL_EACH(g_drawables_2d, it.draw2d, it.draw2d(it));
1710         Draw_ShowNames_All();
1711 #if ENABLE_DEBUGDRAW
1712         Debug_Draw();
1713 #endif
1714
1715         if (autocvar__scoreboard_team_selection)
1716         {
1717                 Scoreboard_UI_Enable(1);
1718                 cvar_set("_scoreboard_team_selection", "0");
1719         }
1720         scoreboard_active = Scoreboard_WouldDraw();
1721
1722         HUD_Draw(this); // this parameter for deep vehicle function
1723
1724         if(NextFrameCommand)
1725         {
1726                 localcmd("\n", NextFrameCommand, "\n");
1727                 NextFrameCommand = string_null;
1728         }
1729
1730         HUD_Mouse(local_player);
1731
1732         cl_notice_run();
1733         unpause_update();
1734         Net_Flush();
1735
1736         // let's reset the view back to normal for the end
1737         setproperty(VF_MIN, '0 0 0');
1738         setproperty(VF_SIZE, '1 0 0' * w + '0 1 0' * h);
1739
1740         IL_ENDFRAME();
1741 }
1742
1743
1744 // following vectors must be global to allow seamless switching between camera modes
1745 vector camera_offset, current_camera_offset, mouse_angles, current_angles, current_origin, current_position;
1746 void CSQC_Demo_Camera()
1747 {
1748         float speed, attenuation, dimensions;
1749         vector tmp, delta;
1750
1751         if( autocvar_camera_reset || !camera_mode )
1752         {
1753                 camera_offset = '0 0 0';
1754                 current_angles = '0 0 0';
1755                 camera_direction = '0 0 0';
1756                 camera_offset.z += 30;
1757                 camera_offset.x += 30 * -cos(current_angles.y * DEG2RAD);
1758                 camera_offset.y += 30 * -sin(current_angles.y * DEG2RAD);
1759                 current_origin = view_origin;
1760                 current_camera_offset  = camera_offset;
1761                 cvar_set("camera_reset", "0");
1762                 camera_mode = CAMERA_CHASE;
1763         }
1764
1765         // Camera angles
1766         if( camera_roll )
1767                 mouse_angles.z += camera_roll * autocvar_camera_speed_roll;
1768
1769         if(autocvar_camera_look_player)
1770         {
1771                 vector dir;
1772                 float n;
1773
1774                 dir = normalize(view_origin - current_position);
1775                 n = mouse_angles.z;
1776                 mouse_angles = vectoangles(dir);
1777                 mouse_angles.x = mouse_angles.x * -1;
1778                 mouse_angles.z = n;
1779         }
1780         else
1781         {
1782                 tmp = getmousepos() * 0.1;
1783                 if(vdist(tmp, >, autocvar_camera_mouse_threshold))
1784                 {
1785                         mouse_angles.x += tmp.y * cos(mouse_angles.z * DEG2RAD) + (tmp.x * sin(mouse_angles.z * DEG2RAD));
1786                         mouse_angles.y -= tmp.x * cos(mouse_angles.z * DEG2RAD) + (tmp.y * -sin(mouse_angles.z * DEG2RAD));
1787                 }
1788         }
1789
1790         while (mouse_angles.x < -180) mouse_angles.x = mouse_angles.x + 360;
1791         while (mouse_angles.x > 180) mouse_angles.x = mouse_angles.x - 360;
1792         while (mouse_angles.y < -180) mouse_angles.y = mouse_angles.y + 360;
1793         while (mouse_angles.y > 180) mouse_angles.y = mouse_angles.y - 360;
1794
1795         // Fix difference when angles don't have the same sign
1796         delta = '0 0 0';
1797         if(mouse_angles.y < -60 && current_angles.y > 60)
1798                 delta = '0 360 0';
1799         if(mouse_angles.y > 60 && current_angles.y < -60)
1800                 delta = '0 -360 0';
1801
1802         if(autocvar_camera_look_player)
1803                 attenuation = autocvar_camera_look_attenuation;
1804         else
1805                 attenuation = autocvar_camera_speed_attenuation;
1806
1807         attenuation = 1 / max(1, attenuation);
1808         current_angles += (mouse_angles - current_angles + delta) * attenuation;
1809
1810         while (current_angles.x < -180) current_angles.x = current_angles.x + 360;
1811         while (current_angles.x > 180) current_angles.x = current_angles.x - 360;
1812         while (current_angles.y < -180) current_angles.y = current_angles.y + 360;
1813         while (current_angles.y > 180) current_angles.y = current_angles.y - 360;
1814
1815         // Camera position
1816         tmp = '0 0 0';
1817         dimensions = 0;
1818
1819         if( camera_direction.x )
1820         {
1821                 tmp.x = camera_direction.x * cos(current_angles.y * DEG2RAD);
1822                 tmp.y = camera_direction.x * sin(current_angles.y * DEG2RAD);
1823                 if( autocvar_camera_forward_follows && !autocvar_camera_look_player )
1824                         tmp.z = camera_direction.x * -sin(current_angles.x * DEG2RAD);
1825                 ++dimensions;
1826         }
1827
1828         if( camera_direction.y )
1829         {
1830                 tmp.x += camera_direction.y * -sin(current_angles.y * DEG2RAD);
1831                 tmp.y += camera_direction.y * cos(current_angles.y * DEG2RAD) * cos(current_angles.z * DEG2RAD);
1832                 tmp.z += camera_direction.y * sin(current_angles.z * DEG2RAD);
1833                 ++dimensions;
1834         }
1835
1836         if( camera_direction.z )
1837         {
1838                 tmp.z += camera_direction.z * cos(current_angles.z * DEG2RAD);
1839                 ++dimensions;
1840         }
1841
1842         if(autocvar_camera_free)
1843                 speed = autocvar_camera_speed_free;
1844         else
1845                 speed = autocvar_camera_speed_chase;
1846
1847         if(dimensions)
1848         {
1849                 speed = speed * sqrt(1 / dimensions);
1850                 camera_offset += tmp * speed;
1851         }
1852
1853         current_camera_offset += (camera_offset - current_camera_offset) * attenuation;
1854
1855         // Camera modes
1856         if( autocvar_camera_free )
1857         {
1858                 if ( camera_mode == CAMERA_CHASE )
1859                 {
1860                         current_camera_offset = current_origin + current_camera_offset;
1861                         camera_offset = current_origin + camera_offset;
1862                 }
1863
1864                 camera_mode = CAMERA_FREE;
1865                 current_position = current_camera_offset;
1866         }
1867         else
1868         {
1869                 if ( camera_mode == CAMERA_FREE )
1870                 {
1871                         current_origin = view_origin;
1872                         camera_offset = camera_offset - current_origin;
1873                         current_camera_offset = current_camera_offset - current_origin;
1874                 }
1875
1876                 camera_mode = CAMERA_CHASE;
1877
1878                 if(autocvar_camera_chase_smoothly)
1879                         current_origin += (view_origin - current_origin) * attenuation;
1880                 else
1881                         current_origin = view_origin;
1882
1883                 current_position = current_origin + current_camera_offset;
1884         }
1885
1886         setproperty(VF_ANGLES, current_angles);
1887         setproperty(VF_ORIGIN, current_position);
1888 }