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