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