Debian Codegraph @

src/deprecated_units/castlecreatures.pas

raw
1 {
2 Copyright 2006-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Creatures. }
17 unit CastleCreatures
18 deprecated 'express creature AI as TCastleBehavior';
19
20 {$I castleconf.inc}
21
22 interface
23
24 {$warnings off} // using deprecated CastleResources in deprecated
25 uses Classes, Generics.Collections,
26 CastleVectors, CastleBoxes, CastleClassUtils, CastleUtils, CastleScene,
27 CastleStringUtils, CastleResources, CastleXMLConfig, CastleTransform,
28 CastleTransformExtra, CastleSoundEngine, CastleFrustum, X3DNodes, CastleColors,
29 CastleDebugTransform, CastleSectors, CastleBehaviors;
30 {$warnings on}
31
32 type
33 TCreatureState = type Integer;
34
35 const
36 csIdle = TCreatureState(0);
37 csWalk = TCreatureState(1);
38 csAttack = TCreatureState(2);
39 csFireMissile = TCreatureState(3);
40 csDie = TCreatureState(4);
41 csDieBack = TCreatureState(5);
42 csHurt = TCreatureState(6);
43 { Maximum TCreatureState value reserved by CastleCreatures unit. }
44 csMax = csHurt;
45
46 type
47 TCreature = class;
48
49 TCreatureClass = class of TCreature;
50
51 { Basic abstract resource used by all creatures.
52 Basic creature can walk or fly, has life and can be hurt,
53 can fall down because of gravity and such.
54
55 A "resource" is an information shared by all creatures of given type,
56 for example you can have two instances of TCreatureResource: Werewolf
57 and Knight. Actually, they would have to be instances of one of
58 the TCreatureResource descendants, like TWalkAttackCreatureResource,
59 as TCreatureResource is abstract. Using them you can create and place
60 on your your level milions of actual werewolves and knights
61 (for example instances of TWalkAttackCreature).
62 Every werewolf on the level will have potentially different life and
63 state (attacking, walking), but all werewolves will share the same
64 resource, so e.g. all werewolves will use the same dying animation
65 (TWalkAttackCreatureResource.DieAnimation) and dying sound
66 (TCreatureResource.SoundDie).
67
68 Note that some of the information stored in resource
69 is only used to initialize new creatures and can be changed later
70 during creature life, for example TCreatureResource.DefaultMaxLife
71 and TCreatureResource.Flying. }
72 TCreatureResource = class(T3DResource)
73 strict private
74 FFlying: boolean;
75 FSoundSuddenPain: TCastleSound;
76 FSoundDie: TCastleSound;
77 FSoundDieTiedToCreature: boolean;
78 FDefaultMaxLife: Single;
79 FKnockBackDistance: Single;
80 FKnockBackSpeed: Single;
81 FCollidesWhenDead: boolean;
82 FScaleMin, FScaleMax: Single;
83
84 FRadiusOverride: Single;
85
86 FAttackDamageConst: Single;
87 FAttackDamageRandom: Single;
88 FAttackKnockbackDistance: Single;
89
90 FFallMinHeightToSound: Single;
91 FFallMinHeightToDamage: Single;
92 FFallDamageScaleMin: Single;
93 FFallDamageScaleMax: Single;
94 FFallSound: TCastleSound;
95
96 FMiddleHeight: Single;
97 protected
98 { Sphere radius for collision detection for alive creatures.
99 Must be something <> 0 for collision detection to work.
100 Defining it in the creature resource.xml file
101 (as radius="xxx" attribute on the root <resource> element)
102 overrides the results of this function. }
103 function RadiusCalculate(const GravityUp: TVector3): Single; virtual;
104
105 { Can the "up" vector be skewed, that is: not equal to gravity up vector.
106 This is used when creating creature in CreateCreature.
107 The default implementation here returns @true,
108 which allows creature model to point slightly upward/downward.
109
110 Override this to return @false if given creature kind for some reason cannot
111 have up vector different. For example, TWalkAttackCreature AI
112 assumes that the non-flying creature is always standing up.
113 For now, non-flying TWalkAttackCreature cannot "stand up" before walking,
114 in case it's up vector gets skewed. }
115 function FlexibleUp: boolean; virtual;
116 public
117 const
118 { Default value for TCreatureResource.DefaultMaxLife.
119 Yes, it's not a typo, this identifier starts with "DefaultDefault". }
120 DefaultDefaultMaxLife = 100.0;
121 DefaultFlying = false;
122 DefaultKnockBackDistance = 4.0;
123 DefaultSoundDieTiedToCreature = true;
124 DefaultAttackDamageConst = 0.0;
125 DefaultAttackDamageRandom = 0.0;
126 DefaultAttackKnockbackDistance = 0.0;
127 DefaultFallMinHeightToSound = 1.0;
128 DefaultFallSoundName = 'creature_fall';
129
130 constructor Create(AOwner: TComponent); override;
131
132 { Flying creatures are not affected by gravity and
133 (in case of TWalkAttackCreatureResource) their move direction is free.
134
135 For all creatures, TCreature.Gravity (inherited from TCastleTransform.Gravity)
136 is set to @code("not Flying") at creation. (Except TMissileCreatureResource,
137 that has special approach to gravity,
138 see TMissileCreatureResource.DirectionFallSpeed.)
139
140 For TWalkAttackCreatureResource, additionally Flying allows to move
141 freely, while non-flying creatures are constrained to move
142 (and think about moving) only horizontally.
143
144 You can always change the Gravity property of a particular creature
145 during it's lifetime, so a creature may start/stop flying during game.
146 For example, this is how you can let your creatures to use jetpack and such.
147 Be careful about creature @link(Radius) and @link(MiddleHeight) properties
148 in this case, make sure that the values (explicitly set or automatically
149 calculated) are suitable for both flying and non-flying states. }
150 property Flying: boolean read FFlying write FFlying default DefaultFlying;
151
152 property SoundSuddenPain: TCastleSound
153 read FSoundSuddenPain write FSoundSuddenPain;
154
155 property SoundDie: TCastleSound
156 read FSoundDie write FSoundDie;
157
158 { See TCreature.Sound3d TiedToCreature parameter docs.
159 You can set this to false if you want SoundDie to last even
160 after the creature object was destroyed. }
161 property SoundDieTiedToCreature: boolean
162 read FSoundDieTiedToCreature write FSoundDieTiedToCreature
163 default DefaultSoundDieTiedToCreature;
164
165 { The default MaxLife for creatures of this resource.
166
167 Note that you can always override it for a particular creature
168 instance. You can use a special creature placeholder with
169 a specific starting life value
170 (see TLevel.Load for placeholders docs,
171 and see https://castle-engine.io/manual_high_level_3d_classes.php
172 about the creature placeholders).
173 Or you can use CreateCreature overloaded version that takes extra MaxLife
174 parameter.
175
176 So this is only a "suggested" default for MaxLife of this creature. }
177 property DefaultMaxLife: Single
178 read FDefaultMaxLife write FDefaultMaxLife {$ifdef FPC}default DefaultDefaultMaxLife{$endif};
179
180 { Create the TCreature instance using this resource.
181 Uses TCreature descendant that can best cooperate with this resource,
182 e.g. if this resource has settings for short-range fight,
183 then the TCreature instance will be able to short-range fight.
184
185 The creature is added to the World, and is owned by World.
186
187 This is the only way to create TCreature instances.
188
189 ADirection passed here is normalized, and then used
190 as initial TCreature.Direction value.
191
192 @groupBegin }
193 function CreateCreature(
194 const ALevel: TAbstractLevel;
195 const APosition, ADirection: TVector3;
196 const MaxLife: Single): TCreature; overload; virtual;
197 function CreateCreature(
198 const ALevel: TAbstractLevel;
199 const APosition, ADirection: TVector3): TCreature; overload;
200 { @groupEnd }
201
202 { Instantiate creature placeholder, by calling CreateCreature. }
203 procedure InstantiatePlaceholder(
204 const ALevel: TAbstractLevel;
205 const APosition, ADirection: TVector3;
206 const NumberPresent: boolean; const Number: Int64); override;
207
208 function CreatureClass: TCreatureClass; virtual; abstract;
209
210 procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
211
212 { Distance this creature is knocked back when hurt (should reflect
213 the creature weight, how easy it is to push this creature).
214
215 Will always be multiplied by the knocking distance of the weapon that
216 caused the push (which should reflect the force of the weapon blow),
217 see TItemWeaponResource.AttackKnockbackDistance.
218
219 Only for TWalkAttackCreature, the final distance the creature
220 is knocked back is capped
221 by the time of the HurtAnimation (HurtAnimation.Duration).
222 When the hurt animation ends, the knockback effect always ends,
223 even if the distance (creature * weapon) indicates it should be knocked
224 further. Otherwise knockback would work on standing creature,
225 which could look bad. This may be changed some day. }
226 property KnockBackDistance: Single
227 read FKnockBackDistance write FKnockBackDistance
228 {$ifdef FPC}default DefaultKnockBackDistance{$endif};
229
230 { See TCastleAlive.KnockBackSpeed. }
231 {$warnings off} // using deprecated in deprecated
232 property KnockBackSpeed: Single
233 read FKnockBackSpeed write FKnockBackSpeed
234 {$ifdef FPC}default TCastleAlive.DefaultKnockBackSpeed{$endif};
235 {$warnings on}
236
237 { By default dead creatures (corpses) don't collide, this usually looks better. }
238 property CollidesWhenDead: boolean
239 read FCollidesWhenDead write FCollidesWhenDead default false;
240
241 { Minimum scale when spawning, must be <= ScaleMax.
242 When we spawn a creature, we set it's scale to random number in
243 [ScaleMin, ScaleMax] range. By default both ScaleMin and ScaleMax are 1,
244 resulting in no scaling. }
245 property ScaleMin: Single read FScaleMin write FScaleMin {$ifdef FPC}default 1{$endif};
246
247 { Maximum scale when spawning, must be >= ScaleMin.
248 When we spawn a creature, we set it's scale to random number in
249 [ScaleMin, ScaleMax] range. By default both ScaleMin and ScaleMax are 1,
250 resulting in no scaling. }
251 property ScaleMax: Single read FScaleMax write FScaleMax {$ifdef FPC}default 1{$endif};
252
253 { Attack damage.
254 Used by the creatures that actually do some kind of direct attack.
255 For example it is used for short-range attack by TWalkAttackCreatureResource
256 (if TWalkAttackCreatureResource.AttackAnimation defined)
257 and for hit of TMissileCreatureResource.
258
259 The damage dealt is a random float in the range
260 [AttackDamageConst, AttackDamageConst + AttackDamageRandom].
261
262 Both AttackDamageConst and AttackDamageRandom must be >= 0.
263
264 @groupBegin }
265 property AttackDamageConst: Single
266 read FAttackDamageConst write FAttackDamageConst
267 {$ifdef FPC}default DefaultAttackDamageConst{$endif};
268
269 { Attack damage, see @link(AttackDamageConst) for documentation. }
270 property AttackDamageRandom: Single
271 read FAttackDamageRandom write FAttackDamageRandom
272 {$ifdef FPC}default DefaultAttackDamageRandom{$endif};
273 { @groupEnd }
274
275 { Attack knockback (how far will the victim be pushed back).
276 Used by the creatures that actually do some kind of direct attack.
277 For example it is used for short-range attack by TWalkAttackCreatureResource
278 (if TWalkAttackCreatureResource.AttackAnimation defined)
279 and for hit of TMissileCreatureResource.
280
281 Must be >= 0. Value equal exactly 0 disables any knockback. }
282 property AttackKnockbackDistance: Single
283 read FAttackKnockbackDistance write FAttackKnockbackDistance
284 {$ifdef FPC}default DefaultAttackKnockbackDistance{$endif};
285
286 { Height of the eyes of the creature,
287 used for various collision detection routines.
288 See TCastleTransform.MiddleHeight for a precise documentation.
289
290 Game developers can use the RenderDebug variable to easily
291 visualize the bounding sphere (and other things) around resources.
292 The bounding sphere is centered around the point derived from MiddleHeight
293 setting and with given creature radius
294 (given in resource.xml, or automatically calculated by
295 @link(TCreatureResource.RadiusCalculate)). }
296 property MiddleHeight: Single
297 read FMiddleHeight write FMiddleHeight
298 {$ifdef FPC}default TCastleTransform.DefaultMiddleHeight{$endif};
299
300 { When creature is falling down, it needs to fall at least the given distance
301 to make a "hurt" sound. }
302 property FallMinHeightToSound: Single
303 read FFallMinHeightToSound write FFallMinHeightToSound
304 {$ifdef FPC}default DefaultFallMinHeightToSound{$endif};
305
306 { When creature is falling down, it needs to fall at least the given distance
307 to get some damage from the fall.
308 The amount of damage is determined by @link(FallDamageScaleMin),
309 @link(FallDamageScaleMax). }
310 property FallMinHeightToDamage: Single
311 read FFallMinHeightToDamage write FFallMinHeightToDamage
312 {$ifdef FPC}default DefaultFallMinHeightToDamage{$endif};
313
314 { When creature is falling down (at least for @link(FallMinHeightToDamage) distance),
315 it will take a random damage in range [FallDamageScaleMin, FallDamageScaleMax]. }
316 property FallDamageScaleMin: Single
317 read FFallDamageScaleMin write FFallDamageScaleMin
318 {$ifdef FPC}default DefaultFallDamageScaleMin{$endif};
319
320 { When creature is falling down (at least for @link(FallMinHeightToDamage) distance),
321 it will take a random damage in range [FallDamageScaleMin, FallDamageScaleMax]. }
322 property FallDamageScaleMax: Single
323 read FFallDamageScaleMax write FFallDamageScaleMax
324 {$ifdef FPC}default DefaultFallDamageScaleMax{$endif};
325
326 { Sound when falling.
327 The default is the sound named 'creature_fall'. }
328 property FallSound: TCastleSound
329 read FFallSound write FFallSound;
330
331 { Radius used for resolving (some) collisions with the alive creature.
332 This can be read from the @code(resource.xml) file.
333 When zero, the radius is automatically calculated looking at the
334 3D model bounding box, and taking into account gravity direction,
335 see @link(TCreatureResource.RadiusCalculate). }
336 property RadiusOverride: Single
337 read FRadiusOverride write FRadiusOverride;
338
339 { Sphere radius for collision detection for alive creatures.
340 Must be something <> 0 for collision detection to work.
341
342 You can define it in the creature resource.xml file,
343 by setting radius="xxx" attribute on the root <resource> element.
344
345 If it's not defined (or zero) in resource.xml file,
346 then we use automatically calculated radius using RadiusCalculate,
347 that is adjusted to the bounding box of the animation.
348
349 This radius is used only for alive creatures, because:
350
351 @unorderedList(
352 @item(It would cause incorrect results on many dead creatures.
353 Dead creatures usually have very different boxes than alive
354 (tall alive humanoid creature probably has a small flat bounding
355 box when it's lying dead on the ground). So the same radius would not work
356 nicely.)
357
358 @item(It is not necessary to use sphere bounding volumes for dead creatures.
359 The main advantage of sphere bounding volumes (over box bounding volumes)
360 is for moving (alive) creatures:
361 sphere better avoids getting stuck into obstacles (because an animation
362 can change the bounding box at any moment).)
363
364 @item(Actually, the results look best when dead creatures don't collide at all.)
365 )
366
367 The sphere center is the Middle point ("eye position") of the given creature.
368 If the creature may be affected by gravity then
369 make sure radius is < than PreferredHeight of the creature,
370 see TCastleTransform.PreferredHeight, otherwise creature may get stuck into ground.
371 In short, if you use the default implementations,
372 PreferredHeight is by default @italic(MiddleHeight (default 0.5) *
373 bounding box height). Your radius must be smaller
374 for all possible bounding box heights when the creature is not dead. }
375 function Radius(const GravityUp: TVector3): Single;
376 end;
377
378 { Creature with smart walking and attacking intelligence.
379 May stand still (idle), walk, attack, fire missiles, and die.
380
381 Tracks the enemy (remembers last seen enemy 3D position,
382 walks/flies to it, possibly through sectors/waypoints ---
383 so it can pass through narrow doors in a labyrinth or walk over a narrow bridge).
384 Attacks the enemy from the right distance (a short-range attack)
385 and/or shoots a missile (adds a missile to the 3D world).
386 Runs away from the enemy (when he's too close and/or our health is low).
387
388 There are a lot of settings to achieve particular behavior,
389 e.g. cowardly/brave, offensive/defensive, melee/ranged, etc. }
390 TWalkAttackCreatureResource = class(TCreatureResource)
391 private
392 FIdleAnimation: T3DResourceAnimation;
393 FIdleToWalkAnimation: T3DResourceAnimation;
394 FWalkAnimation: T3DResourceAnimation;
395 FAttackAnimation: T3DResourceAnimation;
396 FFireMissileAnimation: T3DResourceAnimation;
397 FDieAnimation: T3DResourceAnimation;
398 FDieBackAnimation: T3DResourceAnimation;
399 FHurtAnimation: T3DResourceAnimation;
400
401 FMoveSpeed: Single;
402 FMinLifeLossToHurt: Single;
403 FChanceToHurt: Single;
404 FMaxHeightAcceptableToFall: Single;
405 FRandomWalkDistance: Single;
406 FRemoveDead: boolean;
407 FPreferredDistance: Single;
408 FRunAwayLife: Single;
409 FRunAwayDistance: Single;
410 FVisibilityAngle: Single;
411 FSmellDistance: Single;
412 FAttackMinDelay: Single;
413 FAttackMaxDistance: Single;
414 FAttackMaxAngle: Single;
415 FAttackTime: Single;
416 FAttackSoundHit: TCastleSound;
417 FAttackSoundStart: TCastleSound;
418 FFireMissileTime: Single;
419 FFireMissileMinDelay: Single;
420 FFireMissileMaxDistance: Single;
421 FFireMissileMaxAngle: Single;
422 FFireMissileName: string;
423 FFireMissileHeight: Single;
424 FFireMissileSound: TCastleSound;
425 protected
426 function FlexibleUp: boolean; override;
427 public
428 const
429 DefaultMoveSpeed = 10.0;
430 DefaultMinLifeLossToHurt = 0.0;
431 DefaultChanceToHurt = 1.0;
432 DefaultMaxHeightAcceptableToFall = 1.5;
433 DefaultRandomWalkDistance = 10.0;
434 DefaultRemoveDead = false;
435 DefaultPreferredDistance = 2.0;
436 DefaultRunAwayLife = 0.3;
437 DefaultRunAwayDistance = 10.0;
438 DefaultVisibilityAngle = Pi * 120 / 180;
439 DefaultSmellDistance = 0.0;
440
441 DefaultAttackTime = 0.0;
442 DefaultAttackMinDelay = 2.0;
443 DefaultAttackMaxDistance = DefaultPreferredDistance;
444 DefaultAttackMaxAngle = Pi / 6;
445
446 DefaultFireMissileTime = 0.0;
447 DefaultFireMissileMinDelay = DefaultAttackMinDelay;
448 DefaultFireMissileMaxDistance = 30.0;
449 DefaultFireMissileMaxAngle = DefaultAttackMaxAngle;
450 DefaultFireMissileHeight = 0.5;
451
452 constructor Create(AOwner: TComponent); override;
453 procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
454 function CreatureClass: TCreatureClass; override;
455
456 { An animation of standing still (being idle).
457 Will be played in a loop, so for best look make sure that
458 the beginning and end match. }
459 property IdleAnimation: T3DResourceAnimation read FIdleAnimation;
460
461 { An animation when creature changes from standing still to walking.
462 Optional.
463
464 For best look: It's beginnig should glue with the end of IdleAnimation,
465 it's ending should glue with beginning of WalkAnimation. }
466 property IdleToWalkAnimation: T3DResourceAnimation read FIdleToWalkAnimation;
467
468 { An animation of walking.
469 Will be played in a loop, so for best look make sure that
470 the beginning and end match. }
471 property WalkAnimation: T3DResourceAnimation read FWalkAnimation;
472
473 { An animation of short-range attacking. Optional.
474
475 For best look: Beginning and end of it should roughly glue with (any)
476 frame of WalkAnimation and IdleAnimation.
477
478 @italic(Design notes:)
479 I used to have here property like AttacksWhenWalking for the creature,
480 to indicate whether creature changes state like
481 "csWalk -> csAttack -> csWalk" or
482 "csIdle -> csAttack -> csIdle". But this wasn't good.
483 Intelligent creature sometimes attacks when walking (e.g. if it just
484 made the distance to the enemy closer) or when standing
485 (when the distance was already close enough). And after performing
486 the attack, the creature doesn't need to go back to the original state
487 before the attack. }
488 property AttackAnimation: T3DResourceAnimation read FAttackAnimation;
489
490 { Firing missile animation. Optional. Similar rules like AttackAnimation,
491 but here the "highlight" is not directly hurting enemy,
492 but firing a new creature (missile).
493
494 You can always override TWalkAttackCreature.FireMissile to do pretty
495 much anything you want, and this way treat this as an "alternate attack",
496 not necessarily firing a missile.
497 It's not really required to actually fire a missile --- it's only what
498 happens at the default TWalkAttackCreature.FireMissile implementation,
499 and it happens only if FireMissileName is not empty. }
500 property FireMissileAnimation: T3DResourceAnimation read FFireMissileAnimation;
501
502 { An animation of dying.
503
504 Dying animation is not displayed in a loop, after it runs
505 it's duration we constantly show the final frame,
506 at the TCreature instance will keep existing on the level.
507 Unless you set RemoveDead to @true, then the dead creature
508 will be completely removed from the level.
509
510 For best look: Beginning should roughly glue with any point of
511 the idle/attack/walk animations. }
512 property DieAnimation: T3DResourceAnimation read FDieAnimation;
513
514 { An optional dying animation, used when the creature is killed
515 by hitting it in the back. This may be useful if you want your
516 creature to fall face-down when killed from the back or face-up
517 when killed from the front. If this is defined, then DieAnimation
518 is only used when creature is killed by hitting it from the front.
519 The direction of last hit is taken from LastHurtDirection.
520
521 For best look: Just like DieAnimation, beginning should roughly
522 glue with any point of the idle/attack/walk animations. }
523 property DieBackAnimation: T3DResourceAnimation read FDieBackAnimation;
524
525 { Animation when the creature will be hurt.
526 Beginning and end should *more-or-less* look like
527 any point of the idle/attack/walk animations. }
528 property HurtAnimation: T3DResourceAnimation read FHurtAnimation;
529
530 { The moving speed: how much Direction vector will be scaled
531 when moving in csWalk. }
532 property MoveSpeed: Single read FMoveSpeed write FMoveSpeed
533 {$ifdef FPC}default DefaultMoveSpeed{$endif};
534
535 { The preferred distance between enemy and the creature.
536 The creature will try to walk closer to the enemy if the distance is larger.
537 (If you want to make the creature to also walk father from the enemy
538 when necessary, then set RunAwayLife and RunAwayDistance.)
539
540 This should be <= AttackMaxDistance or FireMissileMaxDistance,
541 if you hope to actually perform a short-range or firing missile attack.
542 The creature can attack enemy from AttackMaxDistance
543 or fire missile from FireMissileMaxDistance,
544 but it will walk closer to the enemy if possible --- until the distance
545 is PreferredDistance. }
546 property PreferredDistance: Single
547 read FPreferredDistance write FPreferredDistance
548 {$ifdef FPC}default DefaultPreferredDistance{$endif};
549
550 { Minimum delay between one attack and the other, in seconds.
551 Note that the duration of AttackAnimation also limits how often creature
552 can do an attack (so e.g. setting this to 0.0 doesn't mean that creature
553 can constantly attack, if AttackAnimation takes 1 second then at least
554 this 1 second will have to pass between actual attack hits). }
555 property AttackMinDelay: Single
556 read FAttackMinDelay write FAttackMinDelay
557 {$ifdef FPC}default DefaultAttackMinDelay{$endif};
558
559 { Maximum distance between enemy and creature to allow creature
560 to start attack. The distance is measured between
561 enemy (see TWalkAttackCreature.Enemy) and current creature
562 Middle (see @link(TCastleTransform.Middle)) points. }
563 property AttackMaxDistance: Single
564 read FAttackMaxDistance write FAttackMaxDistance
565 {$ifdef FPC}default DefaultAttackMaxDistance{$endif};
566
567 { The time point within AttackAnimation at which the short-range attack
568 happens. When exactly happens depends on the virtual
569 @link(TWalkAttackCreature.Attack) method implementation,
570 in the base TWalkAttackCreature it is a short-range
571 attack. }
572 property AttackTime: Single read FAttackTime write FAttackTime
573 {$ifdef FPC}default DefaultAttackTime{$endif};
574
575 { Since most of the creatures will have their weapon
576 on their front (teeth, shooting hands, claws, whatever),
577 they can attack enemy only when they are facing the enemy.
578
579 More precisely, the attack is allowed to start only when
580 the angle between current creature @link(TCastleTransform.Direction Direction)
581 and the vector from creature's Middle to the enemy's Middle (see TCastleTransform.Middle)
582 is <= AttackMaxAngle.
583
584 This is in radians. }
585 property AttackMaxAngle: Single
586 read FAttackMaxAngle write FAttackMaxAngle
587 {$ifdef FPC}default DefaultAttackMaxAngle{$endif};
588
589 { Sound played when short-range attack hits.
590 None (nil) by default. }
591 property AttackSoundHit: TCastleSound
592 read FAttackSoundHit write FAttackSoundHit;
593
594 { Played at the start of attack animation,
595 that is when entering csAttack state.
596 To play a sound when the actual hit happens (at AttackTime)
597 see AttackSoundHit.
598 None (nil) by default. }
599 property AttackSoundStart: TCastleSound
600 read FAttackSoundStart write FAttackSoundStart;
601
602 { The time (in seconds) since the FireMissileAnimation start when we actually
603 spawn a missile. By default zero, which means that we spawn the missile
604 right when FireMissileAnimation starts.
605 Must be < than the FireMissileAnimation duration, otherwise we will never
606 reach tthis time and missile will never be fired. }
607 property FireMissileTime: Single
608 read FFireMissileTime write FFireMissileTime
609 {$ifdef FPC}default DefaultFireMissileTime{$endif};
610
611 { Minimum delay (in seconds) between firing of the missiles.
612 The missile will not be fired if a previous missile was fired within last
613 FireMissileMinDelay seconds.
614 (Even if all other conditions for firing the missile are satisfied.) }
615 property FireMissileMinDelay: Single
616 read FFireMissileMinDelay write FFireMissileMinDelay
617 {$ifdef FPC}default DefaultFireMissileMinDelay{$endif};
618
619 { Maximum distance to the enemy to make firing missiles sensible.
620 The creature will only fire the missile if enemy is within this distance.
621 The creature will also try to shorten distance to the enemy,
622 to get within this distance. }
623 property FireMissileMaxDistance: Single
624 read FFireMissileMaxDistance write FFireMissileMaxDistance
625 {$ifdef FPC}default DefaultFireMissileMaxDistance{$endif};
626
627 { Maximum angle (in radians) between current direction and
628 the direction toward enemy to make firing missiles sensible.
629 The creature will only fire the missile if enemy is within a cone of this angle. }
630 property FireMissileMaxAngle: Single
631 read FFireMissileMaxAngle write FFireMissileMaxAngle
632 {$ifdef FPC}default DefaultFireMissileMaxAngle{$endif};
633
634 { Name of the creature to fire as missile, at AttackTime during AttackAnimation.
635 Leave empty to not fire any missile. }
636 property FireMissileName: string
637 read FFireMissileName write FFireMissileName;
638
639 { Height (between Position and Middle, usually: legs and eyes)
640 of the fired missile (see FireMissileName). }
641 property FireMissileHeight: Single
642 read FFireMissileHeight write FFireMissileHeight
643 {$ifdef FPC}default DefaultFireMissileHeight{$endif};
644
645 { Sound played when missile is fired, see FireMissileName.
646 None (nil) by default. }
647 property FireMissileSound: TCastleSound
648 read FFireMissileSound write FFireMissileSound;
649
650 { Portion of life and distance when the creature decides it's best to run away
651 from the enemy. RunAwayLife is expressed as a fraction of MaxLife.
652 We run if our @code(Life <= MaxLife * RunAwayLife) and the distance
653 to the (last seen) enemy is < RunAwayDistance.
654 Set RunAwayLife = 1 to make the creature always try to keep a safe distance
655 from the enemy.
656 @groupBegin }
657 property RunAwayLife: Single
658 read FRunAwayLife write FRunAwayLife {$ifdef FPC}default DefaultRunAwayLife{$endif};
659 property RunAwayDistance: Single
660 read FRunAwayDistance write FRunAwayDistance
661 {$ifdef FPC}default DefaultRunAwayDistance{$endif};
662 { @groupEnd }
663
664 { Creature sees other things (like enemies) only within a cone
665 of this angle. This way, the creature only looks forward, and you can
666 sneak upon a creature from the back. Simply set this to >= 2 * Pi
667 to remove this limit.
668
669 Note that the creature also becomes aware of the enemy when it is
670 hurt by a direct attack, regardless of VisibilityAngle. This way
671 if you sneak and attack a creature from the back, it will turn around
672 and fight you.
673
674 Creature can also smell others, see SmellDistance. }
675 property VisibilityAngle: Single read FVisibilityAngle write FVisibilityAngle
676 {$ifdef FPC}default DefaultVisibilityAngle{$endif};
677
678 { Creature smells other things (like enemies) within a sphere of this
679 radius. This allows to detect enemy regardless of which direction
680 the creature is facing, regardless of whether there is a line of sight
681 to the enemy, regardless if enemy is moving.
682
683 This is quite powerful ability to detect enemies,
684 if you set this to something large (by default it's zero).
685 Detecting enemies allows to more accurately/faster attack them
686 and/or run away from them.
687
688 Note: If you want the creature to nicely run from behind the corner,
689 be sure to setup good sectors/waypoints in your level.}
690 property SmellDistance: Single read FSmellDistance write FSmellDistance
691 {$ifdef FPC}default DefaultSmellDistance{$endif};
692
693 { When creature is wounded for more than MaxLife * MinLifeLossToHurt
694 points and moreover Random < ChanceToHurt then creature will
695 change to csHurt state and be knocked back.
696 Changing to csHurt state means that any other state will be
697 interrupted (e.g. enemy can interrupt
698 creature's attack this way if AttackTime > 0).
699
700 It's expected that "tougher" creatures will have MinLifeLossToHurt
701 somewhat higher than DefaultMinLifeLossToHurt and ChanceToHurt
702 significantly lower than DefaultChanceToHurt. }
703 property MinLifeLossToHurt: Single
704 read FMinLifeLossToHurt write FMinLifeLossToHurt
705 {$ifdef FPC}default DefaultMinLifeLossToHurt{$endif};
706
707 { See MinLifeLossToHurt. }
708 property ChanceToHurt: Single
709 read FChanceToHurt write FChanceToHurt
710 {$ifdef FPC}default DefaultChanceToHurt{$endif};
711
712 property MaxHeightAcceptableToFall: Single
713 read FMaxHeightAcceptableToFall
714 write FMaxHeightAcceptableToFall
715 {$ifdef FPC}default DefaultMaxHeightAcceptableToFall{$endif};
716
717 property RandomWalkDistance: Single
718 read FRandomWalkDistance
719 write FRandomWalkDistance
720 {$ifdef FPC}default DefaultRandomWalkDistance{$endif};
721
722 property RemoveDead: boolean
723 read FRemoveDead write FRemoveDead default DefaultRemoveDead;
724 end;
725
726 { Creature that blindly moves in a given direction.
727 It just moves into the given direction
728 (with some possible twists, e.g. it can be a "homing"
729 missile and/or be dragged down by gravity).
730 On collision, it hits, potentially hurting the alive 3D object
731 that was colliding (player or other creatures).
732
733 Missiles ignore TCreatureResource.Flying, they use their own way to handle
734 gravity with DirectionFallSpeed. }
735 TMissileCreatureResource = class(TCreatureResource)
736 private
737 FFlyAnimation: T3DResourceAnimation;
738 FDieAnimation: T3DResourceAnimation;
739 FMoveSpeed: Single;
740 FSoundHit: TCastleSound;
741 FCloseDirectionToTargetSpeed: Single;
742 FPauseBetweenSoundIdle: Single;
743 FSoundIdle: TCastleSound;
744 FHitsPlayer: boolean;
745 FHitsCreatures: boolean;
746 FDirectionFallSpeed: Single;
747 FRemoveDead: boolean;
748 protected
749 function RadiusCalculate(const GravityUp: TVector3): Single; override;
750 public
751 const
752 DefaultMoveSpeed = 10.0;
753 DefaultCloseDirectionToTargetSpeed = 0.0;
754 DefaultPauseBetweenSoundIdle = 2.0;
755 DefaultHitsPlayer = true;
756 DefaultHitsCreatures = false;
757 DefaultDirectionFallSpeed = 0.0;
758 DefaultRemoveDead = true;
759
760 constructor Create(AOwner: TComponent); override;
761 function CreatureClass: TCreatureClass; override;
762 procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
763 function CreateCreature(
764 const ALevel: TAbstractLevel;
765 const APosition, ADirection: TVector3;
766 const MaxLife: Single): TCreature; override;
767
768 property FlyAnimation: T3DResourceAnimation read FFlyAnimation;
769
770 { Die (destroying) animation of a missile. Optional.
771 It can depict missile explosion.
772 After showing this animation (or immediately when missile hits something,
773 if this animation is not specified) the missile is removed from the level
774 (unless RemoveDead = @false). }
775 property DieAnimation: T3DResourceAnimation read FDieAnimation;
776
777 { The moving speed: how much Direction vector will be scaled
778 when moving. }
779 property MoveSpeed: Single read FMoveSpeed write FMoveSpeed
780 {$ifdef FPC}default DefaultMoveSpeed{$endif};
781
782 { Sound when missile hits anything.
783 None (nil) by default. }
784 property SoundHit: TCastleSound
785 read FSoundHit write FSoundHit;
786
787 { For "homing" missiles, how fast direction to the target is corrected.
788 Zero (default) means that the missile is not "homing". }
789 property CloseDirectionToTargetSpeed: Single
790 read FCloseDirectionToTargetSpeed
791 write FCloseDirectionToTargetSpeed
792 {$ifdef FPC}default DefaultCloseDirectionToTargetSpeed{$endif};
793
794 { Sound played continuously when the missile is going.
795 None (nil) by default.
796 @seealso PauseBetweenSoundIdle }
797 property SoundIdle: TCastleSound
798 read FSoundIdle write FSoundIdle;
799
800 { This should be synchonized with length of SoundIdle sound. }
801 property PauseBetweenSoundIdle: Single
802 read FPauseBetweenSoundIdle write FPauseBetweenSoundIdle
803 {$ifdef FPC}default DefaultPauseBetweenSoundIdle{$endif};
804
805 property HitsPlayer: boolean
806 read FHitsPlayer write FHitsPlayer default DefaultHitsPlayer;
807 property HitsCreatures: boolean
808 read FHitsCreatures write FHitsCreatures default DefaultHitsCreatures;
809
810 { How fast is the missile pulled down by gravity.
811 Non-zero value causes missile direction to gradually point
812 downward, this way missile flies downward eventually.
813
814 This is quite different (in different units and with slightly different
815 effect) than TCastleTransform.FallSpeed, hence a different name and property.
816 TMissileCreatureResource doesn't use TCastleTransform.Gravity and so ignores
817 T3DResource.FallSpeed, T3DResource.GrowSpeed and other properties.
818
819 0 means to not fall down (missile is not affected by gravity). }
820 property DirectionFallSpeed: Single
821 read FDirectionFallSpeed write FDirectionFallSpeed
822 {$ifdef FPC}default DefaultDirectionFallSpeed{$endif};
823
824 { Should the dead (destroyed) missiles be removed from level.
825 Useful if you want to see arrows stuck into walls where they hit.
826
827 This is like TWalkAttackCreatureResource.RemoveDead
828 and TStillCreatureResource.RemoveDead, except for missiles the default is @true.
829 Also, even if you switch this to @false,
830 it's ignored (works like @true) if the missile hit a dynamic
831 object (like another creature or player).
832 It only works when a missile hit something else than a creature/player,
833 which means that it probably hit a static level wall. }
834 property RemoveDead: boolean
835 read FRemoveDead write FRemoveDead default DefaultRemoveDead;
836 end;
837
838 { Creature that just stays still.
839 This is just a single 3D animation showing a creature. }
840 TStillCreatureResource = class(TCreatureResource)
841 private
842 FIdleAnimation: T3DResourceAnimation;
843 FDieAnimation: T3DResourceAnimation;
844 FRemoveDead: boolean;
845 public
846 const
847 DefaultRemoveDead = false;
848
849 constructor Create(AOwner: TComponent); override;
850 function CreatureClass: TCreatureClass; override;
851 procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
852
853 property IdleAnimation: T3DResourceAnimation read FIdleAnimation;
854 property DieAnimation: T3DResourceAnimation read FDieAnimation;
855 property RemoveDead: boolean
856 read FRemoveDead write FRemoveDead default DefaultRemoveDead;
857 end;
858
859 { Base creature, using any TCreatureResource. }
860 TCreature = class(TCastleAlive)
861 private
862 FResource: TCreatureResource;
863 FResourceObserver: TFreeNotificationObserver;
864 FResourceFrame: TResourceFrame;
865
866 SoundSource: TCastleSoundSource;
867 FSoundDieEnabled: boolean;
868
869 FDebugCaptions: TCastleScene;
870 FDebugCaptionsTransform: TMatrixTransformNode;
871 FDebugCaptionsShape: TShapeNode;
872 FDebugCaptionsText: TTextNode;
873 FDebugCaptionsFontStyle: TFontStyleNode;
874
875 FDebugTransform: TDebugTransform;
876
877 { Calculated @link(Radius) suitable for this creature.
878 This is cached result of @link(TCreatureResource.Radius). }
879 FRadius: Single;
880
881 procedure ResourceFreeNotification(const Sender: TFreeNotificationObserver);
882 protected
883 var
884 { Set by CreateCreature. }
885 Level: TAbstractLevel;
886
887 procedure SetLife(const Value: Single); override;
888 procedure Fall(const FallHeight: Single); override;
889
890 { LerpLegsMiddle interpolates between Position and Middle
891 (intuitively, legs and eye positions). }
892 function LerpLegsMiddle(const A: Single): TVector3;
893
894 { Hurt given enemy. HurtEnemy may be @nil, in this case we do nothing. }
895 procedure AttackHurt(const HurtEnemy: TCastleAlive);
896
897 procedure UpdateDebugCaption(const Lines: TCastleStringList); virtual;
898
899 { Sector where the middle of this 3D object is.
900 Used for AI. @nil if none (maybe because we're not part of any world,
901 maybe because sectors of the world were not initialized,
902 or maybe simply because we're outside of all sectors). }
903 function Sector(const OtherTransform: TCastleTransform): TSector; overload;
904 function Sector: TSector; overload;
905 public
906 class var
907 { Render debug bounding boxes and captions at every creature. }
908 RenderDebug: boolean;
909
910 constructor Create(AOwner: TComponent; const AMaxLife: Single); reintroduce; virtual;
911 destructor Destroy; override;
912 function GetCollides: boolean; override;
913
914 property Resource: TCreatureResource read FResource;
915
916 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
917
918 { You can set this to @false to force the creature to die without
919 making any sound. This is really seldom needed, usefull only to avoid
920 a loud shriek noise when you kill many creatures at once.
921 Primarily for use by debug menu "kill all creatures" and similar things. }
922 property SoundDieEnabled: boolean read FSoundDieEnabled
923 write FSoundDieEnabled default true;
924
925 { Play SoundType where the creature's position is.
926
927 Exactly, the position is between Position and Middle
928 --- SoundHeight = 0 means Position, SoundHeight = 1 means Middle,
929 SoundHeight between means ... well, between Position and Middle.
930 This can also be higher than 1 or lower than 0, should be treated like
931 lerp between Position and Middle.
932
933 If TiedToCreature then the sounds position will be updated
934 as the creature will move, and when the creature object will
935 be destroyed, sound will stop. If not TiedToCreature, then
936 the sound will simply be done at creature's position, but then
937 it will continue to be played independent of this creature. }
938 procedure Sound3d(const SoundType: TCastleSound; const SoundHeight: Single;
939 const TiedToCreature: boolean = true);
940
941 { Can the approximate sphere be used for some collision-detection
942 tasks.
943
944 Set to @false in descendants if Resource.Radius
945 is not appropriate for this creature state.
946
947 In this class, this is implemented to return @code(not Dead).
948 This is usually sensible, since only alive creatures need bounding
949 sphere advantages (stairs climbing), and using sphere with dead
950 creatures would unnecessarily force the sphere radius to be small
951 and Middle to be high. }
952 function Sphere(out ARadius: Single): boolean; override;
953
954 { Sphere radius for collision detection for alive creatures.
955 Must be something <> 0 for collision detection to work.
956 @seealso TCreatureResource.Radius }
957 function Radius: Single;
958
959 property CollidesWithMoving default true;
960 end;
961
962 TCreatureList = class({$ifdef FPC}specialize{$endif} TObjectList<TCreature>)
963 end;
964
965 { Creature using TWalkAttackCreatureResource. }
966 TWalkAttackCreature = class(TCreature)
967 private
968 FState: TCreatureState;
969
970 FStateChangeTime: Single;
971
972 { Time of last State change to csAttack or csFireMissile,
973 taken from LifeTime. }
974 LastAttackTime, LastFireMissileTime: Single;
975 { Whether Attack or FireMissile was already called within this
976 csAttack or csFireMissile state. }
977 AttackDone, FireMissileDone: boolean;
978
979 HasAlternativeTarget: boolean;
980 AlternativeTarget: TVector3;
981 { Time of last setting HasAlternativeTarget to true and AlternativeTarget
982 value, taken from LifeTime. Used to not fall into loop
983 when the creature tries to walk to AlternativeTarget, and is not
984 permanently blocked (so MoveCollision returns true all the time)
985 but at the same time the creature can't get close enough to the
986 AlternativeTarget. In such case we use this variable to resign from
987 AlternativeTarget after some time. }
988 AlternativeTargetTime: Single;
989
990 WaypointsSaved_Begin: TSector;
991 WaypointsSaved_End: TSector;
992 WaypointsSaved: TWaypointList;
993 InternalMiddleForceBoxTime: Single;
994
995 FDebugAlternativeTargetAxis: TDebugAxis;
996 FDebugLastSensedEnemyAxis: TDebugAxis;
997 protected
998 { Last known information about enemy. }
999 HasLastSensedEnemy: boolean;
1000 LastSensedEnemy: TVector3;
1001 LastSensedEnemySector: TSector;
1002
1003 procedure SetState(Value: TCreatureState); virtual;
1004 procedure SetLife(const Value: Single); override;
1005 procedure UpdateDebugCaption(const Lines: TCastleStringList); override;
1006
1007 { Enemy of this creature. In this class, this always returns global
1008 World.Player (if it exists and is still alive).
1009 Return @nil for no enemy. }
1010 function Enemy: TCastleAlive; virtual;
1011
1012 { Last State change time, taken from LifeTime. }
1013 property StateChangeTime: Single read FStateChangeTime;
1014
1015 { Actually do the attack indicated by AttackAnimation
1016 and AttackTime and other AttackXxx properties.
1017 This happens in the middle of AttackAnimation, at the time see AttackTime.
1018
1019 This can happen only if you defined AttackAnimation for this creature.
1020
1021 The default implementation here performs a short range attack,
1022 if enemy is still within reach (AttackMaxDistance; even if it was within
1023 reach at the start of csAttack state, the enemy could step back,
1024 so we need to check AttackMaxDistance again).
1025 The damage and knockback are defined by TCreatureResource.AttackDamageConst,
1026 TCreatureResource.AttackDamageRandom, TCreatureResource.AttackKnockbackDistance. }
1027 procedure Attack; virtual;
1028
1029 { Actually do the attack indicated by FireMissileAnimation
1030 and FireMissileTime and other FireMissileXxx properties.
1031 This happens in the middle of FireMissileAnimation, at the time see
1032 FireMissileTime.
1033
1034 This can happen only if you defined FireMissileAnimation for this creature.
1035
1036 The default implementation here creates a new creature with resource
1037 defined by FireMissileName, if FireMissileName is not empty. }
1038 procedure FireMissile; virtual;
1039 public
1040 constructor Create(AOwner: TComponent; const AMaxLife: Single); override;
1041
1042 destructor Destroy; override;
1043
1044 function Resource: TWalkAttackCreatureResource;
1045
1046 property State: TCreatureState read FState default csIdle;
1047
1048 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
1049
1050 procedure Hurt(const LifeLoss: Single; const HurtDirection: TVector3;
1051 const AKnockbackDistance: Single; const Attacker: TCastleAlive); override;
1052 end;
1053
1054 { Creature using TMissileCreatureResource. }
1055 TMissileCreature = class(TCreature)
1056 private
1057 LastSoundIdleTime: Single;
1058 ForceRemoveDead: boolean;
1059 procedure HitCore;
1060 procedure HitPlayer;
1061 procedure HitCreature(Creature: TCreature);
1062 public
1063 constructor Create(AOwner: TComponent; const AMaxLife: Single); override;
1064 function Resource: TMissileCreatureResource;
1065 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
1066 end;
1067
1068 { Creature using TStillCreatureResource. }
1069 TStillCreature = class(TCreature)
1070 public
1071 function Resource: TStillCreatureResource;
1072 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
1073 end;
1074
1075 TCreatureExistsEvent = function(const Creature: TCreature): boolean of object;
1076
1077 var
1078 DebugTimeStopForCreatures: boolean = false;
1079
1080 implementation
1081
1082 {$warnings off} // using deprecated CastleProgress, CastleGameNotifications in deprecated
1083 uses SysUtils, DOM, Math,
1084 CastleFilesUtils, CastleGLUtils,
1085 CastleProgress, CastleGameNotifications, CastleUIControls;
1086 {$warnings on}
1087
1088 { TCreatureResource -------------------------------------------------------------- }
1089
1090 constructor TCreatureResource.Create(AOwner: TComponent);
1091 begin
1092 inherited;
1093 FFlying := DefaultFlying;
1094 FDefaultMaxLife := DefaultDefaultMaxLife;
1095 FKnockBackDistance := DefaultKnockBackDistance;
1096 {$warnings off} // using deprecated in deprecated
1097 FKnockBackSpeed := TCastleAlive.DefaultKnockBackSpeed;
1098 {$warnings on}
1099 FSoundDieTiedToCreature := DefaultSoundDieTiedToCreature;
1100 FAttackDamageConst := DefaultAttackDamageConst;
1101 FAttackDamageRandom := DefaultAttackDamageRandom;
1102 FAttackKnockbackDistance := DefaultAttackKnockbackDistance;
1103 FMiddleHeight := TCastleTransform.DefaultMiddleHeight;
1104 FFallMinHeightToSound := DefaultFallMinHeightToSound;
1105 FFallMinHeightToDamage := DefaultFallMinHeightToDamage;
1106 FFallDamageScaleMin := DefaultFallDamageScaleMin;
1107 FFallDamageScaleMax := DefaultFallDamageScaleMax;
1108 {$warnings off} // using deprecated in deprecated
1109 FFallSound := SoundEngine.SoundFromName(DefaultFallSoundName, false);
1110 {$warnings on}
1111 ScaleMin := 1;
1112 ScaleMax := 1;
1113 end;
1114
1115 procedure TCreatureResource.LoadFromFile(ResourceConfig: TCastleConfig);
1116 begin
1117 inherited;
1118
1119 {$warnings off} // using deprecated in deprecated
1120 KnockBackSpeed := ResourceConfig.GetFloat('knockback_speed', TCastleAlive.DefaultKnockBackSpeed);
1121 {$warnings on}
1122 CollidesWhenDead := ResourceConfig.GetValue('collides_when_dead', false);
1123 ScaleMin := ResourceConfig.GetFloat('scale_min', 1);
1124 ScaleMax := ResourceConfig.GetFloat('scale_max', 1);
1125 KnockBackDistance := ResourceConfig.GetFloat('knockback_distance',
1126 DefaultKnockBackDistance);
1127 Flying := ResourceConfig.GetValue('flying',
1128 DefaultFlying);
1129 SoundDieTiedToCreature := ResourceConfig.GetValue('sound_die_tied_to_creature',
1130 DefaultSoundDieTiedToCreature);
1131 DefaultMaxLife := ResourceConfig.GetFloat('default_max_life',
1132 DefaultDefaultMaxLife);
1133 FRadiusOverride := ResourceConfig.GetFloat('radius', 0.0);
1134 AttackDamageConst := ResourceConfig.GetFloat('attack/damage/const',
1135 DefaultAttackDamageConst);
1136 AttackDamageRandom := ResourceConfig.GetFloat('attack/damage/random',
1137 DefaultAttackDamageRandom);
1138 AttackKnockbackDistance := ResourceConfig.GetFloat('attack/knockback_distance',
1139 DefaultAttackKnockbackDistance);
1140 MiddleHeight := ResourceConfig.GetFloat('middle_height', TCastleTransform.DefaultMiddleHeight);
1141 FallMinHeightToSound := ResourceConfig.GetFloat('fall/sound/min_height', DefaultFallMinHeightToSound);
1142 FallMinHeightToDamage := ResourceConfig.GetFloat('fall/damage/min_height', DefaultFallMinHeightToDamage);
1143 FallDamageScaleMin := ResourceConfig.GetFloat('fall/damage/scale_min', DefaultFallDamageScaleMin);
1144 FallDamageScaleMax := ResourceConfig.GetFloat('fall/damage/scale_max', DefaultFallDamageScaleMax);
1145
1146 {$warnings off} // using deprecated SoundFromName in deprecated
1147 SoundSuddenPain := SoundEngine.SoundFromName(
1148 ResourceConfig.GetValue('sound_sudden_pain', ''));
1149 SoundDie := SoundEngine.SoundFromName(
1150 ResourceConfig.GetValue('sound_die', ''));
1151 FallSound := SoundEngine.SoundFromName(
1152 ResourceConfig.GetValue('fall/sound/name', DefaultFallSoundName), false);
1153 {$warnings on}
1154 end;
1155
1156 function TCreatureResource.FlexibleUp: boolean;
1157 begin
1158 Result := true;
1159 end;
1160
1161 function TCreatureResource.CreateCreature(
1162 const ALevel: TAbstractLevel;
1163 const APosition, ADirection: TVector3;
1164 const MaxLife: Single): TCreature;
1165 var
1166 Scale: Single;
1167 RootTransform: TCastleRootTransform;
1168 begin
1169 if ALevel.CreaturesRoot = nil then
1170 raise Exception.CreateFmt('Cannot add creature "%s" to level, as the level is not loaded yet. Execute TLevel.Load first', [
1171 Name
1172 ]);
1173
1174 RootTransform := ALevel.RootTransform;
1175
1176 { This is only needed if you did not add creature to <resources>.
1177
1178 Note: we experimented with moving this to TCreature.PrepareResource,
1179 call Resource.Prepare from there. But it just doesn't fully work:
1180 some creatures really want Resource to be prepared
1181 before PrepareResource (from TCastleViewport.BeforeRender) had a chance to work.
1182 For example, on missiles like thrown web we do Sound3d that uses LerpLegsMiddle.
1183 Also TCreature.Idle (which definitely needs Resource) may get called before
1184 PrepareResource. IOW, PrepareResource is just too late. }
1185 Prepare(ALevel.PrepareParams);
1186
1187 Result := CreatureClass.Create(ALevel.FreeAtUnload, MaxLife);
1188 { set properties that in practice must have other-than-default values
1189 to sensibly use the creature }
1190 Result.Level := ALevel;
1191 Result.FResource := Self;
1192 Result.FResourceObserver.Observed := Self;
1193 Result.Orientation := Orientation; // must be set before SetView
1194 Result.SetView(APosition, ADirection, RootTransform.GravityUp, FlexibleUp);
1195 Result.Life := MaxLife;
1196 Result.KnockBackSpeed := KnockBackSpeed;
1197 {$warnings off} // using deprecated in deprecated
1198 Result.Gravity := not Flying;
1199 Result.FallSpeed := FallSpeed;
1200 Result.GrowSpeed := GrowSpeed;
1201 {$warnings on}
1202 Result.CastShadows := CastShadowVolumes;
1203 Result.MiddleHeight := MiddleHeight;
1204 Scale := RandomFloatRange(ScaleMin, ScaleMax);
1205 Result.Scale := Vector3(Scale, Scale, Scale);
1206
1207 ALevel.CreaturesRoot.Add(Result);
1208 end;
1209
1210 function TCreatureResource.CreateCreature(
1211 const ALevel: TAbstractLevel;
1212 const APosition, ADirection: TVector3): TCreature;
1213 begin
1214 Result := CreateCreature(ALevel, APosition, ADirection, DefaultMaxLife);
1215 end;
1216
1217 procedure TCreatureResource.InstantiatePlaceholder(
1218 const ALevel: TAbstractLevel;
1219 const APosition, ADirection: TVector3;
1220 const NumberPresent: boolean; const Number: Int64);
1221 var
1222 CreatureDirection: TVector3;
1223 MaxLife: Single;
1224 begin
1225 { calculate CreatureDirection }
1226 CreatureDirection := ADirection;
1227
1228 { calculate MaxLife }
1229 if NumberPresent then
1230 MaxLife := Number
1231 else
1232 MaxLife := DefaultMaxLife;
1233
1234 CreateCreature(ALevel, APosition, CreatureDirection, MaxLife);
1235 end;
1236
1237 function TCreatureResource.Radius(const GravityUp: TVector3): Single;
1238 begin
1239 if RadiusOverride <> 0 then
1240 Result := RadiusOverride
1241 else
1242 Result := RadiusCalculate(GravityUp);
1243 end;
1244
1245 function TCreatureResource.RadiusCalculate(const GravityUp: TVector3): Single;
1246 var
1247 GC: Integer;
1248 Box: TBox3D;
1249 MaxRadiusForGravity: Single;
1250 begin
1251 { calculate radius.
1252 Descendants can override this to provide better radius calculation,
1253 and user can always override this in resource.xml (in which case,
1254 RadiusCalculate is never called).
1255
1256 So it's Ok to make here some assumptions that should suit usual cases,
1257 but not necessarily all possible cases ---
1258 e.g. our MaxRadiusForGravity calculation assumes you
1259 let default TCastleTransform.PreferredHeight algorithm to work. }
1260
1261 if Animations.Count = 0 then
1262 Box := TBox3D.Empty
1263 else
1264 Box := Animations[0].BoundingBox;
1265
1266 GC := MaxAbsVectorCoord(GravityUp);
1267
1268 if Box.IsEmpty then
1269 Result := 0 else
1270 if Flying then
1271 { For Flying creatures, larger Radius (that *really* surrounds whole
1272 model from middle) is better. Also, MaxRadiusForGravity doesn't concern
1273 us then. }
1274 Result := Box.MaxSize / 2 else
1275 begin
1276 { Maximum radius value that allows gravity to work,
1277 assuming default TCastleTransform.PreferredHeight implementation,
1278 and assuming that Box is the smallest possible bounding box of our creature. }
1279 MaxRadiusForGravity := 0.9 * MiddleHeight * Box.Data[1].Data[GC];
1280 Result := Min(Box.Radius2D(GC), MaxRadiusForGravity);
1281 end;
1282 end;
1283
1284 { TWalkAttackCreatureResource ------------------------------------------------ }
1285
1286 constructor TWalkAttackCreatureResource.Create(AOwner: TComponent);
1287 begin
1288 inherited;
1289
1290 MoveSpeed := DefaultMoveSpeed;
1291 FMinLifeLossToHurt := DefaultMinLifeLossToHurt;
1292 FChanceToHurt := DefaultChanceToHurt;
1293 FMaxHeightAcceptableToFall := DefaultMaxHeightAcceptableToFall;
1294 FRandomWalkDistance := DefaultRandomWalkDistance;
1295 FRemoveDead := DefaultRemoveDead;
1296 FPreferredDistance := DefaultPreferredDistance;
1297 FRunAwayLife := DefaultRunAwayLife;
1298 FRunAwayDistance := DefaultRunAwayDistance;
1299 FVisibilityAngle := DefaultVisibilityAngle;
1300 FSmellDistance := DefaultSmellDistance;
1301 FAttackTime := DefaultAttackTime;
1302 FAttackMinDelay := DefaultAttackMinDelay;
1303 FAttackMaxDistance := DefaultAttackMaxDistance;
1304 FAttackMaxAngle := DefaultAttackMaxAngle;
1305 FFireMissileTime := DefaultFireMissileTime;
1306 FFireMissileMaxDistance := DefaultFireMissileMaxDistance;
1307 FFireMissileMaxAngle := DefaultFireMissileMaxAngle;
1308 FFireMissileMinDelay := DefaultFireMissileMinDelay;
1309 FFireMissileHeight := DefaultFireMissileHeight;
1310
1311 FIdleAnimation := T3DResourceAnimation.Create(Self, 'idle');
1312 FIdleToWalkAnimation := T3DResourceAnimation.Create(Self, 'idle_to_walk', false);
1313 FWalkAnimation := T3DResourceAnimation.Create(Self, 'walk');
1314 FAttackAnimation := T3DResourceAnimation.Create(Self, 'attack', false);
1315 FFireMissileAnimation := T3DResourceAnimation.Create(Self, 'fire_missile', false);
1316 FDieAnimation := T3DResourceAnimation.Create(Self, 'die');
1317 FDieBackAnimation := T3DResourceAnimation.Create(Self, 'die_back', false);
1318 FHurtAnimation := T3DResourceAnimation.Create(Self, 'hurt');
1319 end;
1320
1321 procedure TWalkAttackCreatureResource.LoadFromFile(ResourceConfig: TCastleConfig);
1322 begin
1323 inherited;
1324
1325 MoveSpeed := ResourceConfig.GetFloat('move_speed',
1326 DefaultMoveSpeed);
1327 MinLifeLossToHurt := ResourceConfig.GetFloat('min_life_loss_to_hurt',
1328 DefaultMinLifeLossToHurt);
1329 ChanceToHurt := ResourceConfig.GetFloat('chance_to_hurt',
1330 DefaultChanceToHurt);
1331 MaxHeightAcceptableToFall := ResourceConfig.GetFloat('max_height_acceptable_to_fall',
1332 DefaultMaxHeightAcceptableToFall);
1333 RandomWalkDistance := ResourceConfig.GetFloat('random_walk_distance',
1334 DefaultRandomWalkDistance);
1335 RemoveDead := ResourceConfig.GetValue('remove_dead', DefaultRemoveDead);
1336 RunAwayLife := ResourceConfig.GetFloat('run_away/life', DefaultRunAwayLife);
1337 RunAwayDistance := ResourceConfig.GetFloat('run_away/distance', DefaultRunAwayDistance);
1338 VisibilityAngle := ResourceConfig.GetFloat('visibility/angle', DefaultVisibilityAngle);
1339 SmellDistance := ResourceConfig.GetFloat('smell_distance', DefaultSmellDistance);
1340 PreferredDistance := ResourceConfig.GetFloat('preferred_distance', DefaultPreferredDistance);
1341
1342 AttackTime := ResourceConfig.GetFloat('attack/time', DefaultAttackTime);
1343 AttackMaxDistance := ResourceConfig.GetFloat('attack/max_distance', DefaultAttackMaxDistance);
1344 AttackMaxAngle := ResourceConfig.GetFloat('attack/max_angle', DefaultAttackMaxAngle);
1345 AttackMinDelay := ResourceConfig.GetFloat('attack/min_delay', DefaultAttackMinDelay);
1346 {$warnings off} // using deprecated SoundFromName in deprecated
1347 AttackSoundHit := SoundEngine.SoundFromName(ResourceConfig.GetValue('attack/sound_hit', ''));
1348 AttackSoundStart := SoundEngine.SoundFromName(ResourceConfig.GetValue('attack/sound_start', ''));
1349 {$warnings on}
1350
1351 FireMissileTime := ResourceConfig.GetFloat('fire_missile/time', DefaultFireMissileTime);
1352 FireMissileMaxDistance := ResourceConfig.GetFloat('fire_missile/max_distance', DefaultFireMissileMaxDistance);
1353 FireMissileMaxAngle := ResourceConfig.GetFloat('fire_missile/max_angle', DefaultFireMissileMaxAngle);
1354 FireMissileMinDelay := ResourceConfig.GetFloat('fire_missile/min_delay', DefaultFireMissileMinDelay);
1355 {$warnings off} // using deprecated SoundFromName in deprecated
1356 FireMissileSound := SoundEngine.SoundFromName(ResourceConfig.GetValue('fire_missile/sound', ''));
1357 {$warnings on}
1358 FireMissileName := ResourceConfig.GetValue('fire_missile/name', '');
1359 FireMissileHeight := ResourceConfig.GetFloat('fire_missile/height', DefaultFireMissileHeight);
1360 end;
1361
1362 function TWalkAttackCreatureResource.CreatureClass: TCreatureClass;
1363 begin
1364 Result := TWalkAttackCreature;
1365 end;
1366
1367 function TWalkAttackCreatureResource.FlexibleUp: boolean;
1368 begin
1369 { For non-flying creatures, "up" vector must be always equal to GravityUp. }
1370 Result := Flying;
1371 end;
1372
1373 { TMissileCreatureResource ---------------------------------------------------- }
1374
1375 constructor TMissileCreatureResource.Create(AOwner: TComponent);
1376 begin
1377 inherited;
1378 FMoveSpeed := DefaultMoveSpeed;
1379 FCloseDirectionToTargetSpeed := DefaultCloseDirectionToTargetSpeed;
1380 FPauseBetweenSoundIdle := DefaultPauseBetweenSoundIdle;
1381 FHitsPlayer := DefaultHitsPlayer;
1382 FHitsCreatures := DefaultHitsCreatures;
1383 FDirectionFallSpeed := DefaultDirectionFallSpeed;
1384 FFlyAnimation := T3DResourceAnimation.Create(Self, 'fly');
1385 FDieAnimation := T3DResourceAnimation.Create(Self, 'die', false);
1386 FRemoveDead := DefaultRemoveDead;
1387 end;
1388
1389 function TMissileCreatureResource.CreatureClass: TCreatureClass;
1390 begin
1391 Result := TMissileCreature;
1392 end;
1393
1394 procedure TMissileCreatureResource.LoadFromFile(ResourceConfig: TCastleConfig);
1395 begin
1396 inherited;
1397
1398 MoveSpeed := ResourceConfig.GetFloat('move_speed',
1399 DefaultMoveSpeed);
1400 CloseDirectionToTargetSpeed := ResourceConfig.GetFloat('close_direction_to_target_speed',
1401 DefaultCloseDirectionToTargetSpeed);
1402 PauseBetweenSoundIdle := ResourceConfig.GetFloat('pause_between_sound_idle',
1403 DefaultPauseBetweenSoundIdle);
1404 HitsPlayer := ResourceConfig.GetValue('hits_player',
1405 DefaultHitsPlayer);
1406 HitsCreatures := ResourceConfig.GetValue('hits_creatures',
1407 DefaultHitsCreatures);
1408 DirectionFallSpeed := ResourceConfig.GetFloat('direction_fall_speed',
1409 DefaultDirectionFallSpeed);
1410 RemoveDead := ResourceConfig.GetValue('remove_dead', DefaultRemoveDead);
1411
1412 {$warnings off} // using deprecated SoundFromName in deprecated
1413 SoundHit := SoundEngine.SoundFromName(
1414 ResourceConfig.GetValue('sound_hit', ''));
1415 SoundIdle := SoundEngine.SoundFromName(
1416 ResourceConfig.GetValue('sound_idle', ''));
1417 {$warnings on}
1418 end;
1419
1420 function TMissileCreatureResource.CreateCreature(
1421 const ALevel: TAbstractLevel;
1422 const APosition, ADirection: TVector3;
1423 const MaxLife: Single): TCreature;
1424 begin
1425 Result := inherited;
1426
1427 { Normal gravity is turned off for missiles.
1428
1429 We tried to enable it once, but:
1430 1. Normal gravity doesn't change the direction, so arrows fall down
1431 but they keep pointing upwards. This is noticeable to the player
1432 that looks at the arrow.
1433 2. It also conflicts with current hack with "MaximumFallingDistance -= 0.01"
1434 inside CastleTransform gravity. It could probably be fixed better,
1435 but since the 1st problem would remain anyway...
1436 Also growing up doesn't make any sense for missile that explodes on contact
1437 with ground. So Fall should be overriden to make HitCore,
1438 and GrowSpeed should be disabled below to be 0. (This is obviously doable.)
1439
1440 We also want to turn off Gravity to use Gravity=false case when using
1441 MiddleHeight, so MiddleHeight is always between bounding box bottom and top
1442 for missiles. See TCastleTransform.MiddleHeight. }
1443
1444 {$warnings off} // using deprecated in deprecated
1445 Result.Gravity := false;
1446 {$warnings on}
1447 end;
1448
1449 function TMissileCreatureResource.RadiusCalculate(const GravityUp: TVector3): Single;
1450 var
1451 Box: TBox3D;
1452 begin
1453 Box := FlyAnimation.BoundingBox;
1454
1455 { Use MinSize for missile, since smaller radius for missiles
1456 forces player to aim more precisely. Smaller radius may also allow some
1457 partial collisions to go undetected, but that's not a problem as the
1458 collisions imperfections are not noticeable for fast moving missiles. }
1459 if not Box.IsEmpty then
1460 Result := Box.MinSize / 2
1461 else
1462 Result := inherited;
1463 end;
1464
1465 { TStillCreatureResource ---------------------------------------------------- }
1466
1467 constructor TStillCreatureResource.Create(AOwner: TComponent);
1468 begin
1469 inherited;
1470 FIdleAnimation := T3DResourceAnimation.Create(Self, 'idle');
1471 FDieAnimation := T3DResourceAnimation.Create(Self, 'die', false);
1472 FRemoveDead := DefaultRemoveDead;
1473 end;
1474
1475 function TStillCreatureResource.CreatureClass: TCreatureClass;
1476 begin
1477 Result := TStillCreature;
1478 end;
1479
1480 procedure TStillCreatureResource.LoadFromFile(ResourceConfig: TCastleConfig);
1481 begin
1482 inherited;
1483 RemoveDead := ResourceConfig.GetValue('remove_dead', DefaultRemoveDead);
1484 end;
1485
1486 { TCreature ------------------------------------------------------------------ }
1487
1488 constructor TCreature.Create(AOwner: TComponent; const AMaxLife: Single);
1489 begin
1490 inherited Create(AOwner);
1491 CollidesWithMoving := true;
1492 MaxLife := AMaxLife;
1493 FSoundDieEnabled := true;
1494
1495 FResourceObserver := TFreeNotificationObserver.Create(Self);
1496 FResourceObserver.OnFreeNotification := {$ifdef FPC}@{$endif}ResourceFreeNotification;
1497
1498 SoundSource := TCastleSoundSource.Create(Self);
1499 AddBehavior(SoundSource);
1500
1501 FDebugTransform := TDebugTransform.Create(Self);
1502 FDebugTransform.Parent := Self;
1503
1504 FResourceFrame := TResourceFrame.Create(Self);
1505 Add(FResourceFrame);
1506 end;
1507
1508 procedure TCreature.ResourceFreeNotification(const Sender: TFreeNotificationObserver);
1509 begin
1510 FResource := nil;
1511 end;
1512
1513 function TCreature.GetCollides: boolean;
1514 begin
1515 {$warnings off} // internally using deprecated, in a deprecated unit
1516 Result := (inherited GetCollides) and
1517 (Resource.CollidesWhenDead or (not Dead));
1518 {$warnings on}
1519 end;
1520
1521 destructor TCreature.Destroy;
1522 begin
1523 if Resource <> nil then
1524 Resource.Release;
1525 inherited;
1526 end;
1527
1528 procedure TCreature.Sound3d(const SoundType: TCastleSound; const SoundHeight: Single;
1529 const TiedToCreature: boolean);
1530 var
1531 PlayingSound: TCastlePlayingSoundSource;
1532 begin
1533 if SoundType <> nil then
1534 begin
1535 PlayingSound := TCastlePlayingSoundSource.Create(nil);
1536 PlayingSound.Sound := SoundType;
1537 PlayingSound.FreeOnStop := true;
1538 PlayingSound.Follow := TiedToCreature;
1539 PlayingSound.SoundHeight := SoundHeight;
1540 SoundSource.Play(PlayingSound);
1541 end;
1542 end;
1543
1544 function TCreature.LerpLegsMiddle(const A: Single): TVector3;
1545 begin
1546 Result := Lerp(A, Translation, Middle);
1547 end;
1548
1549 procedure TCreature.UpdateDebugCaption(const Lines: TCastleStringList);
1550 begin
1551 Lines.Add(Format('%s [%f / %f]',
1552 [Resource.Name, Life, MaxLife]));
1553 end;
1554
1555 procedure TCreature.Fall(const FallHeight: Single);
1556 begin
1557 inherited;
1558
1559 if FallHeight > Resource.FallMinHeightToSound then
1560 Sound3d(Resource.FallSound, 0.1, false);
1561
1562 if FallHeight > Resource.FallMinHeightToDamage then
1563 Hurt(Max(0,
1564 FallHeight * MapRange(Random, 0.0, 1.0,
1565 Resource.FallDamageScaleMin,
1566 Resource.FallDamageScaleMax)),
1567 TVector3.Zero, 0, nil);
1568 end;
1569
1570 procedure TCreature.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
1571
1572 procedure UpdateDebugCaptions;
1573 var
1574 Root: TX3DRootNode;
1575 H: Single;
1576 BBox: TBox3D;
1577 begin
1578 if RenderDebug and (FDebugCaptions = nil) then
1579 begin
1580 { create FDebugCaptions on demand }
1581
1582 FDebugCaptionsFontStyle := TFontStyleNode.Create;
1583
1584 FDebugCaptionsText := TTextNode.Create;
1585 FDebugCaptionsText.FontStyle := FDebugCaptionsFontStyle;
1586 FDebugCaptionsText.Solid := false;
1587
1588 FDebugCaptionsShape := TShapeNode.Create;
1589 FDebugCaptionsShape.Geometry := FDebugCaptionsText;
1590
1591 FDebugCaptionsTransform := TMatrixTransformNode.Create;
1592 FDebugCaptionsTransform.AddChildren(FDebugCaptionsShape);
1593
1594 Root := TX3DRootNode.Create;
1595 Root.AddChildren(FDebugCaptionsTransform);
1596
1597 FDebugCaptions := TCastleScene.Create(Self);
1598 FDebugCaptions.Load(Root, true);
1599 FDebugCaptions.Collides := false;
1600 FDebugCaptions.Pickable := false;
1601 FDebugCaptions.CastShadows := false;
1602 FDebugCaptions.InternalExcludeFromParentBoundingVolume := true;
1603
1604 Add(FDebugCaptions);
1605 end;
1606
1607 if FDebugCaptions <> nil then
1608 FDebugCaptions.Exists := RenderDebug;
1609
1610 if RenderDebug then
1611 begin
1612 BBox := BoundingBox;
1613 FDebugCaptionsShape.Visible := not BBox.IsEmpty;
1614 if FDebugCaptionsShape.Visible then
1615 begin
1616 H := BBox.Data[1].Data[World.GravityCoordinate];
1617 FDebugCaptionsFontStyle.Size := H / 8;
1618 FDebugCaptionsTransform.Matrix := TransformToCoordsMatrix(
1619 { move the caption to be at the top }
1620 World.GravityUp * H,
1621 { By default, Text is in XY plane. Adjust it to our Orientation. }
1622 TVector3.CrossProduct(
1623 TCastleTransform.DefaultUp[Orientation],
1624 TCastleTransform.DefaultDirection[Orientation]),
1625 TCastleTransform.DefaultUp[Orientation],
1626 TCastleTransform.DefaultDirection[Orientation]);
1627
1628 FDebugCaptionsText.FdString.Items.Clear;
1629 UpdateDebugCaption(FDebugCaptionsText.FdString.Items);
1630 FDebugCaptionsText.FdString.Changed;
1631 end;
1632 end;
1633 end;
1634
1635 begin
1636 inherited;
1637 if not Exists then Exit;
1638
1639 { In this case (when Exists, regardless of DebugTimeStopForCreatures),
1640 TCastleAlive.Update changed LifeTime.
1641 And LifeTime is used to choose animation frame in GetChild.
1642 So the creature constantly changes, even when it's
1643 transformation (things taken into account in TCastleTransform) stay equal. }
1644 VisibleChangeHere([vcVisibleGeometry]);
1645
1646 FDebugTransform.Exists := RenderDebug;
1647 UpdateDebugCaptions;
1648 end;
1649
1650 procedure TCreature.SetLife(const Value: Single);
1651 begin
1652 if (Life > 0) and (Value <= 0) then
1653 begin
1654 { When dies, we don't play SoundSuddenPain sound. We will play SoundDie. }
1655 if SoundDieEnabled then
1656 Sound3d(Resource.SoundDie, 1.0, Resource.SoundDieTiedToCreature);
1657 end else
1658 if (Life > 0) and (Life - Value > 5) then
1659 begin
1660 Sound3d(Resource.SoundSuddenPain, 1.0);
1661 end;
1662
1663 inherited;
1664 end;
1665
1666 procedure TCreature.AttackHurt(const HurtEnemy: TCastleAlive);
1667 begin
1668 if HurtEnemy <> nil then
1669 HurtEnemy.Hurt(Resource.AttackDamageConst +
1670 Random * Resource.AttackDamageRandom, Direction,
1671 Resource.AttackKnockbackDistance, Self);
1672 end;
1673
1674 function TCreature.Sphere(out ARadius: Single): boolean;
1675 begin
1676 Result := Exists and (not Dead);
1677 ARadius := Radius;
1678 end;
1679
1680 function TCreature.Radius: Single;
1681 begin
1682 if FRadius = 0 then
1683 FRadius := Resource.Radius(World.GravityUp);
1684 Result := FRadius;
1685 end;
1686
1687 function TCreature.Sector(const OtherTransform: TCastleTransform): TSector;
1688 begin
1689 if Level.GetSectors <> nil then
1690 Result := Level.GetSectors.SectorWithPoint(OtherTransform.Middle)
1691 else
1692 Result := nil;
1693 end;
1694
1695 function TCreature.Sector: TSector;
1696 begin
1697 Result := Sector(Self);
1698 end;
1699
1700 { TWalkAttackCreature -------------------------------------------------------- }
1701
1702 constructor TWalkAttackCreature.Create(AOwner: TComponent;
1703 const AMaxLife: Single);
1704 begin
1705 inherited;
1706
1707 if MaxLife > 0 then
1708 begin
1709 FState := csIdle;
1710 FStateChangeTime := 0;
1711 end else
1712 begin
1713 { This means that the creature is created already in dead state...
1714 So we start with csDie state and set FStateChangeTime to fake
1715 the fact that creature was killed long time ago.
1716
1717 This way the creature is created as a dead corpse, without making
1718 any kind of dying (or wounded) sound or animation. }
1719 FState := csDie;
1720 FStateChangeTime := -1000;
1721 end;
1722
1723 WaypointsSaved := TWaypointList.Create(false);
1724 end;
1725
1726 destructor TWalkAttackCreature.Destroy;
1727 begin
1728 FreeAndNil(WaypointsSaved);
1729 inherited;
1730 end;
1731
1732 function TWalkAttackCreature.Resource: TWalkAttackCreatureResource;
1733 begin
1734 Result := TWalkAttackCreatureResource(inherited Resource);
1735 end;
1736
1737 function TWalkAttackCreature.Enemy: TCastleAlive;
1738 begin
1739 {$warnings off} // using deprecated in deprecated
1740 Result := Level.GetPlayer as TCastleAlive;
1741 {$warnings on}
1742 if (Result <> nil) and Result.Dead then
1743 Result := nil; { do not attack dead player }
1744 end;
1745
1746 procedure TWalkAttackCreature.SetState(Value: TCreatureState);
1747 begin
1748 if FState <> Value then
1749 begin
1750 { Force old box value for Middle and PreferredHeight calculation,
1751 for a fraction of a second.
1752
1753 This is crucial for TWalkAttackCreature.Update logic
1754 that could otherwise sometimes get stuck and continuously switching
1755 between walk/idle states, because in idle state Middle indicates
1756 that we should walk (e.g. distance or angle to enemy is not good enough),
1757 but right after switching to walk the LocalBoundingBox changes
1758 (because 1st walk animation frame is suddenly different)
1759 and the distance/angle seems Ok and we switch back to idle and so on,
1760 in a loop. Once this unfortunate situation is reached, the creature
1761 is stuck, blinking between two animation frames and two states,
1762 and never moving (until something else, like enemy (player)
1763 position changes).
1764
1765 Safeguards:
1766
1767 - Don't set to "forced" when it's already forced, as then it could
1768 cause InternalMiddleForceBoxValue change after each SetState to the box
1769 from previous state, and we'll be in a similar trouble
1770 (but with box values always from previous state).
1771 Trouble (without this safeguard) is reproducible on fps_game
1772 with knight flying.
1773
1774 - Don't set to "forced" when switching between other states than idle/walk,
1775 as the other states logic doesn't allow for such switching
1776 (states like attack, fireMissile, hurt, die generally continue until
1777 their time finished; there are no decisions).
1778 (I didn't actually observed a need for this safeguard so far,
1779 but it seems reasonable to limit this hack only to idle/walk situation.)
1780 }
1781 if (not InternalMiddleForceBox) and
1782 ( ((FState = csIdle) and (Value = csWalk)) or
1783 ((FState = csWalk) and (Value = csIdle)) ) then
1784 begin
1785 InternalMiddleForceBox := true;
1786 InternalMiddleForceBoxValue := LocalBoundingBox;
1787 InternalMiddleForceBoxTime := LifeTime + 0.1;
1788 end;
1789
1790 { Some states require special finalization here. }
1791 case FState of
1792 csAttack:
1793 { In case we didn't reach AttackTime, make sure to fire the Attack now. }
1794 if not AttackDone then
1795 begin
1796 AttackDone := true;
1797 Attack;
1798 end;
1799 end;
1800
1801 FState := Value;
1802 FStateChangeTime := LifeTime;
1803
1804 { Some states require special initialization here. }
1805 case FState of
1806 csAttack:
1807 begin
1808 Sound3d(Resource.AttackSoundStart, 1.0);
1809 LastAttackTime := StateChangeTime;
1810 AttackDone := false;
1811 end;
1812 csFireMissile:
1813 begin
1814 LastFireMissileTime := LifeTime;
1815 FireMissileDone := false;
1816 end;
1817 end;
1818 end;
1819 end;
1820
1821 procedure TWalkAttackCreature.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
1822
1823 procedure UpdateResourceFrame;
1824 var
1825 StateTime: Single;
1826 begin
1827 { Time from the change to this state. }
1828 StateTime := LifeTime - StateChangeTime;
1829
1830 case FState of
1831 csIdle:
1832 FResourceFrame.SetFrame(Level, Resource.IdleAnimation, StateTime, true);
1833 csWalk:
1834 if Resource.IdleToWalkAnimation.Defined and
1835 (StateTime < Resource.IdleToWalkAnimation.Duration) then
1836 FResourceFrame.SetFrame(Level, Resource.IdleToWalkAnimation, StateTime, false)
1837 else
1838 FResourceFrame.SetFrame(Level, Resource.WalkAnimation,
1839 StateTime - Resource.IdleToWalkAnimation.Duration, true);
1840 csAttack:
1841 FResourceFrame.SetFrame(Level, Resource.AttackAnimation, StateTime, false);
1842 csFireMissile:
1843 FResourceFrame.SetFrame(Level, Resource.FireMissileAnimation, StateTime, false);
1844 csDie:
1845 FResourceFrame.SetFrame(Level, Resource.DieAnimation, StateTime, false);
1846 csDieBack:
1847 FResourceFrame.SetFrame(Level, Resource.DieBackAnimation, StateTime, false);
1848 csHurt:
1849 FResourceFrame.SetFrame(Level, Resource.HurtAnimation, StateTime, false);
1850 else raise EInternalError.Create('FState ?');
1851 end;
1852 end;
1853
1854 var
1855 EnemySensedNow: boolean;
1856 SqrDistanceToLastSensedEnemy: Single;
1857
1858 function ActionAllowed(const Animation: T3DResourceAnimation;
1859 const LastTime, MinDelay, MaxDistance, MaxAngle: Single): boolean;
1860 var
1861 AngleBetweenTheDirectionToEnemy: Single;
1862 begin
1863 Result := EnemySensedNow and
1864 Animation.Defined and
1865 (LifeTime - LastTime > MinDelay) and
1866 (SqrDistanceToLastSensedEnemy <= Sqr(MaxDistance));
1867
1868 if Result then
1869 begin
1870 { Calculate and check AngleBetweenTheDirectionToEnemy. }
1871 AngleBetweenTheDirectionToEnemy := AngleRadBetweenVectors(
1872 LastSensedEnemy - Middle, Direction);
1873 Result := AngleBetweenTheDirectionToEnemy <= MaxAngle;
1874 end;
1875 end;
1876
1877 function AttackAllowed: boolean;
1878 begin
1879 Result := ActionAllowed(Resource.AttackAnimation, LastAttackTime,
1880 Resource.AttackMinDelay, Resource.AttackMaxDistance, Resource.AttackMaxAngle);
1881 end;
1882
1883 function FireMissileAllowed: boolean;
1884 begin
1885 Result := ActionAllowed(Resource.FireMissileAnimation, LastFireMissileTime,
1886 Resource.FireMissileMinDelay, Resource.FireMissileMaxDistance, Resource.FireMissileMaxAngle);
1887 end;
1888
1889 procedure CalculateDirectionToTarget(
1890 const Target: TVector3;
1891 out DirectionToTarget: TVector3;
1892 out AngleBetweenDirectionToTarget: Single);
1893 begin
1894 { calculate DirectionToTarget }
1895 DirectionToTarget := Target - Middle;
1896 {$warnings off} // using deprecated in deprecated
1897 if Gravity then
1898 {$warnings on}
1899 MakeVectorsOrthoOnTheirPlane(DirectionToTarget, World.GravityUp);
1900
1901 { calculate AngleBetweenDirectionToTarget }
1902 AngleBetweenDirectionToTarget :=
1903 AngleRadBetweenVectors(DirectionToTarget, Direction);
1904 end;
1905
1906 { Call this only when HasLastSensedEnemy }
1907 procedure CalculateDirectionToEnemy(out DirectionToEnemy: TVector3;
1908 out AngleBetweenDirectionToEnemy: Single);
1909 begin
1910 CalculateDirectionToTarget(LastSensedEnemy,
1911 DirectionToEnemy, AngleBetweenDirectionToEnemy);
1912 end;
1913
1914 procedure CalculateDirectionFromEnemy(
1915 var DirectionFromEnemy: TVector3;
1916 var AngleBetweenDirectionFromEnemy: Single);
1917 begin
1918 CalculateDirectionToEnemy(
1919 DirectionFromEnemy, AngleBetweenDirectionFromEnemy);
1920 DirectionFromEnemy := -DirectionFromEnemy;
1921 AngleBetweenDirectionFromEnemy :=
1922 Pi - AngleBetweenDirectionFromEnemy;
1923 end;
1924
1925 { This changes Direction to be closer to DirectionToTarget.
1926 Note that it requires the value of AngleBetweenDirectionToTarget
1927 effectively }
1928 procedure RotateDirectionToFaceTarget(const DirectionToTarget: TVector3;
1929 const AngleBetweenDirectionToTarget: Single);
1930 const
1931 AngleChangeSpeed = 5.0;
1932 var
1933 AngleChange: Single;
1934 NewDirection: TVector3;
1935 begin
1936 if not VectorsParallel(DirectionToTarget, Direction) then
1937 begin
1938 { Rotate Direction, to be closer to DirectionToTarget }
1939
1940 { calculate AngleChange }
1941 AngleChange := AngleChangeSpeed * SecondsPassed;
1942 MinVar(AngleChange, AngleBetweenDirectionToTarget);
1943
1944 NewDirection := RotatePointAroundAxisRad(AngleChange, Direction,
1945 TVector3.CrossProduct(Direction, DirectionToTarget));
1946
1947 { Make sure direction for non-flying creatures is orthogonal to GravityUp. }
1948 {$warnings off} // using deprecated in deprecated
1949 if Gravity then
1950 {$warnings on}
1951 MakeVectorsOrthoOnTheirPlane(NewDirection, World.GravityUp);
1952 Direction := NewDirection;
1953 end;
1954 end;
1955
1956 function CloseEnoughToTarget(const Target: TVector3): boolean;
1957 const
1958 MinDistanceToTarget = 0.1;
1959 var
1960 SqrDistanceToTarget: Single;
1961 begin
1962 {$warnings off} // using deprecated in deprecated
1963 if not Gravity then
1964 SqrDistanceToTarget := PointsDistanceSqr(Middle, Target)
1965 {$warnings on}
1966 else
1967 SqrDistanceToTarget := PointsDistance2DSqr(Middle, Target, World.GravityCoordinate);
1968 Result :=
1969 { If creature is ideally at the target
1970 (for not Flying creatures, this means "ideally under/above the target"),
1971 then there is no way to get closer to the target.
1972
1973 We check this with some "epsilon" (MinDistanceToTarget), as usual, to
1974
1975 1. Avoid the unnecessary moving when Middle is in fact
1976 close enough to the target, but lack of floating precision
1977 can't move it really ideally to Target.
1978
1979 2. In fact, it's not desirable to get exactly at (or under/above)
1980 the target, because this could cause undesirable rotations
1981 of the creature Direction (we usually try to make it in
1982 the Target direction, so when we stand (almost) exactly
1983 at Target, creature could try to stupidly rotate around itself). }
1984 SqrDistanceToTarget <= Sqr(MinDistanceToTarget);
1985 end;
1986
1987 { Assuming that I want to walk in DesiredDirection direction,
1988 is it sensible to do this by moving along current Direction ? }
1989 function WantToWalkInDesiredDirection(
1990 const AngleBetweenDesiredDirection: Single): boolean;
1991 const
1992 MaxAngleToMoveForward = Pi * 60 / 180;
1993 begin
1994 Result :=
1995 { If AngleBetweenDesiredDirection is too large, there is not much point
1996 in moving in given direction anyway. We should just change our Direction. }
1997 (AngleBetweenDesiredDirection <= MaxAngleToMoveForward);
1998 end;
1999
2000 { Assuming that I want to get to Target position, is it sensible
2001 to do this by moving along current Direction ?
2002 This checks whether current Direction points roughly in the
2003 direction of the Target, and if were not already as close as possible
2004 to Target. }
2005 function WantToWalkToTarget(
2006 const Target: TVector3;
2007 const AngleBetweenDirectionToTarget: Single): boolean;
2008 begin
2009 Result :=
2010 WantToWalkInDesiredDirection(AngleBetweenDirectionToTarget) and
2011 { See comments in CloseEnoughToTarget for reasoning why this is needed. }
2012 (not CloseEnoughToTarget(Target));
2013 end;
2014
2015 { This doesn't take into account current Direction,
2016 it only looks at our and enemy Middle positions,
2017 and asks "do I want to get closer" ?
2018 Use only if HasLastSensedEnemy. }
2019 function WantToShortenDistanceToEnemy: boolean;
2020 begin
2021 { Is it wanted to get closer to the LastSensedEnemy?
2022 Yes, if it will help make AttackAllowed from false to true.
2023 See AttackAllowed implementation for conditions. }
2024 Result :=
2025 { There is no point in trying to get closer,
2026 if we would activate WantToRunAway *before* we reach a point from which
2027 we can attack. }
2028 (not
2029 ( (Life <= MaxLife * Resource.RunAwayLife) and
2030 ( (not Resource.FireMissileAnimation.Defined) or (Resource.FireMissileMaxDistance < Resource.RunAwayDistance) ) and
2031 ( (not Resource. AttackAnimation.Defined) or (Resource. AttackMaxDistance < Resource.RunAwayDistance) )
2032 )
2033 ) and
2034 (
2035 { Try to see enemy by walking to last known enemy position. }
2036 (not EnemySensedNow) or
2037
2038 { If EnemySensedNow and SqrDistanceToLastSensedEnemy is small enough,
2039 there's no point in getting closer to the enemy. In fact, it would
2040 be bad to get closer to enemy in this case, as this would allow
2041 enemy to easier attack (shorter distance --- easier to reach with
2042 short-range weapon, or easier to aim with long-range weapon). }
2043 (SqrDistanceToLastSensedEnemy > Sqr(Resource.PreferredDistance))
2044 );
2045 end;
2046
2047 { Is it wanted to get closer to the LastSensedEnemy ?
2048 And (if it's wanted) is it sensible to do this by moving
2049 along current Direction ?
2050 Call this only if HasLastSensedEnemy. }
2051 function WantToWalkToEnemy(
2052 const AngleBetweenDirectionToEnemy: Single): boolean;
2053 begin
2054 Result := WantToShortenDistanceToEnemy and
2055 WantToWalkToTarget(LastSensedEnemy, AngleBetweenDirectionToEnemy);
2056 end;
2057
2058 function WantToRunAway: boolean;
2059 begin
2060 { We want to run away whenever HasLastSensedEnemy, not just when EnemySensedNow.
2061 Otherwise creature that tries to run away could easily get into a loop
2062 (flickering state), caused by small VisibilityAngle:
2063 in DoWalk creature would rotate to face away from enemy,
2064 but after such rotation enemy becomes invisible,
2065 so WantToRunAway would become false, and we would switch to idle,
2066 and in DoIdle creature would rotate back toward the enemy.
2067
2068 So we run away even when we do not see enemy *now*, it's only enough
2069 to know last enemy position. This actually makes sense in Real World too. }
2070 Result := HasLastSensedEnemy and
2071 (Life <= MaxLife * Resource.RunAwayLife) and
2072 (SqrDistanceToLastSensedEnemy < Sqr(Resource.RunAwayDistance));
2073 end;
2074
2075 procedure InitAlternativeTarget;
2076 var
2077 Distance: Single;
2078 I: Integer;
2079 begin
2080 Distance := Resource.RandomWalkDistance;
2081
2082 AlternativeTarget := Middle;
2083 { Add random values to the AlternativeTarget, but only on the components
2084 where creature can reliably move. Creature that cannot fly cannot
2085 move in gravity (UpIndex) direction. }
2086 for I := 0 to 2 do
2087 {$warnings off} // using deprecated in deprecated
2088 if (not Gravity) or (I <> World.GravityCoordinate) then
2089 {$warnings on}
2090 AlternativeTarget.Data[I] := AlternativeTarget.Data[I] + (Random * Distance * 2 - Distance);
2091
2092 HasAlternativeTarget := true;
2093
2094 AlternativeTargetTime := LifeTime;
2095 end;
2096
2097 { Assuming current state is idle (the actual State value ignored),
2098 - perform "idle" AI
2099 - and tell whether you changed the state to something else (returns @true if remained idle). }
2100 function DoIdle: Boolean;
2101 var
2102 DirectionToEnemy: TVector3;
2103 AngleBetweenDirectionToEnemy: Single;
2104 begin
2105 Result := true;
2106 if HasLastSensedEnemy then
2107 begin
2108 CalculateDirectionToEnemy(DirectionToEnemy, AngleBetweenDirectionToEnemy);
2109
2110 if FireMissileAllowed then
2111 begin
2112 SetState(csFireMissile);
2113 Result := false;
2114 end else
2115 if AttackAllowed then
2116 begin
2117 SetState(csAttack);
2118 Result := false;
2119 end else
2120 if WantToRunAway or
2121 WantToWalkToEnemy(AngleBetweenDirectionToEnemy) then
2122 begin
2123 SetState(csWalk);
2124 Result := false;
2125 end else
2126 {$warnings off} // using deprecated in deprecated
2127 if Gravity and
2128 {$warnings on}
2129 (AngleBetweenDirectionToEnemy < 0.01) and
2130 BoundingBox.Contains2D(LastSensedEnemy, World.GravityCoordinate) then
2131 begin
2132 { Then the enemy (or it's last known position) is right above or below us.
2133 Since we can't fly, we can't get there. Standing in place
2134 is one possibility, but it's not really good
2135 - We become easier target to shoot for enemy with the bow.
2136 - Most importantly, this way enemy (like player) can stand on our head
2137 and slash us with a sword without any risk. (This was almost
2138 a standard technique of killing Werewolf or SpiderQueen bosses).
2139 So we move a little --- just for the sake of moving. }
2140 SetState(csWalk);
2141 InitAlternativeTarget;
2142 Result := false;
2143 end else
2144 begin
2145 { Continue csIdle state }
2146 RotateDirectionToFaceTarget(DirectionToEnemy,
2147 AngleBetweenDirectionToEnemy);
2148 end;
2149 end;
2150 end;
2151
2152 procedure DoWalk;
2153
2154 { This performs the real move, which means that it changes Position
2155 and Middle along the Direction vector.
2156
2157 This doesn't check whether this is a sensible move, so use this
2158 only if you know that the creature really wants to go in this Direction.
2159
2160 This checks only the basic (i.e. always wanted) things:
2161 - Collision detection (with level and other collidable stuff like
2162 player and other creatures)
2163 - For not Flying creatures, also the check to not fall down from high
2164 is done. }
2165 function MoveAlongTheDirection: boolean;
2166
2167 { Don't be stupid, and don't walk where you see you will fall down. }
2168 function TooHighAboveTheGround(const NewMiddle: TVector3):
2169 boolean;
2170 var
2171 AboveHeight: Single;
2172 begin
2173 Result := false;
2174 {$warnings off} // using deprecated in deprecated
2175 if Gravity then
2176 {$warnings on}
2177 begin
2178 Height(NewMiddle, AboveHeight);
2179 {$warnings off} // using deprecated in deprecated
2180 if AboveHeight > Resource.MaxHeightAcceptableToFall + PreferredHeight then
2181 {$warnings on}
2182 Result := true;
2183 end;
2184 end;
2185
2186 begin
2187 Result :=
2188 { First check to not step into some deep fall.
2189 Note that I'm not using here NewMiddle
2190 (that will be calculated later by Move)
2191 because they are too close to Middle to be good to test against.
2192 I'm calculating here where I would get after 0.2 second. }
2193 (not TooHighAboveTheGround(Middle + Direction * (Resource.MoveSpeed * 0.2))) and
2194
2195 { Use Move without wall-sliding here.
2196 Things using MoveAlongTheDirection depend on the fact that
2197 MoveAlongTheDirection will return false
2198 if no further way is possible (and wall-sliding would try instead
2199 to return true and correct target position).
2200
2201 Our trick with "AlternativeTarget" should handle
2202 eventual problems with the track of creature, so wall-sliding
2203 should not be needed. }
2204 Move(Direction * (Resource.MoveSpeed * SecondsPassed), false, false);
2205 end;
2206
2207 { Go the way to LastSensedEnemy, *not* by using waypoints.
2208 Assumes HasLastSensedEnemy. }
2209 procedure WalkNormal;
2210 var
2211 DirectionToTarget: TVector3;
2212 AngleBetweenDirectionToTarget: Single;
2213 begin
2214 CalculateDirectionToEnemy(DirectionToTarget,
2215 AngleBetweenDirectionToTarget);
2216
2217 if WantToWalkToEnemy(AngleBetweenDirectionToTarget) then
2218 begin
2219 if not MoveAlongTheDirection then
2220 begin
2221 { Not able to get to enemy this way ? Maybe there exists
2222 some alternative way, not straight. Lets try. }
2223 InitAlternativeTarget;
2224 Exit;
2225 end;
2226 end else
2227 begin
2228 { I don't want to walk anymore. So just stand stil. }
2229 SetState(csIdle);
2230 Exit;
2231 end;
2232
2233 RotateDirectionToFaceTarget(DirectionToTarget,
2234 AngleBetweenDirectionToTarget);
2235 end;
2236
2237 procedure WalkToWaypoint(const Target: TVector3);
2238 var
2239 DirectionToTarget: TVector3;
2240 AngleBetweenDirectionToTarget: Single;
2241 begin
2242 CalculateDirectionToTarget(Target, DirectionToTarget,
2243 AngleBetweenDirectionToTarget);
2244
2245 if WantToShortenDistanceToEnemy then
2246 begin
2247 if not MoveAlongTheDirection then
2248 begin
2249 { Not able to get to waypoint this way ? Maybe there exists
2250 some alternative way, not straight. Lets try. }
2251 InitAlternativeTarget;
2252 Exit;
2253 end;
2254 end else
2255 begin
2256 { I don't want to walk anymore. So just stand stil. }
2257 SetState(csIdle);
2258 Exit;
2259 end;
2260
2261 RotateDirectionToFaceTarget(DirectionToTarget,
2262 AngleBetweenDirectionToTarget);
2263 end;
2264
2265 const
2266 ProbabilityToTryAnotherAlternativeTarget = 0.5;
2267 AngleBetweenDirectionToTargetToResign = Pi * 1 / 180;
2268 MaxTimeForAlternativeTarget = 5.0;
2269 var
2270 DirectionToTarget: TVector3;
2271 AngleBetweenDirectionToTarget: Single;
2272 SectorNow: TSector;
2273 UseWalkNormal: boolean;
2274 begin
2275 if HasAlternativeTarget then
2276 begin
2277 if CloseEnoughToTarget(AlternativeTarget) or
2278 (LifeTime - AlternativeTargetTime > MaxTimeForAlternativeTarget) then
2279 begin
2280 HasAlternativeTarget := false;
2281 Exit;
2282 end;
2283
2284 CalculateDirectionToTarget(AlternativeTarget,
2285 DirectionToTarget, AngleBetweenDirectionToTarget);
2286
2287 if WantToWalkToTarget(AlternativeTarget,
2288 AngleBetweenDirectionToTarget) then
2289 begin
2290 { Note that MoveAlongTheDirection returns false when
2291 moving along the current Direction is not good.
2292 But maybe moving along the DirectionToTarget is possible ?
2293 So we shouldn't just resign from current AlternativeTarget
2294 so fast --- maybe it's good, but we have to adjust
2295 our Direction a little more. That's why I use
2296 AngleBetweenDirectionToTargetToResign.
2297
2298 Note that for normal moving (i.e. toward LastSensedEnemy,
2299 not AlternativeTarget) we in this case just change state
2300 to csIdle, and this allows creature to rotate in csIdle
2301 state. }
2302 if (not MoveAlongTheDirection) and
2303 (AngleBetweenDirectionToTarget <=
2304 AngleBetweenDirectionToTargetToResign) then
2305 begin
2306 if Random <= ProbabilityToTryAnotherAlternativeTarget then
2307 begin
2308 { Try yet another alternative way. }
2309 InitAlternativeTarget;
2310 Exit;
2311 end else
2312 begin
2313 HasAlternativeTarget := false;
2314 Exit;
2315 end;
2316 end;
2317 end else
2318 begin
2319 { We know that WantToWalkToTarget may return false only because
2320 were not directed enough for AlternativeTarget.
2321 (because we already eliminated CloseEnoughToTarget case above).
2322 In each DoWalk call we will gradually fix this,
2323 by RotateDirectionToFaceTarget below.
2324 So do nothing now. Just stay in csWalk mode,
2325 and do RotateDirectionToFaceTarget below. }
2326 end;
2327
2328 RotateDirectionToFaceTarget(DirectionToTarget,
2329 AngleBetweenDirectionToTarget);
2330 end else
2331 if WantToRunAway then
2332 begin
2333 CalculateDirectionFromEnemy(DirectionToTarget,
2334 AngleBetweenDirectionToTarget);
2335
2336 if WantToWalkInDesiredDirection(AngleBetweenDirectionToTarget) then
2337 begin
2338 if (not MoveAlongTheDirection) and
2339 (AngleBetweenDirectionToTarget <=
2340 AngleBetweenDirectionToTargetToResign) then
2341 begin
2342 { Maybe there exists some alternative way, not straight. Lets try. }
2343 InitAlternativeTarget;
2344 Exit;
2345 end;
2346 end;
2347
2348 RotateDirectionToFaceTarget(DirectionToTarget,
2349 AngleBetweenDirectionToTarget);
2350 end else
2351 begin
2352 if not HasLastSensedEnemy then
2353 begin
2354 { Nowhere to go; so just stay here. }
2355 SetState(csIdle);
2356 Exit;
2357 end;
2358
2359 UseWalkNormal := true;
2360
2361 SectorNow := Sector;
2362 if (SectorNow <> LastSensedEnemySector) and
2363 (SectorNow <> nil) and
2364 (LastSensedEnemySector <> nil) then
2365 begin
2366 { The way to LastSensedEnemy is using waypoints. }
2367
2368 { Recalculate WaypointsSaved.
2369 Note that I recalculate only when SectorNow or
2370 LastSensedEnemySector changed. }
2371 if (SectorNow <> WaypointsSaved_Begin) or
2372 (LastSensedEnemySector <> WaypointsSaved_End) then
2373 begin
2374 WaypointsSaved_Begin := SectorNow;
2375 WaypointsSaved_End := LastSensedEnemySector;
2376 TSectorList.FindWay(WaypointsSaved_Begin, WaypointsSaved_End,
2377 WaypointsSaved);
2378 end;
2379
2380 if WaypointsSaved.Count <> 0 then
2381 begin
2382 { There is a space around the waypoint that is within
2383 more than one sector. SectorWithPoint will then answer
2384 with any (it's not specified which) sector that has
2385 given position. This is problematic, because this means
2386 that the creature will be forced to go once again to the same
2387 waypoint that it's already at... This way there could arise
2388 a situation when the creature gets stuck at some waypoint,
2389 because we constantly detect that it must pass through this
2390 waypoint. The check for CloseEnoughToTarget below prevents this. }
2391 if CloseEnoughToTarget(WaypointsSaved[0].Position) then
2392 begin
2393 if WaypointsSaved.Count > 1 then
2394 begin
2395 WalkToWaypoint(WaypointsSaved[1].Position);
2396 UseWalkNormal := false;
2397 end;
2398 end else
2399 begin
2400 WalkToWaypoint(WaypointsSaved[0].Position);
2401 UseWalkNormal := false;
2402 end;
2403 end;
2404 end;
2405
2406 if UseWalkNormal then
2407 WalkNormal;
2408 end;
2409
2410 if FireMissileAllowed then
2411 SetState(csFireMissile) else
2412 if AttackAllowed then
2413 SetState(csAttack);
2414 end;
2415
2416 { Go to the default state, like "idle".
2417 Doing this instead of SetState(csIdle) avoids switching to "idle" just for
2418 a single frame, which looks bad (animation visibly jumps for 1 frame,
2419 and also animation blending is broken by such 1-frame change,
2420 since our animation blending now can only transition from last to next animation). }
2421 procedure BackToDefaultState;
2422 begin
2423 if DoIdle then
2424 SetState(csIdle);
2425 end;
2426
2427 procedure DoAttack;
2428 var
2429 StateTime: Single;
2430 begin
2431 StateTime := LifeTime - StateChangeTime;
2432 if (not AttackDone) and (StateTime >= Resource.AttackTime) then
2433 begin
2434 AttackDone := true;
2435 Attack;
2436 end;
2437 if StateTime > Resource.AttackAnimation.Duration then
2438 BackToDefaultState;
2439 end;
2440
2441 procedure DoFireMissile;
2442 var
2443 StateTime: Single;
2444 begin
2445 StateTime := LifeTime - StateChangeTime;
2446 if (not FireMissileDone) and (StateTime >= Resource.FireMissileTime) then
2447 begin
2448 FireMissileDone := true;
2449 FireMissile;
2450 end;
2451 if StateTime > Resource.FireMissileAnimation.Duration then
2452 BackToDefaultState;
2453 end;
2454
2455 procedure DoHurt;
2456 var
2457 StateTime: Single;
2458 begin
2459 StateTime := LifeTime - StateChangeTime;
2460
2461 if StateTime > Resource.HurtAnimation.Duration then
2462 begin
2463 CancelKnockback;
2464 BackToDefaultState;
2465 end;
2466 end;
2467
2468 { @true if last attack was from the back of the creature,
2469 @false if from the front or unknown (when LastHurtDirection is zero). }
2470 function WasLastAttackBack: boolean;
2471 begin
2472 try
2473 Result := AngleRadBetweenVectors(LastHurtDirection, Direction) < Pi/2;
2474 except
2475 on EVectorInvalidOp do Result := false;
2476 end;
2477 end;
2478
2479 procedure DoDie(const AnimationDuration: Single);
2480 begin
2481 if Resource.RemoveDead and
2482 (LifeTime - StateChangeTime > AnimationDuration) then
2483 RemoveMe := rtRemoveAndFree;
2484 end;
2485
2486 procedure UpdateDebugTransform;
2487 begin
2488 if RenderDebug then
2489 begin
2490 if FDebugAlternativeTargetAxis = nil then
2491 begin
2492 FDebugAlternativeTargetAxis := TDebugAxis.Create(Self, BlueRGB);
2493 FDebugTransform.ParentSpace.AddChildren(FDebugAlternativeTargetAxis.Root);
2494 FDebugTransform.ChangedScene;
2495 end;
2496
2497 FDebugAlternativeTargetAxis.Visible := HasAlternativeTarget;
2498 FDebugAlternativeTargetAxis.ScaleFromBox := BoundingBox;
2499 FDebugAlternativeTargetAxis.Position := AlternativeTarget;
2500
2501 if FDebugLastSensedEnemyAxis = nil then
2502 begin
2503 FDebugLastSensedEnemyAxis := TDebugAxis.Create(Self, RedRGB);
2504 FDebugTransform.ParentSpace.AddChildren(FDebugLastSensedEnemyAxis.Root);
2505 FDebugTransform.ChangedScene;
2506 end;
2507
2508 FDebugLastSensedEnemyAxis.Visible := HasLastSensedEnemy;
2509 FDebugLastSensedEnemyAxis.ScaleFromBox := BoundingBox;
2510 FDebugLastSensedEnemyAxis.Position := LastSensedEnemy;
2511 end;
2512 end;
2513
2514 var
2515 E: TCastleTransform;
2516 begin
2517 inherited;
2518 if (not Exists) or DebugTimeStopForCreatures then Exit;
2519
2520 { eventually turn off InternalMiddleForceBox }
2521 InternalMiddleForceBox := InternalMiddleForceBox and (LifeTime <= InternalMiddleForceBoxTime);
2522
2523 if Dead and not (State in [csDie, csDieBack]) then
2524 begin
2525 if Resource.DieBackAnimation.Defined and WasLastAttackBack then
2526 SetState(csDieBack)
2527 else
2528 SetState(csDie);
2529 UpdateResourceFrame;
2530 Exit;
2531 end;
2532
2533 E := Enemy;
2534 EnemySensedNow := (E <> nil) and (
2535 (
2536 { enemy seen }
2537 (AngleRadBetweenNormals(E.Middle - Middle, Direction) <=
2538 Resource.VisibilityAngle / 2) and
2539 LineOfSight(Middle, E.Middle)
2540 ) or
2541 (
2542 { enemy smelled }
2543 PointsDistanceSqr(E.Middle, Middle) < Sqr(Resource.SmellDistance)
2544 ) );
2545 if EnemySensedNow then
2546 begin
2547 HasLastSensedEnemy := true;
2548 LastSensedEnemy := E.Middle;
2549 LastSensedEnemySector := Sector(E);
2550 end;
2551
2552 if HasLastSensedEnemy then
2553 begin
2554 SqrDistanceToLastSensedEnemy := PointsDistanceSqr(LastSensedEnemy, Middle);
2555 end;
2556
2557 case FState of
2558 csIdle: DoIdle;
2559 csWalk: DoWalk;
2560 csAttack: DoAttack;
2561 csFireMissile: DoFireMissile;
2562 csDie : DoDie(Resource.DieAnimation.Duration);
2563 csDieBack: DoDie(Resource.DieBackAnimation.Duration);
2564 csHurt: DoHurt;
2565 end;
2566
2567 { Flying creatures may change their direction vector freely.
2568 However, we want them to keep their sense of up --- they should try
2569 to keep straight, so their up vector should try to remain close
2570 to GravityUp, not just change wildly.
2571
2572 For non-flying, this is not needed, as then Up should always remain equal
2573 to initial value, which is GravityUp. }
2574 {$warnings off} // using deprecated in deprecated
2575 if not Gravity then
2576 {$warnings on}
2577 UpPrefer(World.GravityUp);
2578
2579 UpdateDebugTransform;
2580 UpdateResourceFrame;
2581 end;
2582
2583 procedure TWalkAttackCreature.SetLife(const Value: Single);
2584 begin
2585 if (not Dead) and
2586 (Life - Value > Resource.MinLifeLossToHurt * MaxLife) and
2587 ( (Resource.ChanceToHurt = 1.0) or
2588 (Random < Resource.ChanceToHurt) ) then
2589 SetState(csHurt);
2590 inherited;
2591 end;
2592
2593 procedure TWalkAttackCreature.Attack;
2594 var
2595 {$warnings off} // using deprecated in deprecated
2596 E: TCastleAlive;
2597 {$warnings on}
2598
2599 function ShortRangeAttackHits: boolean;
2600 var
2601 B, EB: TBox3D;
2602 DistanceLength, DistanceIncrease: Single;
2603 begin
2604 if E = nil then Exit(false); { no enemy to hurt }
2605 B := BoundingBox;
2606 EB := E.BoundingBox;
2607
2608 { We would like to check collision between EB and our B translated
2609 by our Direction now, i.e.
2610 B.Translate(Direction * ???).Collision(EB)
2611 But how much should be scale Direction, i.e. what to put for "???" ?
2612 It must be large enough to compensate even large Resource.AttackMaxDistance,
2613 it must be small enough so that enemy should not be able to avoid
2614 our attacks just by standing very close to the creature.
2615
2616 So we have to check a couple of bounding boxes.
2617 If we move our boxes by Box3DMinSize(B), we're sure that
2618 each box will stick to the previous and next. But maybe
2619 there will be some areas around the sticking points ?
2620 So B.MinSize / 2 seems safe. }
2621 DistanceIncrease := B.MinSize / 2;
2622
2623 DistanceLength := DistanceIncrease;
2624 while DistanceLength < Resource.AttackMaxDistance do
2625 begin
2626 if B.Translate(Direction * DistanceLength).Collision(EB) then
2627 Exit(true);
2628 DistanceLength := DistanceLength + DistanceIncrease;
2629 end;
2630
2631 { Check one last time for Resource.AttackMaxDistance }
2632 Result := B.Translate(Direction * Resource.AttackMaxDistance).Collision(EB);
2633 end;
2634
2635 begin
2636 E := Enemy;
2637 if ShortRangeAttackHits then
2638 begin
2639 Sound3d(Resource.AttackSoundHit, 1.0);
2640 AttackHurt(E);
2641 end;
2642 end;
2643
2644 procedure TWalkAttackCreature.FireMissile;
2645 var
2646 Missile: TCreature;
2647 MissilePosition, MissileDirection: TVector3;
2648 begin
2649 if (Resource.FireMissileName <> '') and HasLastSensedEnemy then
2650 begin
2651 MissilePosition := LerpLegsMiddle(Resource.FireMissileHeight);
2652 MissileDirection := LastSensedEnemy - MissilePosition;
2653 Missile := (Resources.FindName(Resource.FireMissileName) as TCreatureResource).
2654 CreateCreature(Level, MissilePosition, MissileDirection);
2655 Missile.Sound3d(Resource.FireMissileSound, 0.0);
2656 end;
2657 end;
2658
2659 procedure TWalkAttackCreature.UpdateDebugCaption(const Lines: TCastleStringList);
2660 var
2661 StateName: string;
2662 begin
2663 inherited;
2664
2665 case State of
2666 csIdle : StateName := 'Idle';
2667 csWalk : StateName := 'Walk';
2668 csAttack : StateName := 'Attack';
2669 csFireMissile: StateName := 'FireMissile';
2670 csDie : StateName := 'Die';
2671 csDieBack : StateName := 'DieBack';
2672 csHurt : StateName := 'Hurt';
2673 else StateName := Format('Custom State %d', [State]);
2674 end;
2675 Lines.Add(StateName);
2676
2677 if HasLastSensedEnemy then
2678 Lines.Add(Format('Enemy sensed distance: %f',
2679 [PointsDistance(LastSensedEnemy, Middle)]));
2680 end;
2681
2682 procedure TWalkAttackCreature.Hurt(const LifeLoss: Single;
2683 const HurtDirection: TVector3;
2684 const AKnockbackDistance: Single; const Attacker: TCastleAlive);
2685 begin
2686 inherited Hurt(LifeLoss, HurtDirection,
2687 AKnockbackDistance * Resource.KnockBackDistance, Attacker);
2688
2689 { If attacked by Enemy, update LastSensedEnemy fields.
2690 This way when you attack a creature from the back, it will turn around
2691 and fight you. }
2692 if (Attacker <> nil) and (Attacker = Enemy) then
2693 begin
2694 HasLastSensedEnemy := true;
2695 LastSensedEnemy := Attacker.Middle;
2696 LastSensedEnemySector := Sector(Attacker);
2697 end;
2698 end;
2699
2700 { TMissileCreature ----------------------------------------------------------- }
2701
2702 constructor TMissileCreature.Create(AOwner: TComponent; const AMaxLife: Single);
2703 begin
2704 inherited;
2705
2706 { We will check for collisions when missile moves. }
2707 Collides := false;
2708 end;
2709
2710 function TMissileCreature.Resource: TMissileCreatureResource;
2711 begin
2712 Result := TMissileCreatureResource(inherited Resource);
2713 end;
2714
2715 procedure TMissileCreature.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
2716
2717 procedure UpdateResourceFrame;
2718 begin
2719 if Dead and Resource.DieAnimation.Defined then
2720 FResourceFrame.SetFrame(Level, Resource.DieAnimation, LifeTime - DieTime, false)
2721 else
2722 FResourceFrame.SetFrame(Level, Resource.FlyAnimation, LifeTime, true);
2723 end;
2724
2725 var
2726 Player: TCastleTransform;
2727
2728 function MissileMoveAllowed(const OldPos, NewPos: TVector3): boolean;
2729 var
2730 SavedPlayerExists: Boolean;
2731 SavedCreaturesRootExists: Boolean;
2732 begin
2733 {$warnings off} // using deprecated in deprecated
2734 if (not Resource.HitsPlayer) and (Player <> nil) then
2735 begin
2736 SavedPlayerExists := Player.Exists;
2737 Player.Exists := false;
2738 end;
2739 {$warnings on}
2740 if not Resource.HitsCreatures then
2741 begin
2742 SavedCreaturesRootExists := Level.CreaturesRoot.Exists;
2743 Level.CreaturesRoot.Exists := false;
2744 end;
2745 try
2746 Result := MoveAllowed(OldPos, NewPos, false);
2747 finally
2748 if not Resource.HitsCreatures then
2749 Level.CreaturesRoot.Exists := SavedCreaturesRootExists;
2750 {$warnings off} // using deprecated in deprecated
2751 if (not Resource.HitsPlayer) and (Player <> nil) then
2752 Player.Exists := SavedPlayerExists;
2753 {$warnings on}
2754 end;
2755 end;
2756
2757 var
2758 OldMiddle, NewMiddle: TVector3;
2759 AngleBetween, AngleChange: Single;
2760 NewDirection, TargetDirection: TVector3;
2761 I: Integer;
2762 C: TCreature;
2763 begin
2764 inherited;
2765 if (not Exists) or DebugTimeStopForCreatures then Exit;
2766
2767 if Dead then
2768 begin
2769 if (Resource.RemoveDead or ForceRemoveDead) and
2770 (LifeTime - DieTime > Resource.DieAnimation.Duration) then
2771 RemoveMe := rtRemoveAndFree;
2772 Exit;
2773 end;
2774
2775 Player := Level.GetPlayer;
2776
2777 { Missile moves *always*, regardless of MissileMoveAllowed result.
2778 Only after move, if the move made us colliding with something --- we explode. }
2779 OldMiddle := Middle;
2780 Translate(Direction * (Resource.MoveSpeed * SecondsPassed));
2781 NewMiddle := Middle;
2782
2783 if not MissileMoveAllowed(OldMiddle, NewMiddle) then
2784 begin
2785 { Check collision missile <-> player.
2786 Maybe I'll switch to using bounding Sphere here one day?
2787 No reason for sphere or box, either way, for now. }
2788 if Resource.HitsPlayer and
2789 (Player <> nil) and
2790 Player.BoundingBox.Collision(BoundingBox) then
2791 HitPlayer;
2792
2793 if Resource.HitsCreatures then
2794 begin
2795 { TODO: this is unclean. We would prefer to use World.WorldSphereCollision,
2796 wrapped inside MySphereCollision to prevent self-collisions.
2797 However, we need to know which TCreature was actually hit ---
2798 so SphereCollision would need to return a hierarchy of T3D objects,
2799 much like RayCollision.
2800
2801 For now, just browse World directly. }
2802
2803 { Check bounding Sphere of the missile <-> creature's BoundingBox.
2804 Bounding Sphere is better for arrow, that has very large geometry
2805 but small enough bounding Sphere (because bounding Sphere radius
2806 may be adjusted by resource.xml). }
2807 for I := 0 to World.Count - 1 do
2808 if World[I] is TCreature then
2809 begin
2810 C := TCreature(World[I]);
2811 if (C <> Self) and C.CheckCollides and
2812 C.BoundingBox.SphereSimpleCollision(Middle, Radius) then
2813 begin
2814 HitCreature(C);
2815 { TODO: projectiles shouldn't do here "break". }
2816 break;
2817 end;
2818 end;
2819 end;
2820
2821 HitCore;
2822 end;
2823
2824 if Resource.DirectionFallSpeed <> 0 then
2825 begin
2826 NewDirection := Direction -
2827 World.GravityUp * Resource.DirectionFallSpeed * SecondsPassed;
2828 Direction := NewDirection;
2829 end;
2830
2831 if (Resource.CloseDirectionToTargetSpeed <> 0.0) and (Player <> nil) then
2832 begin
2833 TargetDirection := Player.Translation - Translation;
2834 AngleBetween := AngleRadBetweenVectors(TargetDirection, Direction);
2835 AngleChange := Resource.CloseDirectionToTargetSpeed * SecondsPassed;
2836 if AngleBetween <= AngleChange then
2837 Direction := TargetDirection else
2838 begin
2839 NewDirection := Direction;
2840 MakeVectorsAngleRadOnTheirPlane(NewDirection, TargetDirection,
2841 AngleBetween - AngleChange, NewDirection);
2842 Direction := NewDirection;
2843 end;
2844 end;
2845
2846 if (LastSoundIdleTime = 0) or
2847 (LifeTime - LastSoundIdleTime > Resource.PauseBetweenSoundIdle) then
2848 begin
2849 LastSoundIdleTime := LifeTime;
2850 Sound3d(Resource.SoundIdle, 0.0);
2851 end;
2852
2853 UpdateResourceFrame;
2854 end;
2855
2856 procedure TMissileCreature.HitCore;
2857 begin
2858 { TODO: for some missiles, their explosion may hurt everyone around.
2859 So do here additional checks for collision and hurt player and creatures. }
2860
2861 Sound3d(Resource.SoundHit, 0, false);
2862 Hurt(1000 * 1000, TVector3.Zero, 0, Self);
2863 end;
2864
2865 procedure TMissileCreature.HitPlayer;
2866 begin
2867 ForceRemoveDead := true;
2868 {$warnings off} // using deprecated in deprecated
2869 AttackHurt(Level.GetPlayer as TCastleAlive);
2870 {$warnings on}
2871 end;
2872
2873 procedure TMissileCreature.HitCreature(Creature: TCreature);
2874 begin
2875 ForceRemoveDead := true;
2876 AttackHurt(Creature);
2877 end;
2878
2879 { TStillCreature ----------------------------------------------------------- }
2880
2881 function TStillCreature.Resource: TStillCreatureResource;
2882 begin
2883 Result := TStillCreatureResource(inherited Resource);
2884 end;
2885
2886 procedure TStillCreature.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
2887
2888 procedure UpdateResourceFrame;
2889 begin
2890 if Dead and Resource.DieAnimation.Defined then
2891 FResourceFrame.SetFrame(Level, Resource.DieAnimation, LifeTime - DieTime, false)
2892 else
2893 FResourceFrame.SetFrame(Level, Resource.IdleAnimation, LifeTime, true);
2894 end;
2895
2896 begin
2897 inherited;
2898 if (not Exists) or DebugTimeStopForCreatures then Exit;
2899
2900 if Dead then
2901 begin
2902 if Resource.RemoveDead and (LifeTime - DieTime > Resource.DieAnimation.Duration) then
2903 RemoveMe := rtRemoveAndFree;
2904 end;
2905
2906 UpdateResourceFrame;
2907 end;
2908
2909 { initialization / finalization ---------------------------------------------- }
2910
2911 initialization
2912 RegisterResourceClass(TWalkAttackCreatureResource, 'WalkAttack');
2913 RegisterResourceClass(TMissileCreatureResource, 'Missile');
2914 RegisterResourceClass(TStillCreatureResource, 'Still');
2915 end.