]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/monsters/sv_monsters.qc
Merge branch 'master' into Mario/monsters
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / monsters / sv_monsters.qc
1 #include "sv_monsters.qh"
2
3 #include <lib/warpzone/common.qh>
4 #include "../constants.qh"
5 #include "../teams.qh"
6 #include "../util.qh"
7 #include "all.qh"
8 #include "../physics/movelib.qh"
9 #include "../weapons/_mod.qh"
10 #include <server/autocvars.qh>
11 #include <server/defs.qh>
12 #include "../deathtypes/all.qh"
13 #include <server/mutators/_mod.qh>
14 #include <server/steerlib.qh>
15 #include "../turrets/sv_turrets.qh"
16 #include "../turrets/util.qh"
17 #include "../vehicles/all.qh"
18 #include <server/campaign.qh>
19 #include <server/command/_mod.qh>
20 #include "../mapobjects/triggers.qh"
21 #include <lib/csqcmodel/sv_model.qh>
22 #include <server/round_handler.qh>
23 #include <server/weapons/_mod.qh>
24
25 void monsters_setstatus(entity this)
26 {
27         STAT(MONSTERS_TOTAL, this) = monsters_total;
28         STAT(MONSTERS_KILLED, this) = monsters_killed;
29 }
30
31 void monster_dropitem(entity this, entity attacker)
32 {
33         if(!this.candrop || !this.monster_loot)
34                 return;
35
36         vector org = CENTER_OR_VIEWOFS(this);
37         entity e = spawn();
38         Item_SetLoot(e, true);
39         e.spawnfunc_checked = true;
40
41         e.monster_loot = this.monster_loot;
42
43         MUTATOR_CALLHOOK(MonsterDropItem, this, e, attacker);
44         e = M_ARGV(1, entity);
45
46         if(e && e.monster_loot)
47         {
48                 e.noalign = true;
49                 StartItem(e, e.monster_loot);
50                 e.gravity = 1;
51                 setorigin(e, org);
52                 e.velocity = randomvec() * 175 + '0 0 325';
53                 e.item_spawnshieldtime = time + 0.7;
54                 SUB_SetFade(e, time + autocvar_g_monsters_drop_time, 1);
55         }
56 }
57
58 bool monster_facing(entity this, entity targ)
59 {
60         // relies on target having an origin
61         makevectors(this.angles);
62         vector targ_org = targ.origin, my_org = this.origin;
63         if(autocvar_g_monsters_target_infront_2d)
64         {
65                 targ_org = vec2(targ_org);
66                 my_org = vec2(my_org);
67         }
68         float dot = normalize(targ_org - my_org) * v_forward;
69
70         return !(dot <= autocvar_g_monsters_target_infront_range);
71 }
72
73 void monster_makevectors(entity this, entity targ)
74 {
75         if(IS_MONSTER(this))
76         {
77                 vector v = targ.origin + (targ.mins + targ.maxs) * 0.5;
78                 this.v_angle = vectoangles(v - (this.origin + this.view_ofs));
79                 this.v_angle_x = -this.v_angle_x;
80         }
81
82         makevectors(this.v_angle);
83 }
84
85 // ===============
86 // Target handling
87 // ===============
88
89 bool Monster_ValidTarget(entity this, entity targ, bool skipfacing)
90 {
91         // ensure we're not checking nonexistent monster/target
92         if(!this || !targ) { return false; }
93
94         if((targ == this)
95         || (time < game_starttime) // monsters do nothing before match has started
96         || (targ.takedamage == DAMAGE_NO)
97         || (game_stopped)
98         || (targ.items & IT_INVISIBILITY)
99         || (IS_SPEC(targ) || IS_OBSERVER(targ)) // don't attack spectators
100         || (!IS_VEHICLE(targ) && (IS_DEAD(targ) || IS_DEAD(this) || GetResource(targ, RES_HEALTH) <= 0 || GetResource(this, RES_HEALTH) <= 0))
101         || (this.monster_follow == targ || targ.monster_follow == this)
102         || (!IS_VEHICLE(targ) && (targ.flags & FL_NOTARGET))
103         || (!autocvar_g_monsters_typefrag && PHYS_INPUT_BUTTON_CHAT(targ))
104         || (IS_VEHICLE(targ) && !((Monsters_from(this.monsterid)).spawnflags & MON_FLAG_RANGED)) // melee vs vehicle is useless
105         || (SAME_TEAM(targ, this))
106         || (STAT(FROZEN, targ))
107         || (targ.alpha != 0 && targ.alpha < 0.5)
108         || (autocvar_g_monsters_lineofsight && !checkpvs(this.origin + this.view_ofs, targ)) // enemy cannot be seen
109         || (MUTATOR_CALLHOOK(MonsterValidTarget, this, targ))
110         )
111         {
112                 // if any of the above checks fail, target is not valid
113                 return false;
114         }
115
116         vector targ_origin = ((targ.absmin + targ.absmax) * 0.5);
117         traceline(this.origin + this.view_ofs, targ_origin, MOVE_NOMONSTERS, this); // TODO: maybe we can rely a bit on PVS data instead?
118
119         if(trace_fraction < 1 && trace_ent != targ)
120                 return false; // solid
121
122         if(!skipfacing && (autocvar_g_monsters_target_infront || (this.spawnflags & MONSTERFLAG_INFRONT)))
123         if(this.enemy != targ)
124         {
125                 if(!monster_facing(this, targ))
126                         return false;
127         }
128
129         return true; // this target is valid!
130 }
131
132 entity Monster_FindTarget(entity this)
133 {
134         if(MUTATOR_CALLHOOK(MonsterFindTarget)) { return this.enemy; } // Handled by a mutator
135
136         entity closest_target = NULL;
137         vector my_center = CENTER_OR_VIEWOFS(this);
138
139         // find the closest acceptable target to pass to
140         IL_EACH(g_monster_targets, it.monster_attack,
141         {
142                 float trange = this.target_range;
143                 if(PHYS_INPUT_BUTTON_CROUCH(it))
144                         trange *= 0.75; // TODO cvar this
145                 vector theirmid = (it.absmin + it.absmax) * 0.5;
146                 if(vdist(theirmid - this.origin, >, trange))
147                         continue;
148                 if(!Monster_ValidTarget(this, it, false))
149                         continue;
150
151                 // if it's a player, use the view origin as reference (stolen from RadiusDamage functions in g_damage.qc)
152                 vector targ_center = CENTER_OR_VIEWOFS(it);
153
154                 if(closest_target)
155                 {
156                         vector closest_target_center = CENTER_OR_VIEWOFS(closest_target);
157                         if(vlen2(my_center - targ_center) < vlen2(my_center - closest_target_center))
158                                 { closest_target = it; }
159                 }
160                 else { closest_target = it; }
161         });
162
163         return closest_target;
164 }
165
166 void monster_setupcolors(entity this)
167 {
168         if(IS_PLAYER(this.realowner))
169                 this.colormap = this.realowner.colormap;
170         else if(teamplay && this.team)
171                 this.colormap = 1024 + (this.team - 1) * 17;
172         else
173         {
174                 if(this.monster_skill <= MONSTER_SKILL_EASY)
175                         this.colormap = 1126;
176                 else if(this.monster_skill <= MONSTER_SKILL_MEDIUM)
177                         this.colormap = 1075;
178                 else if(this.monster_skill <= MONSTER_SKILL_HARD)
179                         this.colormap = 1228;
180                 else if(this.monster_skill <= MONSTER_SKILL_INSANE)
181                         this.colormap = 1092;
182                 else if(this.monster_skill <= MONSTER_SKILL_NIGHTMARE)
183                         this.colormap = 1160;
184                 else
185                         this.colormap = 1024;
186         }
187
188         if(this.colormap > 0)
189                 this.glowmod = colormapPaletteColor(this.colormap & 0x0F, false);
190         else
191                 this.glowmod = '1 1 1';
192 }
193
194 void monster_changeteam(entity this, int newteam)
195 {
196         if(!teamplay) { return; }
197
198         this.team = newteam;
199         if(!this.monster_attack)
200                 IL_PUSH(g_monster_targets, this);
201         this.monster_attack = true; // new team, activate attacking
202         monster_setupcolors(this);
203
204         if(this.sprite)
205         {
206                 WaypointSprite_UpdateTeamRadar(this.sprite, RADARICON_DANGER, ((newteam) ? Team_ColorRGB(newteam) : '1 0 0'));
207
208                 this.sprite.team = newteam;
209                 this.sprite.SendFlags |= 1;
210         }
211 }
212
213 .void(entity) monster_delayedfunc;
214 void Monster_Delay_Action(entity this)
215 {
216         // TODO: maybe do check for facing here
217         if(Monster_ValidTarget(this.owner, this.owner.enemy, false)) { this.monster_delayedfunc(this.owner); }
218
219         if(this.cnt > 1)
220         {
221                 this.cnt -= 1;
222                 setthink(this, Monster_Delay_Action);
223                 this.nextthink = time + this.count;
224         }
225         else
226         {
227                 setthink(this, SUB_Remove);
228                 this.nextthink = time;
229         }
230 }
231
232 void Monster_Delay(entity this, int repeat_count, float defer_amnt, void(entity) func)
233 {
234         // deferred attacking, checks if monster is still alive and target is still valid before attacking
235         entity e = spawn();
236
237         setthink(e, Monster_Delay_Action);
238         e.nextthink = time + defer_amnt;
239         e.count = defer_amnt;
240         e.owner = this;
241         e.monster_delayedfunc = func;
242         e.cnt = repeat_count;
243 }
244
245
246 // ==============
247 // Monster sounds
248 // ==============
249
250 string get_monster_model_datafilename(string m, float sk, string fil)
251 {
252         if(m)
253                 m = strcat(m, "_");
254         else
255                 m = "models/monsters/*_";
256         if(sk >= 0)
257                 m = strcat(m, ftos(sk));
258         else
259                 m = strcat(m, "*");
260         return strcat(m, ".", fil);
261 }
262
263 void Monster_Sound_Precache(string f)
264 {
265         float fh;
266         string s;
267         fh = fopen(f, FILE_READ);
268         if(fh < 0)
269                 return;
270         while((s = fgets(fh)))
271         {
272                 if(tokenize_console(s) != 3)
273                 {
274                         //LOG_DEBUG("Invalid sound info line: ", s); // probably a comment, no need to spam warnings
275                         continue;
276                 }
277                 PrecacheGlobalSound(strcat(argv(1), " ", argv(2)));
278         }
279         fclose(fh);
280 }
281
282 void Monster_Sounds_Precache(entity this)
283 {
284         string m = (Monsters_from(this.monsterid)).m_model.model_str();
285         float globhandle, n, i;
286         string f;
287
288         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
289         if (globhandle < 0)
290                 return;
291         n = search_getsize(globhandle);
292         for (i = 0; i < n; ++i)
293         {
294                 //print(search_getfilename(globhandle, i), "\n");
295                 f = search_getfilename(globhandle, i);
296                 Monster_Sound_Precache(f);
297         }
298         search_end(globhandle);
299 }
300
301 void Monster_Sounds_Clear(entity this)
302 {
303 #define _MSOUND(m) strfree(this.monstersound_##m);
304         ALLMONSTERSOUNDS
305 #undef _MSOUND
306 }
307
308 .string Monster_Sound_SampleField(string type)
309 {
310         GetMonsterSoundSampleField_notFound = 0;
311         switch(type)
312         {
313 #define _MSOUND(m) case #m: return monstersound_##m;
314                 ALLMONSTERSOUNDS
315 #undef _MSOUND
316         }
317         GetMonsterSoundSampleField_notFound = 1;
318         return string_null;
319 }
320
321 bool Monster_Sounds_Load(entity this, string f, int first)
322 {
323         string s;
324         var .string field;
325         float fh = fopen(f, FILE_READ);
326         if(fh < 0)
327         {
328                 //LOG_DEBUG("Monster sound file not found: ", f); // no biggie, monster has no sounds, let's not spam it
329                 return false;
330         }
331         while((s = fgets(fh)))
332         {
333                 if(tokenize_console(s) != 3)
334                         continue;
335                 field = Monster_Sound_SampleField(argv(0));
336                 if(GetMonsterSoundSampleField_notFound)
337                         continue;
338                 strcpy(this.(field), strcat(argv(1), " ", argv(2)));
339         }
340         fclose(fh);
341         return true;
342 }
343
344 .int skin_for_monstersound;
345 void Monster_Sounds_Update(entity this)
346 {
347         if(this.skin == this.skin_for_monstersound) { return; }
348
349         this.skin_for_monstersound = this.skin;
350         Monster_Sounds_Clear(this);
351         if(!Monster_Sounds_Load(this, get_monster_model_datafilename(this.model, this.skin, "sounds"), 0))
352                 Monster_Sounds_Load(this, get_monster_model_datafilename(this.model, 0, "sounds"), 0);
353 }
354
355 void Monster_Sound(entity this, .string samplefield, float sound_delay, bool delaytoo, float chan)
356 {
357         if(!autocvar_g_monsters_sounds) { return; }
358
359         if(delaytoo)
360         if(time < this.msound_delay)
361                 return; // too early
362         string sample = this.(samplefield);
363         if (sample != "") sample = GlobalSound_sample(sample, random());
364         float myscale = ((this.scale) ? this.scale : 1); // safety net
365         sound7(this, chan, sample, VOL_BASE, ATTEN_NORM, 100 / myscale, 0);
366
367         this.msound_delay = time + sound_delay;
368 }
369
370
371 // =======================
372 // Monster attack handlers
373 // =======================
374
375 bool Monster_Attack_Melee(entity this, entity targ, float damg, vector anim, float er, float animtime, int deathtype, bool dostop)
376 {
377         if(dostop && IS_MONSTER(this)) { this.state = MONSTER_ATTACK_MELEE; }
378
379         setanim(this, anim, false, true, false);
380
381         if(this.animstate_endtime > time && IS_MONSTER(this))
382                 this.attack_finished_single[0] = this.anim_finished = this.animstate_endtime;
383         else
384                 this.attack_finished_single[0] = this.anim_finished = time + animtime;
385
386         monster_makevectors(this, targ);
387
388         traceline(this.origin + this.view_ofs, this.origin + v_forward * er, 0, this);
389
390         if(trace_ent.takedamage)
391                 Damage(trace_ent, this, this, damg * MONSTER_SKILLMOD(this), deathtype, DMG_NOWEP, trace_ent.origin, normalize(trace_ent.origin - this.origin));
392
393         return true;
394 }
395
396 bool Monster_Attack_Leap_Check(entity this, vector vel)
397 {
398         if(this.state && IS_MONSTER(this))
399                 return false; // already attacking
400         if(!IS_ONGROUND(this))
401                 return false; // not on the ground
402         if(GetResource(this, RES_HEALTH) <= 0 || IS_DEAD(this))
403                 return false; // called when dead?
404         if(time < this.attack_finished_single[0])
405                 return false; // still attacking
406
407         vector old = this.velocity;
408
409         this.velocity = vel;
410         tracetoss(this, this);
411         this.velocity = old;
412         if(trace_ent != this.enemy)
413                 return false;
414
415         return true;
416 }
417
418 bool Monster_Attack_Leap(entity this, vector anm, void(entity this, entity toucher) touchfunc, vector vel, float animtime)
419 {
420         if(!Monster_Attack_Leap_Check(this, vel))
421                 return false;
422
423         setanim(this, anm, false, true, false);
424
425         if(this.animstate_endtime > time && IS_MONSTER(this))
426                 this.attack_finished_single[0] = this.anim_finished = this.animstate_endtime;
427         else
428                 this.attack_finished_single[0] = this.anim_finished = time + animtime;
429
430         if(IS_MONSTER(this))
431                 this.state = MONSTER_ATTACK_RANGED;
432         settouch(this, touchfunc);
433         this.origin_z += 1;
434         this.velocity = vel;
435         UNSET_ONGROUND(this);
436
437         return true;
438 }
439
440 void Monster_Attack_Check(entity this, entity targ, .entity weaponentity)
441 {
442         int slot = weaponslot(weaponentity);
443
444         if((!this || !targ)
445         || (!this.monster_attackfunc)
446         || (time < this.attack_finished_single[slot])
447         || ((autocvar_g_monsters_target_infront || (this.spawnflags & MONSTERFLAG_INFRONT)) && !monster_facing(this, targ))
448         ) { return; }
449
450         if(vdist(targ.origin - this.origin, <=, this.attack_range))
451         {
452                 int attack_success = this.monster_attackfunc(MONSTER_ATTACK_MELEE, this, targ, weaponentity);
453                 if(attack_success == 1)
454                         Monster_Sound(this, monstersound_melee, 0, false, CH_VOICE);
455                 else if(attack_success > 0)
456                         return;
457         }
458
459         if(vdist(targ.origin - this.origin, >, this.attack_range))
460         {
461                 int attack_success = this.monster_attackfunc(MONSTER_ATTACK_RANGED, this, targ, weaponentity);
462                 if(attack_success == 1)
463                         Monster_Sound(this, monstersound_melee, 0, false, CH_VOICE);
464                 else if(attack_success > 0)
465                         return;
466         }
467 }
468
469
470 // ======================
471 // Main monster functions
472 // ======================
473
474 void Monster_UpdateModel(entity this)
475 {
476         // assume some defaults
477         /*this.anim_idle   = animfixfps(this, '0 1 0.01', '0 0 0');
478         this.anim_walk   = animfixfps(this, '1 1 0.01', '0 0 0');
479         this.anim_run    = animfixfps(this, '2 1 0.01', '0 0 0');
480         this.anim_fire1  = animfixfps(this, '3 1 0.01', '0 0 0');
481         this.anim_fire2  = animfixfps(this, '4 1 0.01', '0 0 0');
482         this.anim_melee  = animfixfps(this, '5 1 0.01', '0 0 0');
483         this.anim_pain1  = animfixfps(this, '6 1 0.01', '0 0 0');
484         this.anim_pain2  = animfixfps(this, '7 1 0.01', '0 0 0');
485         this.anim_die1   = animfixfps(this, '8 1 0.01', '0 0 0');
486         this.anim_die2   = animfixfps(this, '9 1 0.01', '0 0 0');*/
487
488         // then get the real values
489         Monster mon = Monsters_from(this.monsterid);
490         mon.mr_anim(mon, this);
491 }
492
493 void Monster_Touch(entity this, entity toucher)
494 {
495         if(!toucher) { return; }
496
497         if(toucher.monster_attack && this.enemy != toucher && !IS_MONSTER(toucher) && time >= this.spawn_time)
498         if(Monster_ValidTarget(this, toucher, true))
499                 this.enemy = toucher;
500 }
501
502 void Monster_Miniboss_Check(entity this)
503 {
504         if(MUTATOR_CALLHOOK(MonsterCheckBossFlag, this))
505                 return;
506
507         float chance = random() * 100;
508
509         // g_monsters_miniboss_chance cvar or spawnflags 64 causes a monster to be a miniboss
510         if ((this.spawnflags & MONSTERFLAG_MINIBOSS) || (chance < autocvar_g_monsters_miniboss_chance))
511         {
512                 GiveResource(this, RES_HEALTH, autocvar_g_monsters_miniboss_healthboost);
513                 this.effects |= EF_RED;
514                 if(!this.weapon)
515                         this.weapon = WEP_VORTEX.m_id;
516         }
517 }
518
519 bool Monster_Respawn_Check(entity this)
520 {
521         if(this.deadflag == DEAD_DEAD) // don't call when monster isn't dead
522         if(MUTATOR_CALLHOOK(MonsterRespawn, this))
523                 return true; // enabled by a mutator
524
525         if(this.spawnflags & MONSTERFLAG_NORESPAWN)
526                 return false;
527
528         if(!autocvar_g_monsters_respawn)
529                 return false;
530
531         return true;
532 }
533
534 void Monster_Respawn(entity this) { Monster_Spawn(this, true, this.monsterid); }
535
536 .vector pos1, pos2;
537
538 void Monster_Dead_Fade(entity this)
539 {
540         if(Monster_Respawn_Check(this))
541         {
542                 this.spawnflags |= MONSTERFLAG_RESPAWNED;
543                 setthink(this, Monster_Respawn);
544                 this.nextthink = time + this.respawntime;
545                 this.monster_lifetime = 0;
546                 this.deadflag = DEAD_RESPAWNING;
547                 if(this.spawnflags & MONSTER_RESPAWN_DEATHPOINT)
548                 {
549                         this.pos1 = this.origin;
550                         this.pos2 = this.angles;
551                 }
552                 this.event_damage = func_null;
553                 this.event_heal = func_null;
554                 this.takedamage = DAMAGE_NO;
555                 setorigin(this, this.pos1);
556                 this.angles = this.pos2;
557                 SetResourceExplicit(this, RES_HEALTH, this.max_health);
558                 setmodel(this, MDL_Null);
559         }
560         else
561         {
562                 // number of monsters spawned with mobspawn command
563                 totalspawned -= 1;
564
565                 SUB_SetFade(this, time + 3, 1);
566         }
567 }
568
569 void Monster_Use(entity this, entity actor, entity trigger)
570 {
571         if(Monster_ValidTarget(this, actor, true)) { this.enemy = actor; }
572 }
573
574 vector Monster_Move_Target(entity this, entity targ)
575 {
576         // enemy is always preferred target
577         if(this.enemy)
578         {
579                 vector targ_origin = ((this.enemy.absmin + this.enemy.absmax) * 0.5);
580                 targ_origin = WarpZone_RefSys_TransformOrigin(this.enemy, this, targ_origin); // origin of target as seen by the monster (us)
581                 WarpZone_TraceLine(this.origin, targ_origin, MOVE_NOMONSTERS, this);
582
583                 // cases where the enemy may have changed their state (don't need to check everything here)
584                 if(    (IS_DEAD(this.enemy) || GetResource(this.enemy, RES_HEALTH) < 1)
585                         || (STAT(FROZEN, this.enemy))
586                         || (this.enemy.flags & FL_NOTARGET)
587                         || (this.enemy.alpha < 0.5 && this.enemy.alpha != 0)
588                         || (this.enemy.takedamage == DAMAGE_NO)
589                         || (vdist(this.origin - targ_origin, >, this.target_range))
590                         || ((trace_fraction < 1) && (trace_ent != this.enemy))
591                         )
592                 {
593                         this.enemy = NULL;
594                 }
595
596                 if(this.enemy)
597                 {
598                         /*WarpZone_TrailParticles(NULL, particleeffectnum(EFFECT_RED_PASS), this.origin, targ_origin);
599                         print("Trace origin: ", vtos(targ_origin), "\n");
600                         print("Target origin: ", vtos(this.enemy.origin), "\n");
601                         print("My origin: ", vtos(this.origin), "\n"); */
602
603                         this.monster_movestate = MONSTER_MOVE_ENEMY;
604                         this.last_trace = time + 1.2;
605                         if(this.monster_moveto)
606                                 return this.monster_moveto; // assumes code is properly setting this when monster has an enemy
607                         else
608                                 return targ_origin;
609                 }
610
611                 /*makevectors(this.angles);
612                 this.monster_movestate = MONSTER_MOVE_ENEMY;
613                 this.last_trace = time + 1.2;
614                 return this.enemy.origin; */
615         }
616
617         switch(this.monster_moveflags)
618         {
619                 case MONSTER_MOVE_FOLLOW:
620                 {
621                         this.monster_movestate = MONSTER_MOVE_FOLLOW;
622                         this.last_trace = time + 0.3;
623                         return (this.monster_follow) ? this.monster_follow.origin : this.origin;
624                 }
625                 case MONSTER_MOVE_SPAWNLOC:
626                 {
627                         this.monster_movestate = MONSTER_MOVE_SPAWNLOC;
628                         this.last_trace = time + 2;
629                         return this.pos1;
630                 }
631                 case MONSTER_MOVE_NOMOVE:
632                 {
633                         if(this.monster_moveto)
634                         {
635                                 this.last_trace = time + 0.5;
636                                 return this.monster_moveto;
637                         }
638                         else
639                         {
640                                 this.monster_movestate = MONSTER_MOVE_NOMOVE;
641                                 this.last_trace = time + 2;
642                         }
643                         return this.origin;
644                 }
645                 default:
646                 case MONSTER_MOVE_WANDER:
647                 {
648                         vector pos;
649                         this.monster_movestate = MONSTER_MOVE_WANDER;
650
651                         if(this.monster_moveto)
652                         {
653                                 this.last_trace = time + 0.5;
654                                 pos = this.monster_moveto;
655                         }
656                         else if(targ)
657                         {
658                                 this.last_trace = time + 0.5;
659                                 pos = targ.origin;
660                         }
661                         else
662                         {
663                                 this.last_trace = time + this.wander_delay;
664
665                                 this.angles_y = rint(random() * 500);
666                                 makevectors(this.angles);
667                                 pos = this.origin + v_forward * this.wander_distance;
668
669                                 if(((this.flags & FL_FLY) && (this.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (this.flags & FL_SWIM))
670                                 {
671                                         pos.z = random() * 200;
672                                         if(random() >= 0.5)
673                                                 pos.z *= -1;
674                                 }
675                         }
676
677                         return pos;
678                 }
679         }
680 }
681
682 .entity draggedby;
683
684 void Monster_Move(entity this, float runspeed, float walkspeed, float stpspeed)
685 {
686         // update goal entity if lost
687         if(this.target2 && this.target2 != "" && this.goalentity.targetname != this.target2)
688                 this.goalentity = find(NULL, targetname, this.target2);
689
690         if(STAT(FROZEN, this))
691         {
692                 movelib_brake_simple(this, stpspeed);
693                 setanim(this, this.anim_idle, true, false, false);
694                 return; // no physics while frozen!
695         }
696
697         if(this.flags & FL_SWIM)
698         {
699                 if(this.waterlevel < WATERLEVEL_WETFEET)
700                 {
701                         if(time >= this.last_trace)
702                         {
703                                 this.last_trace = time + 0.4;
704
705                                 Damage (this, NULL, NULL, 2, DEATH_DROWN.m_id, DMG_NOWEP, this.origin, '0 0 0');
706                                 this.angles = '90 90 0';
707                                 if(random() < 0.5)
708                                 {
709                                         this.velocity_y += random() * 50;
710                                         this.velocity_x -= random() * 50;
711                                 }
712                                 else
713                                 {
714                                         this.velocity_y -= random() * 50;
715                                         this.velocity_x += random() * 50;
716                                 }
717                                 this.velocity_z += random() * 150;
718                         }
719
720
721                         set_movetype(this, MOVETYPE_BOUNCE);
722                         //this.velocity_z = -200;
723
724                         return;
725                 }
726                 else if(this.move_movetype == MOVETYPE_BOUNCE)
727                 {
728                         this.angles_x = 0;
729                         set_movetype(this, MOVETYPE_WALK);
730                 }
731         }
732
733         entity targ = this.goalentity;
734
735         if (MUTATOR_CALLHOOK(MonsterMove, this, runspeed, walkspeed, targ)
736                 || game_stopped
737                 || this.draggedby != NULL
738                 || (round_handler_IsActive() && !round_handler_IsRoundStarted())
739                 || time < game_starttime
740                 || (autocvar_g_campaign && !campaign_bots_may_start)
741                 || time < this.spawn_time)
742         {
743                 runspeed = walkspeed = 0;
744                 if(time >= this.spawn_time)
745                         setanim(this, this.anim_idle, true, false, false);
746                 movelib_brake_simple(this, stpspeed);
747                 return;
748         }
749
750         targ = M_ARGV(3, entity);
751         runspeed = bound(0, M_ARGV(1, float) * MONSTER_SKILLMOD(this), runspeed * 2.5); // limit maxspeed to prevent craziness
752         walkspeed = bound(0, M_ARGV(2, float) * MONSTER_SKILLMOD(this), walkspeed * 2.5); // limit maxspeed to prevent craziness
753
754         if(teamplay && autocvar_g_monsters_teams)
755         if(DIFF_TEAM(this.monster_follow, this))
756                 this.monster_follow = NULL;
757
758         if(this.state == MONSTER_ATTACK_RANGED && IS_ONGROUND(this))
759         {
760                 this.state = 0;
761                 settouch(this, Monster_Touch);
762         }
763
764         if(this.state && time >= this.attack_finished_single[0])
765                 this.state = 0; // attack is over
766
767         if(this.state != MONSTER_ATTACK_MELEE) // don't move if set
768         if(time >= this.last_trace || this.enemy) // update enemy or rider instantly
769                 this.moveto = Monster_Move_Target(this, targ);
770
771         if(!this.enemy)
772                 Monster_Sound(this, monstersound_idle, 7, true, CH_VOICE);
773
774         if(this.state == MONSTER_ATTACK_MELEE)
775                 this.moveto = this.origin;
776
777         if(this.enemy && this.enemy.vehicle)
778                 runspeed = 0;
779
780         if(!(this.spawnflags & MONSTERFLAG_FLY_VERTICAL) && !(this.flags & FL_SWIM))
781                 this.moveto_z = this.origin_z;
782
783         fixedmakevectors(this.angles);
784         float vz = this.velocity_z;
785
786         if(!turret_closetotarget(this, this.moveto, 16))
787         {
788                 bool do_run = (this.enemy || this.monster_moveto);
789                 movelib_move_simple(this, v_forward, ((do_run) ? runspeed : walkspeed), 0.4);
790
791                 if(time > this.pain_finished && time > this.anim_finished)
792                 if(!this.state)
793                 {
794                         if(vdist(this.velocity, >, 10))
795                                 setanim(this, ((do_run) ? this.anim_run : this.anim_walk), true, false, false);
796                         else
797                                 setanim(this, this.anim_idle, true, false, false);
798                 }
799         }
800         else
801         {
802                 entity e = this.goalentity; //find(NULL, targetname, this.target2);
803                 if(e.target2 && e.target2 != "")
804                         this.target2 = e.target2;
805                 else if(e.target && e.target != "") // compatibility
806                         this.target2 = e.target;
807
808                 movelib_brake_simple(this, stpspeed);
809                 if(time > this.anim_finished && time > this.pain_finished)
810                 if(!this.state)
811                 if(vdist(this.velocity, <=, 30))
812                         setanim(this, this.anim_idle, true, false, false);
813         }
814
815         if(!((this.flags & FL_FLY) || (this.flags & FL_SWIM)))
816                 this.velocity_z = vz;
817
818         this.steerto = steerlib_attract2(this, ((this.monster_face) ? this.monster_face : this.moveto), 0.5, 500, 0.95);
819
820         vector real_angle = vectoangles(this.steerto) - this.angles;
821         float turny = 25;
822         if(this.state == MONSTER_ATTACK_MELEE)
823                 turny = 0;
824         if(turny)
825         {
826                 turny = bound(turny * -1, shortangle_f(real_angle.y, this.angles.y), turny);
827                 this.angles_y += turny;
828         }
829 }
830
831 void Monster_Remove(entity this)
832 {
833         if(IS_CLIENT(this))
834                 return; // don't remove it?
835
836         if(!this) { return; }
837
838         if(!MUTATOR_CALLHOOK(MonsterRemove, this))
839                 Send_Effect(EFFECT_ITEM_PICKUP, this.origin, '0 0 0', 1);
840
841         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
842         {
843                 .entity weaponentity = weaponentities[slot];
844                 if(this.(weaponentity))
845                         delete(this.(weaponentity));
846         }
847         if(this.iceblock) { delete(this.iceblock); }
848         WaypointSprite_Kill(this.sprite);
849         delete(this);
850 }
851
852 void Monster_Dead_Think(entity this)
853 {
854         this.nextthink = time + this.ticrate;
855
856         Monster mon = Monsters_from(this.monsterid);
857         mon.mr_deadthink(mon, this);
858
859         if(this.monster_lifetime != 0)
860         if(time >= this.monster_lifetime)
861         {
862                 Monster_Dead_Fade(this);
863                 return;
864         }
865 }
866
867 void Monster_Appear(entity this, entity actor, entity trigger)
868 {
869         this.enemy = actor;
870         Monster_Spawn(this, false, this.monsterid);
871 }
872
873 bool Monster_Appear_Check(entity this, int monster_id)
874 {
875         if(!(this.spawnflags & MONSTERFLAG_APPEAR))
876                 return false;
877
878         setthink(this, func_null);
879         this.monsterid = monster_id; // set so this monster is properly registered (otherwise, normal initialization is used)
880         this.nextthink = 0;
881         this.use = Monster_Appear;
882         this.flags = FL_MONSTER; // set so this monster can get butchered
883
884         return true;
885 }
886
887 void Monster_Reset(entity this)
888 {
889         setorigin(this, this.pos1);
890         this.angles = this.pos2;
891
892         Unfreeze(this, false); // remove any icy remains
893
894         SetResourceExplicit(this, RES_HEALTH, this.max_health);
895         this.velocity = '0 0 0';
896         this.enemy = NULL;
897         this.goalentity = NULL;
898         this.attack_finished_single[0] = 0;
899         this.moveto = this.origin;
900 }
901
902 void Monster_Dead_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
903 {
904         TakeResource(this, RES_HEALTH, damage);
905
906         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, this, attacker);
907
908         if(GetResource(this, RES_HEALTH) <= -50) // 100 health until gone?
909         {
910                 Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, this, attacker);
911
912                 // number of monsters spawned with mobspawn command
913                 totalspawned -= 1;
914
915                 setthink(this, SUB_Remove);
916                 this.nextthink = time + 0.1;
917                 this.event_damage = func_null;
918         }
919 }
920
921 void Monster_Dead(entity this, entity attacker, float gibbed)
922 {
923         setthink(this, Monster_Dead_Think);
924         this.nextthink = time;
925         this.monster_lifetime = time + 5;
926
927         if(STAT(FROZEN, this))
928                 Unfreeze(this, false); // remove any icy remains
929
930         monster_dropitem(this, attacker);
931
932         Monster_Sound(this, monstersound_death, 0, false, CH_VOICE);
933
934         if(!(this.spawnflags & MONSTERFLAG_SPAWNED) && !(this.spawnflags & MONSTERFLAG_RESPAWNED))
935                 monsters_killed += 1;
936
937         if(IS_PLAYER(attacker))
938         if(autocvar_g_monsters_score_spawned || !((this.spawnflags & MONSTERFLAG_SPAWNED) || (this.spawnflags & MONSTERFLAG_RESPAWNED)))
939                 GameRules_scoring_add(attacker, SCORE, +autocvar_g_monsters_score_kill);
940
941         if(gibbed)
942         {
943                 // number of monsters spawned with mobspawn command
944                 totalspawned -= 1;
945         }
946
947         if(!gibbed && this.mdl_dead && this.mdl_dead != "")
948                 _setmodel(this, this.mdl_dead);
949
950         this.event_damage       = ((gibbed) ? func_null : Monster_Dead_Damage);
951         this.event_heal         = func_null;
952         this.solid                      = SOLID_CORPSE;
953         this.takedamage         = DAMAGE_AIM;
954         this.deadflag           = DEAD_DEAD;
955         this.enemy                      = NULL;
956         set_movetype(this, MOVETYPE_TOSS);
957         this.moveto                     = this.origin;
958         settouch(this, Monster_Touch); // reset incase monster was pouncing
959         this.reset                      = func_null;
960         this.state                      = 0;
961         this.attack_finished_single[0] = 0;
962         this.effects = 0;
963         this.dphitcontentsmask &= ~DPCONTENTS_BODY;
964
965         if(!((this.flags & FL_FLY) || (this.flags & FL_SWIM)))
966                 this.velocity = '0 0 0';
967
968         CSQCModel_UnlinkEntity(this);
969
970         Monster mon = Monsters_from(this.monsterid);
971         mon.mr_death(mon, this);
972
973         if(this.candrop && this.weapon)
974         {
975                 .entity weaponentity = weaponentities[0]; // TODO: unhardcode
976                 W_ThrowNewWeapon(this, this.weapon, 0, this.origin, randomvec() * 150 + '0 0 325', weaponentity);
977         }
978 }
979
980 void Monster_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
981 {
982         if((this.spawnflags & MONSTERFLAG_INVINCIBLE) && deathtype != DEATH_KILL.m_id && !ITEM_DAMAGE_NEEDKILL(deathtype))
983                 return;
984
985         if(STAT(FROZEN, this) && deathtype != DEATH_KILL.m_id && deathtype != DEATH_NADE_ICE_FREEZE.m_id)
986                 return;
987
988         //if(time < this.pain_finished && deathtype != DEATH_KILL.m_id)
989                 //return;
990
991         if(time < this.spawnshieldtime && deathtype != DEATH_KILL.m_id)
992                 return;
993
994         if(deathtype == DEATH_FALL.m_id && this.draggedby != NULL)
995                 return;
996
997         vector v = healtharmor_applydamage(100, GetResource(this, RES_ARMOR) / 100, deathtype, damage);
998         float take = v.x;
999         //float save = v.y;
1000
1001         Monster mon = Monsters_from(this.monsterid);
1002         take = mon.mr_pain(mon, this, take, attacker, deathtype);
1003
1004         if(take)
1005         {
1006                 TakeResource(this, RES_HEALTH, take);
1007                 Monster_Sound(this, monstersound_pain, 1.2, true, CH_PAIN);
1008         }
1009
1010         if(this.sprite)
1011                 WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1012
1013         this.dmg_time = time;
1014
1015         if(deathtype != DEATH_DROWN.m_id && deathtype != DEATH_FIRE.m_id && sound_allowed(MSG_BROADCAST, attacker))
1016                 spamsound (this, CH_PAIN, SND_BODYIMPACT1, VOL_BASE, ATTEN_NORM);  // FIXME: PLACEHOLDER
1017
1018         this.velocity += force * this.damageforcescale;
1019
1020         if(deathtype != DEATH_DROWN.m_id && take)
1021         {
1022                 Violence_GibSplash_At(hitloc, force, 2, bound(0, take, 200) / 16, this, attacker);
1023                 if (take > 50)
1024                         Violence_GibSplash_At(hitloc, force * -0.1, 3, 1, this, attacker);
1025                 if (take > 100)
1026                         Violence_GibSplash_At(hitloc, force * -0.2, 3, 1, this, attacker);
1027         }
1028
1029         if(GetResource(this, RES_HEALTH) <= 0)
1030         {
1031                 if(deathtype == DEATH_KILL.m_id)
1032                         this.candrop = false; // killed by mobkill command
1033
1034                 // TODO: fix this?
1035                 SUB_UseTargets(this, attacker, this.enemy);
1036                 this.target2 = this.oldtarget2; // reset to original target on death, incase we respawn
1037
1038                 Monster_Dead(this, attacker, (GetResource(this, RES_HEALTH) <= -100 || deathtype == DEATH_KILL.m_id));
1039
1040                 WaypointSprite_Kill(this.sprite);
1041
1042                 MUTATOR_CALLHOOK(MonsterDies, this, attacker, deathtype);
1043
1044                 if(GetResource(this, RES_HEALTH) <= -100 || deathtype == DEATH_KILL.m_id) // check if we're already gibbed
1045                 {
1046                         Violence_GibSplash(this, 1, 0.5, attacker);
1047
1048                         setthink(this, SUB_Remove);
1049                         this.nextthink = time + 0.1;
1050                 }
1051         }
1052 }
1053
1054 bool Monster_Heal(entity targ, entity inflictor, float amount, float limit)
1055 {
1056         float true_limit = ((limit != RES_LIMIT_NONE) ? limit : targ.max_health);
1057         if(GetResource(targ, RES_HEALTH) <= 0 || GetResource(targ, RES_HEALTH) >= true_limit)
1058                 return false;
1059
1060         GiveResourceWithLimit(targ, RES_HEALTH, amount, true_limit);
1061         if(targ.sprite)
1062                 WaypointSprite_UpdateHealth(targ.sprite, GetResource(targ, RES_HEALTH));
1063         return true;
1064 }
1065
1066 // don't check for enemies, just keep walking in a straight line
1067 void Monster_Move_2D(entity this, float mspeed, bool allow_jumpoff)
1068 {
1069         if(game_stopped || (round_handler_IsActive() && !round_handler_IsRoundStarted()) || this.draggedby != NULL || time < game_starttime || (autocvar_g_campaign && !campaign_bots_may_start) || time < this.spawn_time)
1070         {
1071                 mspeed = 0;
1072                 if(time >= this.spawn_time)
1073                         setanim(this, this.anim_idle, true, false, false);
1074                 movelib_brake_simple(this, 0.6);
1075                 return;
1076         }
1077
1078         makevectors(this.angles);
1079         vector a = CENTER_OR_VIEWOFS(this);
1080         vector b = CENTER_OR_VIEWOFS(this) + v_forward * 32;
1081
1082         traceline(a, b, MOVE_NORMAL, this);
1083
1084         bool reverse = false;
1085         if(trace_fraction != 1.0)
1086                 reverse = true;
1087         if(trace_ent && IS_PLAYER(trace_ent) && !(trace_ent.items & ITEM_Strength.m_itemid))
1088                 reverse = false;
1089         if(trace_ent && IS_MONSTER(trace_ent))
1090                 reverse = true;
1091
1092         if(!allow_jumpoff && IS_ONGROUND(this))
1093         {
1094                 traceline(b, b - '0 0 32', MOVE_NORMAL, this);
1095                 if(trace_fraction == 1.0)
1096                         reverse = true;
1097         }
1098
1099         if(reverse)
1100         {
1101                 this.angles_y = anglemods(this.angles_y - 180);
1102                 makevectors(this.angles);
1103         }
1104
1105         movelib_move_simple_gravity(this, v_forward, mspeed, 1);
1106
1107         if(time > this.pain_finished && time > this.attack_finished_single[0])
1108         {
1109                 if(vdist(this.velocity, >, 10))
1110                         setanim(this, this.anim_walk, true, false, false);
1111                 else
1112                         setanim(this, this.anim_idle, true, false, false);
1113         }
1114 }
1115
1116 void Monster_Anim(entity this)
1117 {
1118         int deadbits = (this.anim_state & (ANIMSTATE_DEAD1 | ANIMSTATE_DEAD2));
1119         if(IS_DEAD(this))
1120         {
1121                 if (!deadbits)
1122                 {
1123                         // Decide on which death animation to use.
1124                         if(random() < 0.5)
1125                                 deadbits = ANIMSTATE_DEAD1;
1126                         else
1127                                 deadbits = ANIMSTATE_DEAD2;
1128                 }
1129         }
1130         else
1131         {
1132                 // Clear a previous death animation.
1133                 deadbits = 0;
1134         }
1135         int animbits = deadbits;
1136         if(STAT(FROZEN, this))
1137                 animbits |= ANIMSTATE_FROZEN;
1138         if(this.crouch)
1139                 animbits |= ANIMSTATE_DUCK; // not that monsters can crouch currently...
1140         animdecide_setstate(this, animbits, false);
1141         animdecide_setimplicitstate(this, (IS_ONGROUND(this)));
1142
1143         /* // weapon entities for monsters?
1144         if (this.weaponentity)
1145         {
1146                 updateanim(this.weaponentity);
1147                 if (!this.weaponentity.animstate_override)
1148                         setanim(this.weaponentity, this.weaponentity.anim_idle, true, false, false);
1149         }
1150         */
1151 }
1152
1153 void Monster_Frozen_Think(entity this)
1154 {
1155         if (STAT(FROZEN, this) == FROZEN_TEMP_REVIVING)
1156         {
1157                 STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) + this.ticrate * this.revive_speed, 1);
1158                 SetResourceExplicit(this, RES_HEALTH, max(1, STAT(REVIVE_PROGRESS, this) * this.max_health));
1159                 this.iceblock.alpha = bound(0.2, 1 - STAT(REVIVE_PROGRESS, this), 1);
1160
1161                 if(!(this.spawnflags & MONSTERFLAG_INVINCIBLE) && this.sprite)
1162                         WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1163
1164                 if(STAT(REVIVE_PROGRESS, this) >= 1)
1165                         Unfreeze(this, false);
1166         }
1167         else if (STAT(FROZEN, this) == FROZEN_TEMP_DYING)
1168         {
1169                 STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) - this.ticrate * this.revive_speed, 1);
1170                 SetResourceExplicit(this, RES_HEALTH, max(0, autocvar_g_nades_ice_health + (this.max_health-autocvar_g_nades_ice_health) * STAT(REVIVE_PROGRESS, this)));
1171
1172                 if(!(this.spawnflags & MONSTERFLAG_INVINCIBLE) && this.sprite)
1173                         WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1174
1175                 if(GetResource(this, RES_HEALTH) < 1)
1176                 {
1177                         Unfreeze(this, false);
1178                         if(this.event_damage)
1179                                 this.event_damage(this, this, this.frozen_by, 1, DEATH_NADE_ICE_FREEZE.m_id, DMG_NOWEP, this.origin, '0 0 0');
1180                 }
1181                 else if ( STAT(REVIVE_PROGRESS, this) <= 0 )
1182                         Unfreeze(this, false);
1183         }
1184         // otherwise, no revival!
1185
1186         this.enemy = NULL; // TODO: save enemy, and attack when revived?
1187 }
1188
1189 void Monster_Enemy_Check(entity this)
1190 {
1191         if(this.enemy)
1192                 return;
1193
1194         this.enemy = Monster_FindTarget(this);
1195         if(this.enemy)
1196         {
1197                 WarpZone_RefSys_Copy(this.enemy, this);
1198                 WarpZone_RefSys_AddInverse(this.enemy, this); // wz1^-1 ... wzn^-1 receiver
1199                 // update move target immediately?
1200                 this.moveto = WarpZone_RefSys_TransformOrigin(this.enemy, this, (0.5 * (this.enemy.absmin + this.enemy.absmax)));
1201                 this.monster_moveto = '0 0 0';
1202                 this.monster_face = '0 0 0';
1203
1204                 Monster_Sound(this, monstersound_sight, 0, false, CH_VOICE);
1205         }
1206 }
1207
1208 void Monster_Think(entity this)
1209 {
1210         setthink(this, Monster_Think);
1211         this.nextthink = time + this.ticrate;
1212
1213         if(this.monster_lifetime && time >= this.monster_lifetime)
1214         {
1215                 Damage(this, this, this, GetResource(this, RES_HEALTH) + this.max_health, DEATH_KILL.m_id, DMG_NOWEP, this.origin, this.origin);
1216                 return;
1217         }
1218
1219         if(STAT(FROZEN, this))
1220                 Monster_Frozen_Think(this);
1221         else if(time >= this.last_enemycheck)
1222         {
1223                 Monster_Enemy_Check(this);
1224                 this.last_enemycheck = time + 1; // check for enemies every second
1225         }
1226
1227         Monster mon = Monsters_from(this.monsterid);
1228         if(mon.mr_think(mon, this))
1229         {
1230                 Monster_Move(this, this.speed2, this.speed, this.stopspeed);
1231
1232                 .entity weaponentity = weaponentities[0]; // TODO?
1233                 Monster_Attack_Check(this, this.enemy, weaponentity);
1234         }
1235
1236         Monster_Anim(this);
1237
1238         CSQCMODEL_AUTOUPDATE(this);
1239 }
1240
1241 bool Monster_Spawn_Setup(entity this)
1242 {
1243         Monster mon = Monsters_from(this.monsterid);
1244         mon.mr_setup(mon, this);
1245
1246         // ensure some basic needs are met
1247         if(!GetResource(this, RES_HEALTH)) { SetResourceExplicit(this, RES_HEALTH, 100); }
1248         if(!GetResource(this, RES_ARMOR)) { SetResourceExplicit(this, RES_ARMOR, bound(0.2, 0.5 * MONSTER_SKILLMOD(this), 0.9)); }
1249         if(!this.target_range) { this.target_range = autocvar_g_monsters_target_range; }
1250         if(!this.respawntime) { this.respawntime = autocvar_g_monsters_respawn_delay; }
1251         if(!this.monster_moveflags) { this.monster_moveflags = MONSTER_MOVE_WANDER; }
1252         if(!this.attack_range) { this.attack_range = autocvar_g_monsters_attack_range; }
1253         if(!this.damageforcescale) { this.damageforcescale = autocvar_g_monsters_damageforcescale; }
1254
1255         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED))
1256         {
1257                 Monster_Miniboss_Check(this);
1258                 SetResourceExplicit(this, RES_HEALTH, GetResource(this, RES_HEALTH) * MONSTER_SKILLMOD(this));
1259
1260                 if(!this.skin)
1261                         this.skin = rint(random() * 4);
1262         }
1263
1264         this.max_health = GetResource(this, RES_HEALTH);
1265         this.pain_finished = this.nextthink;
1266         this.last_enemycheck = this.spawn_time + random(); // slight delay
1267
1268         if(IS_PLAYER(this.monster_follow))
1269                 this.effects |= EF_DIMLIGHT;
1270
1271         if(!this.wander_delay) { this.wander_delay = 2; }
1272         if(!this.wander_distance) { this.wander_distance = 600; }
1273
1274         Monster_Sounds_Precache(this);
1275         Monster_Sounds_Update(this);
1276
1277         if(teamplay)
1278         {
1279                 if(!this.monster_attack)
1280                         IL_PUSH(g_monster_targets, this);
1281                 this.monster_attack = true; // we can have monster enemies in team games
1282         }
1283
1284         Monster_Sound(this, monstersound_spawn, 0, false, CH_VOICE);
1285
1286         if(autocvar_g_monsters_healthbars)
1287         {
1288                 entity wp = WaypointSprite_Spawn(WP_Monster, 0, 1024, this, '0 0 1' * (this.maxs.z + 15), NULL, this.team, this, sprite, true, RADARICON_DANGER);
1289                 wp.wp_extra = this.monsterid;
1290                 wp.colormod = ((this.team) ? Team_ColorRGB(this.team) : '1 0 0');
1291                 if(!(this.spawnflags & MONSTERFLAG_INVINCIBLE))
1292                 {
1293                         WaypointSprite_UpdateMaxHealth(this.sprite, this.max_health);
1294                         WaypointSprite_UpdateHealth(this.sprite, GetResource(this, RES_HEALTH));
1295                 }
1296         }
1297
1298         setthink(this, Monster_Think);
1299         this.nextthink = time + this.ticrate;
1300
1301         if(MUTATOR_CALLHOOK(MonsterSpawn, this))
1302                 return false;
1303
1304         return true;
1305 }
1306
1307 bool Monster_Spawn(entity this, bool check_appear, int mon_id)
1308 {
1309         // setup the basic required properties for a monster
1310         entity mon = Monsters_from(mon_id);
1311         if(!mon.monsterid) { return false; } // invalid monster
1312
1313         if(!autocvar_g_monsters) { Monster_Remove(this); return false; }
1314
1315         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED) && !(this.flags & FL_MONSTER))
1316         {
1317                 IL_PUSH(g_monsters, this);
1318                 if(this.mdl && this.mdl != "")
1319                         precache_model(this.mdl);
1320                 if(this.mdl_dead && this.mdl_dead != "")
1321                         precache_model(this.mdl_dead);
1322         }
1323
1324         if(check_appear && Monster_Appear_Check(this, mon_id)) { return true; } // return true so the monster isn't removed
1325
1326         if(!this.monster_skill)
1327                 this.monster_skill = cvar("g_monsters_skill");
1328
1329         // support for quake style removing monsters based on skill
1330         if(this.monster_skill == MONSTER_SKILL_EASY) if(this.spawnflags & MONSTERSKILL_NOTEASY) { Monster_Remove(this); return false; }
1331         if(this.monster_skill == MONSTER_SKILL_MEDIUM) if(this.spawnflags & MONSTERSKILL_NOTMEDIUM) { Monster_Remove(this); return false; }
1332         if(this.monster_skill == MONSTER_SKILL_HARD) if(this.spawnflags & MONSTERSKILL_NOTHARD) { Monster_Remove(this); return false; }
1333
1334         if(this.team && !teamplay)
1335                 this.team = 0;
1336
1337         if(!(this.spawnflags & MONSTERFLAG_SPAWNED)) // naturally spawned monster
1338         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED)) // don't count re-spawning monsters either
1339                 monsters_total += 1;
1340
1341         if(this.mdl && this.mdl != "")
1342                 _setmodel(this, this.mdl);
1343         else
1344                 setmodel(this, mon.m_model);
1345
1346         if(!this.monster_name || this.monster_name == "")
1347                 this.monster_name = mon.monster_name;
1348
1349         this.flags                              = FL_MONSTER;
1350         this.classname                  = "monster";
1351         this.takedamage                 = DAMAGE_AIM;
1352         if(!this.bot_attack)
1353                 IL_PUSH(g_bot_targets, this);
1354         this.bot_attack                 = true;
1355         this.iscreature                 = true;
1356         this.teleportable               = true;
1357         if(!this.damagedbycontents)
1358                 IL_PUSH(g_damagedbycontents, this);
1359         this.damagedbycontents  = true;
1360         this.monsterid                  = mon_id;
1361         this.event_damage               = Monster_Damage;
1362         this.event_heal                 = Monster_Heal;
1363         settouch(this, Monster_Touch);
1364         this.use                                = Monster_Use;
1365         this.solid                              = SOLID_BBOX;
1366         set_movetype(this, MOVETYPE_WALK);
1367         this.spawnshieldtime    = time + autocvar_g_monsters_spawnshieldtime;
1368         this.enemy                              = NULL;
1369         this.velocity                   = '0 0 0';
1370         this.moveto                             = this.origin;
1371         this.pos1                               = this.origin;
1372         this.pos2                               = this.angles;
1373         this.reset                              = Monster_Reset;
1374         this.netname                    = mon.netname;
1375         this.monster_attackfunc = mon.monster_attackfunc;
1376         this.candrop                    = true;
1377         this.oldtarget2                 = this.target2;
1378         this.deadflag                   = DEAD_NO;
1379         this.spawn_time                 = time;
1380         this.gravity                    = 1;
1381         this.monster_moveto             = '0 0 0';
1382         this.monster_face               = '0 0 0';
1383         this.dphitcontentsmask  = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_BOTCLIP | DPCONTENTS_MONSTERCLIP;
1384
1385         if(!this.noalign) { this.noalign = ((mon.spawnflags & MONSTER_TYPE_FLY) || (mon.spawnflags & MONSTER_TYPE_SWIM)); }
1386         if(!this.scale) { this.scale = 1; }
1387         if(autocvar_g_monsters_edit) { this.grab = 1; }
1388         if(autocvar_g_fullbrightplayers) { this.effects |= EF_FULLBRIGHT; }
1389         if(autocvar_g_nodepthtestplayers) { this.effects |= EF_NODEPTHTEST; }
1390         if(mon.spawnflags & MONSTER_TYPE_SWIM) { this.flags |= FL_SWIM; }
1391
1392         if(autocvar_g_monsters_playerclip_collisions)
1393                 this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
1394
1395         if(mon.spawnflags & MONSTER_TYPE_FLY)
1396         {
1397                 this.flags |= FL_FLY;
1398                 set_movetype(this, MOVETYPE_FLY);
1399         }
1400
1401         if((mon.spawnflags & MONSTER_SIZE_QUAKE) && autocvar_g_monsters_quake_resize && !(this.spawnflags & MONSTERFLAG_RESPAWNED))
1402                 this.scale *= 1.3;
1403
1404         setsize(this, mon.m_mins * this.scale, mon.m_maxs * this.scale);
1405         this.view_ofs                   = '0 0 0.7' * (this.maxs_z * 0.5);
1406
1407         this.ticrate = bound(sys_frametime, ((!this.ticrate) ? autocvar_g_monsters_think_delay : this.ticrate), 60);
1408
1409         Monster_UpdateModel(this);
1410
1411         if(!Monster_Spawn_Setup(this))
1412         {
1413                 Monster_Remove(this);
1414                 return false;
1415         }
1416
1417         if(!this.noalign)
1418         {
1419                 setorigin(this, this.origin + '0 0 20');
1420                 tracebox(this.origin + '0 0 64', this.mins, this.maxs, this.origin - '0 0 10000', MOVE_WORLDONLY, this);
1421                 setorigin(this, trace_endpos);
1422         }
1423
1424         if(!(this.spawnflags & MONSTERFLAG_RESPAWNED))
1425                 monster_setupcolors(this);
1426
1427         CSQCMODEL_AUTOINIT(this);
1428
1429         return true;
1430 }