GameScript: Move initialization out of constructor.
[gemrb.git] / gemrb / core / Actor.cpp
blobecd47f946ddb01d42302b1026fd86849e717cb44
1 /* GemRB - Infinity Engine Emulator
2 * Copyright (C) 2003 The GemRB Project
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program 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. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 //This class represents the .cre (creature) files.
22 //Any player or non-player character is a creature.
23 //Actor is a scriptable object (Scriptable). See ActorBlock.cpp
25 #include "win32def.h"
26 #include <cassert>
27 #include "TableMgr.h"
28 #include "Audio.h" //pst (react to death sounds)
29 #include "Actor.h"
30 #include "Interface.h"
31 #include "strrefs.h"
32 #include "overlays.h"
33 #include "Item.h"
34 #include "Spell.h"
35 #include "Projectile.h"
36 #include "Game.h"
37 #include "GameScript.h"
38 #include "GameControl.h" //checking for dialog
39 #include "ScriptEngine.h"
40 #include "GSUtils.h" //needed for DisplayStringCore
41 #include "Video.h"
42 #include "damages.h"
43 #include "ProjectileServer.h"
44 #include "GameData.h"
46 static const Color green = {
47 0x00, 0xff, 0x00, 0xff
49 static const Color red = {
50 0xff, 0x00, 0x00, 0xff
52 static const Color yellow = {
53 0xff, 0xff, 0x00, 0xff
55 static const Color cyan = {
56 0x00, 0xff, 0xff, 0xff
58 static const Color magenta = {
59 0xff, 0x00, 0xff, 0xff
62 static int sharexp = SX_DIVIDE;
63 static int classcount = -1;
64 static char **clericspelltables = NULL;
65 static char **druidspelltables = NULL;
66 static char **wizardspelltables = NULL;
67 static int *turnlevels = NULL;
68 static int *booktypes = NULL;
69 static int *xpbonus = NULL;
70 static int xpbonustypes = -1;
71 static int xpbonuslevels = -1;
72 static int **levelslots = NULL;
73 static int *dualswap = NULL;
74 static int *maxhpconbon = NULL;
75 //static ieVariable IWDDeathVarFormat = "KILL_%s_CNT";
76 //static ieVariable DeathVarFormat = "SPRITE_IS_DEAD%s";
77 static ieVariable CounterNames[4]={"GOOD","LAW","LADY","MURDER"};
79 static int FistRows = -1;
80 int *wmlevels[20];
81 typedef ieResRef FistResType[MAX_LEVEL+1];
83 static FistResType *fistres = NULL;
84 static ieResRef DefaultFist = {"FIST"};
86 //item usability array
87 struct ItemUseType {
88 ieResRef table; //which table contains the stat usability flags
89 ieByte stat; //which actor stat we talk about
90 ieByte mcol; //which column should be matched against the stat
91 ieByte vcol; //which column has the bit value for it
92 ieByte which; //which item dword should be used (1 = kit)
95 static ItemUseType *itemuse = NULL;
96 static int usecount = -1;
98 //item animation override array
99 struct ItemAnimType {
100 ieResRef itemname;
101 ieByte animation;
104 static ItemAnimType *itemanim = NULL;
105 static int animcount = -1;
107 static int fiststat = IE_CLASS;
109 //conversion for 3rd ed
110 static int isclass[11]={0,0,0,0,0,0,0,0,0,0,0};
112 static const int mcwasflags[11] = {
113 MC_WAS_FIGHTER, MC_WAS_MAGE, MC_WAS_THIEF, 0, 0, MC_WAS_CLERIC,
114 MC_WAS_DRUID, 0, 0, MC_WAS_RANGER, 0};
115 static const char *isclassnames[11] = {
116 "FIGHTER", "MAGE", "THIEF", "BARBARIAN", "BARD", "CLERIC",
117 "DRUID", "MONK", "PALADIN", "RANGER", "SORCERER" };
118 static const int levelslotsiwd2[11]={IE_LEVELFIGHTER,IE_LEVELMAGE,IE_LEVELTHIEF,
119 IE_LEVELBARBARIAN,IE_LEVELBARD,IE_LEVELCLERIC,IE_LEVELDRUID,IE_LEVELMONK,
120 IE_LEVELPALADIN,IE_LEVELRANGER,IE_LEVELSORCEROR};
122 //stat values are 0-255, so a byte is enough
123 static ieByte featstats[MAX_FEATS]={0
126 //holds the wspecial table for weapon prof bonuses
127 #define WSPECIAL_COLS 3
128 static int wspecial_max = 0;
129 static int wspattack_rows = 0;
130 static int wspattack_cols = 0;
131 static int **wspecial = NULL;
132 static int **wspattack = NULL;
134 //holds the weapon style bonuses
135 #define STYLE_MAX 3
136 static int **wsdualwield = NULL;
137 static int **wstwohanded = NULL;
138 static int **wsswordshield = NULL;
139 static int **wssingle = NULL;
141 //unhardcoded monk bonuses
142 static int **monkbon = NULL;
143 static int monkbon_cols = 0;
144 static int monkbon_rows = 0;
146 // reputation modifiers
147 static int **reputationmod = NULL;
148 #define CLASS_PCCUTOFF 32
149 #define CLASS_INNOCENT 155
150 #define CLASS_FLAMINGFIST 156
152 static ActionButtonRow *GUIBTDefaults = NULL; //qslots row count
153 ActionButtonRow DefaultButtons = {ACT_TALK, ACT_WEAPON1, ACT_WEAPON2,
154 ACT_NONE, ACT_NONE, ACT_NONE, ACT_NONE, ACT_NONE, ACT_NONE, ACT_NONE,
155 ACT_NONE, ACT_INNATE};
156 static int QslotTranslation = FALSE;
157 static int DeathOnZeroStat = TRUE;
158 static ieDword TranslucentShadows = 0;
159 static int ProjectileSize = 0; //the size of the projectile immunity bitfield (dwords)
161 static const char iwd2gemrb[32] = {
162 0,0,20,2,22,25,0,14,
163 15,23,13,0,1,24,8,21,
164 0,0,0,0,0,0,0,0,
165 0,0,0,0,0,0,0,0
167 static const char gemrb2iwd[32] = {
168 11,12,3,71,72,73,0,0, //0
169 14,80,83,82,81,10,7,8, //8
170 0,0,0,0,2,15,4,9, //16
171 13,5,0,0,0,0,0,0 //24
174 //letters for char sound resolution bg1/bg2
175 static char csound[VCONST_COUNT];
177 static void InitActorTables();
179 #define DAMAGE_LEVELS 19
180 #define ATTACKROLL 20
181 #define SAVEROLL 20
182 #define DEFAULTAC 10
184 static ieResRef d_main[DAMAGE_LEVELS] = {
185 //slot 0 is not used in the original engine
186 "BLOODCR","BLOODS","BLOODM","BLOODL", //blood
187 "SPFIRIMP","SPFIRIMP","SPFIRIMP", //fire
188 "SPSHKIMP","SPSHKIMP","SPSHKIMP", //spark
189 "SPFIRIMP","SPFIRIMP","SPFIRIMP", //ice
190 "SHACID","SHACID","SHACID", //acid
191 "SPDUSTY2","SPDUSTY2","SPDUSTY2" //disintegrate
193 static ieResRef d_splash[DAMAGE_LEVELS] = {
194 "","","","",
195 "SPBURN","SPBURN","SPBURN", //flames
196 "SPSPARKS","SPSPARKS","SPSPARKS", //sparks
197 "","","",
198 "","","",
199 "","",""
202 #define BLOOD_GRADIENT 19
203 #define FIRE_GRADIENT 19
204 #define ICE_GRADIENT 71
205 #define STONE_GRADIENT 93
207 static int d_gradient[DAMAGE_LEVELS] = {
208 BLOOD_GRADIENT,BLOOD_GRADIENT,BLOOD_GRADIENT,BLOOD_GRADIENT,
209 FIRE_GRADIENT,FIRE_GRADIENT,FIRE_GRADIENT,
210 -1,-1,-1,
211 ICE_GRADIENT,ICE_GRADIENT,ICE_GRADIENT,
212 -1,-1,-1,
213 -1,-1,-1
216 static ieResRef hc_overlays[OVERLAY_COUNT]={"SANCTRY","SPENTACI","SPMAGGLO","SPSHIELD",
217 "GREASED","WEBENTD","MINORGLB","","","","","","","","","","","","","","",
218 "","","","SPTURNI2","SPTURNI","","","","","",""};
219 static ieDword hc_locations=0x2ba80030;
221 static int *mxsplwis = NULL;
222 static int spllevels;
224 //for every game except IWD2 we need to reverse TOHIT
225 static int ReverseToHit=TRUE;
226 static int CheckAbilities=FALSE;
228 //internal flags for calculating to hit
229 #define WEAPON_FIST 0
230 #define WEAPON_MELEE 1
231 #define WEAPON_RANGED 2
232 #define WEAPON_STYLEMASK 15
233 #define WEAPON_LEFTHAND 16
234 #define WEAPON_USESTRENGTH 32
236 /* counts the on bits in a number */
237 ieDword bitcount (ieDword n)
239 ieDword count=0;
240 while (n) {
241 count += n & 0x1u;
242 n >>= 1;
244 return count;
247 void ReleaseMemoryActor()
249 if (mxsplwis) {
250 //calloc'd x*y integer matrix
251 free (mxsplwis);
252 mxsplwis = NULL;
255 if (fistres) {
256 delete [] fistres;
257 fistres = NULL;
260 if (itemuse) {
261 delete [] itemuse;
262 itemuse = NULL;
265 if (itemanim) {
266 delete [] itemanim;
267 itemanim = NULL;
269 FistRows = -1;
272 Actor::Actor()
273 : Movable( ST_ACTOR )
275 int i;
277 for (i = 0; i < MAX_STATS; i++) {
278 BaseStats[i] = 0;
279 Modified[i] = 0;
282 SmallPortrait[0] = 0;
283 LargePortrait[0] = 0;
285 anims = NULL;
286 ShieldRef[0]=0;
287 HelmetRef[0]=0;
288 WeaponRef[0]=0;
289 for (i = 0; i < EXTRA_ACTORCOVERS; ++i)
290 extraCovers[i] = NULL;
292 LongName = NULL;
293 ShortName = NULL;
294 LongStrRef = (ieStrRef) -1;
295 ShortStrRef = (ieStrRef) -1;
297 LastProtected = 0;
298 LastFollowed = 0;
299 LastCommander = 0;
300 LastHelp = 0;
301 LastSeen = 0;
302 LastMarked = 0;
303 LastHeard = 0;
304 PCStats = NULL;
305 LastCommand = 0; //used by order
306 LastShout = 0; //used by heard
307 LastDamage = 0;
308 LastDamageType = 0;
309 HotKey = 0;
310 attackcount = 0;
311 attacksperround = 0;
312 nextattack = 0;
313 InTrap = 0;
314 PathTries = 0;
315 TargetDoor = NULL;
316 attackProjectile = NULL;
317 lastInit = 0;
318 roundTime = 0;
319 lastattack = 0;
321 inventory.SetInventoryType(INVENTORY_CREATURE);
322 Equipped = 0;
323 EquippedHeader = 0;
325 fxqueue.SetOwner( this );
326 inventory.SetOwner( this );
327 if (classcount<0) {
328 //This block is executed only once, when the first actor is loaded
329 InitActorTables();
331 TranslucentShadows = 0;
332 core->GetDictionary()->Lookup("Translucent Shadows", TranslucentShadows);
333 //get the needed size to store projectile immunity bitflags in Dwords
334 ProjectileSize = (core->GetProjectileServer()->GetHighestProjectileNumber()+31)/32;
335 //allowing 1024 bits (1024 projectiles ought to be enough for everybody)
336 //the rest of the projectiles would still work, but couldn't be resisted
337 if (ProjectileSize>32) {
338 ProjectileSize=32;
341 projectileImmunity = (ieDword *) calloc(ProjectileSize,sizeof(ieDword));
342 AppearanceFlags = 0;
343 SetDeathVar = IncKillCount = 0;
344 InParty = 0;
345 TalkCount = 0;
346 InteractCount = 0; //numtimesinteracted depends on this
347 appearance = 0xffffff; //might be important for created creatures
348 RemovalTime = ~0;
349 version = 0;
350 //these are used only in iwd2 so we have to default them
351 for(i=0;i<7;i++) {
352 BaseStats[IE_HATEDRACE2+i]=0xff;
354 //this one is saved only for PC's
355 ModalState = 0;
356 //set it to a neutral value
357 ModalSpell[0] = '*';
358 //this one is saved, but not loaded?
359 localID = globalID = 0;
360 //this one is not saved
361 GotLUFeedback = false;
364 Actor::~Actor(void)
366 unsigned int i;
368 delete anims;
370 core->FreeString( LongName );
371 core->FreeString( ShortName );
373 delete PCStats;
375 for (i = 0; i < vvcOverlays.size(); i++) {
376 if (vvcOverlays[i]) {
377 delete vvcOverlays[i];
378 vvcOverlays[i] = NULL;
381 for (i = 0; i < vvcShields.size(); i++) {
382 if (vvcShields[i]) {
383 delete vvcShields[i];
384 vvcShields[i] = NULL;
387 for (i = 0; i < EXTRA_ACTORCOVERS; i++)
388 delete extraCovers[i];
390 delete attackProjectile;
392 free(projectileImmunity);
395 void Actor::SetFistStat(ieDword stat)
397 fiststat = stat;
400 void Actor::SetDefaultActions(int qslot, ieByte slot1, ieByte slot2, ieByte slot3)
402 QslotTranslation=qslot;
403 DefaultButtons[0]=slot1;
404 DefaultButtons[1]=slot2;
405 DefaultButtons[2]=slot3;
408 void Actor::SetName(const char* ptr, unsigned char type)
410 size_t len = strlen( ptr ) + 1;
411 //32 is the maximum possible length of the actor name in the original games
412 if (len>32) len=33;
413 if (type!=2) {
414 LongName = ( char * ) realloc( LongName, len );
415 memcpy( LongName, ptr, len );
416 core->StripLine( LongName, len );
418 if (type!=1) {
419 ShortName = ( char * ) realloc( ShortName, len );
420 memcpy( ShortName, ptr, len );
421 core->StripLine( ShortName, len );
425 void Actor::SetName(int strref, unsigned char type)
427 if (type!=2) {
428 if (LongName) free(LongName);
429 LongName = core->GetString( strref, IE_STR_REMOVE_NEWLINE );
431 if (type!=1) {
432 if (ShortName) free(ShortName);
433 ShortName = core->GetString( strref, IE_STR_REMOVE_NEWLINE );
437 void Actor::SetAnimationID(unsigned int AnimID)
439 //if the palette is locked, then it will be transferred to the new animation
440 Palette *recover = NULL;
442 if (anims) {
443 if (anims->lockPalette) {
444 recover = anims->palette[PAL_MAIN];
446 // Take ownership so the palette won't be deleted
447 if (recover) {
448 recover->IncRef();
450 delete( anims );
452 //hacking PST no palette
453 if (core->HasFeature(GF_ONE_BYTE_ANIMID) ) {
454 if ((AnimID&0xf000)==0xe000) {
455 if (BaseStats[IE_COLORCOUNT]) {
456 printMessage("Actor"," ",YELLOW);
457 printf("Animation ID %x is supposed to be real colored (no recoloring), patched creature\n", AnimID);
459 BaseStats[IE_COLORCOUNT]=0;
462 anims = new CharAnimations( AnimID&0xffff, BaseStats[IE_ARMOR_TYPE]);
463 if(anims->ResRef[0] == 0) {
464 delete anims;
465 anims = NULL;
466 printMessage("Actor", " ",LIGHT_RED);
467 printf("Missing animation for %s\n",LongName);
468 return;
470 anims->SetOffhandRef(ShieldRef);
471 anims->SetHelmetRef(HelmetRef);
472 anims->SetWeaponRef(WeaponRef);
474 //if we have a recovery palette, then set it back
475 assert(anims->palette[PAL_MAIN] == 0);
476 anims->palette[PAL_MAIN] = recover;
477 if (recover) {
478 anims->lockPalette = true;
480 //bird animations are not hindered by searchmap
481 //only animtype==7 (bird) uses this feature
482 //this is a hardcoded hack, but works for all engine type
483 if (anims->GetAnimType()!=IE_ANI_BIRD) {
484 BaseStats[IE_DONOTJUMP]=0;
485 } else {
486 BaseStats[IE_DONOTJUMP]=DNJ_BIRD;
488 SetCircleSize();
489 anims->SetColors(BaseStats+IE_COLORS);
492 CharAnimations* Actor::GetAnims()
494 return anims;
497 /** Returns a Stat value (Base Value + Mod) */
498 ieDword Actor::GetStat(unsigned int StatIndex) const
500 if (StatIndex >= MAX_STATS) {
501 return 0xdadadada;
503 return Modified[StatIndex];
506 void Actor::SetCircleSize()
508 const Color *color;
509 int color_index;
511 if (!anims)
512 return;
514 if (UnselectableTimer) {
515 color = &magenta;
516 color_index = 4;
517 } else if (Modified[IE_STATE_ID] & STATE_PANIC) {
518 color = &yellow;
519 color_index = 5;
520 } else {
521 switch (Modified[IE_EA]) {
522 case EA_PC:
523 case EA_FAMILIAR:
524 case EA_ALLY:
525 case EA_CONTROLLED:
526 case EA_CHARMED:
527 case EA_EVILBUTGREEN:
528 case EA_GOODCUTOFF:
529 color = &green;
530 color_index = 0;
531 break;
533 case EA_ENEMY:
534 case EA_GOODBUTRED:
535 case EA_EVILCUTOFF:
536 color = &red;
537 color_index = 1;
538 break;
539 default:
540 color = &cyan;
541 color_index = 2;
542 break;
546 int csize = anims->GetCircleSize() - 1;
547 if (csize >= MAX_CIRCLE_SIZE)
548 csize = MAX_CIRCLE_SIZE - 1;
550 SetCircle( anims->GetCircleSize(), *color, core->GroundCircles[csize][color_index], core->GroundCircles[csize][(color_index == 0) ? 3 : color_index] );
553 void ApplyClab(Actor *actor, const char *clab, int level)
555 AutoTable table(clab);
556 if (table) {
557 int row = table->GetRowCount();
558 for(int i=0;i<level;i++) {
559 for (int j=0;j<row;j++) {
560 const char *res = table->QueryField(j,i);
561 if (!memcmp(res,"AP_",3)) {
562 core->ApplySpell(res+2, actor, actor, 0);
564 else if (!memcmp(res,"GA_",3)) {
565 actor->LearnSpell(res+2, 0);
567 else if (!memcmp(res,"FA_",3)) {//iwd2 only
568 int x=atoi(res+3);
569 core->DisplayStringName(x,0xffffff,actor,0);
571 else if (!memcmp(res,"FS_",3)) {//iwd2? (song?)
572 int x=atoi(res+3);
573 core->DisplayStringName(x,0xffffff,actor,0);
575 else if (!memcmp(res,"RA_",3)) {//iwd2
576 int x=atoi(res+3);
577 core->DisplayStringName(x,0xffffff,actor,0);
584 #define BG2_KITMASK 0xffffc000
585 #define KIT_BARBARIAN 0x4000
586 #define KIT_BASECLASS 0x40000000
588 //applies a kit on the character (only bg2)
589 bool Actor::ApplyKit(ieDword Value)
591 //get current unmodified level (i guess)
592 int level = GetXPLevel(false);
593 AutoTable table("kitlist");
594 if (table) {
595 ieDword row;
596 //find row by unusability
597 row = table->GetRowCount();
598 while (row) {
599 row--;
600 ieDword Unusability = (ieDword) strtol(table->QueryField(row, 6),NULL,0);
601 if (Value == Unusability) {
602 goto found_row;
605 //if it wasn't found, try the bg2 kit format
606 if ((Value&BG2_KITMASK)==KIT_BARBARIAN) {
607 row = (Value<<16);
609 //cannot find kit
610 if (table->GetRowCount()>=row) {
611 return false;
613 found_row:
614 ieDword cls = (ieDword) atoi(table->QueryField(row, 7));
615 if (cls!=BaseStats[IE_CLASS]) {
616 //cannot apply kit, because the class doesn't fit
617 return false;
619 const char *clab = table->QueryField(row, 4);
620 ApplyClab(this, clab, level);
622 return true;
625 //call this when morale or moralebreak changed
626 //cannot use old or new value, because it is called two ways
627 void pcf_morale (Actor *actor, ieDword /*oldValue*/, ieDword /*newValue*/)
629 if ((actor->Modified[IE_MORALE]<=actor->Modified[IE_MORALEBREAK]) && (actor->Modified[IE_MORALEBREAK] != 0) ) {
630 actor->Panic();
632 //for new colour
633 actor->SetCircleSize();
636 void pcf_ea (Actor *actor, ieDword /*oldValue*/, ieDword /*newValue*/)
638 if (actor->InParty) core->GetGame()->SelectActor(actor, false, SELECT_NORMAL);
639 actor->SetCircleSize();
642 //this is a good place to recalculate level up stuff
643 void pcf_level (Actor *actor, ieDword /*oldValue*/, ieDword /*newValue*/)
645 ieDword sum =
646 actor->GetFighterLevel()+
647 actor->GetMageLevel()+
648 actor->GetThiefLevel()+
649 actor->GetBarbarianLevel()+
650 actor->GetBardLevel()+
651 actor->GetClericLevel()+
652 actor->GetDruidLevel()+
653 actor->GetMonkLevel()+
654 actor->GetPaladinLevel()+
655 actor->GetRangerLevel()+
656 actor->GetSorcererLevel();
657 actor->SetBase(IE_CLASSLEVELSUM,sum);
658 actor->SetupFist();
659 actor->GotLUFeedback = false;
662 void pcf_class (Actor *actor, ieDword /*oldValue*/, ieDword newValue)
664 actor->InitButtons(newValue, false);
666 int sorcerer=0;
667 if (newValue<(ieDword) classcount) {
668 switch(booktypes[newValue]) {
669 case 2: sorcerer = 1<<IE_SPELL_TYPE_WIZARD; break;
670 case 3: sorcerer = 1<<IE_SPELL_TYPE_PRIEST; break;
671 default: break;
674 actor->spellbook.SetBookType(sorcerer);
677 void pcf_animid(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
679 actor->SetAnimationID(newValue);
682 static const ieDword fullwhite[7]={ICE_GRADIENT,ICE_GRADIENT,ICE_GRADIENT,ICE_GRADIENT,ICE_GRADIENT,ICE_GRADIENT,ICE_GRADIENT};
684 static const ieDword fullstone[7]={STONE_GRADIENT,STONE_GRADIENT,STONE_GRADIENT,STONE_GRADIENT,STONE_GRADIENT,STONE_GRADIENT,STONE_GRADIENT};
686 void pcf_state(Actor *actor, ieDword /*oldValue*/, ieDword State)
688 if (State & STATE_PETRIFIED) {
689 actor->SetLockedPalette(fullstone);
690 return;
692 if (State & STATE_FROZEN) {
693 actor->SetLockedPalette(fullwhite);
694 return;
696 if (actor->InParty) core->SetEventFlag(EF_PORTRAIT);
697 actor->UnlockPalette();
700 //changes based on extended state bits, right now it is only the seven eyes
701 //animation (used in how/iwd2)
702 void pcf_extstate(Actor *actor, ieDword oldValue, ieDword State)
704 if ((oldValue^State)&EXTSTATE_SEVEN_EYES) {
705 ieDword mask = EXTSTATE_EYE_MIND;
706 int eyeCount = 7;
707 for (int i=0;i<7;i++)
709 if (State&mask) eyeCount--;
710 mask<<=1;
712 ScriptedAnimation *sca = actor->FindOverlay(OV_SEVENEYES);
713 if (sca) {
714 sca->SetOrientation(eyeCount);
716 sca = actor->FindOverlay(OV_SEVENEYES2);
717 if (sca) {
718 sca->SetOrientation(eyeCount);
723 void pcf_hitpoint(Actor *actor, ieDword /*oldValue*/, ieDword hp)
725 if ((signed) actor->BaseStats[IE_HITPOINTS]>(signed) actor->Modified[IE_MAXHITPOINTS]) {
726 actor->BaseStats[IE_HITPOINTS]=actor->Modified[IE_MAXHITPOINTS];
729 int hptmp = (signed) actor->Modified[IE_MAXHITPOINTS];
730 if ((signed) hp>hptmp) {
731 hp=hptmp;
734 hptmp = (signed) actor->Modified[IE_MINHITPOINTS];
735 if (hptmp && (signed) hp<hptmp) {
736 hp=hptmp;
738 if ((signed) hp<=0) {
739 actor->Die(NULL);
741 actor->BaseStats[IE_HITPOINTS]=hp;
742 actor->Modified[IE_HITPOINTS]=hp;
743 if (actor->InParty) core->SetEventFlag(EF_PORTRAIT);
746 void pcf_maxhitpoint(Actor *actor, ieDword /*oldValue*/, ieDword hp)
748 if ((signed) hp<(signed) actor->BaseStats[IE_HITPOINTS]) {
749 actor->BaseStats[IE_HITPOINTS]=hp;
750 //passing 0 because it is ignored anyway
751 pcf_hitpoint(actor, 0, hp);
755 void pcf_minhitpoint(Actor *actor, ieDword /*oldValue*/, ieDword hp)
757 if ((signed) hp>(signed) actor->BaseStats[IE_HITPOINTS]) {
758 actor->BaseStats[IE_HITPOINTS]=hp;
759 //passing 0 because it is ignored anyway
760 pcf_hitpoint(actor, 0, hp);
764 void pcf_stat(Actor *actor, ieDword newValue, ieDword stat)
766 if ((signed) newValue<=0) {
767 if (DeathOnZeroStat) {
768 actor->Die(NULL);
769 } else {
770 actor->Modified[stat]=1;
775 void pcf_stat_str(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
777 pcf_stat(actor, newValue, IE_STR);
780 void pcf_stat_int(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
782 pcf_stat(actor, newValue, IE_INT);
785 void pcf_stat_wis(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
787 pcf_stat(actor, newValue, IE_WIS);
790 void pcf_stat_dex(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
792 pcf_stat(actor, newValue, IE_DEX);
795 void pcf_stat_con(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
797 pcf_stat(actor, newValue, IE_CON);
798 pcf_hitpoint(actor, 0, actor->BaseStats[IE_HITPOINTS]);
801 void pcf_stat_cha(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
803 pcf_stat(actor, newValue, IE_CHR);
806 void pcf_xp(Actor *actor, ieDword /*oldValue*/, ieDword /*newValue*/)
808 // check if we reached a new level
809 unsigned int pc = actor->InParty;
810 if (pc && !actor->GotLUFeedback) {
811 char varname[16];
812 sprintf(varname, "CheckLevelUp%d", pc);
813 core->GetGUIScriptEngine()->RunFunction("CheckLevelUp", true, pc);
814 ieDword NeedsLevelUp = 0;
815 core->GetDictionary()->Lookup(varname, NeedsLevelUp);
816 if (NeedsLevelUp == 1) {
817 core->DisplayConstantStringName(STR_LEVELUP, 0xffffff, actor);
818 actor->GotLUFeedback = true;
823 void pcf_gold(Actor *actor, ieDword /*oldValue*/, ieDword /*newValue*/)
825 //this function will make a party member automatically donate their
826 //gold to the party pool, not the same as in the original engine
827 if (actor->InParty) {
828 Game *game = core->GetGame();
829 game->AddGold ( actor->BaseStats[IE_GOLD] );
830 actor->BaseStats[IE_GOLD]=0;
834 static void handle_overlay(Actor *actor, ieDword idx)
836 if (actor->FindOverlay(idx))
837 return;
838 ieDword flag = hc_locations&(1<<idx);
839 ScriptedAnimation *sca = gamedata->GetScriptedAnimation(hc_overlays[idx], false);
840 if (sca) {
841 if (flag) {
842 sca->ZPos=-1;
844 actor->AddVVCell(sca);
848 //de/activates the entangle overlay
849 void pcf_entangle(Actor *actor, ieDword oldValue, ieDword newValue)
851 if (newValue&1) {
852 handle_overlay(actor, OV_ENTANGLE);
854 if (oldValue&1) {
855 actor->RemoveVVCell(hc_overlays[OV_ENTANGLE], true);
859 //de/activates the sanctuary and other overlays
860 //unlike IE, gemrb uses this stat for other overlay fields
861 //see the complete list in overlay.2da
862 //it loosely follows the internal representation of overlays in IWD2
863 void pcf_sanctuary(Actor *actor, ieDword oldValue, ieDword newValue)
865 ieDword changed = newValue^oldValue;
866 ieDword mask = 1;
867 for (int i=0;i<32;i++) {
868 if (changed&mask) {
869 if (newValue&mask) {
870 handle_overlay(actor, i);
871 } else {
872 actor->RemoveVVCell(hc_overlays[i], true);
875 mask<<=1;
879 //de/activates the prot from missiles overlay
880 void pcf_shieldglobe(Actor *actor, ieDword oldValue, ieDword newValue)
882 if (newValue&1) {
883 handle_overlay(actor, OV_SHIELDGLOBE);
884 return;
886 if (oldValue&1) {
887 actor->RemoveVVCell(hc_overlays[OV_SHIELDGLOBE], true);
891 //de/activates the globe of invul. overlay
892 void pcf_minorglobe(Actor *actor, ieDword oldValue, ieDword newValue)
894 if (newValue&1) {
895 handle_overlay(actor, OV_MINORGLOBE);
896 return;
898 if (oldValue&1) {
899 actor->RemoveVVCell(hc_overlays[OV_MINORGLOBE], true);
903 //de/activates the grease background
904 void pcf_grease(Actor *actor, ieDword oldValue, ieDword newValue)
906 if (newValue&1) {
907 handle_overlay(actor, OV_GREASE);
908 return;
910 if (oldValue&1) {
911 actor->RemoveVVCell(hc_overlays[OV_GREASE], true);
915 //de/activates the web overlay
916 //the web effect also immobilizes the actor!
917 void pcf_web(Actor *actor, ieDword oldValue, ieDword newValue)
919 if (newValue&1) {
920 handle_overlay(actor, OV_WEB);
921 return;
923 if (oldValue&1) {
924 actor->RemoveVVCell(hc_overlays[OV_WEB], true);
928 //de/activates the spell bounce background
929 void pcf_bounce(Actor *actor, ieDword oldValue, ieDword newValue)
931 if (newValue&1) {
932 handle_overlay(actor, OV_BOUNCE);
933 return;
935 if (oldValue&1) {
936 //it seems we have to remove it abruptly
937 actor->RemoveVVCell(hc_overlays[OV_BOUNCE], false);
941 //no separate values (changes are permanent)
942 void pcf_fatigue(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
944 actor->BaseStats[IE_FATIGUE]=newValue;
947 //no separate values (changes are permanent)
948 void pcf_intoxication(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
950 actor->BaseStats[IE_INTOXICATION]=newValue;
953 void pcf_color(Actor *actor, ieDword /*oldValue*/, ieDword /*newValue*/)
955 CharAnimations *anims = actor->GetAnims();
956 if (anims) {
957 anims->SetColors(actor->Modified+IE_COLORS);
961 void pcf_armorlevel(Actor *actor, ieDword /*oldValue*/, ieDword newValue)
963 CharAnimations *anims = actor->GetAnims();
964 if (anims) {
965 anims->SetArmourLevel(newValue);
969 static int maximum_values[MAX_STATS]={
970 32767,32767,20,100,100,100,100,25,10,25,25,25,25,25,100,100,//0f
971 100,100,100,100,100,100,100,100,100,100,255,255,255,255,100,100,//1f
972 200,200,MAX_LEVEL,255,25,100,25,25,25,25,25,999999999,999999999,999999999,25,25,//2f
973 200,255,200,100,100,200,200,25,5,100,1,1,100,1,1,0,//3f
974 511,1,1,1,MAX_LEVEL,MAX_LEVEL,1,9999,25,100,100,255,1,20,20,25,//4f
975 25,1,1,255,25,25,255,255,25,255,255,255,255,255,255,255,//5f
976 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,//6f
977 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,//7f
978 255,255,255,255,255,255,255,100,100,100,255,5,5,255,1,1,//8f
979 1,25,25,30,1,1,1,25,0,100,100,1,255,255,255,255,//9f
980 255,255,255,255,255,255,20,255,255,1,20,255,999999999,999999999,1,1,//af
981 999999999,999999999,0,0,20,0,0,0,0,0,0,0,0,0,0,0,//bf
982 0,0,0,0,0,0,0,25,25,255,255,255,255,65535,0,0,//cf - 207
983 0,0,0,0,0,0,0,0,MAX_LEVEL,255,65535,3,255,255,255,255,//df - 223
984 255,255,255,255,255,255,255,255,255,255,255,255,65535,65535,15,0,//ef - 239
985 MAX_LEVEL,MAX_LEVEL,MAX_LEVEL,MAX_LEVEL, MAX_LEVEL,MAX_LEVEL,MAX_LEVEL,MAX_LEVEL, //0xf7 - 247
986 MAX_LEVEL,MAX_LEVEL,0,0,0,0,0,0//ff
989 typedef void (*PostChangeFunctionType)(Actor *actor, ieDword oldValue, ieDword newValue);
990 static PostChangeFunctionType post_change_functions[MAX_STATS]={
991 pcf_hitpoint, pcf_maxhitpoint, NULL, NULL, NULL, NULL, NULL, NULL,
992 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //0f
993 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
994 NULL,NULL,NULL,NULL, NULL, NULL, pcf_fatigue, pcf_intoxication, //1f
995 NULL,NULL,pcf_level,NULL, pcf_stat_str, NULL, pcf_stat_int, pcf_stat_wis,
996 pcf_stat_dex,pcf_stat_con,pcf_stat_cha,NULL, pcf_xp, pcf_gold, pcf_morale, NULL, //2f
997 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
998 NULL,NULL,NULL,NULL, NULL, NULL, pcf_entangle, pcf_sanctuary, //3f
999 pcf_minorglobe, pcf_shieldglobe, pcf_grease, pcf_web, pcf_level, pcf_level, NULL, NULL,
1000 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //4f
1001 NULL,NULL,NULL,pcf_minhitpoint, NULL, NULL, NULL, NULL,
1002 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //5f
1003 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1004 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //6f
1005 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1006 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //7f
1007 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1008 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //8f
1009 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1010 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //9f
1011 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1012 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //af
1013 NULL,NULL,NULL,NULL, pcf_morale, pcf_bounce, NULL, NULL,
1014 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL, //bf
1015 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1016 NULL,NULL,NULL,NULL, NULL, pcf_animid,pcf_state, pcf_extstate, //cf
1017 pcf_color,pcf_color,pcf_color,pcf_color, pcf_color, pcf_color, pcf_color, NULL,
1018 NULL,NULL,NULL,pcf_armorlevel, NULL, NULL, NULL, NULL, //df
1019 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL,
1020 pcf_class,NULL,pcf_ea,NULL, NULL, NULL, NULL, NULL, //ef
1021 pcf_level,pcf_level,pcf_level,pcf_level, pcf_level, pcf_level, pcf_level, pcf_level,
1022 NULL,NULL,NULL,NULL, NULL, NULL, NULL, NULL //ff
1025 /** call this from ~Interface() */
1026 void Actor::ReleaseMemory()
1028 int i;
1030 if (classcount>=0) {
1031 if (clericspelltables) {
1032 for (i=0;i<classcount;i++) {
1033 if (clericspelltables[i]) {
1034 free (clericspelltables[i]);
1037 free(clericspelltables);
1038 clericspelltables=NULL;
1040 if (druidspelltables) {
1041 for (i=0;i<classcount;i++) {
1042 if (druidspelltables[i]) {
1043 free (druidspelltables[i]);
1046 free(druidspelltables);
1047 druidspelltables=NULL;
1049 if (wizardspelltables) {
1050 for (i=0;i<classcount;i++) {
1051 if (wizardspelltables[i]) {
1052 free(wizardspelltables[i]);
1055 free(wizardspelltables);
1056 wizardspelltables=NULL;
1058 if (turnlevels) {
1059 free(turnlevels);
1060 turnlevels=NULL;
1063 if (booktypes) {
1064 free(booktypes);
1065 booktypes=NULL;
1068 if (xpbonus) {
1069 free(xpbonus);
1070 xpbonus=NULL;
1071 xpbonuslevels = -1;
1072 xpbonustypes = -1;
1074 if (levelslots) {
1075 for (i=0; i<classcount; i++) {
1076 if (levelslots[i]) {
1077 free(levelslots[i]);
1080 free(levelslots);
1081 levelslots=NULL;
1083 if (dualswap) {
1084 free(dualswap);
1085 dualswap=NULL;
1087 if (maxhpconbon) {
1088 free(maxhpconbon);
1089 maxhpconbon=NULL;
1091 if (wspecial) {
1092 for (i=0; i<=wspecial_max; i++) {
1093 if (wspecial[i]) {
1094 free(wspecial[i]);
1097 free(wspecial);
1098 wspecial=NULL;
1100 if (wspattack) {
1101 for (i=0; i<wspattack_rows; i++) {
1102 if (wspattack[i]) {
1103 free(wspattack[i]);
1106 free(wspattack);
1107 wspattack=NULL;
1109 if (wsdualwield) {
1110 for (i=0; i<=STYLE_MAX; i++) {
1111 if (wsdualwield[i]) {
1112 free(wsdualwield[i]);
1115 free(wsdualwield);
1116 wsdualwield=NULL;
1118 if (wstwohanded) {
1119 for (i=0; i<=STYLE_MAX; i++) {
1120 if (wstwohanded[i]) {
1121 free(wstwohanded[i]);
1124 free(wstwohanded);
1125 wstwohanded=NULL;
1127 if (wsswordshield) {
1128 for (i=0; i<=STYLE_MAX; i++) {
1129 if (wsswordshield[i]) {
1130 free(wsswordshield[i]);
1133 free(wsswordshield);
1134 wsswordshield=NULL;
1136 if (wssingle) {
1137 for (i=0; i<=STYLE_MAX; i++) {
1138 if (wssingle[i]) {
1139 free(wssingle[i]);
1142 free(wssingle);
1143 wssingle=NULL;
1145 if (monkbon) {
1146 for (i=0; i<monkbon_rows; i++) {
1147 if (monkbon[i]) {
1148 free(monkbon[i]);
1151 free(monkbon);
1152 monkbon=NULL;
1154 for(i=0;i<20;i++) {
1155 free(wmlevels[i]);
1156 wmlevels[i]=NULL;
1158 if (reputationmod) {
1159 for (i=0; i<20; i++) {
1160 if (reputationmod[i]) {
1161 free(reputationmod[i]);
1164 free(reputationmod);
1165 reputationmod=NULL;
1168 if (GUIBTDefaults) {
1169 free (GUIBTDefaults);
1170 GUIBTDefaults=NULL;
1172 classcount = -1;
1175 #define COL_HATERACE 0 //ranger type racial enemy
1176 #define COL_CLERIC_SPELL 1 //cleric spells
1177 #define COL_MAGE_SPELL 2 //mage spells
1178 #define COL_STARTXP 3 //starting xp
1179 #define COL_BARD_SKILL 4 //bard skills
1180 #define COL_THIEF_SKILL 5 //thief skills
1182 #define COL_MAIN 0
1183 #define COL_SPARKS 1
1184 #define COL_GRADIENT 2
1186 /* returns the ISCLASS for the class based on name */
1187 int IsClassFromName (const char* name)
1189 //TODO: is there a better way of doing this?
1190 for (int i=0; i<ISCLASSES; i++) {
1191 if (strcmp(name, isclassnames[i]) == 0)
1192 return i;
1194 return -1;
1197 static void InitActorTables()
1199 int i, j;
1201 //if (core->HasFeature(GF_IWD_DEATHVARFORMAT)) {
1202 // memcpy(DeathVarFormat, IWDDeathVarFormat, sizeof(ieVariable));
1205 if (core->HasFeature(GF_CHALLENGERATING)) {
1206 sharexp=SX_DIVIDE|SX_CR;
1207 } else {
1208 sharexp=SX_DIVIDE;
1210 ReverseToHit = core->HasFeature(GF_REVERSE_TOHIT);
1211 CheckAbilities = core->HasFeature(GF_CHECK_ABILITIES);
1212 DeathOnZeroStat = core->HasFeature(GF_DEATH_ON_ZERO_STAT);
1214 //this table lists various level based xp bonuses
1215 AutoTable tm("xpbonus");
1216 if (tm) {
1217 xpbonustypes = tm->GetRowCount();
1218 if (xpbonustypes == 0) {
1219 xpbonuslevels = 0;
1220 } else {
1221 xpbonuslevels = tm->GetColumnCount(0);
1222 xpbonus = (int *) calloc(xpbonuslevels*xpbonustypes, sizeof(int));
1223 for (i = 0; i<xpbonustypes; i++) {
1224 for(j = 0; j<xpbonuslevels; j++) {
1225 xpbonus[i*xpbonuslevels+j] = atoi(tm->QueryField(i,j));
1229 } else {
1230 xpbonustypes = 0;
1231 xpbonuslevels = 0;
1233 //this table lists skill groups assigned to classes
1234 //it is theoretically possible to create hybrid classes
1235 tm.load("clskills");
1236 if (tm) {
1237 classcount = tm->GetRowCount();
1238 memset (isclass,0,sizeof(isclass));
1239 clericspelltables = (char **) calloc(classcount, sizeof(char*));
1240 druidspelltables = (char **) calloc(classcount, sizeof(char*));
1241 wizardspelltables = (char **) calloc(classcount, sizeof(char*));
1242 turnlevels = (int *) calloc(classcount, sizeof(int));
1243 booktypes = (int *) calloc(classcount, sizeof(int));
1245 ieDword bitmask = 1;
1247 for(i = 0; i<classcount; i++) {
1248 const char *field;
1249 int turnlevel = atoi(tm->QueryField( i, 7));
1250 turnlevels[i]=turnlevel;
1252 field = tm->QueryField( i, 0 );
1253 if (field[0]!='*') {
1254 isclass[ISDRUID] |= bitmask;
1255 druidspelltables[i]=strdup(field);
1257 field = tm->QueryField( i, 1 );
1258 if (field[0]!='*') {
1259 isclass[ISCLERIC] |= bitmask;
1260 clericspelltables[i]=strdup(field);
1263 field = tm->QueryField( i, 2 );
1264 if (field[0]!='*') {
1265 isclass[ISMAGE] |= bitmask;
1266 wizardspelltables[i]=strdup(field);
1269 // field 3 holds the starting xp
1271 field = tm->QueryField( i, 4 );
1272 if (field[0]!='*') {
1273 isclass[ISBARD] |= bitmask;
1276 field = tm->QueryField( i, 5 );
1277 if (field[0]!='*') {
1278 isclass[ISTHIEF] |= bitmask;
1281 field = tm->QueryField( i, 6 );
1282 if (field[0]!='*') {
1283 isclass[ISPALADIN] |= bitmask;
1286 // field 7 holds the turn undead level
1288 field = tm->QueryField( i, 8 );
1289 booktypes[i]=atoi(field);
1290 //if booktype == 3 then it is a 'divine sorceror' class
1291 //we shouldn't hardcode iwd2 classes this heavily
1292 if (booktypes[i]==2) {
1293 isclass[ISSORCERER] |= bitmask;
1296 field = tm->QueryField( i, 9 );
1297 if (field[0]!='*') {
1298 isclass[ISRANGER] |= bitmask;
1301 field = tm->QueryField( i, 10 );
1302 if (!strnicmp(field, "CLABMO", 6)) {
1303 isclass[ISMONK] |= bitmask;
1305 bitmask <<=1;
1307 } else {
1308 classcount = 0; //well
1311 i = core->GetMaximumAbility();
1312 maximum_values[IE_STR]=i;
1313 maximum_values[IE_INT]=i;
1314 maximum_values[IE_DEX]=i;
1315 maximum_values[IE_CON]=i;
1316 maximum_values[IE_CHR]=i;
1317 maximum_values[IE_WIS]=i;
1318 if (ReverseToHit) {
1319 //all games except iwd2
1320 maximum_values[IE_ARMORCLASS]=20;
1321 } else {
1322 //iwd2
1323 maximum_values[IE_ARMORCLASS]=199;
1326 //initializing the vvc resource references
1327 tm.load("damage");
1328 if (tm) {
1329 for (i=0;i<DAMAGE_LEVELS;i++) {
1330 const char *tmp = tm->QueryField( i, COL_MAIN );
1331 strnlwrcpy(d_main[i], tmp, 8);
1332 if (d_main[i][0]=='*') {
1333 d_main[i][0]=0;
1335 tmp = tm->QueryField( i, COL_SPARKS );
1336 strnlwrcpy(d_splash[i], tmp, 8);
1337 if (d_splash[i][0]=='*') {
1338 d_splash[i][0]=0;
1340 tmp = tm->QueryField( i, COL_GRADIENT );
1341 d_gradient[i]=atoi(tmp);
1345 tm.load("overlay");
1346 if (tm) {
1347 ieDword mask = 1;
1348 for (i=0;i<OVERLAY_COUNT;i++) {
1349 const char *tmp = tm->QueryField( i, 0 );
1350 strnlwrcpy(hc_overlays[i], tmp, 8);
1351 if (atoi(tm->QueryField( i, 1))) {
1352 hc_locations|=mask;
1354 mask<<=1;
1358 //csound for bg1/bg2
1359 memset(csound,0,sizeof(csound));
1360 if (!core->HasFeature(GF_SOUNDFOLDERS)) {
1361 tm.load("csound");
1362 if (tm) {
1363 for(i=0;i<VCONST_COUNT;i++) {
1364 const char *tmp = tm->QueryField( i, 0 );
1365 if (tmp[0]!='*') {
1366 csound[i]=tmp[0];
1372 tm.load("qslots");
1373 GUIBTDefaults = (ActionButtonRow *) calloc( classcount,sizeof(ActionButtonRow) );
1375 for (i = 0; i < classcount; i++) {
1376 memcpy(GUIBTDefaults+i, &DefaultButtons, sizeof(ActionButtonRow));
1377 if (tm) {
1378 for (int j=0;j<MAX_QSLOTS;j++) {
1379 GUIBTDefaults[i][j+3]=(ieByte) atoi( tm->QueryField(i,j) );
1384 tm.load("itemuse");
1385 if (tm) {
1386 usecount = tm->GetRowCount();
1387 itemuse = new ItemUseType[usecount];
1388 for (i = 0; i < usecount; i++) {
1389 itemuse[i].stat = (ieByte) core->TranslateStat( tm->QueryField(i,0) );
1390 strnlwrcpy(itemuse[i].table, tm->QueryField(i,1),8 );
1391 itemuse[i].mcol = (ieByte) atoi( tm->QueryField(i,2) );
1392 itemuse[i].vcol = (ieByte) atoi( tm->QueryField(i,3) );
1393 itemuse[i].which = (ieByte) atoi( tm->QueryField(i,4) );
1394 //limiting it to 0 or 1 to avoid crashes
1395 if (itemuse[i].which!=1) {
1396 itemuse[i].which=0;
1401 tm.load("itemanim");
1402 if (tm) {
1403 animcount = tm->GetRowCount();
1404 itemanim = new ItemAnimType[animcount];
1405 for (i = 0; i < animcount; i++) {
1406 strnlwrcpy(itemanim[i].itemname, tm->QueryField(i,0),8 );
1407 itemanim[i].animation = (ieByte) atoi( tm->QueryField(i,1) );
1411 tm.load("mxsplwis");
1412 if (tm) {
1413 spllevels = tm->GetColumnCount(0);
1414 int max = core->GetMaximumAbility();
1415 mxsplwis = (int *) calloc(max*spllevels, sizeof(int));
1416 for (i = 0; i < spllevels; i++) {
1417 for(int j = 0; j < max; j++) {
1418 int k = atoi(tm->GetRowName(j))-1;
1419 if (k>=0 && k<max) {
1420 mxsplwis[k*spllevels+i]=atoi(tm->QueryField(j,i));
1426 tm.load("featreq");
1427 if (tm) {
1428 unsigned int tmp;
1430 for(i=0;i<MAX_FEATS;i++) {
1431 //we need the MULTIPLE column only
1432 //it stores the FEAT_* stat index, and could be taken multiple
1433 //times
1434 tmp = core->TranslateStat(tm->QueryField(i,0));
1435 if (tmp>=MAX_STATS) {
1436 printMessage("Actor","Invalid stat value in featreq.2da",YELLOW);
1438 featstats[i] = (ieByte) tmp;
1442 //default all hp con bonuses to 9; this should be updated below
1443 //TODO: check iwd2
1444 maxhpconbon = (int *) calloc(classcount, sizeof(int));
1445 for (i = 0; i < classcount; i++) {
1446 maxhpconbon[i] = 9;
1448 tm.load("classes");
1449 if (tm && !core->HasFeature(GF_LEVELSLOT_PER_CLASS)) {
1450 AutoTable hptm;
1451 //iwd2 just uses levelslotsiwd2 instead
1452 printf("Examining classes.2da\n");
1454 //when searching the levelslots, you must search for
1455 //levelslots[BaseStats[IE_CLASS]-1] as there is no class id of 0
1456 levelslots = (int **) calloc(classcount, sizeof(int*));
1457 dualswap = (int *) calloc(classcount, sizeof(int));
1458 ieDword tmpindex;
1459 for (i=0; i<classcount; i++) {
1460 //make sure we have a valid classid, then decrement
1461 //it to get the correct array index
1462 tmpindex = atoi(tm->QueryField(i, 5));
1463 if (!tmpindex)
1464 continue;
1465 tmpindex--;
1467 printf("\tID: %d ", tmpindex);
1468 //only create the array if it isn't yet made
1469 //i.e. barbarians would overwrite fighters in bg2
1470 if (levelslots[tmpindex]) {
1471 printf ("Already Found!\n");
1472 continue;
1475 const char* classname = tm->GetRowName(i);
1476 printf("Name: %s ", classname);
1477 int classis = 0;
1478 //default all levelslots to 0
1479 levelslots[tmpindex] = (int *) calloc(ISCLASSES, sizeof(int));
1481 //single classes only worry about IE_LEVEL
1482 ieDword tmpclass = atoi(tm->QueryField(i, 4));
1483 if (!tmpclass) {
1484 classis = IsClassFromName(classname);
1485 if (classis>=0) {
1486 printf("Classis: %d ", classis);
1487 levelslots[tmpindex][classis] = IE_LEVEL;
1488 //get the max hp con bonus
1489 hptm.load(tm->QueryField(i, 6));
1490 if (hptm) {
1491 int tmphp = 0;
1492 int rollscolumn = hptm->GetColumnIndex("ROLLS");
1493 while (atoi(hptm->QueryField(tmphp, rollscolumn)))
1494 tmphp++;
1495 printf("TmpHP: %d ", tmphp);
1496 if (tmphp) maxhpconbon[tmpindex] = tmphp;
1499 continue;
1502 //we have to account for dual-swap in the multiclass field
1503 ieDword numfound = 1;
1504 ieDword tmpbits = bitcount (tmpclass);
1506 //we need all the classnames of the multi to compare with the order we load them in
1507 //because the original game set the levels based on name order, not bit order
1508 char **classnames = (char **) calloc(tmpbits, sizeof(char *));
1509 classnames[0] = (char*)strtok(strdup((char*)classname), "_");
1510 while (numfound<tmpbits && (classnames[numfound] = strdup(strtok(NULL, "_")))) {
1511 numfound++;
1513 numfound = 0;
1514 bool foundwarrior = false;
1515 for (int j=0; j<classcount; j++) {
1516 //no sense continuing if we've found all to be found
1517 if (numfound==tmpbits)
1518 break;
1519 if ((1<<j)&tmpclass) {
1520 //save the IE_LEVEL information
1521 const char* currentname = tm->GetRowName((ieDword)(tm->FindTableValue(5, j+1)));
1522 classis = IsClassFromName(currentname);
1523 if (classis>=0) {
1524 //search for the current class in the split of the names to get it's
1525 //correct order
1526 for (ieDword k=0; k<tmpbits; k++) {
1527 if (strcmp(classnames[k], currentname) == 0) {
1528 int tmplevel = 0;
1529 if (k==0) tmplevel = IE_LEVEL;
1530 else if (k==1) tmplevel = IE_LEVEL2;
1531 else tmplevel = IE_LEVEL3;
1532 levelslots[tmpindex][classis] = tmplevel;
1535 printf("Classis: %d ", classis);
1537 //warrior take presedence
1538 if (!foundwarrior) {
1539 foundwarrior = (classis==ISFIGHTER||classis==ISRANGER||classis==ISPALADIN||
1540 classis==ISBARBARIAN);
1541 hptm.load(tm->QueryField(currentname, "HP"));
1542 if (hptm) {
1543 int tmphp = 0;
1544 int rollscolumn = hptm->GetColumnIndex("ROLLS");
1545 while (atoi(hptm->QueryField(tmphp, rollscolumn)))
1546 tmphp++;
1547 //make sure we at least set the first class
1548 if ((tmphp>maxhpconbon[tmpindex])||foundwarrior||numfound==0)
1549 maxhpconbon[tmpindex]=tmphp;
1554 //save the MC_WAS_ID of the first class in the dual-class
1555 if (numfound==0 && tmpbits==2) {
1556 if (strcmp(classnames[0], currentname) == 0) {
1557 dualswap[tmpindex] = strtol(tm->QueryField(classname, "MC_WAS_ID"), NULL, 0);
1559 } else if (numfound==1 && tmpbits==2 && !dualswap[tmpindex]) {
1560 dualswap[tmpindex] = strtol(tm->QueryField(classname, "MC_WAS_ID"), NULL, 0);
1562 numfound++;
1565 if (classnames) {
1566 for (ieDword j=0; j<tmpbits; j++) {
1567 if (classnames[j]) {
1568 free(classnames[j]);
1571 free(classnames);
1572 classnames = NULL;
1574 printf("HPCON: %d ", maxhpconbon[tmpindex]);
1575 printf("DS: %d\n", dualswap[tmpindex]);
1577 /*this could be enabled to ensure all levelslots are filled with at least 0's;
1578 *however, the access code should ensure this never happens
1579 for (i=0; i<classcount; i++) {
1580 if (!levelslots[i]) {
1581 levelslots[i] = (int *) calloc(ISCLASSES, sizeof(int *));
1585 printf("Finished examining classes.2da\n");
1587 //pre-cache hit/damage/speed bonuses for weapons
1588 tm.load("wspecial");
1589 if (tm) {
1590 //load in the identifiers
1591 wspecial_max = tm->GetRowCount()-1;
1592 int cols = tm->GetColumnCount();
1593 wspecial = (int **) calloc(wspecial_max+1, sizeof(int *));
1595 for (i=0; i<=wspecial_max; i++) {
1596 wspecial[i] = (int *) calloc(WSPECIAL_COLS, sizeof(int));
1597 for (int j=0; j<cols; j++) {
1598 wspecial[i][j] = atoi(tm->QueryField(i, j));
1603 //pre-cache attack per round bonuses
1604 tm.load("wspatck");
1605 if (tm) {
1606 wspattack_rows = tm->GetRowCount();
1607 wspattack_cols = tm->GetColumnCount();
1608 wspattack = (int **) calloc(wspattack_rows, sizeof(int *));
1610 int tmp = 0;
1611 for (i=0; i<wspattack_rows; i++) {
1612 wspattack[i] = (int *) calloc(wspattack_cols, sizeof(int));
1613 for (int j=0; j<wspattack_cols; j++) {
1614 tmp = atoi(tm->QueryField(i, j));
1615 //negative values relate to x/2, so we adjust them
1616 //positive values relate to x, so we must times by 2
1617 if (tmp<0) tmp = -2*tmp-1;
1618 else tmp *= 2;
1619 wspattack[i][j] = tmp;
1624 //dual-wielding table
1625 tm.load("wstwowpn");
1626 if (tm) {
1627 wsdualwield = (int **) calloc(STYLE_MAX+1, sizeof(int *));
1628 int cols = tm->GetColumnCount();
1629 for (i=0; i<=STYLE_MAX; i++) {
1630 wsdualwield[i] = (int *) calloc(cols, sizeof(int));
1631 for (int j=0; j<cols; j++) {
1632 wsdualwield[i][j] = atoi(tm->QueryField(i, j));
1637 //two-handed table
1638 tm.load("wstwohnd");
1639 if (tm) {
1640 wstwohanded = (int **) calloc(STYLE_MAX+1, sizeof(int *));
1641 int cols = tm->GetColumnCount();
1642 for (i=0; i<=STYLE_MAX; i++) {
1643 wstwohanded[i] = (int *) calloc(cols, sizeof(int));
1644 for (int j=0; j<cols; j++) {
1645 wstwohanded[i][j] = atoi(tm->QueryField(i, j));
1650 //two-handed table
1651 tm.load("wsshield");
1652 if (tm) {
1653 wsswordshield = (int **) calloc(STYLE_MAX+1, sizeof(int *));
1654 int cols = tm->GetColumnCount();
1655 for (i=0; i<=STYLE_MAX; i++) {
1656 wsswordshield[i] = (int *) calloc(cols, sizeof(int));
1657 for (int j=0; j<cols; j++) {
1658 wsswordshield[i][j] = atoi(tm->QueryField(i, j));
1663 //two-handed table
1664 tm.load("wssingle");
1665 if (tm) {
1666 wssingle = (int **) calloc(STYLE_MAX+1, sizeof(int *));
1667 int cols = tm->GetColumnCount();
1668 for (i=0; i<=STYLE_MAX; i++) {
1669 wssingle[i] = (int *) calloc(cols, sizeof(int));
1670 for (int j=0; j<cols; j++) {
1671 wssingle[i][j] = atoi(tm->QueryField(i, j));
1676 //unhardcoded monk bonus table
1677 tm.load("monkbon");
1678 if (tm) {
1679 monkbon_rows = tm->GetRowCount();
1680 monkbon_cols = tm->GetColumnCount();
1681 monkbon = (int **) calloc(monkbon_rows, sizeof(int *));
1682 for (i=0; i<monkbon_rows; i++) {
1683 monkbon[i] = (int *) calloc(monkbon_cols, sizeof(int));
1684 for (int j=0; j<monkbon_cols; j++) {
1685 monkbon[i][j] = atoi(tm->QueryField(i, j));
1690 //wild magic level modifiers
1691 for(i=0;i<20;i++) {
1692 wmlevels[i]=(int *) calloc(MAX_LEVEL,sizeof(int) );
1694 tm.load("lvlmodwm");
1695 if (tm) {
1696 int maxrow = tm->GetRowCount();
1697 for (i=0;i<20;i++) {
1698 for(j=0;j<MAX_LEVEL;j++) {
1699 int row = maxrow;
1700 if (j<row) row=j;
1701 wmlevels[i][j]=strtol(tm->QueryField(row,i), NULL, 0);
1706 // reputation modifiers
1707 tm.load("reputati");
1708 if (tm) {
1709 reputationmod = (int **) calloc(21, sizeof(int *));
1710 int cols = tm->GetColumnCount();
1711 for (i=0; i<20; i++) {
1712 reputationmod[i] = (int *) calloc(cols, sizeof(int));
1713 for (int j=0; j<cols; j++) {
1714 reputationmod[i][j] = atoi(tm->QueryField(i, j));
1720 void Actor::SetLockedPalette(const ieDword *gradients)
1722 if (!anims) return; //cannot apply it (yet)
1723 anims->LockPalette(gradients);
1726 void Actor::UnlockPalette()
1728 if (!anims) return;
1729 anims->lockPalette=false;
1730 anims->SetColors(Modified+IE_COLORS);
1733 void Actor::AddAnimation(const ieResRef resource, int gradient, int height, int flags)
1735 ScriptedAnimation *sca = gamedata->GetScriptedAnimation(resource, false);
1736 if (!sca)
1737 return;
1738 sca->ZPos=height;
1739 if (flags&AA_PLAYONCE) {
1740 sca->PlayOnce();
1742 if (flags&&AA_BLEND) {
1743 //pst anims need this?
1744 sca->SetBlend();
1746 if (gradient!=-1) {
1747 sca->SetPalette(gradient, 4);
1749 AddVVCell(sca);
1752 void Actor::PlayDamageAnimation(int type, bool hit)
1754 int i;
1756 switch(type) {
1757 case 0: case 1: case 2: case 3: //blood
1758 i = (int) GetStat(IE_ANIMATION_ID)>>16;
1759 if (!i) i = d_gradient[type];
1760 if(hit) {
1761 AddAnimation(d_main[type], i, 0, AA_PLAYONCE);
1763 break;
1764 case 4: case 5: case 6: //fire
1765 if(hit) {
1766 AddAnimation(d_main[type], d_gradient[type], 0, AA_PLAYONCE);
1768 for(i=DL_FIRE;i<=type;i++) {
1769 AddAnimation(d_splash[i], d_gradient[i], 0, AA_PLAYONCE);
1771 break;
1772 case 7: case 8: case 9: //electricity
1773 if (hit) {
1774 AddAnimation(d_main[type], d_gradient[type], 0, AA_PLAYONCE);
1776 for(i=DL_ELECTRICITY;i<=type;i++) {
1777 AddAnimation(d_splash[i], d_gradient[i], 0, AA_PLAYONCE);
1779 break;
1780 case 10: case 11: case 12://cold
1781 if (hit) {
1782 AddAnimation(d_main[type], d_gradient[type], 0, AA_PLAYONCE);
1784 break;
1785 case 13: case 14: case 15://acid
1786 if (hit) {
1787 AddAnimation(d_main[type], d_gradient[type], 0, AA_PLAYONCE);
1789 break;
1790 case 16: case 17: case 18://disintegrate
1791 if (hit) {
1792 AddAnimation(d_main[type], d_gradient[type], 0, AA_PLAYONCE);
1794 break;
1798 bool Actor::SetStat(unsigned int StatIndex, ieDword Value, int pcf)
1800 if (StatIndex >= MAX_STATS) {
1801 return false;
1803 if ( (signed) Value<-100) {
1804 Value = (ieDword) -100;
1806 else {
1807 if ( maximum_values[StatIndex]>0) {
1808 if ( (signed) Value>maximum_values[StatIndex]) {
1809 Value = (ieDword) maximum_values[StatIndex];
1814 unsigned int previous = Modified[StatIndex];
1815 if (Modified[StatIndex]!=Value) {
1816 Modified[StatIndex] = Value;
1817 if (pcf) {
1818 PostChangeFunctionType f = post_change_functions[StatIndex];
1819 if (f) (*f)(this, previous, Value);
1822 return true;
1825 int Actor::GetMod(unsigned int StatIndex)
1827 if (StatIndex >= MAX_STATS) {
1828 return 0xdadadada;
1830 return (signed) Modified[StatIndex] - (signed) BaseStats[StatIndex];
1832 /** Returns a Stat Base Value */
1833 ieDword Actor::GetBase(unsigned int StatIndex)
1835 if (StatIndex >= MAX_STATS) {
1836 return 0xffff;
1838 return BaseStats[StatIndex];
1841 /** Sets a Stat Base Value */
1842 /** If required, modify the modified value and run the pcf function */
1843 bool Actor::SetBase(unsigned int StatIndex, ieDword Value)
1845 if (StatIndex >= MAX_STATS) {
1846 return false;
1848 ieDword diff = Modified[StatIndex]-BaseStats[StatIndex];
1850 //maximize the base stat
1851 if ( maximum_values[StatIndex]) {
1852 if ( (signed) Value>maximum_values[StatIndex]) {
1853 Value = (ieDword) maximum_values[StatIndex];
1857 BaseStats[StatIndex] = Value;
1859 //if already initialized, then the modified stats
1860 //might need to run the post change function (stat change can kill actor)
1861 SetStat (StatIndex, Value+diff, InternalFlags&IF_INITIALIZED);
1862 return true;
1865 bool Actor::SetBaseNoPCF(unsigned int StatIndex, ieDword Value)
1867 if (StatIndex >= MAX_STATS) {
1868 return false;
1870 ieDword diff = Modified[StatIndex]-BaseStats[StatIndex];
1872 //maximize the base stat
1873 if ( maximum_values[StatIndex]) {
1874 if ( (signed) Value>maximum_values[StatIndex]) {
1875 Value = (ieDword) maximum_values[StatIndex];
1879 BaseStats[StatIndex] = Value;
1881 //if already initialized, then the modified stats
1882 //might need to run the post change function (stat change can kill actor)
1883 SetStat (StatIndex, Value+diff, 0);
1884 return true;
1887 bool Actor::SetBaseBit(unsigned int StatIndex, ieDword Value, bool setreset)
1889 if (StatIndex >= MAX_STATS) {
1890 return false;
1892 if (setreset) {
1893 BaseStats[StatIndex] |= Value;
1894 } else {
1895 BaseStats[StatIndex] &= ~Value;
1897 //if already initialized, then the modified stats
1898 //need to run the post change function (stat change can kill actor)
1899 if (setreset) {
1900 SetStat (StatIndex, Modified[StatIndex]|Value, InternalFlags&IF_INITIALIZED);
1901 } else {
1902 SetStat (StatIndex, Modified[StatIndex]&~Value, InternalFlags&IF_INITIALIZED);
1904 return true;
1907 const unsigned char *Actor::GetStateString()
1909 if (!PCStats) {
1910 return NULL;
1912 ieByte *tmp = PCStats->PortraitIconString;
1913 ieWord *Icons = PCStats->PortraitIcons;
1914 int j=0;
1915 for (int i=0;i<MAX_PORTRAIT_ICONS;i++) {
1916 if (!(Icons[i]&0xff00)) {
1917 tmp[j++]=(ieByte) ((Icons[i]&0xff)+66);
1920 tmp[j]=0;
1921 return tmp;
1924 void Actor::AddPortraitIcon(ieByte icon)
1926 if (!PCStats) {
1927 return;
1929 ieWord *Icons = PCStats->PortraitIcons;
1931 for(int i=0;i<MAX_PORTRAIT_ICONS;i++) {
1932 if (Icons[i]==0xffff) {
1933 Icons[i]=icon;
1934 return;
1936 if (icon == (Icons[i]&0xff)) {
1937 return;
1942 void Actor::DisablePortraitIcon(ieByte icon)
1944 if (!PCStats) {
1945 return;
1947 ieWord *Icons = PCStats->PortraitIcons;
1948 int i;
1950 for(i=0;i<MAX_PORTRAIT_ICONS;i++) {
1951 if (icon == (Icons[i]&0xff)) {
1952 Icons[i]=0xff00|icon;
1953 return;
1958 /** call this after load, to apply effects */
1959 void Actor::RefreshEffects(EffectQueue *fx)
1961 ieDword previous[MAX_STATS];
1963 //put all special cleanup calls here
1964 CharAnimations* anims = GetAnims();
1965 if (anims) {
1966 anims->GlobalColorMod.type = RGBModifier::NONE;
1967 anims->GlobalColorMod.speed = 0;
1968 unsigned int location;
1969 for (location = 0; location < 32; ++location) {
1970 anims->ColorMods[location].type = RGBModifier::NONE;
1971 anims->ColorMods[location].speed = 0;
1974 spellbook.ClearBonus();
1975 memset(applyWhenHittingMelee,0,sizeof(ieResRef));
1976 memset(applyWhenHittingRanged,0,sizeof(ieResRef));
1977 memset(applyWhenNearLiving,0,sizeof(ieResRef));
1978 memset(applyWhen50Damage,0,sizeof(ieResRef));
1979 memset(applyWhen90Damage,0,sizeof(ieResRef));
1980 memset(applyWhenEnemySighted,0,sizeof(ieResRef));
1981 memset(applyWhenPoisoned,0,sizeof(ieResRef));
1982 memset(applyWhenHelpless,0,sizeof(ieResRef));
1983 memset(applyWhenAttacked,0,sizeof(ieResRef));
1984 memset(applyWhenBeingHit,0,sizeof(ieResRef));
1985 memset(projectileImmunity,0,ProjectileSize*sizeof(ieDword));
1987 //initialize base stats
1988 bool first = !(InternalFlags&IF_INITIALIZED);
1990 if (first) {
1991 InternalFlags|=IF_INITIALIZED;
1992 memcpy( previous, BaseStats, MAX_STATS * sizeof( ieDword ) );
1993 } else {
1994 memcpy( previous, Modified, MAX_STATS * sizeof( ieDword ) );
1996 memcpy( Modified, BaseStats, MAX_STATS * sizeof( ieDword ) );
1997 if (PCStats) memset( PCStats->PortraitIcons, -1, sizeof(PCStats->PortraitIcons) );
1999 if (fx) {
2000 fx->SetOwner(this);
2001 fx->AddAllEffects(this, Pos);
2002 delete fx;
2003 //copy back the original stats, because the effects
2004 //will be reapplied in ApplyAllEffects again
2005 memcpy( Modified, BaseStats, MAX_STATS * sizeof( ieDword ) );
2006 //also clear the spell bonuses just given, they will be
2007 //recalculated below again
2008 spellbook.ClearBonus();
2011 fxqueue.ApplyAllEffects( this );
2013 // IE_CLASS is >classcount for non-PCs/NPCs
2014 if (BaseStats[IE_CLASS] <= (ieDword)classcount)
2015 RefreshPCStats();
2017 for (unsigned int i=0;i<MAX_STATS;i++) {
2018 if (first || Modified[i]!=previous[i]) {
2019 PostChangeFunctionType f = post_change_functions[i];
2020 if (f) {
2021 (*f)(this, previous[i], Modified[i]);
2025 //add wisdom bonus spells
2026 if (!spellbook.IsIWDSpellBook() && mxsplwis) {
2027 int level = Modified[IE_WIS];
2028 if (level--) {
2029 spellbook.BonusSpells(IE_SPELL_TYPE_PRIEST, spllevels, mxsplwis+spllevels*level);
2033 // check if any new portrait icon was removed or added
2034 if (PCStats) {
2035 if (memcmp(PCStats->PreviousPortraitIcons, PCStats->PortraitIcons, sizeof(PCStats->PreviousPortraitIcons))) {
2036 core->SetEventFlag(EF_PORTRAIT);
2037 memcpy( PCStats->PreviousPortraitIcons, PCStats->PortraitIcons, sizeof(PCStats->PreviousPortraitIcons) );
2042 // refresh stats on creatures (PC or NPC) with a valid class (not animals etc)
2043 // internal use only, and this is maybe a stupid name :)
2044 void Actor::RefreshPCStats() {
2045 //calculate hp bonus
2046 int bonus;
2047 int bonlevel = GetXPLevel(true);
2048 int oldlevel, oldbonus;
2049 oldlevel = oldbonus = 0;
2050 ieDword bonindex = BaseStats[IE_CLASS]-1;
2052 //we must limit the levels to the max allowable
2053 if (bonlevel>maxhpconbon[bonindex])
2054 bonlevel = maxhpconbon[bonindex];
2056 if (IsDualInactive()) {
2057 //we apply the inactive hp bonus if it's better than the new hp bonus, so that we
2058 //never lose hp, only gain, on leveling
2059 oldlevel = IsDualSwap() ? BaseStats[IE_LEVEL] : BaseStats[IE_LEVEL2];
2060 bonlevel = IsDualSwap() ? BaseStats[IE_LEVEL2] : BaseStats[IE_LEVEL];
2061 oldlevel = (oldlevel > maxhpconbon[bonindex]) ? maxhpconbon[bonindex] : oldlevel;
2062 if (Modified[IE_MC_FLAGS] & (MC_WAS_FIGHTER|MC_WAS_RANGER)) {
2063 oldbonus = core->GetConstitutionBonus(STAT_CON_HP_WARRIOR, Modified[IE_CON]);
2064 } else {
2065 oldbonus = core->GetConstitutionBonus(STAT_CON_HP_NORMAL, Modified[IE_CON]);
2069 // warrior (fighter, barbarian, ranger, or paladin) or not
2070 // GetClassLevel now takes into consideration inactive dual-classes
2071 if (IsWarrior()) {
2072 bonus = core->GetConstitutionBonus(STAT_CON_HP_WARRIOR,Modified[IE_CON]);
2073 } else {
2075 bonus = core->GetConstitutionBonus(STAT_CON_HP_NORMAL,Modified[IE_CON]);
2077 bonus *= bonlevel;
2078 oldbonus *= oldlevel;
2079 bonus = (oldbonus > bonus) ? oldbonus : bonus;
2081 //morale recovery every xth AI cycle
2082 int mrec = GetStat(IE_MORALERECOVERYTIME);
2083 if (mrec) {
2084 if (!(core->GetGame()->GameTime%mrec)) {
2085 NewBase(IE_MORALE,1,MOD_ADDITIVE);
2089 if (bonus<0 && (Modified[IE_MAXHITPOINTS]+bonus)<=0) {
2090 bonus=1-Modified[IE_MAXHITPOINTS];
2093 //get the wspattack bonuses for proficiencies
2094 WeaponInfo wi;
2095 ITMExtHeader *header = GetWeapon(wi, false);
2096 ieDword stars;
2097 int dualwielding = IsDualWielding();
2098 if (header && (wi.prof <= MAX_STATS)) {
2099 stars = GetStat(wi.prof)&PROFS_MASK;
2100 if (stars >= (unsigned)wspattack_rows) {
2101 stars = wspattack_rows-1;
2104 int tmplevel = GetWarriorLevel();
2105 if (tmplevel >= wspattack_cols) {
2106 tmplevel = wspattack_cols-1;
2107 } else if (tmplevel < 0) {
2108 tmplevel = 0;
2111 //HACK: attacks per round bonus for monks should only apply to fists
2112 if (isclass[ISMONK]&(1<<BaseStats[IE_CLASS])) {
2113 unsigned int level = GetMonkLevel()-1;
2114 SetBase(IE_NUMBEROFATTACKS, 2 + monkbon[0][level]);
2115 } else {
2116 //wspattack appears to only effect warriors
2117 int defaultattacks = 2 + 2*dualwielding;
2118 if (tmplevel) {
2119 SetBase(IE_NUMBEROFATTACKS, defaultattacks+wspattack[stars][tmplevel]);
2120 } else {
2121 SetBase(IE_NUMBEROFATTACKS, defaultattacks);
2126 //we still apply the maximum bonus to dead characters, but don't apply
2127 //to current HP, or we'd have dead characters showing as having hp
2128 //Modified[IE_MAXHITPOINTS]+=bonus;
2129 //if(BaseStats[IE_STATE_ID]&STATE_DEAD)
2130 // bonus = 0;
2131 // BaseStats[IE_HITPOINTS]+=bonus;
2133 // apply the intelligence and wisdom bonus to lore
2134 Modified[IE_LORE] += core->GetLoreBonus(0, Modified[IE_INT]) + core->GetLoreBonus(0, Modified[IE_WIS]);
2137 void Actor::RollSaves()
2139 if (InternalFlags&IF_USEDSAVE) {
2140 SavingThrow[0]=(ieByte) core->Roll(1, SAVEROLL, 0);
2141 SavingThrow[1]=(ieByte) core->Roll(1, SAVEROLL, 0);
2142 SavingThrow[2]=(ieByte) core->Roll(1, SAVEROLL, 0);
2143 SavingThrow[3]=(ieByte) core->Roll(1, SAVEROLL, 0);
2144 SavingThrow[4]=(ieByte) core->Roll(1, SAVEROLL, 0);
2145 InternalFlags&=~IF_USEDSAVE;
2149 //saving throws:
2150 //type bits in file order in stats
2151 //0 spells 1 4
2152 //1 breath 2 3
2153 //2 death 4 0
2154 //3 wands 8 1
2155 //4 polymorph 16 2
2157 //iwd2 (luckily they use the same bits as it would be with bg2):
2158 //0 not used
2159 //1 not used
2160 //2 fortitude 4 0
2161 //3 reflex 8 1
2162 //4 will 16 2
2164 #define SAVECOUNT 5
2165 static int savingthrows[SAVECOUNT]={IE_SAVEVSSPELL, IE_SAVEVSBREATH, IE_SAVEVSDEATH, IE_SAVEVSWANDS, IE_SAVEVSPOLY};
2167 /** returns true if actor made the save against saving throw type */
2168 bool Actor::GetSavingThrow(ieDword type, int modifier)
2170 assert(type<SAVECOUNT);
2171 InternalFlags|=IF_USEDSAVE;
2172 int ret = SavingThrow[type];
2173 if (ret == 1) return false;
2174 if (ret == SAVEROLL) return true;
2175 ret += modifier + GetStat(IE_LUCK);
2176 return ret > (int) GetStat(savingthrows[type]);
2179 /** implements a generic opcode function, modify modified stats
2180 returns the change
2182 int Actor::NewStat(unsigned int StatIndex, ieDword ModifierValue, ieDword ModifierType)
2184 int oldmod = Modified[StatIndex];
2186 switch (ModifierType) {
2187 case MOD_ADDITIVE:
2188 //flat point modifier
2189 SetStat(StatIndex, Modified[StatIndex]+ModifierValue, 0);
2190 break;
2191 case MOD_ABSOLUTE:
2192 //straight stat change
2193 SetStat(StatIndex, ModifierValue, 0);
2194 break;
2195 case MOD_PERCENT:
2196 //percentile
2197 SetStat(StatIndex, BaseStats[StatIndex] * ModifierValue / 100, 0);
2198 break;
2200 return Modified[StatIndex] - oldmod;
2203 int Actor::NewBase(unsigned int StatIndex, ieDword ModifierValue, ieDword ModifierType)
2205 int oldmod = BaseStats[StatIndex];
2207 switch (ModifierType) {
2208 case MOD_ADDITIVE:
2209 //flat point modifier
2210 SetBase(StatIndex, BaseStats[StatIndex]+ModifierValue);
2211 break;
2212 case MOD_ABSOLUTE:
2213 //straight stat change
2214 SetBase(StatIndex, ModifierValue);
2215 break;
2216 case MOD_PERCENT:
2217 //percentile
2218 SetBase(StatIndex, BaseStats[StatIndex] * ModifierValue / 100);
2219 break;
2221 return BaseStats[StatIndex] - oldmod;
2224 inline int CountElements(const char *s, char separator)
2226 int ret = 1;
2227 while(*s) {
2228 if (*s==separator) ret++;
2229 s++;
2231 return ret;
2234 void Actor::Interact(int type)
2236 int start;
2237 int count;
2239 switch(type) {
2240 case I_INSULT: start=VB_INSULT; count=3; break;
2241 case I_COMPLIMENT: start=VB_COMPLIMENT; count=3; break;
2242 case I_SPECIAL: start=VB_SPECIAL; count=3; break;
2243 default:
2244 return;
2246 VerbalConstant(start, count);
2249 void Actor::VerbalConstant(int start, int count)
2251 count=rand()%count;
2252 while(count>=0 && (!StrRefs[start+count] || (StrRefs[start+count]==(ieStrRef) -1)) ) count--;
2253 if(count>=0) {
2254 DisplayStringCore(this, start+count, DS_CONSOLE|DS_CONST );
2258 void Actor::Response(int type)
2260 int start;
2261 int count;
2263 switch(type) {
2264 case I_INSULT: start=VB_RESP_INS; count=3; break;
2265 case I_COMPLIMENT: start=VB_RESP_COMP; count=3; break;
2266 default:
2267 return;
2270 count=rand()%count;
2271 while(count && StrRefs[start+count]!=0xffff) count--;
2272 if(count>=0) {
2273 DisplayStringCore(this, start+count, DS_CONSOLE|DS_CONST );
2277 void Actor::ReactToDeath(const char * deadname)
2279 AutoTable tm("death");
2280 if (!tm) return;
2281 // lookup value based on died's scriptingname and ours
2282 // if value is 0 - use reactdeath
2283 // if value is 1 - use reactspecial
2284 // if value is string - use playsound instead (pst)
2285 const char *value = tm->QueryField (scriptName, deadname);
2286 switch (value[0]) {
2287 case '0':
2288 DisplayStringCore(this, VB_REACT, DS_CONSOLE|DS_CONST );
2289 break;
2290 case '1':
2291 DisplayStringCore(this, VB_REACT_S, DS_CONSOLE|DS_CONST );
2292 break;
2293 default:
2295 int count = CountElements(value,',');
2296 if (count<=0) break;
2297 count = core->Roll(1,count,-1);
2298 ieResRef resref;
2299 while(count--) {
2300 while(*value && *value!=',') value++;
2301 if (*value==',') value++;
2303 strncpy(resref, value, 8);
2304 for(count=0;count<8 && resref[count]!=',';count++) {};
2305 resref[count]=0;
2307 ieDword len = core->GetAudioDrv()->Play( resref );
2308 ieDword counter = ( AI_UPDATE_TIME * len ) / 1000;
2309 if (counter != 0)
2310 SetWait( counter );
2311 break;
2316 //call this only from gui selects
2317 void Actor::SelectActor()
2319 DisplayStringCore(this, VB_SELECT, DS_CONSOLE|DS_CONST );
2322 void Actor::Panic()
2324 if (GetStat(IE_STATE_ID)&STATE_PANIC) {
2325 //already in panic
2326 return;
2328 if (InParty) core->GetGame()->SelectActor(this, false, SELECT_NORMAL);
2329 SetBaseBit(IE_STATE_ID, STATE_PANIC, true);
2330 DisplayStringCore(this, VB_PANIC, DS_CONSOLE|DS_CONST );
2333 void Actor::SetMCFlag(ieDword arg, int op)
2335 ieDword tmp = BaseStats[IE_MC_FLAGS];
2336 switch (op) {
2337 case BM_SET: tmp = arg; break;
2338 case BM_OR: tmp |= arg; break;
2339 case BM_NAND: tmp &= ~arg; break;
2340 case BM_XOR: tmp ^= arg; break;
2341 case BM_AND: tmp &= arg; break;
2343 SetBase(IE_MC_FLAGS, tmp);
2346 void Actor::DialogInterrupt()
2348 //if dialoginterrupt was set, no verbal constant
2349 if ( Modified[IE_MC_FLAGS]&MC_NO_TALK)
2350 return;
2352 /* this part is unsure */
2353 if (Modified[IE_EA]>=EA_EVILCUTOFF) {
2354 DisplayStringCore(this, VB_HOSTILE, DS_CONSOLE|DS_CONST );
2355 } else {
2356 DisplayStringCore(this, VB_DIALOG, DS_CONSOLE|DS_CONST );
2360 static EffectRef fx_cure_sleep_ref={"Cure:Sleep",NULL,-1};
2362 void Actor::GetHit()
2364 SetStance( IE_ANI_DAMAGE );
2365 DisplayStringCore(this, VB_DAMAGE, DS_CONSOLE|DS_CONST );
2366 if (Modified[IE_STATE_ID]&STATE_SLEEP) {
2367 if (Modified[IE_EXTSTATE_ID]&EXTSTATE_NO_WAKEUP) {
2368 return;
2370 Effect *fx = EffectQueue::CreateEffect(fx_cure_sleep_ref, 0, 0, FX_DURATION_INSTANT_PERMANENT);
2371 fxqueue.AddEffect(fx);
2375 bool Actor::HandleCastingStance(const ieResRef SpellResRef, bool deplete)
2377 if (deplete) {
2378 if (! spellbook.HaveSpell( SpellResRef, HS_DEPLETE )) {
2379 SetStance(IE_ANI_READY);
2380 return true;
2383 SetStance(IE_ANI_CAST);
2384 return false;
2387 static EffectRef fx_sleep_ref={"State:Helpless", NULL, -1};
2389 //returns actual damage
2390 int Actor::Damage(int damage, int damagetype, Scriptable *hitter, int modtype)
2392 //add lastdamagetype up ? maybe
2393 LastDamageType|=damagetype;
2394 if(hitter && hitter->Type==ST_ACTOR) {
2395 LastHitter=((Actor *) hitter)->GetID();
2396 } else {
2397 //Maybe it should be something impossible like 0xffff, and use 'Someone'
2398 LastHitter=GetID();
2401 switch(modtype)
2403 case MOD_ADDITIVE:
2404 //damage = -NewBase(IE_HITPOINTS, (ieDword) -damage, MOD_ADDITIVE);
2405 break;
2406 case MOD_ABSOLUTE:
2407 //damage = -NewBase(IE_HITPOINTS, (ieDword) damage, MOD_ABSOLUTE);
2408 damage = GetBase(IE_HITPOINTS) - damage;
2409 break;
2410 case MOD_PERCENT:
2411 //damage = -NewBase(IE_HITPOINTS, (ieDword) damage, MOD_PERCENT);
2412 damage = GetStat(IE_MAXHITPOINTS) * 100 / damage;
2413 break;
2414 default:
2415 //this shouldn't happen
2416 printMessage("Actor","Invalid damagetype!\n",RED);
2417 return 0;
2420 int resisted = 0;
2421 ModifyDamage (this, (Actor *)hitter, damage, resisted, damagetype, NULL, false);
2422 if (damage) GetHit();
2424 DisplayCombatFeedback(damage, resisted, damagetype, (Actor *)hitter);
2426 if (BaseStats[IE_HITPOINTS] <= (ieDword) damage) {
2427 // common fists do normal damage, but cause sleeping for a round instead of death
2428 if ((damagetype & DAMAGE_STUNNING) && Modified[IE_MINHITPOINTS] <= 0) {
2429 NewBase(IE_HITPOINTS, 1, MOD_ABSOLUTE);
2430 Effect *fx = EffectQueue::CreateEffect(fx_sleep_ref, 0, 0, FX_DURATION_INSTANT_LIMITED);
2431 fx->Duration = 6; // 1 round
2432 core->ApplyEffect(fx, this, this);
2433 delete fx;
2434 } else {
2435 NewBase(IE_HITPOINTS, (ieDword) -damage, MOD_ADDITIVE);
2437 } else {
2438 NewBase(IE_HITPOINTS, (ieDword) -damage, MOD_ADDITIVE);
2440 // also apply reputation damage if we hurt (but not killed) an innocent
2441 int reputation = core->GetGame()->Reputation / 10;
2442 if (Modified[IE_CLASS] == CLASS_INNOCENT) {
2443 core->GetGame()->SetReputation(reputation*10 + reputationmod[reputation-1][1]);
2447 LastDamage=damage;
2448 InternalFlags|=IF_ACTIVE;
2449 int chp = (signed) BaseStats[IE_HITPOINTS];
2450 int damagelevel = 3;
2451 if (damage<5) {
2452 damagelevel = 1;
2453 } else if (damage<10) {
2454 damagelevel = 2;
2455 } else {
2456 NewBase(IE_MORALE, (ieDword) -1, MOD_ADDITIVE);
2457 if (chp<-10) {
2458 damagelevel = 0; //chunky death
2460 else {
2461 damagelevel = 3;
2465 if (damagetype & (DAMAGE_FIRE|DAMAGE_MAGICFIRE) ) {
2466 PlayDamageAnimation(DL_FIRE+damagelevel);
2467 } else if (damagetype & (DAMAGE_COLD|DAMAGE_MAGICCOLD) ) {
2468 PlayDamageAnimation(DL_COLD+damagelevel);
2469 } else if (damagetype & (DAMAGE_ELECTRICITY) ) {
2470 PlayDamageAnimation(DL_ELECTRICITY+damagelevel);
2471 } else if (damagetype & (DAMAGE_ACID) ) {
2472 PlayDamageAnimation(DL_ACID+damagelevel);
2473 } else if (damagetype & (DAMAGE_MAGIC) ) {
2474 PlayDamageAnimation(DL_DISINTEGRATE+damagelevel);
2475 } else {
2476 PlayDamageAnimation(damagelevel);
2479 if (InParty) {
2480 if (chp<(signed) Modified[IE_MAXHITPOINTS]/10) {
2481 core->Autopause(AP_WOUNDED);
2483 if (damage>0) {
2484 core->Autopause(AP_HIT);
2485 core->SetEventFlag(EF_PORTRAIT);
2488 return damage;
2491 //TODO: handle pst
2492 void Actor::DisplayCombatFeedback (unsigned int damage, int resisted, int damagetype, Actor *hitter)
2494 bool detailed = false;
2495 const char *type_name = "unknown";
2496 if (core->GetStringReference(STR_DMG_SLASHING) != (ieStrRef) -1) { // how and iwd2
2497 std::multimap<ieDword, DamageInfoStruct>::iterator it;
2498 it = core->DamageInfoMap.find(damagetype);
2499 if (it != core->DamageInfoMap.end()) {
2500 type_name = core->GetString(it->second.strref, 0);
2502 detailed = true;
2505 if (damage > 0 && resisted != DR_IMMUNE) {
2506 printMessage("Actor", " ", GREEN);
2507 printf("%d damage taken.\n", damage);
2509 if (detailed) {
2510 // 3 choices depending on resistance and boni
2511 // iwd2 also has two Tortoise Shell (spell) absorption strings
2512 core->GetTokenDictionary()->SetAtCopy( "TYPE", type_name);
2513 core->GetTokenDictionary()->SetAtCopy( "AMOUNT", damage);
2514 core->GetTokenDictionary()->SetAtCopy( "DAMAGER", hitter ? hitter->GetName(1) : this->GetName(1) );
2515 if (resisted < 0) {
2516 //Takes <AMOUNT> <TYPE> damage from <DAMAGER> (<RESISTED> damage bonus)
2517 core->GetTokenDictionary()->SetAtCopy( "RESISTED", abs(resisted));
2518 core->DisplayConstantStringName(STR_DAMAGE3, 0xffffff, this);
2519 } else if (resisted > 0) {
2520 //Takes <AMOUNT> <TYPE> damage from <DAMAGER> (<RESISTED> damage resisted)
2521 core->GetTokenDictionary()->SetAtCopy( "RESISTED", abs(resisted));
2522 core->DisplayConstantStringName(STR_DAMAGE2, 0xffffff, this);
2523 } else {
2524 //Takes <AMOUNT> <TYPE> damage from <DAMAGER>
2525 core->DisplayConstantStringName(STR_DAMAGE1, 0xffffff, this);
2527 } else if (stricmp( core->GameType, "pst" ) == 0) {
2528 if(0) printf("TODO: pst floating text\n");
2529 } else if (core->GetStringReference(STR_DAMAGE_IMMUNITY) == (ieStrRef) -1 && core->GetStringReference(STR_DAMAGE1) != (ieStrRef) -1) {
2530 // bg1 and how
2531 // "Damage Taken"
2532 core->DisplayConstantStringName(STR_DAMAGE1, 0xffffff, this);
2533 } else { //bg2
2534 //<DAMAGER> did <AMOUNT> damage to <DAMAGEE>
2535 core->GetTokenDictionary()->SetAtCopy( "DAMAGEE", GetName(1) );
2536 // wipe the DAMAGER token, so we can color it
2537 core->GetTokenDictionary()->SetAtCopy( "DAMAGER", "" );
2538 core->GetTokenDictionary()->SetAtCopy( "AMOUNT", damage);
2539 core->DisplayConstantStringName(STR_DAMAGE1, 0xffffff, hitter);
2541 } else {
2542 if (resisted == DR_IMMUNE) {
2543 printMessage("Actor", " ", GREEN);
2544 printf("is immune to damage type: %s.\n", type_name);
2546 if (detailed) {
2547 //<DAMAGEE> was immune to my <TYPE> damage
2548 core->GetTokenDictionary()->SetAtCopy( "DAMAGEE", GetName(1) );
2549 core->GetTokenDictionary()->SetAtCopy( "TYPE", type_name );
2550 core->DisplayConstantStringName(STR_DAMAGE_IMMUNITY, 0xffffff, hitter);
2551 } else if (core->GetStringReference(STR_DAMAGE_IMMUNITY) != (ieStrRef) -1 && core->GetStringReference(STR_DAMAGE1) != (ieStrRef) -1) {
2552 // bg2
2553 //<DAMAGEE> was immune to my damage.
2554 core->GetTokenDictionary()->SetAtCopy( "DAMAGEE", GetName(1) );
2555 core->DisplayConstantStringName(STR_DAMAGE_IMMUNITY, 0xffffff, hitter);
2556 } // else: other games don't display anything
2557 } else {
2558 // mirror image or stoneskin: no message
2562 //PST hit sounds
2563 DataFileMgr *resdata = core->GetResDataINI();
2564 if (resdata) {
2565 PlayHitSound(resdata, damagetype, false);
2569 //Play PST specific hit sounds (HIT_0<dtype><armor>)
2570 void Actor::PlayHitSound(DataFileMgr *resdata, int damagetype, bool suffix)
2572 int type;
2574 switch(damagetype) {
2575 case DAMAGE_SLASHING: type = 1; break; //slashing
2576 case DAMAGE_PIERCING: type = 2; break; //piercing
2577 case DAMAGE_CRUSHING: type = 3; break; //crushing
2578 case DAMAGE_MISSILE: type = 4; break; //missile
2579 default: return; //other
2582 ieResRef Sound;
2583 char section[12];
2584 unsigned int animid=BaseStats[IE_ANIMATION_ID];
2585 if(core->HasFeature(GF_ONE_BYTE_ANIMID)) {
2586 animid&=0xff;
2589 snprintf(section,10,"%d", animid);
2591 int armor = resdata->GetKeyAsInt(section, "armor",0);
2592 if (armor<0 || armor>35) return;
2594 snprintf(Sound,8,"HIT_0%d%c%c",type, armor+'A', suffix?'1':0);
2596 core->GetAudioDrv()->Play( Sound,Pos.x,Pos.y,0 );
2599 //Just to quickly inspect debug maximum values
2600 #if 0
2601 void Actor::DumpMaxValues()
2603 int symbol = core->LoadSymbol( "stats" );
2604 SymbolMgr *sym = core->GetSymbol( symbol );
2606 for(int i=0;i<MAX_STATS;i++) {
2607 printf("%d (%s) %d\n", i, sym->GetValue(i), maximum_values[i]);
2610 #endif
2612 void Actor::DebugDump()
2614 unsigned int i;
2616 printf( "Debugdump of Actor %s (%s, %s):\n", LongName, ShortName, GetName(-1) );
2617 printf ("Scripts:");
2618 for (i = 0; i < MAX_SCRIPTS; i++) {
2619 const char* poi = "<none>";
2620 if (Scripts[i] && Scripts[i]->script) {
2621 poi = Scripts[i]->GetName();
2623 printf( " %.8s", poi );
2625 printf( "\nArea: %.8s ", Area );
2626 printf( "Dialog: %.8s\n", Dialog );
2627 printf( "Global ID: %d Local ID: %d\n", globalID, localID);
2628 printf( "Script name:%.32s\n", scriptName );
2629 printf( "TalkCount: %d ", TalkCount );
2630 printf( "PartySlot: %d\n", InParty );
2631 printf( "Allegiance: %d current allegiance:%d\n", BaseStats[IE_EA], Modified[IE_EA] );
2632 printf( "Class: %d current class:%d\n", BaseStats[IE_CLASS], Modified[IE_CLASS] );
2633 printf( "Race: %d current race:%d\n", BaseStats[IE_RACE], Modified[IE_RACE] );
2634 printf( "Gender: %d current gender:%d\n", BaseStats[IE_SEX], Modified[IE_SEX] );
2635 printf( "Specifics: %d current specifics:%d\n", BaseStats[IE_SPECIFIC], Modified[IE_SPECIFIC] );
2636 printf( "Alignment: %x current alignment:%x\n", BaseStats[IE_ALIGNMENT], Modified[IE_ALIGNMENT] );
2637 printf( "Morale: %d current morale:%d\n", BaseStats[IE_MORALE], Modified[IE_MORALE] );
2638 printf( "Moralebreak:%d Morale recovery:%d\n", Modified[IE_MORALEBREAK], Modified[IE_MORALERECOVERYTIME] );
2639 printf( "Visualrange:%d (Explorer: %d)\n", Modified[IE_VISUALRANGE], Modified[IE_EXPLORE] );
2640 printf( "current HP:%d\n", BaseStats[IE_HITPOINTS] );
2641 printf( "Mod[IE_ANIMATION_ID]: 0x%04X\n", Modified[IE_ANIMATION_ID] );
2642 printf( "Colors: ");
2643 if (core->HasFeature(GF_ONE_BYTE_ANIMID) ) {
2644 for(i=0;i<Modified[IE_COLORCOUNT];i++) {
2645 printf(" %d", Modified[IE_COLORS+i]);
2648 else {
2649 for(i=0;i<7;i++) {
2650 printf(" %d", Modified[IE_COLORS+i]);
2653 printf( "\nWaitCounter: %d\n", (int) GetWait());
2654 printf( "LastTarget: %d %s\n", LastTarget, GetActorNameByID(LastTarget));
2655 printf( "LastTalked: %d %s\n", LastTalkedTo, GetActorNameByID(LastTalkedTo));
2656 inventory.dump();
2657 spellbook.dump();
2658 fxqueue.dump();
2659 #if 0
2660 DumpMaxValues();
2661 #endif
2664 const char* Actor::GetActorNameByID(ieDword ID) const
2666 Actor *actor = GetCurrentArea()->GetActorByGlobalID(ID);
2667 if (!actor) {
2668 return "<NULL>";
2670 return actor->GetScriptName();
2673 void Actor::SetMap(Map *map, ieWord LID, ieWord GID)
2675 //Did we have an area?
2676 bool effinit=!GetCurrentArea();
2677 Scriptable::SetMap(map); //now we have an area
2678 localID = LID;
2679 globalID = GID;
2681 //These functions are called once when the actor is first put in
2682 //the area. It already has all the items (including fist) at this
2683 //time and it is safe to call effects.
2684 //This hack is to delay the equipping effects until the actor has
2685 //an area (and the game object is also existing)
2686 if (effinit) {
2687 int SlotCount = inventory.GetSlotCount();
2688 for (int Slot = 0; Slot<SlotCount;Slot++) {
2689 int slottype = core->QuerySlotEffects( Slot );
2690 switch (slottype) {
2691 case SLOT_EFFECT_NONE:
2692 case SLOT_EFFECT_MELEE:
2693 break;
2694 default:
2695 inventory.EquipItem( Slot );
2696 break;
2699 //We need to convert this to signed 16 bits, because
2700 //it is actually a 16 bit number.
2701 //It is signed to have the correct math
2702 //when adding it to the base slot (SLOT_WEAPON) in
2703 //case of quivers. (weird IE magic)
2704 //The other word is the equipped header.
2705 //find a quiver for the bow, etc
2706 if (Equipped!=IW_NO_EQUIPPED) {
2707 inventory.EquipItem( Equipped+inventory.GetWeaponSlot());
2708 SetEquippedQuickSlot( inventory.GetEquipped(), EquippedHeader );
2713 void Actor::SetPosition(const Point &position, int jump, int radius)
2715 PathTries = 0;
2716 ClearPath();
2717 Point p;
2718 p.x = position.x/16;
2719 p.y = position.y/12;
2720 if (jump && !(Modified[IE_DONOTJUMP] & DNJ_FIT) && size ) {
2721 GetCurrentArea()->AdjustPosition( p, radius );
2723 p.x = p.x * 16 + 8;
2724 p.y = p.y * 12 + 6;
2725 MoveTo( p );
2728 /* this is returning the level of the character for xp calculations
2729 and the average level for dual/multiclass (rounded up),
2730 also with iwd2's 3rd ed rules, this is why it is a separate function */
2731 ieDword Actor::GetXPLevel(int modified) const
2733 const ieDword *stats;
2735 if (modified) {
2736 stats = Modified;
2738 else {
2739 stats = BaseStats;
2742 float classcount = 0;
2743 float average = 0;
2744 if (core->HasFeature(GF_LEVELSLOT_PER_CLASS)) {
2745 // iwd2
2746 for (int i=0; i < 11; i++) {
2747 if (stats[levelslotsiwd2[i]] > 0) classcount++;
2749 average = stats[IE_CLASSLEVELSUM] / classcount + 0.5;
2751 else {
2752 int levels[3]={stats[IE_LEVEL], stats[IE_LEVEL2], stats[IE_LEVEL3]};
2753 average = levels[0];
2754 classcount = 1;
2755 if (IsDualClassed()) {
2756 // dualclassed
2757 if (levels[1] > 0) {
2758 classcount++;
2759 average += levels[1];
2762 else if (IsMultiClassed()) {
2763 //classcount is the number of on bits in the MULTI field
2764 classcount = bitcount (multiclass);
2765 for (int i=1; i<classcount; i++)
2766 average += levels[i];
2767 } //else single classed
2768 average = average / classcount + 0.5;
2770 return ieDword(average);
2773 int Actor::GetWildMod(int level) const
2775 if(GetStat(IE_KIT)&0x8000) {
2776 if (level>=MAX_LEVEL) level=MAX_LEVEL;
2777 if(level<1) level=1;
2778 return wmlevels[core->Roll(1,20,-1)][level-1];
2780 return 0;
2783 int Actor::CastingLevelBonus(int level, int type) const
2785 int bonus = 0;
2786 switch(type)
2788 case IE_SPL_PRIEST:
2789 bonus = GetStat(IE_CASTINGLEVELBONUSCLERIC);
2790 break;
2791 case IE_SPL_WIZARD:
2792 bonus = GetWildMod(level) + GetStat(IE_CASTINGLEVELBONUSMAGE);
2795 if (!bonus) {
2796 return 0;
2799 core->GetTokenDictionary()->SetAtCopy("LEVELDIF", bonus);
2801 if (bonus > 0) {
2802 core->DisplayConstantStringName(STR_CASTER_LVL_INC, 0xffffff, this);
2803 } else {
2804 core->DisplayConstantStringName(STR_CASTER_LVL_DEC, 0xffffff, this);
2807 return bonus;
2810 /** maybe this would be more useful if we calculate with the strength too
2812 int Actor::GetEncumbrance()
2814 return inventory.GetWeight();
2817 //receive turning
2818 void Actor::Turn(Scriptable *cleric, ieDword turnlevel)
2820 //this is safely hardcoded i guess
2821 if (Modified[IE_GENERAL]!=GEN_UNDEAD) {
2822 return;
2824 //determine if we see the cleric (distance)
2826 //determine alignment (if equals, then no turning)
2828 //determine panic or destruction
2829 //we get the modified level
2830 if (turnlevel>GetXPLevel(true)) {
2831 Die(cleric);
2832 } else {
2833 Panic();
2837 void Actor::Resurrect()
2839 if (!(Modified[IE_STATE_ID ] & STATE_DEAD)) {
2840 return;
2842 InternalFlags&=IF_FROMGAME; //keep these flags (what about IF_INITIALIZED)
2843 InternalFlags|=IF_ACTIVE|IF_VISIBLE; //set these flags
2844 SetBase(IE_STATE_ID, 0);
2845 SetBase(IE_MORALE, 10);
2846 SetBase(IE_HITPOINTS, BaseStats[IE_MAXHITPOINTS]);
2847 ClearActions();
2848 ClearPath();
2849 SetStance(IE_ANI_EMERGE);
2850 //readjust death variable on resurrection
2851 if (core->HasFeature(GF_HAS_KAPUTZ) && (AppearanceFlags&APP_DEATHVAR)) {
2852 ieVariable DeathVar;
2854 snprintf(DeathVar,sizeof(ieVariable),"%s_DEAD",scriptName);
2855 Game *game=core->GetGame();
2856 ieDword value=0;
2858 game->kaputz->Lookup(DeathVar, value);
2859 if (value) {
2860 game->kaputz->SetAt(DeathVar, value-1);
2863 //clear effects?
2866 void Actor::Die(Scriptable *killer)
2868 int i,j;
2870 if (InternalFlags&IF_REALLYDIED) {
2871 return; //can die only once
2874 int minhp = (signed) Modified[IE_MINHITPOINTS];
2875 if (minhp > 0) { //can't die
2876 SetBase(IE_HITPOINTS, minhp);
2877 return;
2879 //Can't simply set Selected to false, game has its own little list
2880 Game *game = core->GetGame();
2881 game->SelectActor(this, false, SELECT_NORMAL);
2882 game->OutAttack(GetID());
2884 ClearActions();
2885 ClearPath();
2886 SetModal( MS_NONE );
2887 core->DisplayConstantStringName(STR_DEATH, 0xffffff, this);
2888 DisplayStringCore(this, VB_DIE, DS_CONSOLE|DS_CONST );
2890 // clearing the search map here means it's not blocked during death animations
2891 // this is perhaps not ideal, but matches other searchmap code which uses
2892 // GA_NO_DEAD to exclude IF_JUSTDIED actors as well as dead ones
2893 if (area)
2894 area->ClearSearchMapFor(this);
2896 //JUSTDIED will be removed when the Die() trigger executed
2897 //otherwise it is the same as REALLYDIED
2898 InternalFlags|=IF_REALLYDIED|IF_JUSTDIED;
2899 SetStance( IE_ANI_DIE );
2901 if (InParty) {
2902 game->PartyMemberDied(this);
2903 core->Autopause(AP_DEAD);
2904 } else {
2905 Actor *act=NULL;
2906 if (!killer) {
2907 killer = area->GetActorByGlobalID(LastHitter);
2910 if (killer) {
2911 if (killer->Type==ST_ACTOR) {
2912 act = (Actor *) killer;
2916 if (act) {
2917 if (act->InParty) {
2918 //adjust kill statistics here
2919 PCStatsStruct *stat = act->PCStats;
2920 if (stat) {
2921 stat->NotifyKill(Modified[IE_XPVALUE], ShortStrRef);
2923 InternalFlags|=IF_GIVEXP;
2926 // friendly party summons' kills also grant xp
2927 if (act->Modified[IE_SEX] == SEX_SUMMON && act->Modified[IE_EA] == EA_CONTROLLED) {
2928 InternalFlags|=IF_GIVEXP;
2933 // XP seems to be handed at out at the moment of death
2934 if (InternalFlags&IF_GIVEXP) {
2935 //give experience to party
2936 game->ShareXP(Modified[IE_XPVALUE], sharexp );
2938 if (!InParty) {
2939 // adjust reputation if the corpse was:
2940 // an innocent, a member of the Flaming Fist or something evil
2941 int reputation = game->Reputation / 10;
2942 int repmod = 0;
2943 if (Modified[IE_CLASS] == CLASS_INNOCENT) {
2944 repmod = reputationmod[reputation-1][0];
2945 } else if (Modified[IE_CLASS] == CLASS_FLAMINGFIST) {
2946 repmod = reputationmod[reputation-1][3];
2948 if (Modified[IE_ALIGNMENT]&AL_EVIL) {
2949 repmod += reputationmod[reputation-1][7];
2951 if (repmod) {
2952 game->SetReputation(reputation*10 + repmod);
2957 ieDword value = 0;
2958 ieVariable varname;
2960 // death variables are updated at the moment of death
2961 if (KillVar[0]) {
2962 if (core->HasFeature(GF_HAS_KAPUTZ) ) {
2963 game->kaputz->Lookup(KillVar, value);
2964 game->kaputz->SetAt(KillVar, value+1);
2965 } else {
2966 // iwd/iwd2 path *sets* this var, so i changed it, not sure about pst above
2967 game->locals->SetAt(KillVar, 1);
2970 if (IncKillVar[0]) {
2971 value = 0;
2972 game->locals->Lookup(IncKillVar, value);
2973 game->locals->SetAt(IncKillVar, value + 1);
2976 if (scriptName[0]) {
2977 value = 0;
2978 if (core->HasFeature(GF_HAS_KAPUTZ) ) {
2979 if (AppearanceFlags&APP_DEATHVAR) {
2980 snprintf(varname, 32, "%s_DEAD", scriptName);
2981 game->kaputz->Lookup(varname, value);
2982 game->kaputz->SetAt(varname, value+1);
2984 if (AppearanceFlags&APP_DEATHTYPE) {
2985 snprintf(varname, 32, "KILL_%s", KillVar);
2986 game->kaputz->Lookup(varname, value);
2987 game->kaputz->SetAt(varname, value+1);
2989 } else {
2990 snprintf(varname, 32, core->GetDeathVarFormat(), scriptName);
2991 game->locals->Lookup(varname, value);
2992 game->locals->SetAt(varname, value+1);
2995 if (SetDeathVar) {
2996 value = 0;
2997 snprintf(varname, 32, "%s_DEAD", scriptName);
2998 game->locals->Lookup(varname, value);
2999 game->locals->SetAt(varname, 1);
3000 if (value) {
3001 snprintf(varname, 32, "%s_KILL_CNT", scriptName);
3002 value = 1;
3003 game->locals->Lookup(varname, value);
3004 game->locals->SetAt(varname, value + 1);
3009 if (IncKillCount) {
3010 // racial dead count
3011 value = 0;
3012 int racetable = core->LoadSymbol("race");
3013 if (racetable != -1) {
3014 SymbolMgr *race = core->GetSymbol(racetable);
3015 const char *raceName = race->GetValue(Modified[IE_RACE]);
3016 if (raceName) {
3017 // todo: should probably not set this for humans in iwd?
3018 snprintf(varname, 32, "KILL_%s_CNT", raceName);
3019 game->locals->Lookup(varname, value);
3020 game->locals->SetAt(varname, value+1);
3025 //death counters for PST
3026 j=APP_GOOD;
3027 for(i=0;i<4;i++) {
3028 if (AppearanceFlags&j) {
3029 ieDword value = 0;
3030 game->locals->Lookup(CounterNames[i], value);
3031 game->locals->SetAt(CounterNames[i], value+DeathCounters[i]);
3033 j+=j;
3036 // EXTRACOUNT is updated at the moment of death
3037 if (Modified[IE_SEX] == SEX_EXTRA || (Modified[IE_SEX] >= SEX_EXTRA2 && Modified[IE_SEX] <= SEX_MAXEXTRA)) {
3038 // if gender is set to one of the EXTRA values, then at death, we have to decrease
3039 // the relevant EXTRACOUNT area variable. scripts use this to check how many actors
3040 // of this extra id are still alive (for example, see the ToB challenge scripts)
3041 ieVariable varname;
3042 if (Modified[IE_SEX] == SEX_EXTRA) {
3043 snprintf(varname, 32, "EXTRACOUNT");
3044 } else {
3045 snprintf(varname, 32, "EXTRACOUNT%d", 2 + (Modified[IE_SEX] - SEX_EXTRA2));
3048 Map *area = GetCurrentArea();
3049 if (area) {
3050 ieDword value = 0;
3051 area->locals->Lookup(varname, value);
3052 // i am guessing that we shouldn't decrease below 0
3053 if (value > 0) {
3054 area->locals->SetAt(varname, value-1);
3059 //a plot critical creature has died (iwd2)
3060 if (BaseStats[IE_MC_FLAGS]&MC_PLOT_CRITICAL) {
3061 core->GetGUIScriptEngine()->RunFunction("DeathWindowPlot", false);
3063 //ensure that the scripts of the actor will run as soon as possible
3064 ImmediateEvent();
3067 void Actor::SetPersistent(int partyslot)
3069 InParty = (ieByte) partyslot;
3070 InternalFlags|=IF_FROMGAME;
3071 //if an actor is coming from a game, it should have these too
3072 CreateStats();
3075 void Actor::DestroySelf()
3077 InternalFlags|=IF_CLEANUP;
3078 // clear search map so that a new actor can immediately go there
3079 // (via ChangeAnimationCore)
3080 if (area)
3081 area->ClearSearchMapFor(this);
3084 bool Actor::CheckOnDeath()
3086 if (InternalFlags&IF_CLEANUP) {
3087 return true;
3089 if (InternalFlags&IF_JUSTDIED) {
3090 if (lastRunTime == 0 || CurrentAction || GetNextAction()) {
3091 return false; //actor is currently dying, let him die first
3094 if (!(InternalFlags&IF_REALLYDIED) ) {
3095 return false;
3097 //don't mess with the already deceased
3098 if (BaseStats[IE_STATE_ID]&STATE_DEAD) {
3099 return false;
3101 // don't destroy actors currently in a dialog
3102 GameControl *gc = core->GetGameControl();
3103 if (gc && (globalID == gc->targetID || globalID == gc->speakerID)) {
3104 return false;
3107 //we need to check animID here, if it has not played the death
3108 //sequence yet, then we could return now
3109 ClearActions();
3110 //missed the opportunity of Died()
3111 InternalFlags&=~IF_JUSTDIED;
3113 // items seem to be dropped at the moment of death
3114 // .. but this can't go in Die() because that is called
3115 // from effects and dropping items might change effects!
3116 DropItem("",0);
3118 //remove all effects that are not 'permanent after death' here
3119 //permanent after death type is 9
3120 SetBaseBit(IE_STATE_ID, STATE_DEAD, true);
3122 // party actors are never removed
3123 if (InParty) return false;
3125 if (Modified[IE_MC_FLAGS]&MC_REMOVE_CORPSE) return true;
3126 if (Modified[IE_MC_FLAGS]&MC_KEEP_CORPSE) return false;
3127 //if chunked death, then return true
3128 if (LastDamageType&DAMAGE_CHUNKING) {
3129 //play chunky animation
3130 //chunks are projectiles
3131 return true;
3133 return false;
3136 /* this will create a heap at location, and transfer the item(s) */
3137 void Actor::DropItem(const ieResRef resref, unsigned int flags)
3139 if (inventory.DropItemAtLocation( resref, flags, area, Pos )) {
3140 ReinitQuickSlots();
3144 void Actor::DropItem(int slot , unsigned int flags)
3146 if (inventory.DropItemAtLocation( slot, flags, area, Pos )) {
3147 ReinitQuickSlots();
3151 /** returns quick item data */
3152 /** if header==-1 which is a 'use quickitem' action */
3153 /** if header is set, then which is the absolute slot index, */
3154 /** and header is the header index */
3155 void Actor::GetItemSlotInfo(ItemExtHeader *item, int which, int header)
3157 ieWord idx;
3158 ieWord headerindex;
3160 memset(item, 0, sizeof(ItemExtHeader) );
3161 if (header<0) {
3162 if (!PCStats) return; //not a player character
3163 PCStats->GetSlotAndIndex(which,idx,headerindex);
3164 if (headerindex==0xffff) return; //headerindex is invalid
3165 } else {
3166 idx=(ieWord) which;
3167 headerindex=(ieWord) header;
3169 const CREItem *slot = inventory.GetSlotItem(idx);
3170 if (!slot) return; //quick item slot is empty
3171 Item *itm = gamedata->GetItem(slot->ItemResRef);
3172 if (!itm) return; //quick item slot contains invalid item resref
3173 ITMExtHeader *ext_header = itm->GetExtHeader(headerindex);
3174 //item has no extended header, or header index is wrong
3175 if (!ext_header) return;
3176 memcpy(item->itemname, slot->ItemResRef, sizeof(ieResRef) );
3177 item->slot = idx;
3178 item->headerindex = headerindex;
3179 memcpy(&(item->AttackType), &(ext_header->AttackType),
3180 ((char *) &(item->itemname)) -((char *) &(item->AttackType)) );
3181 if (headerindex>=CHARGE_COUNTERS) {
3182 item->Charges=0;
3183 } else {
3184 item->Charges=slot->Usages[headerindex];
3186 gamedata->FreeItem(itm,slot->ItemResRef, false);
3189 void Actor::ReinitQuickSlots()
3191 if (!PCStats) {
3192 return;
3195 // Note: (wjp, 20061226)
3196 // This function needs some rethinking.
3197 // It tries to satisfy two things at the moment:
3198 // Fill quickslots when they are empty and an item is placed in the
3199 // inventory slot corresponding to the quickslot
3200 // Reset quickslots when an item is removed
3201 // Currently, it resets all slots when items are removed,
3202 // but it only refills the ACT_QSLOTn slots, not the ACT_WEAPONx slots.
3204 // Refilling a weapon slot is possible, but essentially duplicates a lot
3205 // of code from Inventory::EquipItem() which performs the same steps for
3206 // the Inventory::Equipped slot.
3207 // Hopefully, weapons/arrows are never added to inventory slots without
3208 // EquipItem being called.
3210 int i=sizeof(PCStats->QSlots);
3211 while (i--) {
3212 int slot;
3213 int which;
3214 if (i<0) which = ACT_WEAPON4+i+1;
3215 else which = PCStats->QSlots[i];
3216 switch (which) {
3217 case ACT_WEAPON1:
3218 case ACT_WEAPON2:
3219 case ACT_WEAPON3:
3220 case ACT_WEAPON4:
3221 CheckWeaponQuickSlot(which);
3222 slot = 0;
3223 break;
3224 //WARNING:this cannot be condensed, because the symbols don't come in order!!!
3225 case ACT_QSLOT1: slot = inventory.GetQuickSlot(); break;
3226 case ACT_QSLOT2: slot = inventory.GetQuickSlot()+1; break;
3227 case ACT_QSLOT3: slot = inventory.GetQuickSlot()+2; break;
3228 case ACT_QSLOT4: slot = inventory.GetQuickSlot()+3; break;
3229 case ACT_QSLOT5: slot = inventory.GetQuickSlot()+4; break;
3230 default:
3231 slot = 0;
3233 if (!slot) continue;
3234 //if magic items are equipped the equipping info doesn't change
3235 //(afaik)
3237 // Note: we're now in the QSLOTn case
3238 // If slot is empty, reset quickslot to 0xffff/0xffff
3240 if (!inventory.HasItemInSlot("", slot)) {
3241 SetupQuickSlot(which, 0xffff, 0xffff);
3242 } else {
3243 ieWord idx;
3244 ieWord headerindex;
3245 PCStats->GetSlotAndIndex(which,idx,headerindex);
3246 if (idx != slot || headerindex == 0xffff) {
3247 // If slot just became filled, set it to filled
3248 SetupQuickSlot(which,slot,0);
3253 //these are always present
3254 CheckWeaponQuickSlot(0);
3255 CheckWeaponQuickSlot(1);
3256 //disabling quick weapon slots for certain classes
3257 for(i=0;i<2;i++) {
3258 int which = ACT_WEAPON3+i;
3259 // Assuming that ACT_WEAPON3 and 4 are always in the first two spots
3260 if (PCStats->QSlots[i]!=which) {
3261 SetupQuickSlot(which, 0xffff, 0xffff);
3266 void Actor::CheckWeaponQuickSlot(unsigned int which)
3268 if (!PCStats) return;
3270 bool empty = false;
3271 // If current quickweaponslot doesn't contain an item, reset it to fist
3272 int slot = PCStats->QuickWeaponSlots[which];
3273 int header = PCStats->QuickWeaponHeaders[which];
3274 if (!inventory.HasItemInSlot("", slot) || header == 0xffff) {
3275 //a quiver just went dry, falling back to fist
3276 empty = true;
3277 } else {
3278 // If current quickweaponslot contains ammo, and bow not found, reset
3280 if (core->QuerySlotEffects(slot) == SLOT_EFFECT_MISSILE) {
3281 const CREItem *slotitm = inventory.GetSlotItem(slot);
3282 assert(slotitm);
3283 Item *itm = gamedata->GetItem(slotitm->ItemResRef);
3284 assert(itm);
3285 ITMExtHeader *ext_header = itm->GetExtHeader(header);
3286 if (ext_header) {
3287 int type = ext_header->ProjectileQualifier;
3288 int weaponslot = inventory.FindTypedRangedWeapon(type);
3289 if (weaponslot == inventory.GetFistSlot()) {
3290 empty = true;
3292 } else {
3293 empty = true;
3295 gamedata->FreeItem(itm,slotitm->ItemResRef, false);
3299 if (empty)
3300 SetupQuickSlot(ACT_WEAPON1+which, inventory.GetFistSlot(), 0);
3304 void Actor::SetupQuickSlot(unsigned int which, int slot, int headerindex)
3306 if (!PCStats) return;
3307 PCStats->InitQuickSlot(which, slot, headerindex);
3308 //something changed about the quick items
3309 core->SetEventFlag(EF_ACTION);
3312 bool Actor::ValidTarget(int ga_flags) const
3314 if (Immobile()) return false;
3315 //scripts can still see this type of actor
3317 if (ga_flags&GA_NO_HIDDEN) {
3318 if (Modified[IE_AVATARREMOVAL]) return false;
3319 if (Modified[IE_EA]>EA_GOODCUTOFF && Modified[IE_STATE_ID]&STATE_INVISIBLE) return false;
3322 if (ga_flags&GA_NO_ALLY) {
3323 if(InParty) return false;
3324 if(Modified[IE_EA]<=EA_GOODCUTOFF) return false;
3327 if (ga_flags&GA_NO_ENEMY) {
3328 if(!InParty && (Modified[IE_EA]>=EA_EVILCUTOFF) ) return false;
3331 if (ga_flags&GA_NO_NEUTRAL) {
3332 if((Modified[IE_EA]>EA_GOODCUTOFF) && (Modified[IE_EA]<EA_EVILCUTOFF) ) return false;
3335 switch(ga_flags&GA_ACTION) {
3336 case GA_PICK:
3337 if (Modified[IE_STATE_ID] & STATE_CANTSTEAL) return false;
3338 break;
3339 case GA_TALK:
3340 //can't talk to dead
3341 if (Modified[IE_STATE_ID] & STATE_CANTLISTEN) return false;
3342 //can't talk to hostile
3343 if (Modified[IE_EA]>=EA_EVILCUTOFF) return false;
3344 break;
3346 if (ga_flags&GA_NO_DEAD) {
3347 if (InternalFlags&IF_JUSTDIED) return false;
3348 if (Modified[IE_STATE_ID] & STATE_DEAD) return false;
3350 if (ga_flags&GA_SELECT) {
3351 if (UnselectableTimer) return false;
3353 return true;
3356 //returns true if it won't be destroyed with an area
3357 //in this case it shouldn't be saved with the area either
3358 //it will be saved in the savegame
3359 bool Actor::Persistent() const
3361 if (InParty) return true;
3362 if (InternalFlags&IF_FROMGAME) return true;
3363 return false;
3366 //this is a reimplementation of cheatkey a/s of bg2
3367 //cycling through animation/stance
3368 // a - get next animation, s - get next stance
3370 void Actor::GetNextAnimation()
3372 int RowNum = anims->AvatarsRowNum - 1;
3373 if (RowNum<0)
3374 RowNum = CharAnimations::GetAvatarsCount() - 1;
3375 int NewAnimID = CharAnimations::GetAvatarStruct(RowNum)->AnimID;
3376 printf ("AnimID: %04X\n", NewAnimID);
3377 SetBase( IE_ANIMATION_ID, NewAnimID);
3378 //SetAnimationID ( NewAnimID );
3381 void Actor::GetPrevAnimation()
3383 int RowNum = anims->AvatarsRowNum + 1;
3384 if (RowNum>=CharAnimations::GetAvatarsCount() )
3385 RowNum = 0;
3386 int NewAnimID = CharAnimations::GetAvatarStruct(RowNum)->AnimID;
3387 printf ("AnimID: %04X\n", NewAnimID);
3388 SetBase( IE_ANIMATION_ID, NewAnimID);
3389 //SetAnimationID ( NewAnimID );
3392 //slot is the projectile slot
3393 //This will return the projectile item.
3394 ITMExtHeader *Actor::GetRangedWeapon(WeaponInfo &wi) const
3396 //EquippedSlot is the projectile. To get the weapon, use inventory.GetUsedWeapon()
3397 wi.slot = inventory.GetEquippedSlot();
3398 const CREItem *wield = inventory.GetSlotItem(wi.slot);
3399 if (!wield) {
3400 return NULL;
3402 Item *item = gamedata->GetItem(wield->ItemResRef);
3403 if (!item) {
3404 return NULL;
3406 //The magic of the bow and the arrow add up?
3407 wi.enchantment += item->Enchantment;
3408 wi.itemflags = wield->Flags;
3409 //wi.range is not set, the projectile has no effect on range?
3411 ITMExtHeader *which = item->GetWeaponHeader(true);
3412 gamedata->FreeItem(item, wield->ItemResRef, false);
3413 return which;
3416 int Actor::IsDualWielding() const
3418 int slot;
3419 //if the shield slot is a weapon, we're dual wielding
3420 const CREItem *wield = inventory.GetUsedWeapon(true, slot);
3421 if (!wield) {
3422 return 0;
3425 Item *itm = gamedata->GetItem( wield->ItemResRef );
3426 if (!itm) {
3427 return 0;
3430 //if the item is usable in weapon slot, then it is weapon
3431 int weapon = core->CanUseItemType( SLOT_WEAPON, itm );
3432 gamedata->FreeItem( itm, wield->ItemResRef, false );
3433 //is just weapon>0 ok?
3434 return (weapon>0)?1:0;
3437 //returns weapon header currently used (bow in case of bow+arrow)
3438 //if range is nonzero, then the returned header is valid
3439 ITMExtHeader *Actor::GetWeapon(WeaponInfo &wi, bool leftorright)
3441 //only use the shield slot if we are dual wielding
3442 leftorright = leftorright && IsDualWielding();
3444 const CREItem *wield = inventory.GetUsedWeapon(leftorright, wi.slot);
3445 if (!wield) {
3446 return 0;
3448 Item *item = gamedata->GetItem(wield->ItemResRef);
3449 if (!item) {
3450 return 0;
3453 wi.enchantment = item->Enchantment;
3454 wi.itemflags = wield->Flags;
3455 wi.prof = item->WeaProf;
3457 //select first weapon header
3458 ITMExtHeader *which;
3459 if (GetAttackStyle() == WEAPON_RANGED) {
3460 which = item->GetWeaponHeader(true);
3461 wi.backstabbing = false;
3462 } else {
3463 which = item->GetWeaponHeader(false);
3464 // any melee weapon usable by a single class thief is game (UAI does not affect this)
3465 wi.backstabbing = !(item->UsabilityBitmask & 0x400000);
3468 //make sure we use 'false' in this freeitem
3469 //so 'which' won't point into invalid memory
3470 gamedata->FreeItem(item, wield->ItemResRef, false);
3471 if (!which) {
3472 return 0;
3474 if (which->Location!=ITEM_LOC_WEAPON) {
3475 return 0;
3477 wi.range = which->Range+1;
3478 return which;
3479 //return which->Range+1;
3482 void Actor::GetNextStance()
3484 static int Stance = IE_ANI_AWAKE;
3486 if (--Stance < 0) Stance = MAX_ANIMS-1;
3487 printf ("StanceID: %d\n", Stance);
3488 SetStance( Stance );
3491 int Actor::LearnSpell(const ieResRef spellname, ieDword flags)
3493 if (spellbook.HaveSpell(spellname, 0) ) {
3494 return LSR_KNOWN;
3496 Spell *spell = gamedata->GetSpell(spellname);
3497 if (!spell) {
3498 return LSR_INVALID; //not existent spell
3501 if (flags & LS_STATS) {
3502 // chance to learn roll
3503 if (LuckyRoll(1,100,0) > core->GetIntelligenceBonus(0, GetStat(IE_INT))) {
3504 return LSR_FAILED;
3508 int explev = spellbook.LearnSpell(spell, flags&LS_MEMO);
3509 int tmp = spell->SpellName;
3510 if (flags&LS_LEARN) {
3511 core->GetTokenDictionary()->SetAt("SPECIALABILITYNAME", core->GetString(tmp));
3512 switch (spell->SpellType) {
3513 case IE_SPL_INNATE:
3514 tmp = STR_GOTABILITY;
3515 break;
3516 case IE_SPL_SONG:
3517 tmp = STR_GOTSONG;
3518 break;
3519 default:
3520 tmp = STR_GOTSPELL;
3521 break;
3523 } else tmp = 0;
3524 gamedata->FreeSpell(spell, spellname, false);
3525 if (!explev) {
3526 return LSR_INVALID;
3528 if (tmp) {
3529 core->DisplayConstantStringName(tmp, 0xbcefbc, this);
3531 if (flags&LS_ADDXP) {
3532 AddExperience(XP_LEARNSPELL, explev);
3534 return LSR_OK;
3537 const char *Actor::GetDialog(int flags) const
3539 if (!flags) {
3540 return Dialog;
3542 if (Modified[IE_EA]>=EA_EVILCUTOFF) {
3543 return NULL;
3546 if ( (InternalFlags & IF_NOINT) && CurrentAction) {
3547 if (flags>1) {
3548 core->DisplayConstantString(STR_TARGETBUSY,0xff0000);
3550 return NULL;
3552 return Dialog;
3555 void Actor::CreateStats()
3557 if (!PCStats) {
3558 PCStats = new PCStatsStruct();
3562 const char* Actor::GetScript(int ScriptIndex) const
3564 return Scripts[ScriptIndex]->GetName();
3567 void Actor::SetModal(ieDword newstate, bool force)
3569 switch(newstate) {
3570 case MS_NONE:
3571 break;
3572 case MS_BATTLESONG:
3573 break;
3574 case MS_DETECTTRAPS:
3575 break;
3576 case MS_STEALTH:
3577 break;
3578 case MS_TURNUNDEAD:
3579 break;
3580 default:
3581 return;
3584 if (InParty) {
3585 // display the turning-off message
3586 if (ModalState != MS_NONE) {
3587 core->DisplayStringName(core->ModalStates[ModalState].leaving_str, 0xffffff, this, IE_STR_SOUND|IE_STR_SPEECH);
3590 // when called with the same state twice, toggle to MS_NONE
3591 if (!force && ModalState == newstate) {
3592 ModalState = MS_NONE;
3593 } else {
3594 ModalState = newstate;
3597 //update the action bar
3598 core->SetEventFlag(EF_ACTION);
3599 } else {
3600 ModalState = newstate;
3604 //this is just a stub function for now, attackstyle could be melee/ranged
3605 //even spells got this attack style
3606 int Actor::GetAttackStyle()
3608 WeaponInfo wi;
3609 //Non NULL if the equipped slot is a projectile or a throwing weapon
3610 //TODO some weapons have both melee and ranged capability
3611 if (GetRangedWeapon(wi) != NULL) return WEAPON_RANGED;
3612 return WEAPON_MELEE;
3615 void Actor::SetTarget( Scriptable *target)
3617 if (target->Type==ST_ACTOR) {
3618 Actor *tar = (Actor *) target;
3619 LastTarget = tar->GetID();
3620 tar->LastAttacker = GetID();
3621 //we tell the game object that this creature
3622 //must be added to the list of combatants
3623 core->GetGame()->InAttack(tar->LastAttacker);
3625 SetOrientation( GetOrient( target->Pos, Pos ), false );
3628 //in case of LastTarget = 0
3629 void Actor::StopAttack()
3631 SetStance(IE_ANI_READY);
3632 core->GetGame()->OutAttack(GetID());
3633 InternalFlags|=IF_TARGETGONE; //this is for the trigger!
3634 if (InParty) {
3635 core->Autopause(AP_NOTARGET);
3639 int Actor::Immobile() const
3641 if (GetStat(IE_CASTERHOLD)) {
3642 return 1;
3644 if (GetStat(IE_HELD)) {
3645 return 1;
3647 return 0;
3650 //calculate how many attacks will be performed
3651 //in the next round
3652 //only called when Game thinks we are in attack
3653 //so it is safe to do cleanup here (it will be called only once)
3654 void Actor::InitRound(ieDword gameTime, bool secondround)
3656 lastInit = gameTime;
3658 //roundTime will equal 0 if we aren't attacking something
3659 if (roundTime) {
3660 //only perform calculations at the beginning of the round!
3661 if (((gameTime-roundTime)%ROUND_SIZE != 0) || \
3662 (roundTime == lastInit)) {
3663 return;
3667 //reset variables used in PerformAttack
3668 attackcount = 0;
3669 attacksperround = 0;
3670 nextattack = 0;
3671 lastattack = 0;
3673 //we set roundTime to zero on any of the following returns, because this
3674 //is guaranteed to be the start of a round, and we only want roundTime
3675 //if we are attacking this round
3676 if (InternalFlags&IF_STOPATTACK) {
3677 core->GetGame()->OutAttack(GetID());
3678 roundTime = 0;
3679 return;
3682 if (!LastTarget) {
3683 StopAttack();
3684 roundTime = 0;
3685 return;
3688 //if held or disabled, etc, then cannot continue attacking
3689 ieDword state = GetStat(IE_STATE_ID);
3690 if (state&STATE_CANTMOVE) {
3691 roundTime = 0;
3692 return;
3694 if (Immobile()) {
3695 roundTime = 0;
3696 return;
3699 //add one for second round to get an extra attack only if we
3700 //are x/2 attacks per round
3701 attackcount = GetStat(IE_NUMBEROFATTACKS);
3702 if (secondround) {
3703 attackcount++;
3705 //all numbers of attacks are stored at twice their value
3706 attackcount >>= 1;
3708 //make sure we always get at least 1apr
3709 if (attackcount < 1) attackcount = 1;
3711 //set our apr and starting round time
3712 attacksperround = attackcount;
3713 roundTime = gameTime;
3715 //print a little message :)
3716 printMessage("InitRound", " ", WHITE);
3717 printf("Name: %s | Attacks: %d | Start: %d\n", ShortName, attacksperround, gameTime);
3719 // this might not be the right place, but let's give it a go
3720 if (attacksperround && InParty) {
3721 core->Autopause(AP_ENDROUND);
3725 bool Actor::GetCombatDetails(int &tohit, bool leftorright, WeaponInfo& wi, ITMExtHeader *&header, ITMExtHeader *&hittingheader, \
3726 ieDword &Flags, int &DamageBonus, int &speed, int &CriticalBonus, int &style)
3728 tohit = GetStat(IE_TOHIT);
3729 speed = -GetStat(IE_PHYSICALSPEED);
3730 bool dualwielding = IsDualWielding();
3731 header = GetWeapon(wi, leftorright && dualwielding);
3732 if (!header) {
3733 return false;
3735 style = 0;
3736 CriticalBonus = 0;
3737 hittingheader = header;
3738 ITMExtHeader *rangedheader = NULL;
3739 int THAC0Bonus = hittingheader->THAC0Bonus;
3740 DamageBonus = hittingheader->DamageBonus;
3741 switch(hittingheader->AttackType) {
3742 case ITEM_AT_MELEE:
3743 Flags = WEAPON_MELEE;
3744 break;
3745 case ITEM_AT_PROJECTILE: //throwing weapon
3746 Flags = WEAPON_RANGED;
3747 break;
3748 case ITEM_AT_BOW:
3749 rangedheader = GetRangedWeapon(wi);
3750 if (!rangedheader) {
3751 //display out of ammo verbal constant if there is any???
3752 //DisplayStringCore(this, VB_OUTOFAMMO, DS_CONSOLE|DS_CONST );
3753 SetStance(IE_ANI_READY);
3754 //set some trigger?
3755 return false;
3757 Flags = WEAPON_RANGED;
3758 //The bow can give some bonuses, but the core attack is made by the arrow.
3759 hittingheader = rangedheader;
3760 THAC0Bonus += rangedheader->THAC0Bonus;
3761 DamageBonus += rangedheader->DamageBonus;
3762 break;
3763 default:
3764 //item is unsuitable for fight
3765 SetStance(IE_ANI_READY);
3766 return false;
3767 }//melee or ranged
3768 //this flag is set by the bow in case of projectile launcher.
3769 if (header->RechargeFlags&IE_ITEM_USESTRENGTH) Flags|=WEAPON_USESTRENGTH;
3771 // get our dual wielding modifier
3772 if (dualwielding) {
3773 if (leftorright) {
3774 DamageBonus += GetStat(IE_DAMAGEBONUSLEFT);
3775 } else {
3776 DamageBonus += GetStat(IE_DAMAGEBONUSRIGHT);
3779 leftorright = leftorright && dualwielding;
3780 if (leftorright) Flags|=WEAPON_LEFTHAND;
3782 //add in proficiency bonuses
3783 ieDword stars;
3784 if (wi.prof && (wi.prof <= MAX_STATS)) {
3785 stars = GetStat(wi.prof)&PROFS_MASK;
3787 //hit/damage/speed bonuses from wspecial
3788 if ((signed)stars > wspecial_max) {
3789 stars = wspecial_max;
3791 THAC0Bonus += wspecial[stars][0];
3792 DamageBonus += wspecial[stars][1];
3793 speed += wspecial[stars][2];
3794 // add non-proficiency penalty, which is missing from the table
3795 if (stars == 0) THAC0Bonus -= 4;
3798 if (IsDualWielding() && wsdualwield) {
3799 //add dual wielding penalty
3800 stars = GetStat(IE_PROFICIENCY2WEAPON)&PROFS_MASK;
3801 if (stars > STYLE_MAX) stars = STYLE_MAX;
3803 style = 1000*stars + IE_PROFICIENCY2WEAPON;
3804 THAC0Bonus += wsdualwield[stars][leftorright?1:0];
3805 } else if (wi.itemflags&(IE_INV_ITEM_TWOHANDED) && (Flags&WEAPON_MELEE) && wstwohanded) {
3806 //add two handed profs bonus
3807 stars = GetStat(IE_PROFICIENCY2HANDED)&PROFS_MASK;
3808 if (stars > STYLE_MAX) stars = STYLE_MAX;
3810 style = 1000*stars + IE_PROFICIENCY2HANDED;
3811 DamageBonus += wstwohanded[stars][0];
3812 CriticalBonus = wstwohanded[stars][1];
3813 speed += wstwohanded[stars][2];
3814 } else if (Flags&WEAPON_MELEE) {
3815 int slot;
3816 CREItem *weapon = inventory.GetUsedWeapon(true, slot);
3817 if(wssingle && weapon == NULL) {
3818 //NULL return from GetUsedWeapon means no shield slot
3819 stars = GetStat(IE_PROFICIENCYSINGLEWEAPON)&PROFS_MASK;
3820 if (stars > STYLE_MAX) stars = STYLE_MAX;
3822 style = 1000*stars + IE_PROFICIENCYSINGLEWEAPON;
3823 CriticalBonus = wssingle[stars][1];
3824 } else if (wsswordshield && weapon) {
3825 stars = GetStat(IE_PROFICIENCYSWORDANDSHIELD)&PROFS_MASK;
3826 if (stars > STYLE_MAX) stars = STYLE_MAX;
3828 style = 1000*stars + IE_PROFICIENCYSWORDANDSHIELD;
3829 } else {
3830 // no bonus
3832 } else {
3833 // ranged - no bonus
3836 // TODO: Elves get a racial THAC0 bonus with all swords and bows in BG2 (but not daggers)
3838 //second parameter is left or right hand flag
3839 tohit = GetToHit(THAC0Bonus, Flags);
3840 return true;
3843 int Actor::GetToHit(int bonus, ieDword Flags)
3845 int tohit = bonus;
3847 //get our dual wielding modifier
3848 if (IsDualWielding()) {
3849 if (Flags&WEAPON_LEFTHAND) {
3850 tohit += GetStat(IE_HITBONUSLEFT);
3851 } else {
3852 tohit += GetStat(IE_HITBONUSRIGHT);
3856 //get attack style (melee or ranged)
3857 switch(Flags&WEAPON_STYLEMASK) {
3858 case WEAPON_MELEE:
3859 tohit += GetStat(IE_MELEETOHIT);
3860 break;
3861 case WEAPON_FIST:
3862 tohit += GetStat(IE_FISTHIT);
3863 break;
3864 case WEAPON_RANGED:
3865 tohit += GetStat(IE_MISSILEHITBONUS);
3866 //add dexterity bonus
3867 tohit += core->GetDexterityBonus(STAT_DEX_MISSILE, GetStat(IE_DEX));
3868 break;
3871 //add strength bonus if we need
3872 if (Flags&WEAPON_USESTRENGTH) {
3873 tohit += core->GetStrengthBonus(0,GetStat(IE_STR), GetStat(IE_STREXTRA) );
3876 // if the target is using a ranged weapon while we're meleeing, we get a +4 bonus
3877 if ((Flags&WEAPON_STYLEMASK) != WEAPON_RANGED) {
3878 Actor *target = area->GetActorByGlobalID(LastTarget);
3879 if (target && target->GetAttackStyle() == WEAPON_RANGED) {
3880 tohit += 4;
3884 // add +4 attack bonus vs racial enemies
3885 if (GetRangerLevel()) {
3886 Actor *target = area->GetActorByGlobalID(LastTarget);
3887 if (target && IsRacialEnemy(target)) {
3888 tohit += 4;
3892 if (ReverseToHit) {
3893 tohit = (signed)GetStat(IE_TOHIT)-tohit;
3894 } else {
3895 tohit += GetStat(IE_TOHIT);
3897 return tohit;
3900 static const int weapon_damagetype[] = {DAMAGE_CRUSHING, DAMAGE_PIERCING,
3901 DAMAGE_CRUSHING, DAMAGE_SLASHING, DAMAGE_MISSILE, DAMAGE_STUNNING};
3903 int Actor::GetDefense(int DamageType)
3905 //specific damage type bonus.
3906 int defense = 0;
3907 if(DamageType > 5)
3908 DamageType = 0;
3909 switch (weapon_damagetype[DamageType]) {
3910 case DAMAGE_CRUSHING:
3911 defense += GetStat(IE_ACCRUSHINGMOD);
3912 break;
3913 case DAMAGE_PIERCING:
3914 defense += GetStat(IE_ACPIERCINGMOD);
3915 break;
3916 case DAMAGE_SLASHING:
3917 defense += GetStat(IE_ACSLASHINGMOD);
3918 break;
3919 case DAMAGE_MISSILE:
3920 defense += GetStat(IE_ACMISSILEMOD);
3921 break;
3922 //What about stunning ?
3923 default :
3924 break;
3927 //check for s/s and single weapon ac bonuses
3928 if (!IsDualWielding() && wssingle && wsswordshield) {
3929 WeaponInfo wi;
3930 ITMExtHeader* header;
3931 header = GetWeapon(wi, false);
3932 //make sure we're wielding a single melee weapon
3933 if (header && (header->AttackType == ITEM_AT_MELEE)) {
3934 int slot;
3935 ieDword stars;
3936 if (inventory.GetUsedWeapon(true, slot) == NULL) {
3937 //single-weapon style applies to all ac
3938 stars = GetStat(IE_PROFICIENCYSINGLEWEAPON)&PROFS_MASK;
3939 if (stars>STYLE_MAX) stars = STYLE_MAX;
3940 defense += wssingle[stars][0];
3941 } else if (weapon_damagetype[DamageType] == DAMAGE_MISSILE) {
3942 //sword-shield style applies only to missile ac
3943 stars = GetStat(IE_PROFICIENCYSWORDANDSHIELD)&PROFS_MASK;
3944 if (stars>STYLE_MAX) stars = STYLE_MAX;
3945 defense += wsswordshield[stars][0];
3950 if (ReverseToHit) {
3951 defense = GetStat(IE_ARMORCLASS)-defense;
3952 } else {
3953 defense += GetStat(IE_ARMORCLASS);
3955 //Dexterity bonus is stored negative in 2da files.
3956 return defense + core->GetDexterityBonus(STAT_DEX_AC, GetStat(IE_DEX) );
3959 void Actor::PerformAttack(ieDword gameTime)
3961 // start a new round if we really don't have one yet
3962 if (!roundTime) {
3963 InitRound(gameTime, false);
3966 //only return if we don't have any attacks left this round
3967 if (attackcount==0) return;
3969 // this check shouldn't be necessary, but it causes a divide-by-zero below,
3970 // so i would like it to be clear if it ever happens
3971 if (attacksperround==0) {
3972 printMessage("Actor", "APR was 0 in PerformAttack!\n", RED);
3973 return;
3976 //don't continue if we can't make the attack yet
3977 //we check lastattack because we will get the same gameTime a few times
3978 if ((nextattack > gameTime) || (gameTime == lastattack)) {
3979 // fuzzie added the following line as part of the UpdateActorState hack below
3980 lastattack = gameTime;
3981 return;
3984 if (InternalFlags&IF_STOPATTACK) {
3985 // this should be avoided by the AF_ALIVE check by all the calling actions
3986 printMessage("Actor", "Attack by dead actor!\n", LIGHT_RED);
3987 return;
3990 if (!LastTarget) {
3991 printMessage("Actor", "Attack without valid target ID!\n", LIGHT_RED);
3992 return;
3994 //get target
3995 Actor *target = area->GetActorByGlobalID(LastTarget);
3997 if (target && (target->GetStat(IE_STATE_ID)&STATE_DEAD)) {
3998 target = NULL;
4001 if (!target) {
4002 printMessage("Actor", "Attack without valid target!\n", LIGHT_RED);
4003 return;
4006 printf("Performattack for %s, target is: %s\n", ShortName, target->ShortName);
4008 //which hand is used
4009 //we do apr - attacksleft so we always use the main hand first
4010 bool leftorright = (bool) ((attacksperround-attackcount)&1);
4012 WeaponInfo wi;
4013 ITMExtHeader *header = NULL;
4014 ITMExtHeader *hittingheader = NULL;
4015 int tohit;
4016 ieDword Flags;
4017 int DamageBonus, CriticalBonus;
4018 int speed, style;
4020 //will return false on any errors (eg, unusable weapon)
4021 if (!GetCombatDetails(tohit, leftorright, wi, header, hittingheader, Flags, DamageBonus, speed, CriticalBonus, style)) {
4022 return;
4025 //if this is the first call of the round, we need to update next attack
4026 if (nextattack == 0) {
4027 //FIXME: figure out exactly how initiative is calculated
4028 int initiative = core->Roll(1, 5, GetXPLevel(true)/(-8));
4029 int spdfactor = hittingheader->Speed + speed + initiative;
4030 if (spdfactor<0) spdfactor = 0;
4031 if (spdfactor>10) spdfactor = 10;
4033 //(round_size/attacks_per_round)*(initiative) is the first delta
4034 nextattack = ROUND_SIZE*spdfactor/(attacksperround*10) + gameTime;
4036 //we can still attack this round if we have a speed factor of 0
4037 if (nextattack > gameTime) {
4038 return;
4042 if((PersonalDistance(this, target) > wi.range*10) || (GetCurrentArea()!=target->GetCurrentArea() ) ) {
4043 // this is a temporary double-check, remove when bugfixed
4044 printMessage("Actor", "Attack action didn't bring us close enough!", LIGHT_RED);
4045 return;
4048 SetStance(AttackStance);
4050 //figure out the time for our next attack since the old time has the initiative
4051 //in it, we only have to add the basic delta
4052 attackcount--;
4053 nextattack += (ROUND_SIZE/attacksperround);
4054 lastattack = gameTime;
4056 //debug messages
4057 if (leftorright && IsDualWielding()) {
4058 printMessage("Attack","(Off) ", YELLOW);
4059 } else {
4060 printMessage("Attack","(Main) ", GREEN);
4062 if (attacksperround) {
4063 printf("Left: %d | ", attackcount);
4064 printf("Next: %d ", nextattack);
4067 int roll = LuckyRoll(1, ATTACKROLL, 0);
4068 if (roll==1) {
4069 //critical failure
4070 printBracket("Critical Miss", RED);
4071 printf("\n");
4072 core->DisplayConstantStringName(STR_CRITICAL_MISS, 0xffffff, this);
4073 DisplayStringCore(this, VB_CRITMISS, DS_CONSOLE|DS_CONST );
4074 if (Flags&WEAPON_RANGED) {//no need for this with melee weapon!
4075 UseItem(wi.slot, (ieDword)-2, target, UI_MISS);
4076 } else if (core->HasFeature(GF_BREAKABLE_WEAPONS)) {
4077 //break sword
4078 //TODO: this appears to be a random roll on-hit (perhaps critical failure
4079 // too); we use 1% (1d20*1d5==1)
4080 if ((header->RechargeFlags&IE_ITEM_BREAKABLE) && core->Roll(1,5,0) == 1) {
4081 inventory.BreakItemSlot(wi.slot);
4084 ResetState();
4085 return;
4087 //damage type is?
4088 //modify defense with damage type
4089 ieDword damagetype = hittingheader->DamageType;
4090 int damage = 0;
4091 int resisted = 0;
4093 if (hittingheader->DiceThrown<256) {
4094 damage += LuckyRoll(hittingheader->DiceThrown, hittingheader->DiceSides, 0, 1, 0);
4095 damage += DamageBonus;
4096 printf("| Damage %dd%d%+d = %d ",hittingheader->DiceThrown, hittingheader->DiceSides, DamageBonus, damage);
4097 } else {
4098 printf("| No Damage");
4099 damage = 0;
4102 if (roll >= (ATTACKROLL - (int) GetStat(IE_CRITICALHITBONUS) - CriticalBonus)) {
4103 //critical success
4104 printBracket("Critical Hit", GREEN);
4105 printf("\n");
4106 core->DisplayConstantStringName(STR_CRITICAL_HIT, 0xffffff, this);
4107 DisplayStringCore(this, VB_CRITHIT, DS_CONSOLE|DS_CONST );
4108 ModifyDamage (target, this, damage, resisted, weapon_damagetype[damagetype], &wi, true);
4109 UseItem(wi.slot, Flags&WEAPON_RANGED?-2:-1, target, 0, damage);
4110 ResetState();
4112 return;
4116 //get target's defense against attack
4117 int defense = target->GetDefense(damagetype);
4119 bool success;
4120 if(ReverseToHit) {
4121 success = roll > tohit - defense;
4122 } else {
4123 success = tohit + roll > defense;
4126 if (!success) {
4127 //hit failed
4128 if (Flags&WEAPON_RANGED) {//Launch the projectile anyway
4129 UseItem(wi.slot, (ieDword)-2, target, UI_MISS);
4131 ResetState();
4132 printBracket("Missed", LIGHT_RED);
4133 printf("\n");
4134 return;
4136 printBracket("Hit", GREEN);
4137 printf("\n");
4138 ModifyDamage (target, this, damage, resisted, weapon_damagetype[damagetype], &wi, false);
4139 UseItem(wi.slot, Flags&WEAPON_RANGED?-2:-1, target, 0, damage);
4140 ResetState();
4143 static EffectRef fx_stoneskin_ref={"StoneSkinModifier",NULL,-1};
4144 static EffectRef fx_stoneskin2_ref={"StoneSkin2Modifier",NULL,-1};
4145 static EffectRef fx_mirrorimage_ref={"MirrorImageModifier",NULL,-1};
4146 static EffectRef fx_aegis_ref={"Aegis",NULL,-1};
4148 void Actor::ModifyDamage(Actor *target, Actor *hitter, int &damage, int &resisted, int damagetype, WeaponInfo *wi, bool critical)
4151 int mirrorimages = target->Modified[IE_MIRRORIMAGES];
4152 if (mirrorimages) {
4153 if (LuckyRoll(1,mirrorimages+1,0) != 1) {
4154 target->fxqueue.DecreaseParam1OfEffect(fx_mirrorimage_ref, 1);
4155 target->Modified[IE_MIRRORIMAGES]--;
4156 damage = 0;
4157 return;
4161 // only check stone skins if damage type is physical or magical
4162 // DAMAGE_CRUSHING is 0, so we can't AND with it to check for its presence
4163 if (!(damagetype & ~(DAMAGE_PIERCING|DAMAGE_SLASHING|DAMAGE_MISSILE|DAMAGE_MAGIC))) {
4164 int stoneskins = target->Modified[IE_STONESKINS];
4165 if (stoneskins) {
4166 target->fxqueue.DecreaseParam1OfEffect(fx_stoneskin_ref, 1);
4167 target->fxqueue.DecreaseParam1OfEffect(fx_aegis_ref, 1);
4168 target->Modified[IE_STONESKINS]--;
4169 damage = 0;
4170 return;
4173 stoneskins = target->Modified[IE_STONESKINSGOLEM];
4174 if (stoneskins) {
4175 target->fxqueue.DecreaseParam1OfEffect(fx_stoneskin2_ref, 1);
4176 target->Modified[IE_STONESKINSGOLEM]--;
4177 damage = 0;
4178 return;
4182 if (wi) {
4183 if (BaseStats[IE_BACKSTABDAMAGEMULTIPLIER] > 1) {
4184 if (Modified[IE_STATE_ID] & (ieDword) (STATE_INVISIBLE) || Modified[IE_ALWAYSBACKSTAB]) {
4185 if ( !(core->HasFeature(GF_PROPER_BACKSTAB) && !IsBehind(target)) ) {
4186 if (target->Modified[IE_DISABLEBACKSTAB]) {
4187 // The backstab seems to have failed
4188 core->DisplayConstantString (STR_BACKSTAB_FAIL, 0xffffff);
4189 } else {
4190 if (wi->backstabbing) {
4191 damage *= Modified[IE_BACKSTABDAMAGEMULTIPLIER];
4192 // display a simple message instead of hardcoding multiplier names
4193 core->DisplayConstantStringValue (STR_BACKSTAB, 0xffffff, Modified[IE_BACKSTABDAMAGEMULTIPLIER]);
4194 } else {
4195 // weapon is unsuitable for backstab
4196 core->DisplayConstantString (STR_BACKSTAB_BAD, 0xffffff);
4203 // add strength bonus; backstab does not affect it
4204 // TODO: should actually check WEAPON_USESTRENGTH, since a sling in bg2 has it
4205 if (GetAttackStyle() != WEAPON_RANGED) {
4206 damage += core->GetStrengthBonus(1, GetStat(IE_STR), GetStat(IE_STREXTRA) );
4210 if (wi && target->fxqueue.WeaponImmunity(wi->enchantment, wi->itemflags)) {
4211 damage = 0;
4212 resisted = DR_IMMUNE; // mark immunity for GetCombatDetails
4213 } else {
4214 // check damage type immunity / resistance / susceptibility
4215 std::multimap<ieDword, DamageInfoStruct>::iterator it;
4216 it = core->DamageInfoMap.find(damagetype);
4217 if (it == core->DamageInfoMap.end()) {
4218 printf("Unhandled damagetype:%d\n", damagetype);
4219 } else if (it->second.resist_stat == 0) {
4220 // damage type without a resistance stat
4221 } else {
4222 damage += (signed)target->GetStat(IE_DAMAGEBONUS);
4223 resisted = (int) (damage * (signed)target->GetStat(it->second.resist_stat)/100.0);
4224 // check for bonuses for specific damage types
4225 if (core->HasFeature(GF_SPECIFIC_DMG_BONUS) && hitter) {
4226 int bonus = hitter->fxqueue.SpecificDamageBonus(it->second.iwd_mod_type);
4227 if (bonus) {
4228 resisted -= int (damage * bonus / 100.0);
4229 printf("Bonus damage of %d (%+d%%), neto: %d\n", int (damage * bonus / 100.0), bonus, -resisted);
4232 damage -= resisted;
4233 printf("Resisted %d of %d at %d%% resistance to %d\n", resisted, damage+resisted, target->GetStat(it->second.resist_stat), damagetype);
4234 if (damage <= 0) resisted = DR_IMMUNE;
4238 //check casting failure
4239 if (damage<0) damage = 0;
4240 if (!damage) {
4241 DisplayStringCore(this, VB_TIMMUNE, DS_CONSOLE|DS_CONST );
4242 return;
4245 if (critical) {
4246 //a critical surely raises the morale?
4247 NewBase(IE_MORALE, 1, MOD_ADDITIVE);
4248 int head = inventory.GetHeadSlot();
4249 if ((head!=-1) && target->inventory.HasItemInSlot("",(ieDword) head)) {
4250 //critical hit is averted by helmet
4251 core->DisplayConstantStringName(STR_NO_CRITICAL, 0xffffff, target);
4252 } else {
4253 damage <<=1; //critical damage is always double?
4254 core->timer->SetScreenShake(16,16,8);
4257 return;
4260 void Actor::UpdateActorState(ieDword gameTime) {
4261 //apply the modal effect on the beginning of each round
4262 if (((gameTime-roundTime)%ROUND_SIZE==0) && ModalState) {
4263 if (!ModalSpell[0]) {
4264 printMessage("Actor","Modal Spell Effect was not set!\n", YELLOW);
4265 ModalSpell[0]='*';
4266 } else if(ModalSpell[0]!='*') {
4267 if (ModalSpellSkillCheck()) {
4268 core->ApplySpell(ModalSpell, this, this, 0);
4269 if (InParty) {
4270 core->DisplayStringName(core->ModalStates[ModalState].entering_str, 0xffffff, this, IE_STR_SOUND|IE_STR_SPEECH);
4272 } else {
4273 if (InParty) {
4274 core->DisplayStringName(core->ModalStates[ModalState].failed_str, 0xffffff, this, IE_STR_SOUND|IE_STR_SPEECH);
4276 ModalState = MS_NONE;
4277 // TODO: wait for a round until allowing new states?
4282 // this is a HACK, fuzzie can't work out where else to do this for now
4283 // but we shouldn't be resetting rounds/attacks just because the actor
4284 // wandered away, the action code should probably be responsible somehow
4285 // see also line above (search for comment containing UpdateActorState)!
4286 if (LastTarget && lastattack && lastattack < (gameTime - 1)) {
4287 Actor *target = area->GetActorByGlobalID(LastTarget);
4288 if (!target || target->GetStat(IE_STATE_ID)&STATE_DEAD) {
4289 StopAttack();
4290 } else {
4291 printMessage("Attack","(Leaving attack)", GREEN);
4292 core->GetGame()->OutAttack(GetID());
4295 roundTime = 0;
4296 lastattack = 0;
4300 //idx could be: 0-6, 16-22, 32-38, 48-54
4301 //the colors are stored in 7 dwords
4302 //maybe it would be simpler to store them in 28 bytes (without using stats?)
4303 void Actor::SetColor( ieDword idx, ieDword grd)
4305 ieByte gradient = (ieByte) (grd&255);
4306 ieByte index = (ieByte) (idx&15);
4307 ieByte shift = (ieByte) (idx/16);
4308 ieDword value;
4310 //invalid value, would crash original IE
4311 if (index>6) {
4312 return;
4314 if (shift == 15) {
4315 // put gradient in all four bytes of value
4316 value = gradient;
4317 value |= (value << 8);
4318 value |= (value << 16);
4319 for (index=0;index<7;index++) {
4320 Modified[IE_COLORS+index] = value;
4322 } else {
4323 //invalid value, would crash original IE
4324 if (shift>3) {
4325 return;
4327 shift *= 8;
4328 value = gradient << shift;
4329 value |= Modified[IE_COLORS+index] & ~(255<<shift);
4330 Modified[IE_COLORS+index] = value;
4334 void Actor::SetColorMod( ieDword location, RGBModifier::Type type, int speed,
4335 unsigned char r, unsigned char g, unsigned char b,
4336 int phase)
4338 CharAnimations* ca = GetAnims();
4339 if (!ca) return;
4341 if (location == 0xff) {
4342 ca->GlobalColorMod.type = type;
4343 ca->GlobalColorMod.speed = speed;
4344 ca->GlobalColorMod.rgb.r = r;
4345 ca->GlobalColorMod.rgb.g = g;
4346 ca->GlobalColorMod.rgb.b = b;
4347 ca->GlobalColorMod.rgb.a = 0;
4348 if (phase >= 0)
4349 ca->GlobalColorMod.phase = phase;
4350 else {
4351 if (ca->GlobalColorMod.phase > 2*speed)
4352 ca->GlobalColorMod.phase=0;
4354 return;
4356 //00xx0yyy-->000xxyyy
4357 if (location&0xffffffc8) return; //invalid location
4358 location = (location &7) | ((location>>1)&0x18);
4359 ca->ColorMods[location].type = type;
4360 ca->ColorMods[location].speed = speed;
4361 ca->ColorMods[location].rgb.r = r;
4362 ca->ColorMods[location].rgb.g = g;
4363 ca->ColorMods[location].rgb.b = b;
4364 ca->ColorMods[location].rgb.a = 0;
4365 if (phase >= 0)
4366 ca->ColorMods[location].phase = phase;
4367 else {
4368 if (ca->ColorMods[location].phase > 2*speed)
4369 ca->ColorMods[location].phase = 0;
4373 void Actor::SetLeader(Actor *actor, int xoffset, int yoffset)
4375 LastFollowed = actor->GetID();
4376 FollowOffset.x = xoffset;
4377 FollowOffset.y = yoffset;
4380 //if days == 0, it means full healing
4381 void Actor::Heal(int days)
4383 if (days) {
4384 SetBase(IE_HITPOINTS, BaseStats[IE_HITPOINTS]+days*2);
4385 } else {
4386 SetBase(IE_HITPOINTS, BaseStats[IE_MAXHITPOINTS]);
4390 void Actor::AddExperience(int exp)
4392 SetBase(IE_XP,BaseStats[IE_XP]+exp);
4395 void Actor::AddExperience(int type, int level)
4397 if (type>=xpbonustypes) {
4398 return;
4400 unsigned int l = (unsigned int) (level - 1);
4402 if (l>=(unsigned int) xpbonuslevels) {
4403 l=xpbonuslevels-1;
4405 int xp = xpbonus[type*xpbonuslevels+l];
4406 core->DisplayConstantStringValue(STR_GOTXP, 0xbcefbc, (ieDword) xp);
4407 AddExperience(xp);
4410 bool Actor::Schedule(ieDword gametime, bool checkhide)
4412 if (checkhide) {
4413 if (!(InternalFlags&IF_VISIBLE) ) {
4414 return false;
4418 //check for schedule
4419 ieDword bit = 1<<((gametime/ROUND_SIZE)%7200/300);
4420 if (appearance & bit) {
4421 return true;
4423 return false;
4426 void Actor::NewPath()
4428 PathTries++;
4429 Point tmp = Destination;
4430 ClearPath();
4431 if (PathTries>10) {
4432 return;
4434 Movable::WalkTo(tmp, size );
4437 void Actor::SetInTrap(ieDword setreset)
4439 InTrap = setreset;
4440 if (setreset) {
4441 InternalFlags |= IF_INTRAP;
4442 } else {
4443 InternalFlags &= ~IF_INTRAP;
4447 void Actor::SetRunFlags(ieDword flags)
4449 InternalFlags &= ~IF_RUNFLAGS;
4450 InternalFlags |= (flags & IF_RUNFLAGS);
4453 void Actor::WalkTo(Point &Des, ieDword flags, int MinDistance)
4455 PathTries = 0;
4456 if (InternalFlags&IF_REALLYDIED) {
4457 return;
4459 SetRunFlags(flags);
4460 // is this true???
4461 if (Des.x==-2 && Des.y==-2) {
4462 Point p((ieWord) Modified[IE_SAVEDXPOS], (ieWord) Modified[IE_SAVEDYPOS] );
4463 Movable::WalkTo(p, MinDistance);
4464 } else {
4465 Movable::WalkTo(Des, MinDistance);
4469 //there is a similar function in Map for stationary vvcs
4470 void Actor::DrawVideocells(Region &screen, vvcVector &vvcCells, Color &tint)
4472 Map* area = GetCurrentArea();
4474 for (unsigned int i = 0; i < vvcCells.size(); i++) {
4475 ScriptedAnimation* vvc = vvcCells[i];
4476 /* we don't allow holes anymore
4477 if (!vvc)
4478 continue;
4481 // actually this is better be drawn by the vvc
4482 bool endReached = vvc->Draw(screen, Pos, tint, area, WantDither(), GetOrientation());
4483 if (endReached) {
4484 delete vvc;
4485 vvcCells.erase(vvcCells.begin()+i);
4486 continue;
4491 void Actor::DrawActorSprite(Region &screen, int cx, int cy, Region& bbox,
4492 SpriteCover*& newsc, Animation** anims,
4493 unsigned char Face, Color& tint)
4495 CharAnimations* ca = GetAnims();
4496 int PartCount = ca->GetTotalPartCount();
4497 Video* video = core->GetVideoDriver();
4498 Region vp = video->GetViewport();
4500 // display current frames in the right order
4501 const int* zOrder = ca->GetZOrder(Face);
4502 for (int part = 0; part < PartCount; ++part) {
4503 int partnum = part;
4504 if (zOrder) partnum = zOrder[part];
4505 Animation* anim = anims[partnum];
4506 Sprite2D* nextFrame = 0;
4507 if (anim)
4508 nextFrame = anim->GetFrame(anim->GetCurrentFrame());
4509 if (nextFrame && bbox.InsideRegion( vp ) ) {
4510 if (!newsc || !newsc->Covers(cx, cy, nextFrame->XPos, nextFrame->YPos, nextFrame->Width, nextFrame->Height)) {
4511 // the first anim contains the animarea for
4512 // the entire multi-part animation
4513 newsc = area->BuildSpriteCover(cx,
4514 cy, -anims[0]->animArea.x,
4515 -anims[0]->animArea.y,
4516 anims[0]->animArea.w,
4517 anims[0]->animArea.h, WantDither() );
4519 assert(newsc->Covers(cx, cy, nextFrame->XPos, nextFrame->YPos, nextFrame->Width, nextFrame->Height));
4521 unsigned int flags = TranslucentShadows ? BLIT_TRANSSHADOW : 0;
4522 if (!ca->lockPalette) flags|=BLIT_TINTED;
4524 video->BlitGameSprite( nextFrame, cx + screen.x, cy + screen.y,
4525 flags, tint, newsc, ca->GetPartPalette(partnum), &screen);
4531 static const int OrientdX[16] = { 0, -4, -7, -9, -10, -9, -7, -4, 0, 4, 7, 9, 10, 9, 7, 4 };
4532 static const int OrientdY[16] = { 10, 9, 7, 4, 0, -4, -7, -9, -10, -9, -7, -4, 0, 4, 7, 9 };
4533 static const unsigned int MirrorImageLocation[8] = { 4, 12, 8, 0, 6, 14, 10, 2 };
4534 static const unsigned int MirrorImageZOrder[8] = { 2, 4, 6, 0, 1, 7, 5, 3 };
4536 bool Actor::ShouldHibernate() {
4537 //finding an excuse why we don't hybernate the actor
4538 if (Modified[IE_ENABLEOFFSCREENAI])
4539 return false;
4540 if (LastTarget) //currently attacking someone
4541 return false;
4542 if (!lastRunTime) // haven't had a chance to run a script
4543 return false;
4544 if (CurrentAction)
4545 return false;
4546 if (GetNextStep())
4547 return false;
4548 if (GetNextAction())
4549 return false;
4550 if (GetWait()) //would never stop waiting
4551 return false;
4552 return true;
4555 void Actor::Draw(Region &screen)
4557 Map* area = GetCurrentArea();
4559 int cx = Pos.x;
4560 int cy = Pos.y;
4561 int explored = Modified[IE_DONOTJUMP]&DNJ_UNHINDERED;
4562 //check the deactivation condition only if needed
4563 //this fixes dead actors disappearing from fog of war (they should be permanently visible)
4564 if ((!area->IsVisible( Pos, explored) || (InternalFlags&IF_REALLYDIED) ) && (InternalFlags&IF_ACTIVE) ) {
4565 //turning actor inactive if there is no action next turn
4566 if (ShouldHibernate()) {
4567 InternalFlags|=IF_IDLE;
4569 if (!(InternalFlags&IF_REALLYDIED)) {
4570 // for a while this didn't return (disable drawing) if about to hibernate;
4571 // Avenger said (aa10aaed) "we draw the actor now for the last time".
4572 return;
4576 if (InTrap) {
4577 area->ClearTrap(this, InTrap-1);
4580 // if an actor isn't visible, should we still handle animations, draw
4581 // video cells, etc? let us assume not, for now..
4582 if (!(InternalFlags & IF_VISIBLE)) {
4583 return;
4586 //visual feedback
4587 CharAnimations* ca = GetAnims();
4588 if (!ca)
4589 return;
4591 //explored or visibilitymap (bird animations are visible in fog)
4592 //0 means opaque
4593 int NoCircle = Modified[IE_NOCIRCLE];
4594 int Trans = Modified[IE_TRANSLUCENT];
4596 if (Trans>255) {
4597 Trans=255;
4600 //iwd has this flag saved in the creature
4601 if (Modified[IE_AVATARREMOVAL]) {
4602 Trans = 255;
4603 NoCircle = 1;
4606 int Frozen = Immobile();
4607 int State = Modified[IE_STATE_ID];
4609 if (State&STATE_DEAD) {
4610 NoCircle = 1;
4613 if (State&STATE_STILL) {
4614 Frozen = 1;
4617 //adjust invisibility for enemies
4618 if (Modified[IE_EA]>EA_GOODCUTOFF) {
4619 if (State&STATE_INVISIBLE) {
4620 Trans = 255;
4624 //can't move this, because there is permanent blur state where
4625 //there is no effect (just state bit)
4626 if ((State&STATE_BLUR) && Trans < 128) {
4627 Trans = 128;
4629 Color tint = area->LightMap->GetPixel( cx / 16, cy / 12);
4630 tint.a = (ieByte) (255-Trans);
4632 unsigned char heightmapindex = area->HeightMap->GetAt( cx / 16, cy / 12);
4633 if (heightmapindex > 15) {
4634 // there are 8bpp lightmaps (eg, bg2's AR1300) and fuzzie
4635 // cannot work out how they work, so here is an incorrect
4636 // hack (probably). please fix!
4637 heightmapindex = 15;
4640 //don't use cy for area map access beyond this point
4641 cy -= heightmapindex;
4643 //draw videocells under the actor
4644 DrawVideocells(screen, vvcShields, tint);
4646 Video* video = core->GetVideoDriver();
4647 Region vp = video->GetViewport();
4649 bool drawcircle = (NoCircle == 0);
4650 if ((core->GetGameControl()->GetScreenFlags()&SF_CUTSCENE)) {
4651 // ground circles are not drawn in cutscenes
4652 // they SHOULD be drawn for at least white speaker circles
4653 // (eg, via VerbalConstant), please fix :)
4654 drawcircle = false;
4656 if (BaseStats[IE_STATE_ID]&STATE_DEAD || InternalFlags&IF_JUSTDIED) {
4657 drawcircle = false;
4659 bool drawtarget = drawcircle;
4660 // we always show circle/target on pause
4661 if (drawcircle && !(core->GetGameControl()->GetDialogueFlags() & DF_FREEZE_SCRIPTS)) {
4662 // check marker feedback level
4663 ieDword markerfeedback = 4;
4664 core->GetDictionary()->Lookup("GUI Feedback Level", markerfeedback);
4665 if (Over) {
4666 // picked creature
4667 drawcircle = markerfeedback >= 1;
4668 } else if (Selected) {
4669 // selected creature
4670 drawcircle = markerfeedback >= 2;
4671 } else if (IsPC()) {
4672 // selectable
4673 drawcircle = markerfeedback >= 3;
4674 } else if (Modified[IE_EA] >= EA_EVILCUTOFF) {
4675 // hostile
4676 drawcircle = markerfeedback >= 5;
4677 } else {
4678 // all
4679 drawcircle = markerfeedback >= 6;
4681 drawtarget = Selected && markerfeedback >= 4;
4683 if (drawcircle) {
4684 DrawCircle(vp);
4686 if (drawtarget) {
4687 DrawTargetPoint(vp);
4690 unsigned char StanceID = GetStance();
4691 unsigned char Face = GetNextFace();
4692 Animation** anims = ca->GetAnimation( StanceID, Face );
4693 if (anims) {
4694 // update bounding box and such
4695 int PartCount = ca->GetTotalPartCount();
4696 Sprite2D* nextFrame = 0;
4697 nextFrame = anims[0]->GetFrame(anims[0]->GetCurrentFrame());
4699 //make actor unselectable and unselected when it is not moving
4700 //dead, petriefied, frozen, paralysed etc.
4701 if (Frozen) {
4702 if (Selected!=0x80) {
4703 Selected = 0x80;
4704 core->GetGame()->SelectActor(this, false, SELECT_NORMAL);
4707 //If you find a better place for it, I'll really be glad to put it there
4708 //IN BG1 and BG2, this is at the ninth frame...
4709 if(attackProjectile && (anims[0]->GetCurrentFrame() == 8/*anims[0]->GetFramesCount()/2*/)) {
4710 GetCurrentArea()->AddProjectile(attackProjectile, Pos, LastTarget);
4711 attackProjectile = NULL;
4713 if (nextFrame && lastFrame != nextFrame) {
4714 Region newBBox;
4715 if (PartCount == 1) {
4716 newBBox.x = cx - nextFrame->XPos;
4717 newBBox.w = nextFrame->Width;
4718 newBBox.y = cy - nextFrame->YPos;
4719 newBBox.h = nextFrame->Height;
4720 } else {
4721 // FIXME: currently using the animarea instead
4722 // of the real bounding box of this (multi-part) frame.
4723 // Shouldn't matter much, though. (wjp)
4724 newBBox.x = cx + anims[0]->animArea.x;
4725 newBBox.y = cy + anims[0]->animArea.y;
4726 newBBox.w = anims[0]->animArea.w;
4727 newBBox.h = anims[0]->animArea.h;
4729 lastFrame = nextFrame;
4730 SetBBox( newBBox );
4733 // Drawing the actor:
4734 // * mirror images:
4735 // Drawn without transparency, unless fully invisible.
4736 // Order: W, E, N, S, NW, SE, NE, SW
4737 // Uses extraCovers 3-10
4738 // * blurred copies (3 of them)
4739 // Drawn with transparency.
4740 // distance between copies depends on IE_MOVEMENTRATE
4741 // TODO: actually, the direction is the real movement direction,
4742 // not the (rounded) direction given Face
4743 // Uses extraCovers 0-2
4744 // * actor itself
4745 // Uses main spritecover
4747 //comments by Avenger:
4748 // currently we don't have a real direction, but the orientation field
4749 // could be used with higher granularity. When we need the face value
4750 // it could be divided so it will become a 0-15 number.
4753 SpriteCover *sc = 0, *newsc = 0;
4754 int blurx = cx;
4755 int blury = cy;
4756 int blurdx = (OrientdX[Face]*(int)Modified[IE_MOVEMENTRATE])/20;
4757 int blurdy = (OrientdY[Face]*(int)Modified[IE_MOVEMENTRATE])/20;
4758 Color mirrortint = tint;
4759 //mirror images are also half transparent when invis
4760 //if (mirrortint.a > 0) mirrortint.a = 255;
4762 int i;
4764 // mirror images behind the actor
4765 for (i = 0; i < 4; ++i) {
4766 unsigned int m = MirrorImageZOrder[i];
4767 if (m < Modified[IE_MIRRORIMAGES]) {
4768 Region sbbox = BBox;
4769 int dir = MirrorImageLocation[m];
4770 int icx = cx + 3*OrientdX[dir];
4771 int icy = cy + 3*OrientdY[dir];
4772 Point iPos(icx, icy);
4773 if (area->GetBlocked(iPos) & (PATH_MAP_PASSABLE|PATH_MAP_ACTOR)) {
4774 sbbox.x += 3*OrientdX[dir];
4775 sbbox.y += 3*OrientdY[dir];
4776 newsc = sc = extraCovers[3+m];
4777 DrawActorSprite(screen, icx, icy, sbbox, newsc,
4778 anims, Face, mirrortint);
4779 if (newsc != sc) {
4780 delete sc;
4781 extraCovers[3+m] = newsc;
4784 } else {
4785 delete extraCovers[3+m];
4786 extraCovers[3+m] = NULL;
4790 // blur sprites behind the actor
4791 if (State & STATE_BLUR) {
4792 if (Face < 4 || Face >= 12) {
4793 Region sbbox = BBox;
4794 sbbox.x -= 4*blurdx; sbbox.y -= 4*blurdy;
4795 blurx -= 4*blurdx; blury -= 4*blurdy;
4796 for (i = 0; i < 3; ++i) {
4797 sbbox.x += blurdx; sbbox.y += blurdy;
4798 blurx += blurdx; blury += blurdy;
4799 newsc = sc = extraCovers[i];
4800 DrawActorSprite(screen, blurx, blury, sbbox, newsc,
4801 anims, Face, tint);
4802 if (newsc != sc) {
4803 delete sc;
4804 extraCovers[i] = newsc;
4810 // actor itself
4811 newsc = sc = GetSpriteCover();
4812 DrawActorSprite(screen, cx, cy, BBox, newsc, anims, Face, tint);
4813 if (newsc != sc) SetSpriteCover(newsc);
4815 // blur sprites in front of the actor
4816 if (State & STATE_BLUR) {
4817 if (Face >= 4 && Face < 12) {
4818 Region sbbox = BBox;
4819 for (i = 0; i < 3; ++i) {
4820 sbbox.x -= blurdx; sbbox.y -= blurdy;
4821 blurx -= blurdx; blury -= blurdy;
4822 newsc = sc = extraCovers[i];
4823 DrawActorSprite(screen, blurx, blury, sbbox, newsc,
4824 anims, Face, tint);
4825 if (newsc != sc) {
4826 delete sc;
4827 extraCovers[i] = newsc;
4833 // mirror images in front of the actor
4834 for (i = 4; i < 8; ++i) {
4835 unsigned int m = MirrorImageZOrder[i];
4836 if (m < Modified[IE_MIRRORIMAGES]) {
4837 Region sbbox = BBox;
4838 int dir = MirrorImageLocation[m];
4839 int icx = cx + 3*OrientdX[dir];
4840 int icy = cy + 3*OrientdY[dir];
4841 Point iPos(icx, icy);
4842 if (area->GetBlocked(iPos) & (PATH_MAP_PASSABLE|PATH_MAP_ACTOR)) {
4843 sbbox.x += 3*OrientdX[dir];
4844 sbbox.y += 3*OrientdY[dir];
4845 newsc = sc = extraCovers[3+m];
4846 DrawActorSprite(screen, icx, icy, sbbox, newsc,
4847 anims, Face, mirrortint);
4848 if (newsc != sc) {
4849 delete sc;
4850 extraCovers[3+m] = newsc;
4853 } else {
4854 delete extraCovers[3+m];
4855 extraCovers[3+m] = NULL;
4859 // advance animations one frame (in sync)
4860 if (Frozen)
4861 anims[0]->LastFrame();
4862 else
4863 anims[0]->NextFrame();
4865 for (int part = 1; part < PartCount; ++part) {
4866 if (anims[part])
4867 anims[part]->GetSyncedNextFrame(anims[0]);
4870 if (anims[0]->endReached) {
4871 if (HandleActorStance() ) {
4872 anims[0]->endReached = false;
4873 anims[0]->SetPos(0);
4877 ca->PulseRGBModifiers();
4880 //draw videocells over the actor
4881 DrawVideocells(screen, vvcOverlays, tint);
4884 /* Handling automatic stance changes */
4885 bool Actor::HandleActorStance()
4887 CharAnimations* ca = GetAnims();
4888 int StanceID = GetStance();
4890 if (ca->autoSwitchOnEnd) {
4891 int nextstance = ca->nextStanceID;
4893 if (nextstance == IE_ANI_READY) {
4894 if (!core->GetGame()->CombatCounter) {
4895 nextstance = IE_ANI_AWAKE;
4899 SetStance( nextstance );
4900 ca->autoSwitchOnEnd = false;
4901 return true;
4903 int x = rand()%1000;
4904 if ((StanceID==IE_ANI_AWAKE) && !x ) {
4905 SetStance( IE_ANI_HEAD_TURN );
4906 return true;
4908 // added CurrentAction as part of blocking action fixes
4909 if ((StanceID==IE_ANI_READY) && !CurrentAction && !GetNextAction()) {
4910 SetStance( IE_ANI_AWAKE );
4911 return true;
4913 if (StanceID == IE_ANI_ATTACK || StanceID == IE_ANI_ATTACK_JAB ||
4914 StanceID == IE_ANI_ATTACK_SLASH || StanceID == IE_ANI_ATTACK_BACKSLASH ||
4915 StanceID == IE_ANI_SHOOT)
4917 SetStance( AttackStance );
4918 return true;
4920 return false;
4923 void Actor::GetSoundFrom2DA(ieResRef Sound, unsigned int index)
4925 if (!anims) return;
4927 AutoTable tab(anims->ResRef);
4928 if (!tab)
4929 return;
4931 switch (index) {
4932 case VB_ATTACK:
4933 index = 0;
4934 break;
4935 case VB_DAMAGE:
4936 index = 8;
4937 break;
4938 case VB_DIE:
4939 index = 10;
4940 break;
4941 case VB_SELECT:
4942 index = 36+rand()%4;
4943 break;
4945 strnlwrcpy(Sound, tab->QueryField (index, 0), 8);
4948 void Actor::GetSoundFromINI(ieResRef Sound, unsigned int index)
4950 const char *resource = "";
4951 char section[12];
4952 unsigned int animid=BaseStats[IE_ANIMATION_ID];
4953 if(core->HasFeature(GF_ONE_BYTE_ANIMID)) {
4954 animid&=0xff;
4956 snprintf(section,10,"%d", animid);
4958 switch(index) {
4959 case VB_ATTACK:
4960 resource = core->GetResDataINI()->GetKeyAsString(section, "at1sound","");
4961 break;
4962 case VB_DAMAGE:
4963 resource = core->GetResDataINI()->GetKeyAsString(section, "hitsound","");
4964 break;
4965 case VB_DIE:
4966 resource = core->GetResDataINI()->GetKeyAsString(section, "dfbsound","");
4967 break;
4968 case VB_SELECT:
4969 break;
4971 int count = CountElements(resource,',');
4972 if (count<=0) return;
4973 count = core->Roll(1,count,-1);
4974 while(count--) {
4975 while(*resource && *resource!=',') resource++;
4976 if (*resource==',') resource++;
4978 strncpy(Sound, resource, 8);
4979 for(count=0;count<8 && Sound[count]!=',';count++) {};
4980 Sound[count]=0;
4983 void Actor::ResolveStringConstant(ieResRef Sound, unsigned int index)
4985 //resolving soundset (bg1/bg2 style)
4986 if (PCStats && PCStats->SoundSet[0]&& csound[index]) {
4987 snprintf(Sound, sizeof(ieResRef), "%s%c", PCStats->SoundSet, csound[index]);
4988 return;
4991 Sound[0]=0;
4993 if (core->HasFeature(GF_RESDATA_INI)) {
4994 GetSoundFromINI(Sound, index);
4995 } else {
4996 GetSoundFrom2DA(Sound, index);
5000 void Actor::SetActionButtonRow(ActionButtonRow &ar)
5002 for(int i=0;i<MAX_QSLOTS;i++) {
5003 ieByte tmp = ar[i+3];
5004 if (QslotTranslation) {
5005 tmp=gemrb2iwd[tmp];
5007 PCStats->QSlots[i]=tmp;
5011 //the first 3 buttons are untouched by this function
5012 void Actor::GetActionButtonRow(ActionButtonRow &ar)
5014 InitButtons(GetStat(IE_CLASS), false);
5015 for(int i=0;i<GUIBT_COUNT-3;i++) {
5016 ieByte tmp=PCStats->QSlots[i];
5017 if (QslotTranslation) {
5018 if (tmp>=90) { //quick weapons
5019 tmp=16+tmp%10;
5020 } else if (tmp>=80) { //quick items
5021 tmp=9+tmp%10;
5022 } else if (tmp>=70) { //quick spells
5023 tmp=3+tmp%10;
5024 } else {
5025 tmp=iwd2gemrb[tmp];
5028 ar[i+3]=tmp;
5030 memcpy(ar,DefaultButtons,3*sizeof(ieByte) );
5033 void Actor::SetPortrait(const char* ResRef, int Which)
5035 int i;
5037 if (ResRef == NULL) {
5038 return;
5040 if (InParty) {
5041 core->SetEventFlag(EF_PORTRAIT);
5044 if(Which!=1) {
5045 memset( SmallPortrait, 0, 8 );
5046 strncpy( SmallPortrait, ResRef, 8 );
5048 if(Which!=2) {
5049 memset( LargePortrait, 0, 8 );
5050 strncpy( LargePortrait, ResRef, 8 );
5052 if(!Which) {
5053 for (i = 0; i < 8 && ResRef[i]; i++) {};
5054 SmallPortrait[i] = 'S';
5055 LargePortrait[i] = 'M';
5059 void Actor::SetSoundFolder(const char *soundset)
5061 if (core->HasFeature(GF_SOUNDFOLDERS)) {
5062 char filepath[_MAX_PATH];
5064 strnlwrcpy(PCStats->SoundFolder, soundset, 32);
5065 PathJoin(filepath,core->GamePath,"sounds",PCStats->SoundFolder,0);
5066 char file[_MAX_PATH];
5067 if (FileGlob(file, filepath, "?????01")) {
5068 file[5] = '\0';
5069 } else if (FileGlob(file, filepath, "????01")) {
5070 file[4] = '\0';
5071 } else {
5072 return;
5074 strnlwrcpy(PCStats->SoundSet, file, 8);
5075 } else {
5076 strnlwrcpy(PCStats->SoundSet, soundset, 8);
5077 PCStats->SoundFolder[0]=0;
5081 bool Actor::HasVVCCell(const ieResRef resource)
5083 int j = true;
5084 vvcVector *vvcCells=&vvcShields;
5085 retry:
5086 size_t i=vvcCells->size();
5087 while (i--) {
5088 ScriptedAnimation *vvc = (*vvcCells)[i];
5089 if (vvc == NULL) {
5090 continue;
5092 if ( strnicmp(vvc->ResName, resource, 8) == 0) {
5093 return true;
5096 vvcCells=&vvcOverlays;
5097 if (j) { j = false; goto retry; }
5098 return false;
5101 void Actor::RemoveVVCell(const ieResRef resource, bool graceful)
5103 bool j = true;
5104 vvcVector *vvcCells=&vvcShields;
5105 retry:
5106 size_t i=vvcCells->size();
5107 while (i--) {
5108 ScriptedAnimation *vvc = (*vvcCells)[i];
5109 if (vvc == NULL) {
5110 continue;
5112 if ( strnicmp(vvc->ResName, resource, 8) == 0) {
5113 if (graceful) {
5114 vvc->SetPhase(P_RELEASE);
5115 } else {
5116 delete vvc;
5117 vvcCells->erase(vvcCells->begin()+i);
5121 vvcCells=&vvcOverlays;
5122 if (j) { j = false; goto retry; }
5125 //this is a faster version of hasvvccell, because it knows where to look
5126 //for the overlay, it also returns the vvc for further manipulation
5127 //use this for the seven eyes overlay
5128 ScriptedAnimation *Actor::FindOverlay(int index)
5130 vvcVector *vvcCells;
5132 if (index>31) return NULL;
5134 if (hc_locations&(1<<index)) vvcCells=&vvcShields;
5135 else vvcCells=&vvcOverlays;
5137 const char *resRef = hc_overlays[index];
5139 size_t i=vvcCells->size();
5140 while (i--) {
5141 ScriptedAnimation *vvc = (*vvcCells)[i];
5142 if (vvc == NULL) {
5143 continue;
5145 if ( strnicmp(vvc->ResName, resRef, 8) == 0) {
5146 return vvc;
5149 return NULL;
5152 void Actor::AddVVCell(ScriptedAnimation* vvc)
5154 vvcVector *vvcCells;
5156 //if the vvc was not created, don't try to add it
5157 if (!vvc) {
5158 return;
5160 if (vvc->ZPos<0) {
5161 vvcCells=&vvcShields;
5162 } else {
5163 vvcCells=&vvcOverlays;
5165 size_t i=vvcCells->size();
5166 while (i--) {
5167 if ((*vvcCells)[i] == NULL) {
5168 (*vvcCells)[i] = vvc;
5169 return;
5172 vvcCells->push_back( vvc );
5175 //returns restored spell level
5176 int Actor::RestoreSpellLevel(ieDword maxlevel, ieDword type)
5178 int typemask;
5180 switch (type) {
5181 case 0: //allow only mage
5182 typemask = ~2;
5183 break;
5184 case 1: //allow only cleric
5185 typemask = ~1;
5186 break;
5187 default:
5188 //allow any (including innates)
5189 typemask = ~0;
5191 for (int i=maxlevel;i>0;i--) {
5192 CREMemorizedSpell *cms = spellbook.FindUnchargedSpell(typemask, maxlevel);
5193 if (cms) {
5194 spellbook.ChargeSpell(cms);
5195 return i;
5198 return 0;
5201 //replenishes spells, cures fatigue
5202 void Actor::Rest(int hours)
5204 if (hours) {
5205 //do remove effects
5206 int remaining = hours*10;
5207 //removes hours*10 fatigue points
5208 NewStat (IE_FATIGUE, -remaining, MOD_ADDITIVE);
5209 NewStat (IE_INTOXICATION, -remaining, MOD_ADDITIVE);
5210 //restore hours*10 spell levels
5211 //rememorization starts with the lower spell levels?
5212 inventory.ChargeAllItems (remaining);
5213 for (int level = 1; level<16; level++) {
5214 if (level<remaining) {
5215 break;
5217 while (remaining>0) {
5218 remaining -= RestoreSpellLevel(level,0);
5221 } else {
5222 SetBase (IE_FATIGUE, 0);
5223 SetBase (IE_INTOXICATION, 0);
5224 inventory.ChargeAllItems (0);
5225 spellbook.ChargeAllSpells ();
5229 //returns the actual slot from the quickslot
5230 int Actor::GetQuickSlot(int slot)
5232 assert(slot<8);
5233 if (inventory.HasItemInSlot("",inventory.GetMagicSlot())) {
5234 return inventory.GetMagicSlot();
5236 if (!PCStats) {
5237 return slot+inventory.GetWeaponSlot();
5239 return PCStats->QuickWeaponSlots[slot];
5242 //marks the quickslot as equipped
5243 int Actor::SetEquippedQuickSlot(int slot, int header)
5245 if (!PCStats) {
5246 if (header<0) header=0;
5247 inventory.SetEquippedSlot(slot, header);
5248 return 0;
5252 if ((slot<0) || (slot == IW_NO_EQUIPPED) ) {
5253 if (slot == IW_NO_EQUIPPED) {
5254 slot = inventory.GetFistSlot();
5256 int i;
5257 for(i=0;i<MAX_QUICKWEAPONSLOT;i++) {
5258 if(slot+inventory.GetWeaponSlot()==PCStats->QuickWeaponSlots[i]) {
5259 slot = i;
5260 break;
5263 if (i==MAX_QUICKWEAPONSLOT) {
5264 return 0;
5268 assert(slot<MAX_QUICKWEAPONSLOT);
5269 if (header==-1) {
5270 header = PCStats->QuickWeaponHeaders[slot];
5272 else {
5273 PCStats->QuickWeaponHeaders[slot]=header;
5275 slot = PCStats->QuickWeaponSlots[slot]-inventory.GetWeaponSlot();
5276 Equipped = (ieWordSigned) slot;
5277 EquippedHeader = (ieWord) header;
5278 if (inventory.SetEquippedSlot(slot, header)) {
5279 return 0;
5281 return STR_MAGICWEAPON;
5284 //if target is a non living scriptable, then we simply shoot for its position
5285 //the fx should get a NULL target, and handle itself by using the position
5286 //(shouldn't crash when target is NULL)
5287 bool Actor::UseItemPoint(ieDword slot, ieDword header, Point &target, ieDword flags)
5289 CREItem *item = inventory.GetSlotItem(slot);
5290 if (!item)
5291 return false;
5293 ieResRef tmpresref;
5294 strnuprcpy(tmpresref, item->ItemResRef, sizeof(ieResRef)-1);
5296 Item *itm = gamedata->GetItem(tmpresref);
5297 if (!itm) return false; //quick item slot contains invalid item resref
5298 //item is depleted for today
5299 if(itm->UseCharge(item->Usages, header, false)==CHG_DAY) {
5300 return false;
5303 Projectile *pro = itm->GetProjectile(slot, header, flags&UI_MISS);
5304 ChargeItem(slot, header, item, itm, flags&UI_SILENT);
5305 gamedata->FreeItem(itm,tmpresref, false);
5306 if (pro) {
5307 pro->SetCaster(globalID);
5308 GetCurrentArea()->AddProjectile(pro, Pos, target);
5309 return true;
5311 return false;
5314 static EffectRef fx_damage_ref={"Damage",NULL,-1};
5316 bool Actor::UseItem(ieDword slot, ieDword header, Scriptable* target, ieDword flags, int damage)
5318 if (target->Type!=ST_ACTOR) {
5319 return UseItemPoint(slot, header, target->Pos, flags);
5322 Actor *tar = (Actor *) target;
5323 CREItem *item = inventory.GetSlotItem(slot);
5324 if (!item)
5325 return false;
5327 ieResRef tmpresref;
5328 strnuprcpy(tmpresref, item->ItemResRef, sizeof(ieResRef)-1);
5330 Item *itm = gamedata->GetItem(tmpresref);
5331 if (!itm) return false; //quick item slot contains invalid item resref
5332 //item is depleted for today
5333 if (itm->UseCharge(item->Usages, header, false)==CHG_DAY) {
5334 return false;
5337 Projectile *pro = itm->GetProjectile(slot, header, flags&UI_MISS);
5338 ChargeItem(slot, header, item, itm, flags&UI_SILENT);
5339 gamedata->FreeItem(itm,tmpresref, false);
5340 if (pro) {
5341 //ieDword is unsigned!!
5342 pro->SetCaster(globalID);
5343 if(((int)header < 0) && !(flags&UI_MISS)) { //using a weapon
5344 ITMExtHeader *which = itm->GetWeaponHeader(header == (ieDword)-2);
5345 Effect* AttackEffect = EffectQueue::CreateEffect(fx_damage_ref, damage, (weapon_damagetype[which->DamageType])<<16, FX_DURATION_INSTANT_LIMITED);
5346 AttackEffect->Projectile = which->ProjectileAnimation;
5347 AttackEffect->Target = FX_TARGET_PRESET;
5348 pro->GetEffects()->AddEffect(AttackEffect, true);
5349 //AddEffect created a copy, the original needs to be scrapped
5350 delete AttackEffect;
5351 attackProjectile = pro;
5352 } else //launch it now as we are not attacking
5353 GetCurrentArea()->AddProjectile(pro, Pos, tar->globalID);
5354 return true;
5356 return false;
5359 void Actor::ChargeItem(ieDword slot, ieDword header, CREItem *item, Item *itm, bool silent)
5361 if (!itm) {
5362 item = inventory.GetSlotItem(slot);
5363 if (!item)
5364 return;
5365 itm = gamedata->GetItem(item->ItemResRef);
5367 if (!itm) return; //quick item slot contains invalid item resref
5369 if (InParty) {
5370 core->SetEventFlag( EF_ACTION );
5373 if (!silent) {
5374 ieByte stance = AttackStance;
5375 for (int i=0;i<animcount;i++) {
5376 if ( strnicmp(item->ItemResRef, itemanim[i].itemname, 8) == 0) {
5377 stance = itemanim[i].animation;
5380 if (stance!=0xff) {
5381 SetStance(stance);
5382 //play only one cycle of animations
5384 // this was crashing for fuzzie due to NULL anims
5385 if (anims) {
5386 anims->nextStanceID=IE_ANI_READY;
5387 anims->autoSwitchOnEnd=true;
5392 switch(itm->UseCharge(item->Usages, header, true)) {
5393 case CHG_DAY:
5394 break;
5395 case CHG_BREAK: //both
5396 if (!silent) {
5397 core->PlaySound(DS_ITEM_GONE);
5399 //fall through
5400 case CHG_NOSOUND: //remove item
5401 inventory.BreakItemSlot(slot);
5402 break;
5403 default: //don't do anything
5404 break;
5408 int Actor::IsReverseToHit()
5410 return ReverseToHit;
5413 void Actor::InitButtons(ieDword cls, bool forced)
5415 if (!PCStats) {
5416 return;
5418 if ( (PCStats->QSlots[0]!=0xff) && !forced) {
5419 return;
5422 ActionButtonRow myrow;
5423 if ((int) cls >= classcount) {
5424 memcpy(&myrow, &DefaultButtons, sizeof(ActionButtonRow));
5425 } else {
5426 memcpy(&myrow, GUIBTDefaults+cls, sizeof(ActionButtonRow));
5428 SetActionButtonRow(myrow);
5431 void Actor::SetFeat(unsigned int feat, int mode)
5433 if (feat>=MAX_FEATS) {
5434 return;
5436 ieDword mask = 1<<(feat&31);
5437 ieDword idx = feat>>5;
5438 switch (mode) {
5439 case BM_SET: case BM_OR:
5440 BaseStats[IE_FEATS1+idx]|=mask;
5441 break;
5442 case BM_NAND:
5443 BaseStats[IE_FEATS1+idx]&=~mask;
5444 break;
5445 case BM_XOR:
5446 BaseStats[IE_FEATS1+idx]^=mask;
5447 break;
5451 void Actor::SetUsedWeapon(const char* AnimationType, ieWord* MeleeAnimation, int wt)
5453 memcpy(WeaponRef, AnimationType, sizeof(WeaponRef) );
5454 if (wt != -1) WeaponType = wt;
5455 if (!anims)
5456 return;
5457 anims->SetWeaponRef(AnimationType);
5458 anims->SetWeaponType(WeaponType);
5459 SetAttackMoveChances(MeleeAnimation);
5460 if (InParty) {
5461 //update the paperdoll weapon animation
5462 core->SetEventFlag(EF_UPDATEANIM);
5464 WeaponInfo wi;
5465 ITMExtHeader *header = GetWeapon(wi);
5467 if(header && (header->AttackType == ITEM_AT_BOW)) {
5468 ITMExtHeader* projHeader = GetRangedWeapon(wi);
5469 if (projHeader->ProjectileQualifier == 0) return; /* no ammo yet? */
5470 AttackStance = IE_ANI_SHOOT;
5471 anims->SetRangedType(projHeader->ProjectileQualifier-1);
5472 //bows ARE one handed, from an anim POV at least
5473 anims->SetWeaponType(IE_ANI_WEAPON_1H);
5474 return;
5476 if(header && (header->AttackType == ITEM_AT_PROJECTILE)) {
5477 AttackStance = IE_ANI_ATTACK_SLASH; //That's it!!
5478 return;
5480 AttackStance = IE_ANI_ATTACK;
5483 void Actor::SetUsedShield(const char* AnimationType, int wt)
5485 memcpy(ShieldRef, AnimationType, sizeof(ShieldRef) );
5486 if (wt != -1) WeaponType = wt;
5487 if (AnimationType[0] == ' ' || AnimationType[0] == 0)
5488 if (WeaponType == IE_ANI_WEAPON_2W)
5489 WeaponType = IE_ANI_WEAPON_1H;
5491 if (!anims)
5492 return;
5493 anims->SetOffhandRef(AnimationType);
5494 anims->SetWeaponType(WeaponType);
5495 if (InParty) {
5496 //update the paperdoll weapon animation
5497 core->SetEventFlag(EF_UPDATEANIM);
5501 void Actor::SetUsedHelmet(const char* AnimationType)
5503 memcpy(HelmetRef, AnimationType, sizeof(HelmetRef) );
5504 if (!anims)
5505 return;
5506 anims->SetHelmetRef(AnimationType);
5507 if (InParty) {
5508 //update the paperdoll weapon animation
5509 core->SetEventFlag(EF_UPDATEANIM);
5513 void Actor::SetupFist()
5515 int slot = core->QuerySlot( 0 );
5516 assert (core->QuerySlotEffects(slot)==SLOT_EFFECT_FIST);
5517 int row = GetBase(fiststat);
5518 int col = GetXPLevel(false);
5520 if (FistRows<0) {
5521 FistRows=0;
5522 AutoTable fist("fistweap");
5523 if (fist) {
5524 //default value
5525 strnlwrcpy( DefaultFist, fist->QueryField( (unsigned int) -1), 8);
5526 FistRows = fist->GetRowCount();
5527 fistres = new FistResType[FistRows];
5528 for (int i=0;i<FistRows;i++) {
5529 int maxcol = fist->GetColumnCount(i)-1;
5530 for (int cols = 0;cols<MAX_LEVEL;cols++) {
5531 strnlwrcpy( fistres[i][cols], fist->QueryField( i, cols>maxcol?maxcol:cols ), 8);
5533 *(int *) fistres[i] = atoi(fist->GetRowName( i));
5537 if (col>MAX_LEVEL) col=MAX_LEVEL;
5538 if (col<1) col=1;
5540 const char *ItemResRef = DefaultFist;
5541 for (int i = 0;i<FistRows;i++) {
5542 if (*(int *) fistres[i] == row) {
5543 ItemResRef = fistres[i][col];
5546 inventory.SetSlotItemRes(ItemResRef, slot);
5549 static ieDword ResolveTableValue(const char *resref, ieDword stat, ieDword mcol, ieDword vcol) {
5550 long ret = 0;
5551 //don't close this table, it can mess with the guiscripts
5552 int table = gamedata->LoadTable(resref);
5553 TableMgr *tm = gamedata->GetTable(table);
5554 if (tm) {
5555 unsigned int row;
5556 if (mcol == 0xff) {
5557 row = stat;
5558 } else {
5559 row = tm->FindTableValue(mcol, stat);
5560 if (row==0xffffffff) {
5561 return 0;
5564 if (valid_number(tm->QueryField(row, vcol), ret)) {
5565 return (ieDword) ret;
5569 return 0;
5572 static ieDword GetKitIndex (ieDword kit, const char *resref="kitlist")
5574 int kitindex = 0;
5576 if ((kit&BG2_KITMASK) == KIT_BARBARIAN) {
5577 kitindex = kit&0xfff;
5580 // carefully looking for kit by the usability flag
5581 // since the barbarian kit id clashes with the no-kit value
5582 if (kitindex == 0 && kit != KIT_BARBARIAN) {
5583 TableMgr *tm = gamedata->GetTable(gamedata->LoadTable(resref) );
5584 if (tm) {
5585 kitindex = tm->FindTableValue(6, kit);
5586 if (kitindex < 0) {
5587 kitindex = 0;
5592 return (ieDword)kitindex;
5595 int Actor::CheckUsability(Item *item) const
5597 ieDword itembits[2]={item->UsabilityBitmask, item->KitUsability};
5599 for (int i=0;i<usecount;i++) {
5600 ieDword itemvalue = itembits[itemuse[i].which];
5601 ieDword stat = GetStat(itemuse[i].stat);
5602 ieDword mcol = itemuse[i].mcol;
5603 //if we have a kit, we just we use it's index for the lookup
5604 if (itemuse[i].stat==IE_KIT) {
5605 stat = GetKitIndex(stat, itemuse[i].table);
5606 mcol = 0xff;
5608 stat = ResolveTableValue(itemuse[i].table, stat, mcol, itemuse[i].vcol);
5609 if (stat&itemvalue) {
5610 //printf("failed usability: itemvalue %d, stat %d, stat value %d\n", itemvalue, itemuse[i].stat, stat);
5611 return STR_CANNOT_USE_ITEM;
5615 return 0;
5618 //checks usability only
5619 int Actor::Unusable(Item *item) const
5621 if (!GetStat(IE_CANUSEANYITEM)) {
5622 int unusable = CheckUsability(item);
5623 if (unusable) {
5624 return unusable;
5628 // iesdp says this is always checked?
5629 if (item->MinLevel>GetXPLevel(true)) {
5630 return STR_CANNOT_USE_ITEM;
5633 if (!CheckAbilities) {
5634 return 0;
5637 if (item->MinStrength>GetStat(IE_STR)) {
5638 return STR_CANNOT_USE_ITEM;
5641 if (item->MinStrength==18) {
5642 if (GetStat(IE_STR)==18) {
5643 if (item->MinStrengthBonus>GetStat(IE_STREXTRA)) {
5644 return STR_CANNOT_USE_ITEM;
5649 if (item->MinIntelligence>GetStat(IE_INT)) {
5650 return STR_CANNOT_USE_ITEM;
5652 if (item->MinDexterity>GetStat(IE_DEX)) {
5653 return STR_CANNOT_USE_ITEM;
5655 if (item->MinWisdom>GetStat(IE_WIS)) {
5656 return STR_CANNOT_USE_ITEM;
5658 if (item->MinConstitution>GetStat(IE_CON)) {
5659 return STR_CANNOT_USE_ITEM;
5661 if (item->MinCharisma>GetStat(IE_CHR)) {
5662 return STR_CANNOT_USE_ITEM;
5664 //note, weapon proficiencies shouldn't be checked here
5665 //missing proficiency causes only attack penalty
5666 return 0;
5669 //full palette will be shaded in gradient color
5670 void Actor::SetGradient(ieDword gradient)
5672 gradient |= (gradient <<16);
5673 gradient |= (gradient <<8);
5674 for(int i=0;i<7;i++) {
5675 Modified[IE_COLORS+i]=gradient;
5679 //sets one bit of the sanctuary stat (used for overlays)
5680 void Actor::SetOverlay(unsigned int overlay)
5682 if (overlay>=32) return;
5683 Modified[IE_SANCTUARY]|=1<<overlay;
5686 //returns true if spell state is already set or illegal
5687 bool Actor::SetSpellState(unsigned int spellstate)
5689 if (spellstate>=192) return true;
5690 unsigned int pos = IE_SPLSTATE_ID1+(spellstate>>5);
5691 unsigned int bit = 1<<(spellstate&31);
5692 if (Modified[pos]&bit) return true;
5693 Modified[pos]|=bit;
5694 return false;
5697 //returns true if spell state is already set
5698 bool Actor::HasSpellState(unsigned int spellstate)
5700 if (spellstate>=192) return false;
5701 unsigned int pos = IE_SPLSTATE_ID1+(spellstate>>5);
5702 unsigned int bit = 1<<(spellstate&31);
5703 if (Modified[pos]&bit) return true;
5704 return false;
5707 //returns the numeric value of a feat, different from HasFeat
5708 //for multiple feats
5709 int Actor::GetFeat(unsigned int feat) const
5711 if (feat>=MAX_FEATS) {
5712 return -1;
5714 if (Modified[IE_FEATS1+(feat>>5)]&(1<<(feat&31)) ) {
5715 //return the numeric stat value, instead of the boolean
5716 if (featstats[feat]) {
5717 return Modified[featstats[feat]];
5719 return 1;
5721 return 0;
5724 //returns true if the feat exists
5725 bool Actor::HasFeat(unsigned int featindex) const
5727 if (featindex>=MAX_FEATS) return false;
5728 unsigned int pos = IE_FEATS1+(featindex>>5);
5729 unsigned int bit = 1<<(featindex&31);
5730 if (Modified[pos]&bit) return true;
5731 return false;
5734 ieDword Actor::ImmuneToProjectile(ieDword projectile) const
5736 int idx;
5738 idx = projectile/32;
5739 if (idx>ProjectileSize) {
5740 return 0;
5742 return projectileImmunity[idx]&(1<<(projectile&31));
5745 void Actor::AddProjectileImmunity(ieDword projectile)
5747 projectileImmunity[projectile/32]|=1<<(projectile&31);
5750 //2nd edition rules
5751 void Actor::CreateDerivedStatsBG()
5753 int turnundeadlevel = 0;
5754 int classid = BaseStats[IE_CLASS];
5756 //this works only for PC classes
5757 if (classid>=CLASS_PCCUTOFF) return;
5759 //recalculate all level based changes
5760 pcf_level(this,0,0);
5762 //even though the original didn't allow a cleric/paladin dual or multiclass
5763 //we shouldn't restrict the possibility by using "else if" here
5764 if (isclass[ISCLERIC]&(1<<classid)) {
5765 turnundeadlevel += GetClericLevel()+1-turnlevels[classid];
5766 if (turnundeadlevel<0) turnundeadlevel=0;
5768 if (isclass[ISPALADIN]&(1<<classid)) {
5769 turnundeadlevel += GetPaladinLevel()+1-turnlevels[classid];
5770 if (turnundeadlevel<0) turnundeadlevel=0;
5773 // barbarian immunity to backstab was hardcoded
5774 if (GetBarbarianLevel()) {
5775 BaseStats[IE_DISABLEBACKSTAB] = 1;
5778 ieDword backstabdamagemultiplier=GetThiefLevel();
5779 if (backstabdamagemultiplier) {
5780 // HACK: swashbucklers can't backstab
5781 if ((BaseStats[IE_KIT]&0xfff) == 12) {
5782 backstabdamagemultiplier = 1;
5783 } else {
5784 AutoTable tm("backstab");
5785 //fallback to a general algorithm (bg2 backstab.2da version) if we can't find backstab.2da
5786 //TODO: AP_SPCL332 (increase backstab by one) seems to not be effecting this at all
5787 //for assassins perhaps the effect is being called prior to this, and this overwrites it;
5788 //stalkers work correctly, which is even more odd, considering as they use the same
5789 //effect and backstabmultiplier would be 0 for them
5790 if (tm) {
5791 ieDword cols = tm->GetColumnCount();
5792 if (backstabdamagemultiplier >= cols) backstabdamagemultiplier = cols;
5793 backstabdamagemultiplier = atoi(tm->QueryField(0, backstabdamagemultiplier));
5794 } else {
5795 backstabdamagemultiplier = (backstabdamagemultiplier+7)/4;
5797 printf("\n");
5798 if (backstabdamagemultiplier>7) backstabdamagemultiplier=7;
5802 // monk's level dictated ac and ac vs missiles bonus
5803 // attacks per round bonus will be handled elsewhere, since it only applies to fist apr
5804 if (isclass[ISMONK]&(1<<classid)) {
5805 unsigned int level = GetMonkLevel()-1;
5806 BaseStats[IE_ARMORCLASS] = DEFAULTAC - monkbon[1][level];
5807 BaseStats[IE_ACMISSILEMOD] = - monkbon[2][level];
5810 BaseStats[IE_TURNUNDEADLEVEL]=turnundeadlevel;
5811 BaseStats[IE_BACKSTABDAMAGEMULTIPLIER]=backstabdamagemultiplier;
5812 BaseStats[IE_LAYONHANDSAMOUNT]=GetPaladinLevel()*2;
5815 //3rd edition rules
5816 void Actor::CreateDerivedStatsIWD2()
5818 int i;
5819 int turnundeadlevel = 0;
5821 ieDword backstabdamagemultiplier=GetThiefLevel();
5822 if (backstabdamagemultiplier) {
5823 AutoTable tm("backstab");
5824 if (tm) {
5825 ieDword cols = tm->GetColumnCount();
5826 if (backstabdamagemultiplier >= cols) backstabdamagemultiplier = cols;
5827 backstabdamagemultiplier = atoi(tm->QueryField(0, backstabdamagemultiplier));
5828 } else {
5829 backstabdamagemultiplier = (BaseStats[IE_LEVELTHIEF]+1)/2;
5831 printf("\n");
5832 if (backstabdamagemultiplier>7) backstabdamagemultiplier=7;
5835 int layonhandsamount = (int) BaseStats[IE_LEVELPALADIN];
5836 if (layonhandsamount) {
5837 layonhandsamount *= BaseStats[IE_CHR]/2-5;
5838 if (layonhandsamount<1) layonhandsamount = 1;
5841 for (i=0;i<11;i++) {
5842 int tmp;
5844 if (turnlevels[i+1]) {
5845 tmp = BaseStats[IE_LEVELBARBARIAN+i]+1-turnlevels[i+1];
5846 if (tmp<0) tmp=0;
5847 if (tmp>turnundeadlevel) turnundeadlevel=tmp;
5850 BaseStats[IE_TURNUNDEADLEVEL]=turnundeadlevel;
5851 BaseStats[IE_BACKSTABDAMAGEMULTIPLIER]=backstabdamagemultiplier;
5852 BaseStats[IE_LAYONHANDSAMOUNT]=(ieDword) layonhandsamount;
5855 //set up stuff here, like attack number, turn undead level
5856 //and similar derived stats that change with level
5857 void Actor::CreateDerivedStats()
5859 //we have to calculate multiclass for further code
5860 AutoTable tm("classes");
5861 if (tm) {
5862 // currently we need only the MULTI value
5863 char tmpmulti[8];
5864 long tmp;
5865 strcpy(tmpmulti, tm->QueryField(tm->FindTableValue(5, BaseStats[IE_CLASS]), 4));
5866 if (!valid_number(tmpmulti, tmp))
5867 multiclass = 0;
5868 else
5869 multiclass = (ieDword)tmp;
5872 if (core->HasFeature(GF_3ED_RULES)) {
5873 CreateDerivedStatsIWD2();
5874 } else {
5875 CreateDerivedStatsBG();
5878 /* Checks if the actor is multiclassed (the MULTI column is positive) */
5879 bool Actor::IsMultiClassed() const
5881 return (multiclass > 0);
5884 /* Checks if the actor is dualclassed */
5885 bool Actor::IsDualClassed() const
5887 return (Modified[IE_MC_FLAGS] & MC_WAS_ANY) > 0;
5890 Actor *Actor::CopySelf() const
5892 Actor *newActor = new Actor();
5894 newActor->SetName(GetName(0),0);
5895 newActor->SetName(GetName(1),1);
5896 memcpy(newActor->BaseStats, BaseStats, sizeof(BaseStats) );
5897 // illusions aren't worth any xp
5898 newActor->BaseStats[IE_XPVALUE] = 0;
5900 //IF_INITIALIZED shouldn't be set here, yet
5901 newActor->SetMCFlag(MC_EXPORTABLE, BM_NAND);
5903 //the creature importer does this too
5904 memcpy(newActor->Modified,newActor->BaseStats, sizeof(Modified) );
5906 //these need to be called too to have a valid inventory
5907 newActor->inventory.SetSlotCount(inventory.GetSlotCount());
5908 newActor->CreateDerivedStats();
5910 //copy the running effects
5911 EffectQueue *newFXQueue = fxqueue.CopySelf();
5913 area->AddActor(newActor);
5914 newActor->SetPosition( Pos, CC_CHECK_IMPASSABLE, 0 );
5915 newActor->SetOrientation(GetOrientation(),0);
5916 newActor->SetStance( IE_ANI_READY );
5918 //and apply them
5919 newActor->RefreshEffects(newFXQueue);
5920 return newActor;
5923 ieDword Actor::GetClassLevel(const ieDword id) const
5925 if (id>=ISCLASSES)
5926 return 0;
5928 //return iwd2 value if appropriate
5929 if (version==22)
5930 return BaseStats[levelslotsiwd2[id]];
5932 //houston, we gots a problem!
5933 if (!levelslots || !dualswap)
5934 return 0;
5936 //only works with PC's
5937 ieDword classid = BaseStats[IE_CLASS]-1;
5938 if (classid>=(ieDword)classcount || !levelslots[classid])
5939 return 0;
5941 //handle barbarians specially, since they're kits and not in levelslots
5942 if (id == ISBARBARIAN && levelslots[classid][ISFIGHTER] && GetKitIndex(BaseStats[IE_KIT]) == 31) {
5943 return BaseStats[IE_LEVEL];
5946 //get the levelid (IE_LEVEL,*2,*3)
5947 ieDword levelid = levelslots[classid][id];
5948 if (!levelid)
5949 return 0;
5951 //do dual-swap
5952 if (IsDualClassed()) {
5953 //if the old class is inactive, and it is the class
5954 //being searched for, return 0
5955 if (IsDualInactive() && ((Modified[IE_MC_FLAGS]&MC_WAS_ANY)==(ieDword)mcwasflags[id]))
5956 return 0;
5958 return BaseStats[levelid];
5961 bool Actor::IsDualInactive() const
5963 if (!IsDualClassed()) return 0;
5965 //we assume the old class is in IE_LEVEL2, unless swapped
5966 ieDword oldlevel = IsDualSwap() ? BaseStats[IE_LEVEL] : BaseStats[IE_LEVEL2];
5968 //since GetXPLevel returns the average of the 2 levels, oldclasslevel will
5969 //only be less than GetXPLevel when the new class surpasses it
5970 return oldlevel>=GetXPLevel(false);
5973 bool Actor::IsDualSwap() const
5975 //the dualswap[class-1] holds the info
5976 if (!IsDualClassed()) return false;
5977 ieDword tmpclass = BaseStats[IE_CLASS]-1;
5978 if (tmpclass>=(ieDword)classcount) return false;
5979 return (ieDword)dualswap[tmpclass]==(Modified[IE_MC_FLAGS]&MC_WAS_ANY);
5982 ieDword Actor::GetWarriorLevel() const
5984 if (!IsWarrior()) return 0;
5986 ieDword warriorlevels[4] = {
5987 GetBarbarianLevel(),
5988 GetFighterLevel(),
5989 GetPaladinLevel(),
5990 GetRangerLevel()
5993 ieDword highest = 0;
5994 for (int i=0; i<4; i++) {
5995 if (warriorlevels[i] > highest) {
5996 highest = warriorlevels[i];
6000 return highest;
6003 bool Actor::BlocksSearchMap() const
6005 return Modified[IE_DONOTJUMP] < 2;
6008 //return true if the actor doesn't want to use an entrance
6009 bool Actor::CannotPassEntrance() const
6011 if (InternalFlags&IF_USEEXIT) {
6012 return false;
6014 return true;
6017 void Actor::UseExit(int flag) {
6018 if (flag) {
6019 InternalFlags|=IF_USEEXIT;
6020 } else {
6021 InternalFlags&=~IF_USEEXIT;
6025 // luck increases the minimum roll per dice, but only up to the number of dice sides;
6026 // luck does not affect critical hit chances:
6027 // if critical is set, it will return 1/sides on a critical, otherwise it can never
6028 // return a critical miss when luck is positive and can return a false critical hit
6029 int Actor::LuckyRoll(int dice, int size, int add, bool critical, bool only_damage, Actor* opponent) const
6031 assert(this != opponent);
6033 ieDword stat;
6034 if (only_damage) {
6035 stat = IE_DAMAGELUCK;
6036 } else {
6037 stat = IE_LUCK;
6040 int luck = (signed) GetStat(stat);
6041 if (opponent) luck -= (signed) opponent->GetStat(stat);
6042 if (dice < 1 || size < 1) {
6043 return add + luck;
6046 if (dice > 100) {
6047 int bonus;
6048 if (abs(luck) > size) {
6049 bonus = luck/abs(luck) * size;
6050 } else {
6051 bonus = luck;
6053 int roll = core->Roll(1, dice*size, 0);
6054 if (critical && (roll == 1 || roll == size)) {
6055 return roll;
6056 } else {
6057 return add + dice * (size + bonus) / 2;
6061 int roll, result = 0, misses = 0, hits = 0;
6062 for (int i = 0; i < dice; i++) {
6063 roll = core->Roll(1, size, 0);
6064 if (roll == 1) {
6065 misses++;
6066 } else if (roll == size) {
6067 hits++;
6069 roll += luck;
6070 if (roll > size) {
6071 roll = size;
6072 } else if (roll < 1) {
6073 roll = 1;
6075 result += roll;
6078 // ensure we can still return a critical failure/success
6079 if (critical && dice == misses) return 1;
6080 if (critical && dice == hits) return size;
6082 return result + add;
6085 static EffectRef fx_remove_invisible_state_ref={"ForceVisible",NULL,-1};
6087 // removes the (normal) invisibility state
6088 void Actor::CureInvisibility()
6090 if (Modified[IE_STATE_ID] & (ieDword) (STATE_INVISIBLE)) {
6091 //SetBaseBit(IE_STATE_ID, STATE_INVISIBLE, false);
6092 //fxqueue.RemoveAllEffectsWithParam(fx_set_invisible_state_ref, 0);
6094 //this is much closer to what the original engine does here
6095 Effect *newfx;
6097 newfx = EffectQueue::CreateEffect(fx_remove_invisible_state_ref, 0, 0, FX_DURATION_INSTANT_PERMANENT);
6098 core->ApplyEffect(newfx, this, this);
6100 delete newfx;
6102 //not sure, but better than nothing
6103 if (! (Modified[IE_STATE_ID]& STATE_INVISIBLE)) {
6104 InternalFlags|=IF_BECAMEVISIBLE;
6109 static EffectRef fx_remove_sanctuary_ref={"Cure:Sanctuary",NULL,-1};
6111 // removes the sanctuary effect
6112 void Actor::CureSanctuary()
6114 Effect *newfx;
6116 newfx = EffectQueue::CreateEffect(fx_remove_sanctuary_ref, 0, 0, FX_DURATION_INSTANT_PERMANENT);
6117 core->ApplyEffect(newfx, this, this);
6119 delete newfx;
6122 void Actor::ResetState()
6124 CureInvisibility();
6125 CureSanctuary();
6126 SetModal(MS_NONE);
6129 // doesn't check the range, but only that the azimuth and the target
6130 // orientation match with a +/-2 allowed difference
6131 bool Actor::IsBehind(Actor* target)
6133 unsigned char tar_orient = target->GetOrientation();
6134 // computed, since we don't care where we face
6135 unsigned char my_orient = GetOrient(target->Pos, Pos);
6137 signed char diff;
6138 for (int i=-2; i <= 2; i++) {
6139 diff = my_orient+i;
6140 if (diff >= MAX_ORIENT) diff -= MAX_ORIENT;
6141 if (diff <= -1) diff += MAX_ORIENT;
6142 if (diff == (signed)tar_orient) return true;
6144 return false;
6147 // checks all the actor's stats to see if the target is her racial enemy
6148 bool Actor::IsRacialEnemy(Actor* target)
6150 if (Modified[IE_HATEDRACE] == target->Modified[IE_RACE]) {
6151 return true;
6152 } else if (core->HasFeature(GF_3ED_RULES)) {
6153 // iwd2 supports multiple racial enemies gained through level progression
6154 for (unsigned int i=0; i<7; i++) {
6155 if (Modified[IE_HATEDRACE2+i] == target->Modified[IE_RACE]) {
6156 return true;
6160 return false;
6163 bool Actor::ModalSpellSkillCheck() {
6164 switch(ModalState) {
6165 case MS_BATTLESONG:
6166 case MS_DETECTTRAPS:
6167 case MS_TURNUNDEAD:
6168 return true;
6169 case MS_STEALTH:
6170 return TryToHide();
6171 case MS_NONE:
6172 default:
6173 return false;
6177 static EffectRef fx_disable_button_ref={ "DisableButton", NULL, -1 };
6179 inline void HideFailed(Actor* actor)
6181 Effect *newfx;
6182 newfx = EffectQueue::CreateEffect(fx_disable_button_ref, 0, ACT_STEALTH, FX_DURATION_INSTANT_LIMITED);
6183 newfx->Duration = 6; // 90 ticks, 1 round
6184 core->ApplyEffect(newfx, actor, actor);
6185 delete newfx;
6188 bool Actor::TryToHide() {
6189 ieDword roll = LuckyRoll(1, 100, 0);
6190 if (roll == 1) {
6191 HideFailed(this);
6192 return false;
6195 // check for disabled dualclassed thieves (not sure if we need it)
6197 if (Modified[IE_DISABLEDBUTTON] & (1<<ACT_STEALTH)) {
6198 HideFailed(this);
6199 return false;
6202 // check if the pc is in combat (seen / heard)
6203 Game *game = core->GetGame();
6204 if (game->PCInCombat(this)) {
6205 HideFailed(this);
6206 return false;
6209 ieDword skill;
6210 if (core->HasFeature(GF_HAS_HIDE_IN_SHADOWS)) {
6211 skill = (GetStat(IE_HIDEINSHADOWS) + GetStat(IE_STEALTH))/2;
6212 } else {
6213 skill = GetStat(IE_STEALTH);
6216 // check how bright our spot is
6217 ieDword lightness = game->GetCurrentArea()->GetLightLevel(Pos);
6218 // seems to be the color overlay at midnight; lightness of a point with rgb (200, 100, 100)
6219 // TODO: but our NightTint computes to a higher value, which one is bad?
6220 ieDword ref_lightness = 43;
6221 ieDword light_diff = int((lightness - ref_lightness) * 100 / (100 - ref_lightness)) / 2;
6222 ieDword chance = (100 - light_diff) * skill/100;
6224 if (roll > chance) {
6225 HideFailed(this);
6226 return false;
6228 return true;