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