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