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