]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/main.qc
Merge branch 'k9er/strafehud-changes' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / main.qc
1 #include "main.qh"
2
3 #include <common/command/generic.qh>
4 #include <common/constants.qh>
5 #include <common/deathtypes/all.qh>
6 #include <common/debug.qh>
7 #include <common/mapinfo.qh>
8 #include <common/mapobjects/_mod.qh>
9 #include <common/monsters/sv_monsters.qh>
10 #include <common/util.qh>
11 #include <common/vehicles/all.qh>
12 #include <common/weapons/_all.qh>
13 #include <lib/csqcmodel/sv_model.qh>
14 #include <lib/warpzone/common.qh>
15 #include <lib/warpzone/server.qh>
16 #include <server/anticheat.qh>
17 #include <server/bot/api.qh>
18 #include <server/command/common.qh>
19 #include <server/compat/quake3.qh>
20 #include <server/damage.qh>
21 #include <server/gamelog.qh>
22 #include <server/hook.qh>
23 #include <server/ipban.qh>
24 #include <server/mutators/_mod.qh>
25 #include <server/spawnpoints.qh>
26 #include <server/weapons/common.qh>
27 #include <server/weapons/csqcprojectile.qh>
28 #include <server/world.qh>
29
30 void dropclient_do(entity this)
31 {
32         if (this.owner)
33                 dropclient(this.owner);
34         delete(this);
35 }
36
37 /**
38  * Schedules dropclient for a player and returns true;
39  * if dropclient is already scheduled (for that player) it does nothing and returns false.
40  *
41  * NOTE: this function exists only to allow sending a message to the kicked player with
42  * Send_Notification, which doesn't work if called together with dropclient
43  */
44 bool dropclient_schedule(entity this)
45 {
46         bool scheduled = false;
47         FOREACH_ENTITY_CLASS("dropclient_handler", true,
48         {
49                 if(it.owner == this)
50                 {
51                         scheduled = true;
52                         break; // can't use return here, compiler shows a warning
53                 }
54         });
55         if (scheduled)
56                 return false;
57
58         entity e = new_pure(dropclient_handler);
59         setthink(e, dropclient_do);
60         e.owner = this;
61         e.nextthink = time + 0.1;
62
63         // ignore this player for team balancing and queuing
64         this.team = -1;
65         this.wants_join = 0;
66         this.classname = STR_OBSERVER;
67         return true;
68 }
69
70 void CreatureFrame_hotliquids(entity this)
71 {
72         if (this.contents_damagetime >= time)
73         {
74                 return;
75         }
76
77         this.contents_damagetime = time + autocvar_g_balance_contents_damagerate;
78
79         if (this.flags & FL_PROJECTILE)
80         {
81                 if (this.watertype == CONTENT_LAVA)
82                         Damage (this, NULL, NULL, autocvar_g_balance_contents_projectiledamage * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
83                 else if (this.watertype == CONTENT_SLIME)
84                         Damage (this, NULL, NULL, autocvar_g_balance_contents_projectiledamage * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
85         }
86         else
87         {
88                 if (STAT(FROZEN, this))
89                 {
90                         if (this.watertype == CONTENT_LAVA)
91                                 Damage(this, NULL, NULL, 10000, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
92                         else if (this.watertype == CONTENT_SLIME)
93                                 Damage(this, NULL, NULL, 10000, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
94                 }
95                 else if (this.watertype == CONTENT_LAVA)
96                 {
97                         if (this.watersound_finished < time)
98                         {
99                                 this.watersound_finished = time + 0.5;
100                                 sound (this, CH_PLAYER_SINGLE, SND_LAVA, VOL_BASE, ATTEN_NORM);
101                         }
102                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_lava * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
103                         if(autocvar_g_balance_contents_playerdamage_lava_burn)
104                                 Fire_AddDamage(this, NULL, autocvar_g_balance_contents_playerdamage_lava_burn * this.waterlevel, autocvar_g_balance_contents_playerdamage_lava_burn_time * this.waterlevel, DEATH_LAVA.m_id);
105                 }
106                 else if (this.watertype == CONTENT_SLIME)
107                 {
108                         if (this.watersound_finished < time)
109                         {
110                                 this.watersound_finished = time + 0.5;
111                                 sound (this, CH_PLAYER_SINGLE, SND_SLIME, VOL_BASE, ATTEN_NORM);
112                         }
113                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_slime * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
114                 }
115         }
116 }
117
118 void CreatureFrame_Liquids(entity this)
119 {
120         if (this.watertype <= CONTENT_WATER && this.waterlevel > 0) // workaround a retarded bug made by id software :P (yes, it's that old of a bug)
121         {
122                 if (!(this.flags & FL_INWATER))
123                 {
124                         this.flags |= FL_INWATER;
125                         this.contents_damagetime = 0;
126                 }
127
128                 CreatureFrame_hotliquids(this);
129         }
130         else
131         {
132                 if (this.flags & FL_INWATER)
133                 {
134                         // play leave water sound
135                         this.flags &= ~FL_INWATER;
136                         this.contents_damagetime = 0;
137                 }
138         }
139 }
140
141 void CreatureFrame_FallDamage(entity this)
142 {
143         if(IS_VEHICLE(this) || (this.flags & FL_PROJECTILE))
144                 return; // vehicles and projectiles don't receive fall damage
145         if(!(this.velocity || this.oldvelocity))
146                 return; // if the entity hasn't moved and isn't moving, then don't do anything
147
148         // check for falling damage
149         bool have_hook = false;
150         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
151         {
152                 .entity weaponentity = weaponentities[slot];
153                 if(this.(weaponentity).hook && this.(weaponentity).hook.state)
154                 {
155                         have_hook = true;
156                         break;
157                 }
158         }
159         if(!have_hook)
160         {
161                 float dm; // dm is the velocity DECREASE. Velocity INCREASE should never cause a sound or any damage.
162                 if(autocvar_g_balance_falldamage_onlyvertical)
163                         dm = fabs(this.oldvelocity.z) - vlen(this.velocity);
164                 else
165                         dm = vlen(this.oldvelocity) - vlen(this.velocity);
166                 if (IS_DEAD(this))
167                         dm = (dm - autocvar_g_balance_falldamage_deadminspeed) * autocvar_g_balance_falldamage_factor;
168                 else
169                         dm = min((dm - autocvar_g_balance_falldamage_minspeed) * autocvar_g_balance_falldamage_factor, autocvar_g_balance_falldamage_maxdamage);
170                 if (dm > 0)
171                 {
172                         tracebox(this.origin, this.mins, this.maxs, this.origin - '0 0 1', MOVE_NOMONSTERS, this);
173                         if (!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NODAMAGE))
174                                 Damage (this, NULL, NULL, dm, DEATH_FALL.m_id, DMG_NOWEP, this.origin, '0 0 0');
175                 }
176         }
177
178         if(autocvar_g_maxspeed > 0 && vdist(this.velocity, >, autocvar_g_maxspeed))
179                 Damage (this, NULL, NULL, 100000, DEATH_SHOOTING_STAR.m_id, DMG_NOWEP, this.origin, '0 0 0');
180 }
181
182 void CreatureFrame_All()
183 {
184         if(game_stopped || time < game_starttime)
185                 return;
186
187         IL_EACH(g_damagedbycontents, it.damagedbycontents,
188         {
189                 if (it.move_movetype == MOVETYPE_NOCLIP) continue;
190                 CreatureFrame_Liquids(it);
191                 CreatureFrame_FallDamage(it);
192                 it.oldvelocity = it.velocity;
193         });
194 }
195
196 // called shortly after map change in dedicated
197 void Pause_TryPause_Dedicated(entity this)
198 {
199         if (player_count == 0 && !intermission_running && !autocvar__endmatch)
200                 setpause(1);
201 }
202
203 // called every normal frame in singleplayer/listen
204 void Pause_TryPause()
205 {
206         int n = 0, p = 0;
207         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
208                 if (PHYS_INPUT_BUTTON_CHAT(it)) ++p;
209                 ++n;
210         });
211         if (!n) return;
212         if (n == p)
213                 setpause(1);
214         else
215                 setpause(0);
216 }
217
218 // called every paused frame by DP
219 void SV_PausedTic(float elapsedtime)
220 {
221         if (autocvar__endmatch) // `endmatch` while paused
222                 setpause(0); // proceed to intermission
223         else if (!server_is_dedicated)
224         {
225                 if (autocvar_sv_autopause)
226                         Pause_TryPause();
227                 else
228                         setpause(0);
229         }
230 }
231
232 void dedicated_print(string input)
233 {
234         if (server_is_dedicated) print(input);
235 }
236
237 void make_safe_for_remove(entity e)
238 {
239         if (e.initialize_entity)
240         {
241                 entity ent, prev = NULL;
242                 for (ent = initialize_entity_first; ent; )
243                 {
244                         if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
245                         {
246                                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
247                                 // skip it in linked list
248                                 if (prev)
249                                 {
250                                         prev.initialize_entity_next = ent.initialize_entity_next;
251                                         ent = prev.initialize_entity_next;
252                                 }
253                                 else
254                                 {
255                                         initialize_entity_first = ent.initialize_entity_next;
256                                         ent = initialize_entity_first;
257                                 }
258                         }
259                         else
260                         {
261                                 prev = ent;
262                                 ent = ent.initialize_entity_next;
263                         }
264                 }
265         }
266 }
267
268 void remove_except_protected(entity e)
269 {
270         if(e.remove_except_protected_forbidden)
271                 error("not allowed to remove this at this point");
272         builtin_remove(e);
273 }
274
275 void remove_unsafely(entity e)
276 {
277         if(e.classname == "spike")
278                 error("Removing spikes is forbidden (crylink bug), please report");
279         builtin_remove(e);
280 }
281
282 void remove_safely(entity e)
283 {
284         make_safe_for_remove(e);
285         builtin_remove(e);
286 }
287
288 /*
289 =============
290 StartFrame
291
292 Called before each frame by the server
293 =============
294 */
295
296 bool game_delay_last;
297
298 void systems_update();
299 void sys_phys_update(entity this, float dt);
300 void StartFrame()
301 {
302         FOREACH_CLIENT(IS_FAKE_CLIENT(it),
303         {
304                 // DP calls these for real clients only
305                 sys_phys_update(it, frametime); // called by SV_PlayerPhysics for players
306                 PlayerPreThink(it);
307         });
308
309         execute_next_frame();
310
311         delete_fn = remove_unsafely; // not during spawning!
312         serverprevtime = servertime;
313         servertime = time;
314         serverframetime = frametime;
315
316 #ifdef PROFILING
317         if(time > client_cefc_accumulatortime + 1)
318         {
319                 float t = client_cefc_accumulator / (time - client_cefc_accumulatortime);
320                 int c_seeing = 0;
321                 int c_seen = 0;
322                 FOREACH_CLIENT(true, {
323                         if(IS_REAL_CLIENT(it))
324                                 ++c_seeing;
325                         if(IS_PLAYER(it))
326                                 ++c_seen;
327                 });
328                 LOG_INFO(
329                         "CEFC time: ", ftos(t * 1000), "ms; ",
330                         "CEFC calls per second: ", ftos(c_seeing * (c_seen - 1) / t), "; ",
331                         "CEFC 100% load at: ", ftos(solve_quadratic(t, -t, -1) * '0 1 0')
332                 );
333                 client_cefc_accumulatortime = time;
334                 client_cefc_accumulator = 0;
335         }
336 #endif
337
338         IL_EACH(g_projectiles, it.csqcprojectile_clientanimate, CSQCProjectile_Check(it));
339
340         if (RedirectionThink()) return;
341
342         UncustomizeEntitiesRun();
343         InitializeEntitiesRun();
344
345         WarpZone_StartFrame();
346
347         sys_frametime = autocvar_sys_ticrate * autocvar_slowmo;
348         if (sys_frametime <= 0) sys_frametime = 1.0 / 60.0; // somewhat safe fallback
349
350         if (timeout_status == TIMEOUT_LEADTIME) // just before the timeout (when timeout_status will be TIMEOUT_ACTIVE)
351                 orig_slowmo = autocvar_slowmo; // slowmo will be restored after the timeout
352
353         // detect when the pre-game countdown (if any) has ended and the game has started
354         bool game_delay = (time < game_starttime);
355         if (autocvar_sv_eventlog && game_delay_last && !game_delay)
356                 GameLogEcho(":startdelay_ended");
357         game_delay_last = game_delay;
358
359         CreatureFrame_All();
360         CheckRules_World();
361
362         // after CheckRules_World() as it may set intermission_running, and after RedirectionThink() in case listen server is closing
363         if (autocvar_sv_autopause && !server_is_dedicated && !intermission_running)
364                 Pause_TryPause();
365
366         if (warmup_stage && !game_stopped && warmup_limit > 0 && time - game_starttime >= warmup_limit) {
367                 ReadyRestart(true);
368                 return;
369         }
370
371         bot_serverframe();
372         anticheat_startframe();
373         MUTATOR_CALLHOOK(SV_StartFrame);
374
375         GlobalStats_updateglobal();
376         FOREACH_CLIENT(true,
377         {
378                 GlobalStats_update(it);
379                 if (IS_FAKE_CLIENT(it))
380                         PlayerPostThink(it); // DP calls this for real clients only
381                 PlayerFrame(it);
382         });
383 }
384
385 .vector originjitter;
386 .vector anglesjitter;
387 .float anglejitter;
388 .string gametypefilter;
389 .string cvarfilter;
390
391 void SV_OnEntityPreSpawnFunction(entity this)
392 {
393         if (this)
394         if (this.gametypefilter != "")
395         if (!isGametypeInFilter(MapInfo_LoadedGametype, teamplay, have_team_spawns, this.gametypefilter))
396         {
397                 delete(this);
398                 return;
399         }
400         if (this.cvarfilter != "" && !expr_evaluate(this.cvarfilter)) {
401                 delete(this);
402                 return;
403         }
404
405         if (q3compat && DoesQ3ARemoveThisEntity(this)) {
406                 delete(this);
407                 return;
408         }
409
410         set_movetype(this, this.movetype);
411
412         if (this.monster_attack) {
413                 IL_PUSH(g_monster_targets, this);
414         }
415
416         // support special -1 and -2 angle from radiant
417         if (this.angles == '0 -1 0') {
418                 this.angles = '-90 0 0';
419         } else if (this.angles == '0 -2 0') {
420                 this.angles = '+90 0 0';
421         }
422
423         #define X(out, in) MACRO_BEGIN \
424                 if (in != 0) { out = out + (random() * 2 - 1) * in; } \
425         MACRO_END
426         X(this.origin.x, this.originjitter.x); X(this.origin.y, this.originjitter.y); X(this.origin.z, this.originjitter.z);
427         X(this.angles.x, this.anglesjitter.x); X(this.angles.y, this.anglesjitter.y); X(this.angles.z, this.anglesjitter.z);
428         X(this.angles.y, this.anglejitter);
429         #undef X
430
431         if (MUTATOR_CALLHOOK(OnEntityPreSpawn, this)) {
432                 delete(this);
433                 return;
434         }
435 }
436
437 /** Retrieves the value of a map entity field from fullspawndata.
438  * This bypasses field value changes made by the engine,
439  * eg string-to-float and escape sequence substitution.
440  *
441  * Avoids the need to declare fields just to read them once :)
442  *
443  * Returns the last instance of the field to match DarkPlaces behaviour.
444  *
445  * Path support: converts \ to / and checks the file exists, if vfspath is true.
446  * Returns string_null if the entity does not have the field, or the file is not in the VFS.
447  *
448  * FIXME: entities with //comments are not supported.
449  */
450 string GetField_fullspawndata(entity e, string fieldname, bool vfspath)
451 {
452         string v = string_null;
453
454         if (!e.fullspawndata) // Engine lacks support, warning spam in CheckEngineExtensions()
455                 return v;
456
457         if (strstrofs(e.fullspawndata, "//", 0) >= 0)
458         {
459                 // tokenize and tokenize_console return early if "//" is reached,
460                 // which can leave an odd number of tokens and break key:value pairing.
461                 LOG_WARNF("^1EDICT %s fullspawndata contains unsupported //comment^7%s", ftos(num_for_edict(e)), e.fullspawndata);
462                 return v;
463         }
464
465         //print(sprintf("%s(EDICT %s, FIELD %s)\n", __FUNC__, ftos(num_for_edict(e)), fieldname));
466         //print(strcat("FULLSPAWNDATA:", e.fullspawndata, "\n"));
467
468         // tokenize treats \ as an escape, but tokenize_console returns the required literal
469         for (int t = tokenize_console(e.fullspawndata) - 3; t > 0; t -= 2)
470         {
471                 //print(sprintf("\tTOKEN %s:%s\t%s:%s\n", ftos(t), ftos(t + 1), argv(t), argv(t + 1)));
472                 if (argv(t) == fieldname)
473                 {
474                         v = argv(t + 1);
475                         break;
476                 }
477         }
478
479         //print(strcat("RESULT: ", v, "\n\n"));
480
481         if (v && vfspath)
482         {
483                 v = strreplace("\\", "/", v);
484                 if (whichpack(v) == "")
485                         return string_null;
486         }
487
488         return v;
489 }
490
491 /*
492 =============
493 FindFileInMapPack
494
495 Returns the first matching VFS file path that exists in the current map's pack.
496 Returns string_null if no files match or the map isn't packaged.
497 =============
498 */
499 string FindFileInMapPack(string pattern)
500 {
501         if (!checkextension("DP_QC_FS_SEARCH_PACKFILE"))
502                 return string_null;
503
504         string base_pack = whichpack(strcat("maps/", mapname, ".bsp"));
505         if (base_pack == "" || !base_pack) // this map isn't packaged or there was an error
506                 return string_null;
507
508         int glob = search_packfile_begin(pattern, true, true, base_pack);
509         if (glob < 0)
510                 return string_null;
511
512         string file = search_getfilename(glob, 0);
513         search_end(glob);
514         return file;
515 }
516
517 void WarpZone_PostInitialize_Callback()
518 {
519         // create waypoint links for warpzones
520         entity tracetest_ent = spawn();
521         setsize(tracetest_ent, PL_MIN_CONST, PL_MAX_CONST);
522         tracetest_ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
523         //for(entity e = warpzone_first; e; e = e.warpzone_next)
524         for(entity e = NULL; (e = find(e, classname, "trigger_warpzone")); )
525                 waypoint_spawnforteleporter_wz(e, tracetest_ent);
526         delete(tracetest_ent);
527 }
528
529 /** engine callback */
530 void URI_Get_Callback(float id, float status, string data)
531 {
532         if(url_URI_Get_Callback(id, status, data))
533         {
534                 // handled
535         }
536         else if (id == URI_GET_DISCARD)
537         {
538                 // discard
539         }
540         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
541         {
542                 // sv_cmd curl
543                 Curl_URI_Get_Callback(id, status, data);
544         }
545         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
546         {
547                 // online ban list
548                 OnlineBanList_URI_Get_Callback(id, status, data);
549         }
550         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
551         {
552                 // handled by a mutator
553         }
554         else
555         {
556                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".");
557         }
558 }
559
560 /*
561 ==================
562 main
563
564 unused but required by the engine
565 ==================
566 */
567 void main ()
568 {
569
570 }