Combat changes and bug fixes

Added the combo and proc systems
Added scripts for most weaponskill and spells as well as some abilities and status effects
Added support for multihit attacks
Added AbilityState for abilities
Added hiteffects that change based on an attack's parameters
Added positionals

Changed how targeting works for battlecommands

Fixed bug that occurred when moving or swapping hotbar commands
Fixed bug that occurred when losing status effects
This commit is contained in:
yogurt 2018-02-15 13:20:46 -06:00
parent 837c7a9223
commit b8d6a943aa
175 changed files with 4361 additions and 1213 deletions

View file

@ -364,11 +364,13 @@ namespace FFXIVClassic_Map_Server.Actors
return classParams;
}
//character's newMainState kind of messes with this
public void ChangeState(ushort newState)
{
//if (newState != currentMainState)
if (newState != currentMainState)
{
currentMainState = newState;
updateFlags |= (ActorUpdateFlags.State | ActorUpdateFlags.Position);
}
}
@ -403,20 +405,23 @@ namespace FFXIVClassic_Map_Server.Actors
if (positionUpdates != null && positionUpdates.Count > 0)
{
var pos = positionUpdates[0];
oldPositionX = positionX;
oldPositionY = positionY;
oldPositionZ = positionZ;
oldRotation = rotation;
if (pos != null)
{
oldPositionX = positionX;
oldPositionY = positionY;
oldPositionZ = positionZ;
oldRotation = rotation;
positionX = pos.X;
positionY = pos.Y;
positionZ = pos.Z;
positionX = pos.X;
positionY = pos.Y;
positionZ = pos.Z;
zone.UpdateActorPosition(this);
//Program.Server.GetInstance().mLuaEngine.OnPath(actor, position, positionUpdates)
zone.UpdateActorPosition(this);
//Program.Server.GetInstance().mLuaEngine.OnPath(actor, position, positionUpdates)
}
positionUpdates.Remove(pos);
}
packets.Add(CreatePositionUpdatePacket());
}

View file

@ -141,29 +141,30 @@ namespace FFXIVClassic_Map_Server.Actors
public void RemoveActorFromZone(Actor actor)
{
lock (mActorList)
{
mActorList.Remove(actor.actorId);
if (actor != null)
lock (mActorList)
{
mActorList.Remove(actor.actorId);
int gridX = (int)actor.positionX / boundingGridSize;
int gridY = (int)actor.positionZ / boundingGridSize;
int gridX = (int)actor.positionX / boundingGridSize;
int gridY = (int)actor.positionZ / boundingGridSize;
gridX += halfWidth;
gridY += halfHeight;
gridX += halfWidth;
gridY += halfHeight;
//Boundries
if (gridX < 0)
gridX = 0;
if (gridX >= numXBlocks)
gridX = numXBlocks - 1;
if (gridY < 0)
gridY = 0;
if (gridY >= numYBlocks)
gridY = numYBlocks - 1;
//Boundries
if (gridX < 0)
gridX = 0;
if (gridX >= numXBlocks)
gridX = numXBlocks - 1;
if (gridY < 0)
gridY = 0;
if (gridY >= numYBlocks)
gridY = numYBlocks - 1;
lock (mActorBlock)
mActorBlock[gridX, gridY].Remove(actor);
}
lock (mActorBlock)
mActorBlock[gridX, gridY].Remove(actor);
}
}
public void UpdateActorPosition(Actor actor)
@ -487,7 +488,6 @@ namespace FFXIVClassic_Map_Server.Actors
return null;
uint zoneId;
if (this is PrivateArea)
zoneId = ((PrivateArea)this).GetParentZone().actorId;
else
@ -500,8 +500,9 @@ namespace FFXIVClassic_Map_Server.Actors
npc = new Npc(mActorList.Count + 1, actorClass, uniqueId, this, x, y, z, rot, state, animId, null);
npc.LoadEventConditions(actorClass.eventConditions);
//npc.SetMaxHP(3000);
//npc.SetHP(3000);
npc.SetMaxHP(30000);
npc.SetHP(30000);
npc.ResetMoveSpeeds();
AddActorToZone(npc);
@ -668,7 +669,7 @@ namespace FFXIVClassic_Map_Server.Actors
lock (mActorList)
{
foreach (Actor a in mActorList.Values.ToList())
a.Update(tick);
a.Update(tick);
if ((tick - lastUpdateScript).TotalMilliseconds > 1500)
{

View file

@ -125,13 +125,18 @@ namespace FFXIVClassic_Map_Server.Actors
public ushort newMainState;
public float spawnX, spawnY, spawnZ;
//I needed some values I could reuse for random stuff, delete later
public int extraInt;
public uint extraUint;
public float extraFloat;
protected Dictionary<string, UInt64> tempVars = new Dictionary<string, UInt64>();
public Character(uint actorID) : base(actorID)
{
//Init timer array to "notimer"
for (int i = 0; i < charaWork.statusShownTime.Length; i++)
charaWork.statusShownTime[i] = 0xFFFFFFFF;
charaWork.statusShownTime[i] = 0;
this.statusEffects = new StatusEffectContainer(this);
@ -192,9 +197,12 @@ namespace FFXIVClassic_Map_Server.Actors
var i = 0;
foreach (var effect in statusEffects.GetStatusEffects())
{
propPacketUtil.AddProperty($"charaWork.statusShownTime[{i}]");
propPacketUtil.AddProperty(String.Format("charaWork.statusShownTime[{0}]", i));
i++;
if (!effect.GetHidden())
{
propPacketUtil.AddProperty($"charaWork.statusShownTime[{i}]");
propPacketUtil.AddProperty(String.Format("charaWork.statusShownTime[{0}]", i));
i++;
}
}
return propPacketUtil.Done();
}
@ -230,6 +238,7 @@ namespace FFXIVClassic_Map_Server.Actors
{
int currentIndex = 0;
//AoE abilities only ever hit 16 people, so we probably won't need this loop anymore
//Apparently aoe are limited to 8?
while (true)
{
if (actions.Length - currentIndex >= 10)
@ -255,7 +264,7 @@ namespace FFXIVClassic_Map_Server.Actors
while (true)
{
if (actions.Count - currentIndex >= 18)
if (actions.Count - currentIndex >= 10)
zone.BroadcastPacketAroundActor(this, BattleActionX18Packet.BuildPacket(actorId, animationId, commandId, actions, ref currentIndex));
else if (actions.Count - currentIndex > 1)
zone.BroadcastPacketAroundActor(this, BattleActionX10Packet.BuildPacket(actorId, animationId, commandId, actions, ref currentIndex));
@ -586,12 +595,15 @@ namespace FFXIVClassic_Map_Server.Actors
public void AddTP(int tp)
{
charaWork.parameterTemp.tp = (short)((charaWork.parameterTemp.tp + tp).Clamp(0, 3000));
tpBase = (ushort) charaWork.parameterTemp.tp;
updateFlags |= ActorUpdateFlags.HpTpMp;
if (IsAlive())
{
charaWork.parameterTemp.tp = (short)((charaWork.parameterTemp.tp + tp).Clamp(0, 3000));
tpBase = (ushort)charaWork.parameterTemp.tp;
updateFlags |= ActorUpdateFlags.HpTpMp;
if (tpBase >= 1000)
lua.LuaEngine.GetInstance().OnSignal("tpOver1000");
if (tpBase >= 1000)
lua.LuaEngine.GetInstance().OnSignal("tpOver1000");
}
}
public void DelHP(int hp)
@ -609,14 +621,9 @@ namespace FFXIVClassic_Map_Server.Actors
AddTP(-tp);
}
public void CalculateBaseStats()
virtual public void CalculateBaseStats()
{
// todo: apply mods and shit here, get race/level/job and shit
}
public void RecalculateStats()
{
uint hpMod = (uint) GetMod((uint)Modifier.Hp);
if (hpMod != 0)
{
@ -644,6 +651,14 @@ namespace FFXIVClassic_Map_Server.Actors
}
// todo: recalculate stats and crap
updateFlags |= ActorUpdateFlags.HpTpMp;
SetMod((uint)Modifier.HitCount, 1);
}
public void RecalculateStats()
{
//CalculateBaseStats();
}
public void SetStat(uint statId, uint val)
@ -664,57 +679,65 @@ namespace FFXIVClassic_Map_Server.Actors
public virtual void OnAttack(State state, BattleAction action, ref BattleAction error)
{
// todo: change animation based on equipped weapon
action.effectId |= (uint)HitEffect.HitVisual1; // melee
var target = state.GetTarget();
// todo: change animation based on equipped weapon
// todo: get hitrate and shit, handle protect effect and whatever
if (BattleUtils.TryAttack(this, target, action, ref error))
{
action.amount = BattleUtils.CalculateAttackDamage(this, target, action);
//var packet = BattleActionX01Packet.BuildPacket(owner.actorId, owner.actorId, target.actorId, (uint)0x19001000, (uint)0x8000604, (ushort)0x765D, (ushort)BattleActionX01PacketCommand.Attack, (ushort)damage, (byte)0x1);
}
// todo: call onAttack/onDamageTaken
BattleUtils.DamageTarget(this, target, action, DamageTakenType.Attack);
AddTP(115);
AddTP(200);
target.AddTP(100);
}
public virtual void OnCast(State state, BattleAction[] actions, ref BattleAction[] errors)
public virtual void OnCast(State state, BattleAction[] actions, BattleCommand spell, ref BattleAction[] errors)
{
var spell = ((MagicState)state).GetSpell();
// damage is handled in script
var spellCost = spell.CalculateCost((uint)this.GetLevel());
var spellCost = spell.CalculateMpCost(this);
this.DelMP(spellCost); // mpCost can be set in script e.g. if caster has something for free spells
foreach (BattleAction action in actions)
{
if (zone.FindActorInArea<Character>(action.targetId) is Character chara)
BattleUtils.DamageTarget(this, chara, action, DamageTakenType.Magic);
{
//BattleUtils.HandleHitType(this, chara, action);
BattleUtils.DoAction(this, chara, action, DamageTakenType.Magic);
}
}
lua.LuaEngine.GetInstance().OnSignal("spellUsed");
}
public virtual void OnWeaponSkill(State state, BattleAction[] actions, ref BattleAction[] errors)
public virtual void OnWeaponSkill(State state, BattleAction[] actions, BattleCommand skill, ref BattleAction[] errors)
{
var skill = ((WeaponSkillState)state).GetWeaponSkill();
// damage is handled in script
this.DelTP(skill.tpCost);
foreach (BattleAction action in actions)
{
//Should we just store the character insteado f having to find it again?
if (zone.FindActorInArea<Character>(action.targetId) is Character chara)
BattleUtils.DamageTarget(this, chara, action, DamageTakenType.Weaponskill);
{
BattleUtils.DoAction(this, chara, action, DamageTakenType.Weaponskill);
}
}
this.DelTP(skill.tpCost);
//Do procs reset on weaponskills?
ResetProcs();
lua.LuaEngine.GetInstance().OnSignal("weaponskillUsed");
}
public virtual void OnAbility(State state, BattleAction[] actions, ref BattleAction[] errors)
public virtual void OnAbility(State state, BattleAction[] actions, BattleCommand ability, ref BattleAction[] errors)
{
if (target is BattleNpc)
((BattleNpc)target).lastAttacker = this;
foreach (var action in actions)
zone.FindActorInArea<BattleNpc>(action.targetId)?.OnDamageTaken(this, action, DamageTakenType.Ability);
{
if (zone.FindActorInArea<Character>(action.targetId) is Character chara)
{
BattleUtils.DoAction(this, chara, action, DamageTakenType.Ability);
}
}
}
public virtual void OnSpawn()
@ -810,6 +833,97 @@ namespace FFXIVClassic_Map_Server.Actors
}
#endregion lua helpers
#endregion ai stuff
}
}
//Reset procs. Only send packet if any procs were actually reset.
//This assumes you can't use weaponskills between getting a proc and using the procced ability
public void ResetProcs()
{
var propPacketUtil = new ActorPropertyPacketUtil("charaWork/timingCommand", this);
bool shouldSend = false;
for (int i = 0; i < 4; i++)
{
if (charaWork.battleTemp.timingCommandFlag[i])
{
shouldSend = true;
charaWork.battleTemp.timingCommandFlag[i] = false;
propPacketUtil.AddProperty($"charaWork.battleTemp.timingCommandFlag[{i}]");
}
}
if (shouldSend && this is Player player)
player.QueuePackets(propPacketUtil.Done());
}
//Set given proc to true and send packet if this is a player
// todo: hidden status effects for timing when the procs fall off
public void SetProc(int procId, bool val = true)
{
charaWork.battleTemp.timingCommandFlag[procId] = val;
uint effectId = (uint)StatusEffectId.EvadeProc + (uint)procId;
//If a proc just occurred, add a hidden effect effect
if (val)
{
StatusEffect procEffect = Server.GetWorldManager().GetStatusEffect(effectId);
procEffect.SetDuration(5000);
statusEffects.AddStatusEffect(procEffect, this, true, true);
string procFunc = "";
//is there any reason we need this
switch(procId)
{
case (0):
procFunc = "onEvade";
break;
case (1):
procFunc = "onBlock";
break;
case (2):
procFunc = "onParry";
break;
case (3):
procFunc = "onMiss";
break;
}
//lua.LuaEngine.CallLuaBattleFunction(this, procFunc, this);
}
//Otherwise we're reseting a proc, remove the status
else
{
statusEffects.RemoveStatusEffect(statusEffects.GetStatusEffectById((uint)effectId));
}
if (this is Player player)
{
var propPacketUtil = new ActorPropertyPacketUtil("charaWork/timingCommand", this);
propPacketUtil.AddProperty($"charaWork.battleTemp.timingCommandFlag[{procId}]");
player.QueuePackets(propPacketUtil.Done());
}
}
public HitDirection GetHitDirection(Actor target)
{
//Get between taget's position and our position
double angle = Vector3.GetAngle(target.GetPosAsVector3(), GetPosAsVector3());
//Add to the target's rotation, mod by 2pi. This is the angle relative to where the target is looking
//Actor's rotation is 0 degrees on their left side, rotate it by 45 degrees so that quadrants line up with sides
angle = (angle + target.rotation - (.25 * Math.PI)) % (2 * Math.PI);
//Make positive
if (angle < 0)
angle = angle + (2 * Math.PI);
//Get the side we're on. 0 is front, 1 is right, 2 is rear, 3 is left
var side = (int) (angle / (.5 * Math.PI)) % 4;
return (HitDirection) (1 << side);
}
//Called when this character evades attacker's action
public void OnEvade(Character attacker, BattleAction action)
{
}
}
}

View file

@ -8,51 +8,58 @@ namespace FFXIVClassic_Map_Server.actors.chara
{
enum Modifier : UInt32
{
None = 0,
Hp = 1,
HpPercent = 2,
Mp = 3,
MpPercent = 4,
Tp = 5,
TpPercent = 6,
Regen = 7,
Refresh = 8,
Strength = 9,
Vitality = 10,
Dexterity = 11,
Intelligence = 12,
Mind = 13,
Piety = 14,
Attack = 15,
Accuracy = 16,
Defense = 17,
Evasion = 18,
MagicAttack = 19,
MagicHeal = 20, // is this needed? shouldnt it just be calc'd from mind
MagicAccuracy = 21,
MagicEvasion = 22,
MagicDefense = 23,
MagicEnhancePotency = 24,
MagicEnfeeblingPotency = 25,
ResistFire = 26,
ResistIce = 27,
ResistWind = 28,
ResistLightning = 29,
ResistEarth = 30,
ResistWater = 31, // <3 u jorge
AttackRange = 32,
Speed = 33,
AttackDelay = 34,
CraftProcessing = 35,
CraftMagicProcessing = 36,
CraftProcessControl = 37,
None = 0,
Hp = 1,
HpPercent = 2,
Mp = 3,
MpPercent = 4,
Tp = 5,
TpPercent = 6,
Regen = 7,
Refresh = 8,
Strength = 9,
Vitality = 10,
Dexterity = 11,
Intelligence = 12,
Mind = 13,
Piety = 14,
Attack = 15,
Accuracy = 16,
Defense = 17,
Evasion = 18,
MagicAttack = 19,
MagicHeal = 20, // is this needed? shouldnt it just be calc'd from mind
MagicAccuracy = 21,
MagicEvasion = 22,
MagicDefense = 23,
MagicEnhancePotency = 24,
MagicEnfeeblingPotency = 25,
ResistFire = 26,
ResistIce = 27,
ResistWind = 28,
ResistLightning = 29,
ResistEarth = 30,
ResistWater = 31, // <3 u jorge
AttackRange = 32,
Speed = 33,
AttackDelay = 34,
HarvestPotency = 38,
HarvestLimit = 39,
HarvestRate = 40,
CraftProcessing = 35,
CraftMagicProcessing = 36,
CraftProcessControl = 37,
Raise = 41,
MinimumHpLock = 42, // hp cannot fall below this value
HarvestPotency = 38,
HarvestLimit = 39,
HarvestRate = 40,
Raise = 41,
MinimumHpLock = 42, // hp cannot fall below this value
AttackType = 43, // slashing, piercing, etc
BlockRate = 44,
Block = 45,
CritRating = 46,
HasShield = 47, // Need this because shields are required for blocks. Could have used BlockRate or Block but BlockRate is provided by Gallant Sollerets and Block is provided by some buffs.
HitCount = 48 // Amount of hits in an auto attack. Usually 1, 2 for h2h, 3 with spinning heel
}
}

View file

@ -35,9 +35,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
actionQueue = new ActionQueue(owner);
}
public void UpdateLastActionTime()
public void UpdateLastActionTime(uint delay = 0)
{
lastActionTime = DateTime.Now;
lastActionTime = DateTime.Now.AddSeconds(delay);
}
public DateTime GetLastActionTime()
@ -62,6 +62,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
controller.Update(tick);
State top;
while (states.Count > 0 && (top = states.Peek()).Update(tick))
{
if (top == GetCurrentState())
@ -330,7 +331,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
{
if (CanChangeState())
{
ChangeState(new AbilityState(owner, target, (ushort)abilityId));
}
}

View file

@ -8,6 +8,7 @@ using FFXIVClassic_Map_Server.actors.chara.player;
using FFXIVClassic.Common;
using FFXIVClassic_Map_Server.packets.send.actor;
using FFXIVClassic_Map_Server.actors.chara.ai.utils;
using MoonSharp.Interpreter;
namespace FFXIVClassic_Map_Server.actors.chara.ai
{
@ -38,10 +39,10 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
public enum BattleCommandProcRequirement : byte
{
None,
Evade = 0x01,
Block = 0x02,
Parry = 0x04,
Miss = 0x08
Miss,
Evade,
Parry,
Block
}
public enum BattleCommandValidUser : byte
@ -51,6 +52,16 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
Monster
}
public enum BattleCommandCastType : ushort
{
None,
Weaponskill = 1,
Weaponskill2 = 2,
BlackMagic = 3,
WhiteMagic = 4,
SongMagic = 8
}
class BattleCommand
{
public ushort id;
@ -58,28 +69,41 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
public byte job;
public byte level;
public BattleCommandRequirements requirements;
public ValidTarget validTarget;
public TargetFindAOEType aoeType;
public TargetFindAOETarget aoeTarget;
public byte numHits;
public BattleCommandPositionBonus positionBonus;
public BattleCommandProcRequirement procRequirement;
public int range;
public uint debuffDurationSeconds;
public uint buffDurationSeconds;
public byte castType;
public uint castTimeSeconds;
public uint recastTimeSeconds;
public ValidTarget mainTarget; //what the skill has to be used on. ie self for flare, enemy for ring of talons even though both are self-centere aoe
public ValidTarget validTarget; //what type of character the skill can hit
public TargetFindAOEType aoeType; //shape of aoe
public TargetFindAOETarget aoeTarget; //where the center of the aoe is (target/self)
public byte numHits; //amount of hits in the skill
public BattleCommandPositionBonus positionBonus; //bonus for front/flank/rear
public BattleCommandProcRequirement procRequirement;//if the skill requires a block/parry/evade before using
public int range; //max distance to use skill
public uint statusId; //id of statuseffect that the skill might inflict
public uint statusDuration; //duration of statuseffect in milliseconds
public float statusChance; //percent chance of status landing, 0-1.0. Usually 1.0 for buffs
public byte castType; //casting animation, 2 for blm, 3 for whm, 8 for brd
public uint castTimeMs; //cast time in milliseconds
public uint recastTimeMs; //recast time in milliseconds
public uint maxRecastTimeSeconds; //maximum recast time in seconds
public ushort mpCost;
public ushort tpCost;
public byte animationType;
public ushort effectAnimation;
public ushort modelAnimation;
public ushort animationDurationSeconds;
public uint battleAnimation;
public ushort worldMasterTextId;
public int aoeRange;
public int aoeRange; //size of aoe effect. (how will this work for box aoes?)
public int[] comboNextCommandId = new int[2]; //next two skills in a combo
public short comboStep; //Where in a combo string this skill is
public byte statusTier; //tief of status to put on target
public ushort basePotency; //damage variable
public float enmityModifier; //multiples by damage done to get final enmity
public float accuracyModifier; //modifies accuracy
public bool isCombo;
public lua.LuaScript script; //cached script
public TargetFind targetFind;
public BattleCommandValidUser validUser;
@ -89,6 +113,12 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
this.id = id;
this.name = name;
this.range = 0;
this.enmityModifier = 1;
this.accuracyModifier = 1;
this.statusTier = 1;
this.statusChance = 50;
this.recastTimeMs = (uint) maxRecastTimeSeconds * 1000;
this.isCombo = false;
}
public BattleCommand Clone()
@ -96,17 +126,31 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
return (BattleCommand)MemberwiseClone();
}
public int CallLuaFunction(Character chara, string functionName, params object[] args)
{
if (script != null && !script.Globals.Get(functionName).IsNil())
{
DynValue res = new DynValue();
res = script.Call(script.Globals.Get(functionName), args);
if (res != null)
return (int)res.Number;
}
return -1;
}
public bool IsSpell()
{
return mpCost != 0 || castTimeSeconds != 0;
return mpCost != 0 || castTimeMs != 0;
}
public bool IsInstantCast()
{
return castTimeSeconds == 0;
return castTimeMs == 0;
}
public bool IsValidTarget(Character user, Character target)
//Checks whether the skill can be used on the given target
public bool IsValidMainTarget(Character user, Character target)
{
targetFind = new TargetFind(user);
@ -122,7 +166,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
/*
worldMasterTextId
32512 cannot be performed on a KO'd target.
32512 cannot be performed on a KO'd target.
32513 can only be performed on a KO'd target.
32514 cannot be performed on yourself.
32515 can only be performed on yourself.
@ -130,24 +174,36 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
32517 can only be performed on a friendly target.
32518 cannot be performed on an enemy.
32519 can only be performed on an enemy,
32556 unable to execute [weaponskill]. Conditions for use are not met.
*/
// cant target dead
if ((validTarget & (ValidTarget.Corpse | ValidTarget.CorpseOnly)) == 0 && target.IsDead())
if ((mainTarget & (ValidTarget.Corpse | ValidTarget.CorpseOnly)) == 0 && target.IsDead())
{
// cannot be perfomed on
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32512, 0x20, (uint)id);
return false;
}
if (level > user.charaWork.parameterSave.state_mainSkillLevel)
//level too high
if (level > user.GetLevel())
{
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32527, 0x20, (uint)id);
return false;
}
if (tpCost > user.GetTP())
//Proc requirement
if (procRequirement != BattleCommandProcRequirement.None && !user.charaWork.battleTemp.timingCommandFlag[(int) procRequirement - 1])
{
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32556, 0x20, (uint)id);
return false;
}
//costs too much tp
if (CalculateTpCost(user) > user.GetTP())
{
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32546, 0x20, (uint)id);
@ -155,7 +211,6 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
}
// todo: calculate cost based on modifiers also (probably in BattleUtils)
if (BattleUtils.CalculateSpellCost(user, target, this) > user.GetMP())
{
if (user is Player)
@ -175,8 +230,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
}
}
// todo: i dont care to message for each scenario, just the most common ones..
if ((validTarget & ValidTarget.CorpseOnly) != 0)
if ((mainTarget & ValidTarget.CorpseOnly) != 0)
{
if (target != null && target.IsAlive())
{
@ -186,7 +242,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
}
}
if ((validTarget & ValidTarget.Enemy) != 0)
if ((mainTarget & ValidTarget.Enemy) != 0)
{
if (target == user || target != null &&
user.allegiance == target.allegiance)
@ -197,21 +253,43 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
}
}
if ((validTarget & (ValidTarget.PartyMember | ValidTarget.Player | ValidTarget.Ally)) != 0)
if ((mainTarget & ValidTarget.Ally) != 0)
{
if (target == null || target.allegiance != user.allegiance)
{
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32516, 0x20, (uint)id);
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32517, 0x20, (uint)id);
return false;
}
}
return targetFind.CanTarget(target, true, true, true);
if ((mainTarget & ValidTarget.PartyMember) != 0)
{
if (target == null || target.currentParty != user.currentParty)
{
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32547, 0x20, (uint)id);
return false;
}
}
if ((mainTarget & ValidTarget.Player) != 0)
{
if (!(target is Player))
{
if (user is Player)
((Player)user).SendGameMessage(Server.GetWorldManager().GetActor(), 32517, 0x20, (uint)id);
return false;
}
}
return true;// targetFind.CanTarget(target, true, true, true); //this will be done later
}
public ushort CalculateCost(uint level)
public ushort CalculateMpCost(Character user)
{
// todo: use precalculated costs instead
var level = user.GetLevel();
ushort cost = 0;
if (level <= 10)
cost = (ushort)(100 + level * 10);
@ -230,15 +308,59 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
else
cost = (ushort)(8000 + (level - 70) * 500);
if (mpCost != 0)
return (ushort)Math.Ceiling((cost * mpCost * 0.001));
//scale the mpcost by level
cost = (ushort)Math.Ceiling((cost * mpCost * 0.001));
return mpCost != 0 ? (ushort)Math.Ceiling((cost * mpCost * 0.001)) : (ushort)0;
//if user is player, check if spell is a part of combo
if (user is Player)
{
var player = user as Player;
if (player.playerWork.comboNextCommandId[0] == id || player.playerWork.comboNextCommandId[1] == id)
cost = (ushort)Math.Ceiling(cost * (1 - player.playerWork.comboCostBonusRate));
}
return mpCost != 0 ? cost : (ushort)0;
}
//Calculate TP cost taking into considerating the combo bonus rate for players
//Should this set tpCost or should it be called like CalculateMp where it gets calculated each time?
//Might cause issues with the delay between starting and finishing a WS
public ushort CalculateTpCost(Character user)
{
ushort tp = tpCost;
//Calculate tp cost
if (user is Player)
{
var player = user as Player;
if (player.playerWork.comboNextCommandId[0] == id || player.playerWork.comboNextCommandId[1] == id)
tp = (ushort)Math.Ceiling((float)tpCost * (1 - player.playerWork.comboCostBonusRate));
}
return tp;
}
public List<Character> GetTargets()
{
return targetFind?.GetTargets<Character>();
}
//Handles setting the correct target for self-targeted spells
public Character GetMainTarget(Character caster, Character target)
{
//If skill can only be used on self
if (mainTarget == ValidTarget.Self)
return caster;
//If skill can only be used on party members and the target is not a party member
else if (((mainTarget & ValidTarget.PartyMember) != 0) && (target.currentParty != caster.currentParty))
return caster;
//If skill can only be used on allys and the target is not an ally
else if (((mainTarget & ValidTarget.Ally) != 0) && (target.allegiance != caster.allegiance))
return caster;
//If skill can only be used on players and the target is not a player
else if (((mainTarget & ValidTarget.Player) != 0) && (!(target is Player)))
return caster;
return target;
}
}
}

View file

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MoonSharp.Interpreter;
namespace FFXIVClassic_Map_Server.actors.chara.ai
{
@ -322,24 +323,50 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
// custom effects here
// status for having procs fall off
EvadeProc = 253003,
BlockProc = 253004,
ParryProc = 253005,
MissProc = 253006
}
[Flags]
enum StatusEffectFlags : uint
{
None = 0x00,
Silent = 0x01, // dont display effect loss message
LoseOnDeath = 0x02, // effects removed on death
LoseOnZoning = 0x04, // effects removed on zoning
LoseOnEsuna = 0x08, // effects which can be removed with esuna (debuffs)
LoseOnDispel = 0x10, // some buffs which player might be able to dispel from mob
LoseOnLogout = 0x20, // effects removed on logging out
LoseOnAttacking = 0x40, // effects removed when owner attacks another entity
LoseOnCasting = 0x80, // effects removed when owner starts casting
LoseOnDamageTaken = 0x100, // effects removed when owner takes damage
None = 0,
Silent = 1 << 0, // dont display effect loss message
PreventAction = 0x200, // effects which prevent actions such as sleep/paralyze/petrify
Stealth = 0x400, // sneak/invis
//Loss flags
LoseOnDeath = 1 << 1, // effects removed on death
LoseOnZoning = 1 << 2, // effects removed on zoning
LoseOnEsuna = 1 << 3, // effects which can be removed with esuna (debuffs)
LoseOnDispel = 1 << 4, // some buffs which player might be able to dispel from mob
LoseOnLogout = 1 << 5, // effects removed on logging out
LoseOnAttacking = 1 << 6, // effects removed when owner attacks another entity
LoseOnCasting = 1 << 7, // effects removed when owner starts casting
LoseOnDamageTaken = 1 << 8, // effects removed when owner takes damage
LoseOnParry = 1 << 9, // effects removed when owner parries an attack (foresight)
LoseOnEvade = 1 << 10, // effects removed when owner evades an attack (decoy)
LoseOnCrit = 1 << 11, // effects removed when owner deals a critical hit (excruciate)
LoseOnAggro = 1 << 12, // effects removed when owner gains enmity (swiftsong)
//Activate flags, do we need the LoseOn flags if we have these? could just remove itself in the activate function
ActivateOnAttack = 1 << 13,
ActivateOnSpell = 1 << 14,
ActivateOnDamageTaken = 1 << 15,
ActivateOnBlock = 1 << 16,
ActivateOnMiss = 1 << 17,
//Prevent flags. Sleep/stun/petrify/etc combine these
PreventSpell= 1 << 18, // effects which prevent using spells, such as silence
PreventWeaponSkill = 1 << 19, // effects which prevent using weaponskills, such as pacification
PreventAbility = 1 << 20, // effects which prevent using abilities, such as amnesia
PreventAttack = 1 << 21, // effects which prevent basic attacks
PreventMovement = 1 << 22, // effects which prevent movement such as bind, still allows turning in place
PreventTurn = 1 << 23, // effects which prevent turning such as fixation, still allows movement and actions
Stealth = 1 << 24, // sneak/invis
Stance = 1 << 25, // effects that do not have a timer
}
enum StatusEffectOverwrite : byte
@ -360,7 +387,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
private string name; // name of this effect
private DateTime startTime; // when was this effect added
private DateTime lastTick; // when did this effect last tick
private uint durationMs; // how long should this effect last in ms
private uint duration; // how long should this effect last in seconds
private uint tickMs; // how often should this effect proc
private UInt64 magnitude; // a value specified by scripter which is guaranteed to be used by all effects
private byte tier; // same effect with higher tier overwrites this
@ -368,17 +395,19 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
private StatusEffectFlags flags; // death/erase/dispel etc
private StatusEffectOverwrite overwrite; // how to handle adding an effect with same id (see StatusEfectOverwrite)
private bool silent = false; // do i send a message on losing effect
private bool hidden = false;
public LuaScript script;
HitEffect animationEffect;
public StatusEffect(Character owner, uint id, UInt64 magnitude, uint tickMs, uint durationMs, byte tier = 0)
public StatusEffect(Character owner, uint id, UInt64 magnitude, uint tickMs, uint duration, byte tier = 0)
{
this.owner = owner;
this.source = owner;
this.id = (StatusEffectId)id;
this.magnitude = magnitude;
this.tickMs = tickMs;
this.durationMs = durationMs;
this.duration = duration;
this.tier = tier;
this.startTime = DateTime.Now;
@ -392,7 +421,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
this.id = effect.id;
this.magnitude = effect.magnitude;
this.tickMs = effect.tickMs;
this.durationMs = effect.durationMs;
this.duration = effect.duration;
this.tier = effect.tier;
this.startTime = effect.startTime;
this.lastTick = effect.lastTick;
@ -401,14 +430,16 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
this.flags = effect.flags;
this.overwrite = effect.overwrite;
this.extra = effect.extra;
this.script = effect.script;
}
public StatusEffect(uint id, string name, uint flags, uint overwrite)
public StatusEffect(uint id, string name, uint flags, uint overwrite, uint tickMs)
{
this.id = (StatusEffectId)id;
this.name = name;
this.flags = (StatusEffectFlags)flags;
this.overwrite = (StatusEffectOverwrite)overwrite;
this.tickMs = tickMs;
}
// return true when duration has elapsed
@ -420,13 +451,28 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
LuaEngine.CallLuaStatusEffectFunction(this.owner, this, "onTick", this.owner, this);
}
if (durationMs != 0 && (tick - startTime).TotalMilliseconds >= durationMs)
if (duration != 0xFFFFFFFF && (tick - startTime).TotalSeconds >= duration)
{
return true;
}
return false;
}
public int CallLuaFunction(Character chara, string functionName, params object[] args)
{
DynValue res = new DynValue();
if (!script.Globals.Get(functionName).IsNil())
{
res = script.Call(script.Globals.Get(functionName), args);
if (res != null)
return (int)res.Number;
}
return -1;
}
public Character GetOwner()
{
return owner;
@ -457,9 +503,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
return name;
}
public uint GetDurationMs()
public uint GetDuration()
{
return durationMs;
return duration;
}
public uint GetTickMs()
@ -497,6 +543,11 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
return silent;
}
public bool GetHidden()
{
return hidden;
}
public void SetStartTime(DateTime time)
{
this.startTime = time;
@ -523,9 +574,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
this.magnitude = magnitude;
}
public void SetDurationMs(uint durationMs)
public void SetDuration(uint duration)
{
this.durationMs = durationMs;
this.duration = duration;
}
public void SetTickMs(uint tickMs)
@ -558,6 +609,11 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
this.silent = silent;
}
public void SetHidden(bool hidden)
{
this.hidden = hidden;
}
public void SetAnimation(uint hitEffect)
{
animationEffect = (HitEffect)hitEffect;

View file

@ -9,6 +9,7 @@ using FFXIVClassic_Map_Server.lua;
using FFXIVClassic_Map_Server.actors.area;
using FFXIVClassic_Map_Server.packets.send;
using FFXIVClassic_Map_Server.packets.send.actor;
using FFXIVClassic_Map_Server.packets.send.actor.battle;
using System.Collections.ObjectModel;
using FFXIVClassic_Map_Server.utils;
@ -61,32 +62,47 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
return effects.ContainsKey((uint)id);
}
public bool AddStatusEffect(uint id, UInt64 magnitude, double tickMs, double durationMs, byte tier = 0)
public bool AddStatusEffect(uint id, UInt64 magnitude, uint tickMs, uint duration, byte tier = 0)
{
return AddStatusEffect(new StatusEffect(this.owner, id, magnitude, (uint)(tickMs * 1000), (uint)(durationMs * 1000), tier), owner);
var se = Server.GetWorldManager().GetStatusEffect(id);
if (se != null)
{
se.SetDuration(duration);
se.SetStartTime(DateTime.Now);
se.SetOwner(owner);
}
return AddStatusEffect(se ?? new StatusEffect(this.owner, id, magnitude, tickMs, duration, tier), owner);
}
public bool AddStatusEffect(StatusEffect newEffect, Character source, bool silent = false)
public bool AddStatusEffect(StatusEffect newEffect, Character source, bool silent = false, bool hidden = false)
{
/*
worldMasterTextId
32001 [@2B([@IF($E4($EB(1),$EB(2)),you,[@IF($E9(7),[@SHEETEN(xtx/displayName,2,$E9(7),1,1)],$EB(2))])])] [@IF($E4($EB(1),$EB(2)),resist,resists)] the effect of [@SHEET(xtx/status,$E8(11),3)].
32002 [@SHEET(xtx/status,$E8(11),3)] fails to take effect.
*/
if (HasStatusEffect(newEffect.GetStatusEffectId()) && (newEffect.GetFlags() & (uint)StatusEffectFlags.Stance) != 0)
{
RemoveStatusEffect(newEffect);
return false;
}
var effect = GetStatusEffectById(newEffect.GetStatusEffectId());
bool canOverwrite = false;
if (effect != null)
{
var overwritable = effect.GetOverwritable();
canOverwrite = (overwritable == (uint)StatusEffectOverwrite.Always) ||
(overwritable == (uint)StatusEffectOverwrite.GreaterOnly && (effect.GetDurationMs() < newEffect.GetDurationMs() || effect.GetMagnitude() < newEffect.GetMagnitude())) ||
(overwritable == (uint)StatusEffectOverwrite.GreaterOrEqualTo && (effect.GetDurationMs() <= newEffect.GetDurationMs() || effect.GetMagnitude() <= newEffect.GetMagnitude()));
(overwritable == (uint)StatusEffectOverwrite.GreaterOnly && (effect.GetDuration() < newEffect.GetDuration() || effect.GetMagnitude() < newEffect.GetMagnitude())) ||
(overwritable == (uint)StatusEffectOverwrite.GreaterOrEqualTo && (effect.GetDuration() <= newEffect.GetDuration() || effect.GetMagnitude() <= newEffect.GetMagnitude()));
}
if (canOverwrite || effect == null)
{
// send packet to client with effect added message
if (!silent || !effect.GetSilent() || (effect.GetFlags() & (uint)StatusEffectFlags.Silent) == 0)
if (effect != null && (!silent || !effect.GetSilent() || (effect.GetFlags() & (uint)StatusEffectFlags.Silent) == 0))
{
// todo: send packet to client with effect added message
}
@ -95,16 +111,36 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
if (canOverwrite)
effects.Remove(newEffect.GetStatusEffectId());
newEffect.SetStartTime(DateTime.Now);
newEffect.SetOwner(owner);
if (effects.Count < MAX_EFFECTS)
{
if(newEffect.script != null)
newEffect.CallLuaFunction(this.owner, "onGain", this.owner, newEffect);
else
LuaEngine.CallLuaStatusEffectFunction(this.owner, newEffect, "onGain", this.owner, newEffect);
effects.Add(newEffect.GetStatusEffectId(), newEffect);
newEffect.SetSilent(silent);
newEffect.SetHidden(hidden);
if (!newEffect.GetHidden())
{
var index = Array.IndexOf(effects.Values.ToArray(), newEffect);
int index = 0;
if (owner.charaWork.status.Contains(newEffect.GetStatusId()))
index = Array.IndexOf(owner.charaWork.status, newEffect.GetStatusId());
else
index = Array.IndexOf(owner.charaWork.status, (ushort) 0);
owner.charaWork.status[index] = newEffect.GetStatusId();
owner.charaWork.statusShownTime[index] = Utils.UnixTimeStampUTC() + (newEffect.GetDurationMs() / 1000);
//Stance statuses need their time set to an extremely high number so their icon doesn't flash
//Adding getduration with them doesn't work because it overflows
uint time = (newEffect.GetFlags() & (uint) StatusEffectFlags.Stance) == 0 ? Utils.UnixTimeStampUTC() + (newEffect.GetDuration()) : 0xFFFFFFFF;
owner.charaWork.statusShownTime[index] = time;
this.owner.zone.BroadcastPacketAroundActor(this.owner, SetActorStatusPacket.BuildPacket(this.owner.actorId, (ushort)index, (ushort)newEffect.GetStatusId()));
}
{
owner.zone.BroadcastPacketsAroundActor(owner, owner.GetActorStatusPackets());
}
@ -117,24 +153,29 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
public void RemoveStatusEffect(StatusEffect effect, bool silent = false)
{
if (effects.ContainsKey(effect.GetStatusEffectId()))
if (effect != null && effects.ContainsKey(effect.GetStatusEffectId()) )
{
// send packet to client with effect remove message
if (!silent && !effect.GetSilent() || (effect.GetFlags() & (uint)StatusEffectFlags.Silent) == 0)
{
// todo: send packet to client with effect added message
}
//hidden effects not in charawork
if(!effect.GetHidden())
{
var index = Array.IndexOf(effects.Values.ToArray(), effect);
var index = Array.IndexOf(owner.charaWork.status, effect.GetStatusId());
owner.charaWork.status[index] = 0;
owner.charaWork.statusShownTime[index] = uint.MaxValue;
owner.charaWork.statusShownTime[index] = 0;
this.owner.zone.BroadcastPacketAroundActor(this.owner, SetActorStatusPacket.BuildPacket(owner.actorId, (ushort)index, (ushort)0));
}
// function onLose(actor, effect)
LuaEngine.CallLuaStatusEffectFunction(this.owner, effect, "onLose", this.owner, effect);
effects.Remove(effect.GetStatusEffectId());
if(effect.script != null)
effect.CallLuaFunction(owner, "onLose", owner, effect);
else
LuaEngine.CallLuaStatusEffectFunction(this.owner, effect, "onLose", this.owner, effect);
owner.RecalculateStats();
sendUpdate = true;
}

View file

@ -53,7 +53,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
}
//Only move if owner isn't dead and is either too far away from their spawn point or is meant to roam
else if (!owner.IsDead() && (owner.isMovingToSpawn || owner.GetMobMod((uint)MobModifier.Roams) > 0))
if (!owner.IsDead() && (owner.isMovingToSpawn || owner.GetMobMod((uint)MobModifier.Roams) > 0))
{
DoRoamTick(tick);
}
@ -83,8 +83,8 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
{
foreach (var chara in owner.zone.GetActorsAroundActor<Character>(owner, 50))
{
if (owner.allegiance == chara.allegiance)
continue;
if (chara.allegiance == owner.allegiance)
continue;
if (owner.aiContainer.pathFind.AtPoint() && owner.detectionType != DetectionType.None)
{
@ -119,8 +119,6 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
if (owner.GetState() != SetActorStatePacket.MAIN_STATE_ACTIVE)
owner.ChangeState(SetActorStatePacket.MAIN_STATE_ACTIVE);
owner.moveState = 2;
//owner.SetMod((uint)Modifier.Speed, 5);
lastActionTime = DateTime.Now;
battleStartTime = lastActionTime;
// todo: adjust cooldowns with modifiers
@ -138,7 +136,6 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
{
var target = owner.target;
base.Disengage();
owner.statusEffects.RemoveStatusEffectsByFlags((uint)StatusEffectFlags.LoseOnDeath, true);
// todo:
lastActionTime = lastUpdate.AddSeconds(5);
owner.isMovingToSpawn = true;
@ -213,13 +210,13 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
Disengage();
return;
}
Move();
if ((tick - lastCombatTickScript).TotalSeconds > 2)
owner.SetMod((uint)Modifier.Speed, 5);
if ((tick - lastCombatTickScript).TotalSeconds > 3)//Program.Random.Next(10, 15))
{
lua.LuaEngine.CallLuaBattleFunction(owner, "onCombatTick", owner, owner.target, Utils.UnixTimeStampUTC(tick), contentGroupCharas);
Move();
//if (owner.aiContainer.CanChangeState())
//owner.aiContainer.WeaponSkill(owner.zone.FindActorInArea<Character>(owner.target.actorId), 27155);
//lua.LuaEngine.CallLuaBattleFunction(owner, "onCombatTick", owner, owner.target, Utils.UnixTimeStampUTC(tick), contentGroupCharas);
lastCombatTickScript = tick;
}
}
@ -239,7 +236,6 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
var targetPos = new Vector3(owner.target.positionX, owner.target.positionY, owner.target.positionZ);
var distance = Utils.Distance(owner.positionX, owner.positionY, owner.positionZ, targetPos.X, targetPos.Y, targetPos.Z);
if (distance > owner.GetAttackRange() - 0.2f || owner.aiContainer.CanFollowPath())
{
if (CanMoveForward(distance))
@ -276,12 +272,13 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
{
FaceTarget();
}
lastRoamUpdate = DateTime.Now;
}
protected void FaceTarget()
{
// todo: check if stunned etc
if (owner.statusEffects.HasStatusEffectsByFlag(StatusEffectFlags.PreventAction))
if (owner.statusEffects.HasStatusEffectsByFlag(StatusEffectFlags.PreventTurn) )
{
}
else
@ -392,14 +389,17 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.controllers
public override void ChangeTarget(Character target)
{
owner.target = target;
owner.currentLockedTarget = target?.actorId ?? Actor.INVALID_ACTORID;
owner.currentTarget = target?.actorId ?? Actor.INVALID_ACTORID;
if (target != owner.target)
{
owner.target = target;
owner.currentLockedTarget = target?.actorId ?? Actor.INVALID_ACTORID;
owner.currentTarget = target?.actorId ?? Actor.INVALID_ACTORID;
foreach (var player in owner.zone.GetActorsAroundActor<Player>(owner, 50))
player.QueuePacket(owner.GetHateTypePacket(player));
foreach (var player in owner.zone.GetActorsAroundActor<Player>(owner, 50))
player.QueuePacket(owner.GetHateTypePacket(player));
base.ChangeTarget(target);
base.ChangeTarget(target);
}
}
}
}

View file

@ -177,61 +177,68 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
if (aoeType != TargetFindAOEType.None)
{
if (IsPlayer(owner))
{
if (masterTarget is Player)
{
findType = TargetFindCharacterType.PlayerToPlayer;
if (masterTarget.currentParty != null)
{
if ((validTarget & (ValidTarget.Ally | ValidTarget.PartyMember)) != 0)
AddAllInAlliance(masterTarget, withPet);
else
AddAllInParty(masterTarget, withPet);
}
else
{
AddTarget(masterTarget, withPet);
}
}
else
{
findType = TargetFindCharacterType.PlayerToBattleNpc;
AddAllBattleNpcs(masterTarget, false);
}
}
else
{
// todo: this needs checking..
if (masterTarget is Player || owner.allegiance == CharacterTargetingAllegiance.Player)
findType = TargetFindCharacterType.BattleNpcToPlayer;
else
findType = TargetFindCharacterType.BattleNpcToBattleNpc;
// todo: configurable pet aoe buff
if (findType == TargetFindCharacterType.BattleNpcToBattleNpc && TryGetMasterTarget(target) != null)
withPet = true;
// todo: does ffxiv have call for help flag?
//if ((findFlags & ValidTarget.HitAll) != 0)
//{
// AddAllInZone(masterTarget, withPet);
//}
AddAllInAlliance(target, withPet);
if (findType == TargetFindCharacterType.BattleNpcToPlayer)
{
if (owner.allegiance == CharacterTargetingAllegiance.Player)
AddAllInZone(masterTarget, withPet);
else
AddAllInHateList();
}
}
AddAllInRange(target, withPet);
}
if(targets.Count > 16)
targets.RemoveRange(16, targets.Count - 16);
/*
if (aoeType != TargetFindAOEType.None)
{
if (IsPlayer(owner))
{
if (masterTarget is Player)
{
findType = TargetFindCharacterType.PlayerToPlayer;
if (masterTarget.currentParty != null)
{
if ((validTarget & (ValidTarget.Ally | ValidTarget.PartyMember)) != 0)
AddAllInAlliance(masterTarget, withPet);
else
AddAllInParty(masterTarget, withPet);
}
else
{
AddTarget(masterTarget, withPet);
}
}
else
{
findType = TargetFindCharacterType.PlayerToBattleNpc;
AddAllBattleNpcs(masterTarget, false);
}
}
else
{
// todo: this needs checking..
if (masterTarget is Player || owner.allegiance == CharacterTargetingAllegiance.Player)
findType = TargetFindCharacterType.BattleNpcToPlayer;
else
findType = TargetFindCharacterType.BattleNpcToBattleNpc;
// todo: configurable pet aoe buff
if (findType == TargetFindCharacterType.BattleNpcToBattleNpc && TryGetMasterTarget(target) != null)
withPet = true;
// todo: does ffxiv have call for help flag?
//if ((findFlags & ValidTarget.HitAll) != 0)
//{
// AddAllInZone(masterTarget, withPet);
//}
AddAllInAlliance(target, withPet);
if (findType == TargetFindCharacterType.BattleNpcToPlayer)
{
if (owner.allegiance == CharacterTargetingAllegiance.Player)
AddAllInZone(masterTarget, withPet);
else
AddAllInHateList();
}
}
}*/
if (targets.Count > 16)
targets.RemoveRange(16, targets.Count - 16);
}
/// <summary>
@ -311,6 +318,18 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
}
}
private void AddAllInRange(Character target, bool withPet)
{
int dist = (int)maxDistance;
var actors = owner.zone.GetActorsAroundActor<Character>(target, dist);
foreach (Character actor in actors)
{
AddTarget(actor, false);
}
}
private void AddAllInHateList()
{
if (!(owner is BattleNpc))
@ -342,6 +361,12 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai
if ((validTarget & ValidTarget.Enemy) != 0 && target.allegiance == owner.allegiance)
return false;
if ((validTarget & ValidTarget.PartyMember) == 0 && target.currentParty == owner.currentParty)
return false;
if ((validTarget & ValidTarget.PartyMember) != 0 && target.currentParty != owner.currentParty)
return false;
if ((validTarget & ValidTarget.NPC) != 0 && target.isStatic)
return false;

View file

@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FFXIVClassic.Common;
using FFXIVClassic_Map_Server.Actors;
using FFXIVClassic_Map_Server.packets.send.actor;
using FFXIVClassic_Map_Server.packets.send.actor.battle;
using FFXIVClassic_Map_Server.packets.send;
namespace FFXIVClassic_Map_Server.actors.chara.ai.state
{
class AbilityState : State
{
private BattleCommand skill;
public AbilityState(Character owner, Character target, ushort skillId) :
base(owner, target)
{
this.startTime = DateTime.Now;
this.skill = Server.GetWorldManager().GetBattleCommand(skillId);
var returnCode = lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "ability", "onAbilityPrepare", owner, target, skill);
this.target = skill.GetMainTarget(owner, target);
if (returnCode == 0)
{
OnStart();
}
else
{
errorResult = null;
interrupt = true;
}
}
public override void OnStart()
{
var returnCode = lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "ability", "onAbilityStart", owner, target, skill);
if (returnCode != 0)
{
interrupt = true;
errorResult = new BattleAction(owner.actorId, (ushort)(returnCode == -1 ? 32558 : returnCode), 0);
}
else
{
//owner.LookAt(target);
//If owner already has this status effect and it's a stance that gets removed on reuse, remove it and don't continue
var effect = owner.statusEffects.GetStatusEffectById(skill.statusId);
if (effect!= null && (effect.GetFlags() & (uint) StatusEffectFlags.Stance) != 0)
{
owner.statusEffects.RemoveStatusEffect(effect);
interrupt = true;
}
}
}
public override bool Update(DateTime tick)
{
if (skill != null)
{
TryInterrupt();
if (interrupt)
{
OnInterrupt();
return true;
}
// todo: check weapon delay/haste etc and use that
var actualCastTime = skill.castTimeMs;
if ((tick - startTime).Milliseconds >= skill.castTimeMs)
{
OnComplete();
return true;
}
return false;
}
return true;
}
public override void OnInterrupt()
{
// todo: send paralyzed/sleep message etc.
if (errorResult != null)
{
owner.DoBattleAction(skill.id, errorResult.animation, errorResult);
errorResult = null;
}
}
public override void OnComplete()
{
bool hitTarget = false;
skill.targetFind.FindWithinArea(target, skill.validTarget, skill.aoeTarget);
isCompleted = true;
var targets = skill.targetFind.GetTargets();
List<BattleAction> actions = new List<BattleAction>();
List<StatusEffect> effects = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.ActivateOnAttack);
foreach (var chara in targets)
{
for (int hitNum = 0; hitNum < skill.numHits; hitNum++)
{
//30328 - Your [ability] grants you the effect of [status]
//30320 - You use [ability]. You recover x HP.
var action = new BattleAction(chara.actorId, skill.worldMasterTextId, 0, 0, 1, 1);
//uncached
lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "ability", "onAbilityFinish", owner, target, skill, action);
//cached
//skill.CallLuaFunction(owner, "onAbilityFinish", owner, target, skill, action);
//if hit type isn't evade or miss
if (((action.hitType & HitType.Evade) | (action.hitType & HitType.Miss)) == 0)
hitTarget = true;
actions.AddRange(action.GetAllActions());
}
}
// todo: this is fuckin stupid, probably only need *one* error packet, not an error for each action
BattleAction[] errors = (BattleAction[])actions.ToArray().Clone();
owner.OnAbility(this, actions.ToArray(), skill, ref errors);
owner.DoBattleAction(skill.id, skill.battleAnimation, actions);
}
public override void TryInterrupt()
{
if (interrupt)
return;
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventAbility))
{
// todo: sometimes paralyze can let you attack, get random percentage of actually letting you attack
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventAbility);
uint effectId = 0;
if (list.Count > 0)
{
// todo: actually check proc rate/random chance of whatever effect
effectId = list[0].GetStatusEffectId();
}
interrupt = true;
return;
}
interrupt = !CanUse();
}
private bool CanUse()
{
return skill.IsValidMainTarget(owner, target);
}
public BattleCommand GetWeaponSkill()
{
return skill;
}
public override void Cleanup()
{
owner.aiContainer.UpdateLastActionTime(skill.animationDurationSeconds);
}
}
}

View file

@ -82,7 +82,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
public override void OnComplete()
{
BattleAction action = new BattleAction(target.actorId, 0x765D, (uint) HitEffect.Hit, 0, (byte) HitDirection.None);
//BattleAction action = new BattleAction(target.actorId, 0x765D, (uint) HitEffect.Hit, 0, (byte) HitDirection.None);
errorResult = null;
// todo: implement auto attack damage bonus in Character.OnAttack
@ -99,16 +99,35 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
* The above damage bonus also applies to Shot attacks by archers.
*/
// handle paralyze/intimidate/sleep/whatever in Character.OnAttack
owner.OnAttack(this, action, ref errorResult);
owner.DoBattleAction((ushort)BattleActionX01PacketCommand.Attack, action.animation, errorResult == null ? action : errorResult);
List<BattleAction> actions = new List<BattleAction>();
var i = 0;
for (int hitNum = 0; hitNum < owner.GetMod((uint) Modifier.HitCount); hitNum++)
{
BattleAction action = new BattleAction(target.actorId, 0x765D, (uint)HitEffect.Hit, 100, (byte)HitDirection.None, (byte) hitNum);
action.battleActionType = BattleActionType.AttackPhysical;
// evasion, miss, dodge, etc to be handled in script, calling helpers from scripts/weaponskills.lua
// temporary evade/miss/etc function to test hit effects
utils.BattleUtils.CalcHitType(owner, target, null, action);
actions.AddRange(action.GetAllActions());
}
// todo: this is fuckin stupid, probably only need *one* error packet, not an error for each action
BattleAction[] errors = (BattleAction[])actions.ToArray().Clone();
owner.OnAttack(this, actions[0], ref errorResult);
owner.DoBattleAction(22104, 0x19001000, actions);
target.SetMod((uint) Modifier.MinimumHpLock, 0);
}
public override void TryInterrupt()
{
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventAction))
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventAttack))
{
// todo: sometimes paralyze can let you attack, calculate proc rate
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventAction);
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventAttack);
uint statusId = 0;
if (list.Count > 0)
{
@ -124,7 +143,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
private bool IsAttackReady()
{
// todo: this enforced delay should really be changed if it's not retail..
return Program.Tick >= attackTime && Program.Tick >= owner.aiContainer.GetLastActionTime().AddSeconds(1);
return Program.Tick >= attackTime && Program.Tick >= owner.aiContainer.GetLastActionTime();
}
private bool CanAttack()

View file

@ -15,9 +15,10 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
: base(owner, null)
{
owner.Disengage();
//owner.ChangeState(SetActorStatePacket.MAIN_STATE_DEAD);
var deathStatePacket = SetActorStatePacket.BuildPacket(owner.actorId, SetActorStatePacket.MAIN_STATE_DEAD, owner.currentSubState);
owner.zone.BroadcastPacketAroundActor(owner, deathStatePacket);
owner.ChangeState(SetActorStatePacket.MAIN_STATE_DEAD);
owner.statusEffects.RemoveStatusEffectsByFlags((uint)StatusEffectFlags.LoseOnDeath, true);
//var deathStatePacket = SetActorStatePacket.BuildPacket(owner.actorId, SetActorStatePacket.MAIN_STATE_DEAD2, owner.currentSubState);
//owner.zone.BroadcastPacketAroundActor(owner, deathStatePacket);
canInterrupt = false;
startTime = tick;
despawnTime = startTime.AddSeconds(timeToFadeOut);

View file

@ -27,7 +27,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
if (owner.IsDead())
return true;
if (!owner.statusEffects.HasStatusEffectsByFlag(StatusEffectFlags.PreventAction))
if (!owner.statusEffects.HasStatusEffectsByFlag(StatusEffectFlags.PreventMovement))
return true;
}

View file

@ -26,7 +26,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
this.spell = Server.GetWorldManager().GetBattleCommand(spellId);
var returnCode = lua.LuaEngine.CallLuaBattleCommandFunction(owner, spell, "magic", "onMagicPrepare", owner, target, spell);
if (returnCode == 0 && owner.CanCast(target, spell))
this.target = spell.GetMainTarget(owner, target);
if (returnCode == 0 && owner.CanCast(this.target, spell))
{
OnStart();
}
@ -51,16 +53,28 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
// todo: check within attack range
float[] baseCastDuration = { 1.0f, 0.25f };
float spellSpeed = spell.castTimeSeconds;
//Check combo stuff here because combos can impact spell cast times
// command casting duration
if (owner is Player)
float spellSpeed = spell.castTimeMs;
//There are no positional spells, so just check onCombo, need to check first because certain spells change aoe type/accuracy
//If owner is a player and the spell being used is part of the current combo
if (spell.comboStep == 1 || ((owner is Player p) && (p.playerWork.comboNextCommandId[0] == spell.id || p.playerWork.comboNextCommandId[1] == spell.id)))
{
// todo: modify spellSpeed based on modifiers and stuff
((Player)owner).SendStartCastbar(spell.id, Utils.UnixTimeStampUTC(DateTime.Now.AddSeconds(spellSpeed)));
lua.LuaEngine.CallLuaBattleCommandFunction(owner, spell, "magic", "onCombo", owner, target, spell);
spell.isCombo = true;
}
if (!spell.IsInstantCast())
{
// command casting duration
if (owner is Player)
{
// todo: modify spellSpeed based on modifiers and stuff
((Player)owner).SendStartCastbar(spell.id, Utils.UnixTimeStampUTC(DateTime.Now.AddMilliseconds(spellSpeed)));
}
owner.SendChant(0xf, 0x0);
owner.DoBattleAction(spell.id, (uint) 0x6F000000 | spell.castType, new BattleAction(target.actorId, 30128, 1, 0, 1)); //You begin casting (6F000002: BLM, 6F000003: WHM, 0x6F000008: BRD)
}
owner.SendChant(0xF, 0x0);
owner.DoBattleAction(spell.id, 0x6F000002, new BattleAction(target.actorId, 30128, 1, 0, 1)); //You begin casting (6F000002: BLM, 6F000003: WHM)
}
}
@ -77,9 +91,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
}
// todo: check weapon delay/haste etc and use that
var actualCastTime = spell.castTimeSeconds;
var actualCastTime = spell.castTimeMs;
if ((tick - startTime).TotalSeconds >= spell.castTimeSeconds)
if ((tick - startTime).TotalMilliseconds >= spell.castTimeMs)
{
OnComplete();
return true;
@ -102,24 +116,58 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
public override void OnComplete()
{
//How do combos/hitdirs work for aoe abilities or does that not matter for aoe?
HitDirection hitDir = owner.GetHitDirection(target);
bool hitTarget = false;
spell.targetFind.FindWithinArea(target, spell.validTarget, spell.aoeTarget);
isCompleted = true;
var targets = spell.targetFind.GetTargets();
BattleAction[] actions = new BattleAction[targets.Count];
var i = 0;
foreach (var chara in targets)
List<BattleAction> actions = new List<BattleAction>();
if (targets.Count > 0)
{
var action = new BattleAction(chara.actorId, spell.worldMasterTextId, spell.battleAnimation, 0, (byte)HitDirection.None, 1);
action.amount = (ushort)lua.LuaEngine.CallLuaBattleCommandFunction(owner, spell, "magic", "onMagicFinish", owner, chara, spell, action);
actions[i++] = action;
List<StatusEffect> effects = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.ActivateOnSpell);
//modify skill based on status effects
foreach (var effect in effects)
lua.LuaEngine.CallLuaStatusEffectFunction(owner, effect, "onWeaponSkill", owner, effect, spell);
//Now that combos and positionals bonuses are done, we can calculate hits/crits/etc and damage
foreach (var chara in targets)
{
for (int hitNum = 0; hitNum < spell.numHits; hitNum++)
{
var action = new BattleAction(chara.actorId, spell.worldMasterTextId, 0, 0, (byte) hitDir, (byte) hitNum);
lua.LuaEngine.CallLuaBattleCommandFunction(owner, spell, "magic", "onMagicFinish", owner, chara, spell, action);
//if hit type isn't evade or miss
if (action.hitType > HitType.Evade)
hitTarget = true;
actions.AddRange(action.GetAllActions());
}
}
}
else
{
//No targets hit, cast failed
actions.Add(new BattleAction(target.actorId, 30202, (uint) (0)));
}
// todo: this is fuckin stupid, probably only need *one* error packet, not an error for each action
var errors = (BattleAction[])actions.Clone();
owner.OnCast(this, actions, ref errors);
owner.DoBattleAction(spell.id, spell.battleAnimation, actions);
// todo: this is fuckin stupid, probably only need *one* error packet, not an error for each action
BattleAction[] errors = (BattleAction[])actions.ToArray().Clone();
owner.OnCast(this, actions.ToArray(), spell, ref errors);
owner.DoBattleAction(spell.id, spell.battleAnimation, actions);
owner.statusEffects.RemoveStatusEffectsByFlags((uint)StatusEffectFlags.LoseOnCasting);
//Now that we know if we hit the target we can check if the combo continues
if (owner is Player player)
if (spell.isCombo && hitTarget)
player.SetCombos(spell.comboNextCommandId);
else
player.SetCombos();
}
public override void TryInterrupt()
@ -127,10 +175,10 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
if (interrupt)
return;
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventAction))
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventSpell))
{
// todo: sometimes paralyze can let you attack, get random percentage of actually letting you attack
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventAction);
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventSpell);
uint effectId = 0;
if (list.Count > 0)
{
@ -154,7 +202,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
private bool CanCast()
{
return owner.CanCast(target, spell) && spell.IsValidTarget(owner, target) && !HasMoved();
return owner.CanCast(target, spell) && spell.IsValidMainTarget(owner, target) && !HasMoved();
}
private bool HasMoved()
@ -170,7 +218,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
{
((Player)owner).SendEndCastbar();
}
owner.aiContainer.UpdateLastActionTime();
owner.aiContainer.UpdateLastActionTime(spell.animationDurationSeconds);
}
public BattleCommand GetSpell()

View file

@ -15,11 +15,12 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
{
private BattleCommand skill;
private HitDirection hitDirection;
public WeaponSkillState(Character owner, Character target, ushort skillId) :
base(owner, target)
{
this.startTime = DateTime.Now;
//this.target = skill.targetFind.
this.skill = Server.GetWorldManager().GetBattleCommand(skillId);
var returnCode = lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "weaponskill", "onSkillPrepare", owner, target, skill);
@ -46,6 +47,37 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
else
{
owner.LookAt(target);
hitDirection = owner.GetHitDirection(target);
//Do positionals and combo effects first because these can influence accuracy and amount of targets/numhits, which influence the rest of the steps
//If there is no positon required or if the position bonus should be activated
if ((skill.positionBonus & utils.BattleUtils.ConvertHitDirToPosition(hitDirection)) == skill.positionBonus)
{
//If there is a position bonus
if (skill.positionBonus != BattleCommandPositionBonus.None)
//lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "weaponskill", "onPositional", owner, target, skill);
skill.CallLuaFunction(owner, "onPositional", owner, target, skill);
//Combo stuff
if (owner is Player p)
{
//If skill is part of owner's class/job, it can be used in a combo
if (skill.job == p.GetClass() || skill.job == p.GetCurrentClassOrJob())
{
//If owner is a player and the skill being used is part of the current combo
if (p.playerWork.comboNextCommandId[0] == skill.id || p.playerWork.comboNextCommandId[1] == skill.id)
{
lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "weaponskill", "onCombo", owner, target, skill);
skill.CallLuaFunction(owner, "onCombo", owner, target, skill);
skill.isCombo = true;
}
//or if this just the start of a combo
else if (skill.comboStep == 1)
skill.isCombo = true;
}
}
}
}
}
@ -62,9 +94,9 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
}
// todo: check weapon delay/haste etc and use that
var actualCastTime = skill.castTimeSeconds;
var actualCastTime = skill.castTimeMs;
if ((tick - startTime).TotalSeconds >= skill.castTimeSeconds)
if ((tick - startTime).Milliseconds >= skill.castTimeMs)
{
OnComplete();
return true;
@ -86,28 +118,55 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
public override void OnComplete()
{
bool hitTarget = false;
skill.targetFind.FindWithinArea(target, skill.validTarget, skill.aoeTarget);
isCompleted = true;
var targets = skill.targetFind.GetTargets();
BattleAction[] actions = new BattleAction[targets.Count];
//Need a variable size list of actions because status effects may add extra actions
//BattleAction[] actions = new BattleAction[targets.Count * skill.numHits];
List<BattleAction> actions = new List<BattleAction>();
List<StatusEffect> effects = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.ActivateOnAttack);
var i = 0;
//modify skill based on status effects
foreach (var effect in effects)
effect.CallLuaFunction(owner, "onWeaponSkill", skill);
//Now that combos and positionals bonuses are done, we can calculate hits/crits/etc and damage for each action
foreach (var chara in targets)
{
var action = new BattleAction(chara.actorId, skill.worldMasterTextId, (uint)HitEffect.Hit, 0, 1, 1);
// evasion, miss, dodge, etc to be handled in script, calling helpers from scripts/weaponskills.lua
action.amount = (ushort)lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "weaponskill", "onSkillFinish", owner, target, skill, action);
actions[i++] = action;
chara.Engage(chara.actorId, 1);
for (int hitNum = 0; hitNum < skill.numHits; hitNum++)
{
var action = new BattleAction(chara.actorId, skill.worldMasterTextId, 0, 0, (byte) hitDirection, 1);
//For older versions this will need to be in the database for magic weaponskills
action.battleActionType = BattleActionType.AttackPhysical;
//uncached script
lua.LuaEngine.CallLuaBattleCommandFunction(owner, skill, "weaponskill", "onSkillFinish", owner, target, skill, action);
//cached script
//skill.CallLuaFunction(owner, "onSkillFinish", owner, target, skill, action);
action.hitNum = (byte)hitNum;
if (action.hitType > HitType.Evade)
hitTarget = true;
actions.AddRange(action.GetAllActions());
}
}
// todo: this is fuckin stupid, probably only need *one* error packet, not an error for each action
var errors = (BattleAction[])actions.Clone();
owner.OnWeaponSkill(this, actions, ref errors);
BattleAction[] errors = (BattleAction[]) actions.ToArray().Clone();
owner.OnWeaponSkill(this, actions.ToArray(), skill, ref errors);
owner.DoBattleAction(skill.id, skill.battleAnimation, actions);
owner.statusEffects.RemoveStatusEffectsByFlags((uint) StatusEffectFlags.LoseOnAttacking);
//Now that we know if we hit the target we can check if the combo continues
if (owner is Player player)
if (skill.isCombo && hitTarget)
player.SetCombos(skill.comboNextCommandId);
else
player.SetCombos();
}
public override void TryInterrupt()
@ -115,10 +174,10 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
if (interrupt)
return;
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventAction))
if (owner.statusEffects.HasStatusEffectsByFlag((uint)StatusEffectFlags.PreventWeaponSkill))
{
// todo: sometimes paralyze can let you attack, get random percentage of actually letting you attack
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventAction);
var list = owner.statusEffects.GetStatusEffectsByFlag((uint)StatusEffectFlags.PreventWeaponSkill);
uint effectId = 0;
if (list.Count > 0)
{
@ -134,7 +193,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
private bool CanUse()
{
return owner.CanWeaponSkill(target, skill) && skill.IsValidTarget(owner, target);
return owner.CanWeaponSkill(target, skill) && skill.IsValidMainTarget(owner, target);
}
public BattleCommand GetWeaponSkill()
@ -144,7 +203,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.state
public override void Cleanup()
{
owner.aiContainer.UpdateLastActionTime();
owner.aiContainer.UpdateLastActionTime(skill.animationDurationSeconds);
}
}
}

View file

@ -7,22 +7,161 @@ using System.Threading.Tasks;
using FFXIVClassic_Map_Server.Actors;
using FFXIVClassic_Map_Server.packets.send.actor;
using FFXIVClassic_Map_Server.packets.send.actor.battle;
using FFXIVClassic_Map_Server.actors.chara.player;
using FFXIVClassic_Map_Server.dataobjects;
using FFXIVClassic.Common;
namespace FFXIVClassic_Map_Server.actors.chara.ai.utils
{
static class BattleUtils
{
public static Dictionary<HitType, ushort> HitTypeTextIds = new Dictionary<HitType, ushort>()
{
{ HitType.Miss, 30311 },
{ HitType.Evade, 30310 },
{ HitType.Parry, 30308 },
{ HitType.Block, 30306 },
{ HitType.Resist, 30306 },//I can't find what the actual textid for resists is
{ HitType.Hit, 30301 },
{ HitType.Crit, 30302 }
};
public static Dictionary<HitType, HitEffect> HitTypeEffects = new Dictionary<HitType, HitEffect>()
{
{ HitType.Miss, 0 },
{ HitType.Evade, HitEffect.Evade },
{ HitType.Parry, HitEffect.Parry },
{ HitType.Block, HitEffect.Block },
{ HitType.Resist, HitEffect.RecoilLv1 },//Probably don't need this, resists are handled differently to the rest
{ HitType.Hit, HitEffect.Hit },
{ HitType.Crit, HitEffect.Crit }
};
public static bool TryAttack(Character attacker, Character defender, BattleAction action, ref BattleAction error)
{
// todo: get hit rate, hit count, set hit effect
action.effectId |= (uint)(HitEffect.RecoilLv2 | HitEffect.Hit | HitEffect.HitVisual1);
//action.effectId |= (uint)(HitEffect.RecoilLv2 | HitEffect.Hit | HitEffect.HitVisual1);
return true;
}
private static double CalculateDlvlModifier(short dlvl)
{
//this is just a really, really simplified version of the graph from http://kanican.livejournal.com/55915.html
//actual formula is definitely more complicated
//I'm going to assum these formulas are linear, and they're clamped so the modifier never goes below 0.
double modifier = 0;
if (dlvl >= 0)
modifier = (.35 * dlvl) + .225;
else
modifier = (.01 * dlvl) + .25;
return modifier.Clamp(0, 1);
}
//Damage calculations
//Calculate damage of action
//We could probably just do this when determining the action's hit type
public static void CalculateDamage(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
short dlvl = (short)(defender.GetLevel() - attacker.GetLevel());
switch (action.hitType)
{
//Misses and evades deal no damage.
case (HitType.Miss):
case (HitType.Evade):
action.amount = 0;
break;
// todo: figure out parry damage reduction. For now assume 25% reduction
case (HitType.Parry):
CalculateParryDamage(attacker, defender, skill, action);
break;
case (HitType.Block):
CalculateBlockDamage(attacker, defender, skill, action);
break;
//There are 3 (or 4?) tiers of resists, each decreasing damage dealt by 25%. For now just assume level 2 resist (50% reduction)
// todo: figure out resist tiers
case (HitType.Resist):
CalculateResistDamage(attacker, defender, skill, action);
break;
case (HitType.Crit):
CalculateCritDamage(attacker, defender, skill, action);
break;
}
ushort finalAmount = action.amount;
//dlvl, Defense, and Vitality all effect how much damage is taken after hittype takes effect
//player attacks cannot do more than 9999 damage.
action.amount = (ushort) (finalAmount - CalculateDlvlModifier(dlvl) * (defender.GetMod((uint)Modifier.Defense) + 0.67 * defender.GetMod((uint)Modifier.Vitality))).Clamp(0, 9999);
}
public static void CalculateBlockDamage(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
double percentBlocked = defender.GetMod((uint)Modifier.Block) * .2;//Every point of Block adds .2% to how much is blocked
percentBlocked += defender.GetMod((uint)Modifier.Vitality) * .1;//Every point of vitality adds .1% to how much is blocked
percentBlocked = 1 - percentBlocked;
action.amount = (ushort)(action.amount * percentBlocked);
}
//don't know crit formula
public static void CalculateCritDamage(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
short dlvl = (short)(defender.GetLevel() - attacker.GetLevel());
double bonus = (.04 * (dlvl * dlvl)) - 2 * dlvl;
bonus += 1.20;
double potencyModifier = (-.075 * dlvl) + 1.73;
// + potency bonus
//bonus += attacker.GetMod((uint) Modifier.CriticalPotency) * potencyModifier;
// - Crit resilience
//bonus -= attacker.GetMod((uint)Modifier.CriticalResilience) * potencyModifier;
//need to add something for bonus potency as a part of skill (ie thundara)
action.amount = (ushort)(action.amount * bonus.Clamp(1.15, 1.75));//min bonus of 115, max bonus of 175
}
public static void CalculateParryDamage(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
double percentParry = .75;
action.amount = (ushort)(action.amount * percentParry);
}
//There are 3 or 4 tiers of resist that are flat 25% decreases in damage.
//It's possible we could just calculate the damage at the same time as we determine the hit type (the same goes for the rest of the hit types)
//Or we could have HitTypes for DoubleResist, TripleResist, and FullResist that get used here.
public static void CalculateResistDamage(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
double percentResist = .5;
action.amount = (ushort)(action.amount * percentResist);
}
//Used for attacks and abilities like Jump that deal damage
public static ushort CalculateAttackDamage(Character attacker, Character defender, BattleAction action)
{
ushort damage = (ushort)(Program.Random.Next(10) * 10);
ushort damage = (ushort)100;
if (attacker is Player p)
{
var weapon = p.GetEquipment().GetItemAtSlot(Equipment.SLOT_MAINHAND);
if (weapon != null)
{
var weaponData = Server.GetItemGamedata(weapon.itemId);
//just some numbers from https://www.bluegartr.com/threads/107403-Stats-and-how-they-work/page24
damage += (ushort) (2.225 * (weaponData as WeaponItem).damagePower + (attacker.GetMod((uint) Modifier.Attack) * .38));
}
}
// todo: handle all other crap before protect/stoneskin
@ -60,23 +199,18 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.utils
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Shell))
{
// todo: shell probably only shows on magic..
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Shell))
{
if (action != null)
action.effectId |= (uint)HitEffect.Shell;
}
}
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Stoneskin))
{
if (action != null)
action.effectId |= (uint)HitEffect.Stoneskin;
}
return damage;
}
public static void DamageTarget(Character attacker, Character defender, BattleAction action, DamageTakenType type)
public static void DamageTarget(Character attacker, Character defender, BattleAction action, DamageTakenType type, bool sendBattleAction = false)
{
if (defender != null)
{
@ -88,14 +222,289 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.utils
{
bnpc.hateContainer.AddBaseHate(attacker);
}
bnpc.hateContainer.UpdateHate(attacker, action.amount);
bnpc.hateContainer.UpdateHate(attacker, action.enmity);
bnpc.lastAttacker = attacker;
}
defender.DelHP((short)action.amount);
defender.DelHP((short) action.amount);
defender.OnDamageTaken(attacker, action, type);
}
}
public static void DoAction(Character user, Character receiver, BattleAction action, DamageTakenType type = DamageTakenType.None)
{
switch(action.battleActionType)
{
//split attack into phys/mag?
case (BattleActionType.AttackMagic)://not sure if these use different damage taken formulas
case (BattleActionType.AttackPhysical):
DamageTarget(user, receiver, action, type, false);
break;
case (BattleActionType.Heal):
receiver.AddHP(action.amount);
break;
}
if ((type == DamageTakenType.Ability || type == DamageTakenType.Attack) && action.amount != 0)
{
receiver.AddTP(150);
user.AddTP(200);
}
}
/*
* Rate functions
*/
//How is accuracy actually calculated?
public static double GetHitRate(Character attacker, Character defender, BattleCommand skill)
{
double hitRate = .80;
//Certain skills have lower or higher accuracy rates depending on position/combo
return hitRate * (skill != null ? skill.accuracyModifier : 1);
}
//Whats the parry formula?
public static double GetParryRate(Character attacker, Character defender, BattleCommand skill)
{
//Can't parry with shield, must be facing attacker
if (defender.GetMod((uint)Modifier.HasShield) > 0 || !defender.IsFacing(attacker))
return 0;
return .10;
}
public static double GetCritRate(Character attacker, Character defender, BattleCommand skill)
{
double critRate = 10;// .0016 * attacker.GetMod((uint)Modifier.CritRating);//Crit rating adds .16% per point
return Math.Min(critRate, .20);//Crit rate is capped at 20%
}
//http://kanican.livejournal.com/55370.html
// todo: figure that out
public static double GetResistRate(Character attacker, Character defender, BattleCommand skill)
{
return .95;
}
//Block Rate follows 4 simple rules:
//(1) Every point in DEX gives +0.1% rate
//(2) Every point in "Block Rate" gives +0.2% rate
//(3) True block proc rate is capped at 75%. No clue on a possible floor.
//(4) The baseline rate is based on dLVL only(mob stats play no role). The baseline rate is summarized in this raw data sheet: https://imgbox.com/aasLyaJz
public static double GetBlockRate(Character attacker, Character defender, BattleCommand skill)
{
//Shields are required to block.
if (defender.GetMod((uint)Modifier.HasShield) == 0)//|| !defender.IsFacing(attacker))
return 0;
short dlvl = (short) (attacker.GetLevel() - defender.GetLevel());
double blockRate = (-2.5 * dlvl) - 5; // Base block rate
blockRate += attacker.GetMod((uint) Modifier.Dexterity) * .1;// .1% for every dex
blockRate += attacker.GetMod((uint) Modifier.BlockRate) * .2;// .2% for every block rate
return Math.Min(blockRate, 25);
}
/*
* HitType helpers. Used for determining if attacks are hits, crits, blocks, etc. and changing their damage based on that
*/
public static bool TryCrit(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
if (Program.Random.NextDouble() < GetCritRate(attacker, defender, skill))
{
action.hitType = HitType.Crit;
CalculateCritDamage(attacker, defender, skill, action);
return true;
}
return false;
}
public static bool TryResist(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
if (Program.Random.NextDouble() < GetResistRate(attacker, defender, skill))
{
action.hitType = HitType.Resist;
CalculateResistDamage(attacker, defender, skill, action);
return true;
}
return false;
}
public static bool TryBlock(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
if (Program.Random.NextDouble() < GetBlockRate(attacker, defender, skill))
{
action.hitType = HitType.Block;
defender.SetProc((int)HitType.Block);
CalculateBlockDamage(attacker, defender, skill, action);
return true;
}
return false;
}
public static bool TryParry(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
if (Program.Random.NextDouble() < GetParryRate(attacker, defender, skill))
{
action.hitType = HitType.Parry;
defender.SetProc((int)HitType.Parry);
CalculateParryDamage(attacker, defender, skill, action);
return true;
}
return false;
}
//TryMiss instead of tryHit because hits are the default and don't change damage
public static bool TryMiss(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
if (Program.Random.NextDouble() > GetHitRate(attacker, defender, skill))
{
action.hitType = HitType.Miss;
action.amount = 0;
defender.SetProc((int)HitType.Evade);
attacker.SetProc((int)HitType.Miss);
return true;
}
return false;
}
/*
* Hit Effecthelpers. Different types of hit effects hits use some flags for different things, so they're split into physical, magical, heal, and status
*/
public static void CalcHitType(Character caster, Character target, BattleCommand skill, BattleAction action)
{
//Might be a simpler way to do this?
switch(action.battleActionType)
{
case (BattleActionType.AttackPhysical):
SetHitEffectPhysical(caster, target, skill, action);
break;
case (BattleActionType.AttackMagic):
SetHitEffectMagical(caster, target, skill, action);
break;
case (BattleActionType.Heal):
SetHitEffectHeal(caster, target, skill, action);
break;
case (BattleActionType.Status):
SetHitEffectStatus(caster, target, skill, action);
break;
}
}
public static void SetHitEffectPhysical(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
//Determine the hittype of the action and change amount of damage it does based on that
if (!TryMiss(attacker, defender, skill, action))
if (!TryCrit(attacker, defender, skill, action))
if (!TryBlock(attacker, defender, skill, action))
TryParry(attacker, defender, skill, action);
var hitEffect = HitEffect.HitEffectType;
//Don't know what recoil is actually based on, just guessing
//Crit is 2 and 3 together
if (action.hitType == HitType.Crit)
hitEffect |= HitEffect.CriticalHit;
else
{
double percentDealt = (100.0 * (action.amount / defender.GetMaxHP()));
if (percentDealt > 5.0)
hitEffect |= HitEffect.RecoilLv2;
else if(percentDealt > 10)
hitEffect |= HitEffect.RecoilLv3;
}
action.worldMasterTextId = HitTypeTextIds[action.hitType];
hitEffect |= HitTypeEffects[action.hitType];
if (skill != null && skill.isCombo && action.hitType > HitType.Evade)
hitEffect |= (HitEffect)(skill.comboStep << 15);
//if attack hit the target, take into account protective status effects
if (action.hitType >= HitType.Parry)
{
//Protect / Shell only show on physical/ magical attacks respectively.
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Protect))
if (action != null)
hitEffect |= HitEffect.Protect;
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Stoneskin))
if (action != null)
hitEffect |= HitEffect.Stoneskin;
}
action.effectId = (uint) hitEffect;
}
public static void SetHitEffectMagical(Character attacker, Character defender, BattleCommand skill, BattleAction action)
{
//Determine the hit type of the action
if (!TryMiss(attacker, defender, skill, action))
if (!TryCrit(attacker, defender, skill, action))
TryResist(attacker, defender, skill, action);
var hitEffect = HitEffect.MagicEffectType;
//Recoil levels for spells are a bit different than physical. Recoil levels are used for resists.
//Lv1 is for larger resists, Lv2 is for smaller resists and Lv3 is for no resists. Crit is still used for crits
if (action.hitType == HitType.Resist)
{
//todo: calculate resist levels and figure out what the difference between Lv1 and 2 in retail was. For now assuming a full resist with 0 damage dealt is Lv1, all other resists Lv2
if (action.amount == 0)
hitEffect |= HitEffect.RecoilLv1;
else
hitEffect |= HitEffect.RecoilLv2;
}
else if (action.hitType == HitType.Crit)
hitEffect |= HitEffect.Crit;
else
hitEffect |= HitEffect.RecoilLv3;
action.worldMasterTextId = HitTypeTextIds[action.hitType];
hitEffect |= HitTypeEffects[action.hitType];
if (skill != null && skill.isCombo)
hitEffect |= (HitEffect)(skill.comboStep << 15);
//if attack hit the target, take into account protective status effects
if (action.hitType >= HitType.Block)
{
//Protect / Shell only show on physical/ magical attacks respectively.
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Shell))
if (action != null)
hitEffect |= HitEffect.Shell;
if (defender.statusEffects.HasStatusEffect(StatusEffectId.Stoneskin))
if (action != null)
hitEffect |= HitEffect.Stoneskin;
}
action.effectId = (uint)hitEffect;
}
public static void SetHitEffectHeal(Character caster, Character receiver, BattleCommand skill, BattleAction action)
{
var hitEffect = HitEffect.MagicEffectType | HitEffect.Heal;
//Heals use recoil levels in some way as well. Possibly for very low health clutch heals or based on percentage of current health healed (not max health).
// todo: figure recoil levels out for heals
hitEffect |= HitEffect.RecoilLv3;
//do heals crit?
action.effectId = (uint)hitEffect;
}
public static void SetHitEffectStatus(Character caster, Character receiver, BattleCommand skill, BattleAction action)
{
var hitEffect = (uint) HitEffect.StatusEffectType | skill.statusId;
action.effectId = hitEffect;
}
public static int CalculateSpellDamage(Character attacker, Character defender, BattleCommand spell)
{
// todo: spell formulas and stuff (stoneskin, mods, stats, etc)
@ -104,7 +513,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.utils
public static uint CalculateSpellCost(Character caster, Character target, BattleCommand spell)
{
var scaledCost = spell.CalculateCost((uint)caster.charaWork.parameterSave.state_mainSkillLevel);
var scaledCost = spell.CalculateMpCost(caster);
// todo: calculate cost for mob/player
if (caster is BattleNpc)
@ -117,5 +526,66 @@ namespace FFXIVClassic_Map_Server.actors.chara.ai.utils
}
return scaledCost;
}
//Convert a HitDirection to a BattleCommandPositionBonus. Basically just combining left/right into flank
public static BattleCommandPositionBonus ConvertHitDirToPosition(HitDirection hitDir)
{
BattleCommandPositionBonus position = BattleCommandPositionBonus.None;
switch(hitDir)
{
case (HitDirection.Front):
position = BattleCommandPositionBonus.Front;
break;
case (HitDirection.Right):
case (HitDirection.Left):
position = BattleCommandPositionBonus.Flank;
break;
case (HitDirection.Rear):
position = BattleCommandPositionBonus.Rear;
break;
}
return position;
}
//IsAdditional is needed because additional actions may be required for some actions' effects
//For instance, Goring Blade's bleed effect requires another action so the first action can still show damage numbers
//Sentinel doesn't require an additional action because it doesn't need to show those numbers
public static void TryStatus(Character caster, Character target, BattleCommand skill, BattleAction action, bool isAdditional = true)
{
double rand = Program.Random.NextDouble();
(caster as Player).SendMessage(0x20, "", rand.ToString());
if (skill != null && action.amount < target.GetHP() && skill.statusId != 0 && action.hitType > HitType.Evade && rand < skill.statusChance)
{
StatusEffect effect = Server.GetWorldManager().GetStatusEffect(skill.statusId);
//Because combos might change duration or tier
if (effect != null)
{
effect.SetDuration(skill.statusDuration);
effect.SetTier(skill.statusTier);
effect.SetOwner(target);
if (target.statusEffects.AddStatusEffect(effect, caster))
{
//If we need an extra action to show the status text
if (isAdditional)
action.AddStatusAction(target.actorId, skill.statusId);
}
else
action.worldMasterTextId = 32002;//Is this right?
}
else
{
if (target.statusEffects.AddStatusEffect(skill.statusId, 1, 3000, skill.statusDuration, skill.statusTier))
{
//If we need an extra action to show the status text
if (isAdditional)
action.AddStatusAction(target.actorId, skill.statusId);
}
else
action.worldMasterTextId = 32002;//Is this right?
}
}
}
}
}

View file

@ -118,34 +118,33 @@ namespace FFXIVClassic_Map_Server.Actors
return subpackets;
}
//This might need more work
//I think there migh be something that ties mobs to parties
//and the client checks if any mobs are tied to the current party
//and bases the color on that. Adding mob to party obviously doesn't work
//Based on depictionjudge script:
//HATE_TYPE_NONE is for passive
//HATE_TYPE_ENGAGED is for aggroed mobs
//HATE_TYPE_ENGAGED_PARTY is for claimed mobs, client uses occupancy group to determine if mob is claimed by player's party
//for now i'm just going to assume that occupancygroup will be BattleNpc's currentparties when they're in combat,
//so if party isn't null, they're claimed.
public SubPacket GetHateTypePacket(Player player)
{
npcWork.hateType = 1;
npcWork.hateType = NpcWork.HATE_TYPE_NONE;
if (player != null)
{
if (aiContainer.IsEngaged())
{
npcWork.hateType = 2;
}
npcWork.hateType = NpcWork.HATE_TYPE_ENGAGED;
if (player.actorId == this.currentLockedTarget)
{
npcWork.hateType = NpcWork.HATE_TYPE_ENGAGED_PARTY;
}
else if (player.currentParty != null)
{
foreach (var memberId in ((Party)player.currentParty).members)
if (this.currentParty != null)
{
if (this.currentLockedTarget == memberId)
{
npcWork.hateType = NpcWork.HATE_TYPE_ENGAGED_PARTY;
break;
}
npcWork.hateType = NpcWork.HATE_TYPE_ENGAGED_PARTY;
}
}
}
var propPacketUtil = new ActorPropertyPacketUtil("npcWork", this);
npcWork.hateType = 2;
var propPacketUtil = new ActorPropertyPacketUtil("npcWork/hate", this);
propPacketUtil.AddProperty("npcWork.hateType");
return propPacketUtil.Done()[0];
}
@ -198,7 +197,7 @@ namespace FFXIVClassic_Map_Server.Actors
public override bool CanWeaponSkill(Character target, BattleCommand skill)
{
// todo:
return false;
return true;
}
public override bool CanUseAbility(Character target, BattleCommand ability)
@ -359,18 +358,18 @@ namespace FFXIVClassic_Map_Server.Actors
lua.LuaEngine.CallLuaBattleFunction(this, "onAttack", this, state.GetTarget(), action.amount);
}
public override void OnCast(State state, BattleAction[] actions, ref BattleAction[] errors)
public override void OnCast(State state, BattleAction[] actions, BattleCommand spell, ref BattleAction[] errors)
{
base.OnCast(state, actions, ref errors);
base.OnCast(state, actions, spell, ref errors);
if (GetMobMod((uint)MobModifier.SpellScript) != 0)
foreach (var action in actions)
lua.LuaEngine.CallLuaBattleFunction(this, "onCast", this, zone.FindActorInArea<Character>(action.targetId), ((MagicState)state).GetSpell(), action);
}
public override void OnAbility(State state, BattleAction[] actions, ref BattleAction[] errors)
public override void OnAbility(State state, BattleAction[] actions, BattleCommand ability, ref BattleAction[] errors)
{
base.OnAbility(state, actions, ref errors);
base.OnAbility(state, actions, ability, ref errors);
/*
if (GetMobMod((uint)MobModifier.AbilityScript) != 0)
@ -379,9 +378,9 @@ namespace FFXIVClassic_Map_Server.Actors
*/
}
public override void OnWeaponSkill(State state, BattleAction[] actions, ref BattleAction[] errors)
public override void OnWeaponSkill(State state, BattleAction[] actions, BattleCommand skill, ref BattleAction[] errors)
{
base.OnWeaponSkill(state, actions, ref errors);
base.OnWeaponSkill(state, actions, skill, ref errors);
if (GetMobMod((uint)MobModifier.WeaponSkillScript) != 0)
foreach (var action in actions)

View file

@ -194,8 +194,8 @@ namespace FFXIVClassic_Map_Server.Actors
subpackets.Add(CreateSpeedPacket());
subpackets.Add(CreateSpawnPositonPacket(0x0));
if (isMapObj)
subpackets.Add(SetActorBGPropertiesPacket.BuildPacket(actorId, instance, layout));
if (isMapObj)
subpackets.Add(SetActorBGPropertiesPacket.BuildPacket(actorId, instance, layout));
else
subpackets.Add(CreateAppearancePacket());
@ -245,7 +245,7 @@ namespace FFXIVClassic_Map_Server.Actors
//Status Times
for (int i = 0; i < charaWork.statusShownTime.Length; i++)
{
if (charaWork.statusShownTime[i] != 0xFFFFFFFF)
if (charaWork.statusShownTime[i] != 0)
propPacketUtil.AddProperty(String.Format("charaWork.statusShownTime[{0}]", i));
}

View file

@ -163,6 +163,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.player
owner.QueuePacket(InventoryEndChangePacket.BuildPacket(owner.actorId));
list[slot] = item;
owner.CalculateBaseStats();// RecalculateStats();
}
public void ToggleDBWrite(bool flag)
@ -189,6 +190,7 @@ namespace FFXIVClassic_Map_Server.actors.chara.player
owner.QueuePacket(InventoryEndChangePacket.BuildPacket(owner.actorId));
list[slot] = null;
owner.RecalculateStats();
}
private void SendEquipmentPackets(ushort equipSlot, InventoryItem item)

View file

@ -26,6 +26,7 @@ using FFXIVClassic_Map_Server.packets.send.actor.battle;
using FFXIVClassic_Map_Server.actors.chara.ai.utils;
using FFXIVClassic_Map_Server.actors.chara.ai.state;
using FFXIVClassic_Map_Server.actors.chara.npc;
using FFXIVClassic_Map_Server.actors.chara;
namespace FFXIVClassic_Map_Server.Actors
{
@ -228,6 +229,7 @@ namespace FFXIVClassic_Map_Server.Actors
this.aiContainer = new AIContainer(this, new PlayerController(this), null, new TargetFind(this));
allegiance = CharacterTargetingAllegiance.Player;
CalculateBaseStats();
}
public List<SubPacket> Create0x132Packets()
@ -361,7 +363,7 @@ namespace FFXIVClassic_Map_Server.Actors
//Status Times
for (int i = 0; i < charaWork.statusShownTime.Length; i++)
{
if (charaWork.statusShownTime[i] != 0xFFFFFFFF)
if (charaWork.statusShownTime[i] != 0)
propPacketUtil.AddProperty(String.Format("charaWork.statusShownTime[{0}]", i));
}
@ -614,6 +616,7 @@ namespace FFXIVClassic_Map_Server.Actors
catch (Exception e)
{
this.SendMessage(SendMessagePacket.MESSAGE_TYPE_SYSTEM_ERROR, "[SendPacket]", "Unable to send packet.");
this.SendMessage(SendMessagePacket.MESSAGE_TYPE_SYSTEM_ERROR, "[SendPacket]", e.Message);
}
}
@ -1705,20 +1708,22 @@ namespace FFXIVClassic_Map_Server.Actors
Party partyGroup = (Party) currentParty;
for (int i = 0; i < partyGroup.members.Count; i++)
{
if (partyGroup.members[i] == actorId)
{
partyGroup.members.RemoveAt(i);
break;
}
}
partyGroup.RemoveMember(actorId);
//for (int i = 0; i < partyGroup.members.Count; i++)
//{
// if (partyGroup.members[i] == actorId)
// {
// partyGroup.members.RemoveAt(i);
// break;
// }
//}
//currentParty.members.Remove(this);
if (partyGroup.members.Count == 0)
Server.GetWorldManager().NoMembersInParty((Party)currentParty);
currentParty = null;
//currentParty = new Party(0, actorId);
}
public void IssueChocobo(byte appearanceId, string nameResponse)
@ -1842,27 +1847,23 @@ namespace FFXIVClassic_Map_Server.Actors
//If the class we're equipping for is the current class, we can just look at charawork.command
if(classId == charaWork.parameterSave.state_mainSkill[0])
{
hotbarSlot = FindFirstCommandSlotById(0);
}
//Otherwise, we need to check the database.
else
{
hotbarSlot = (ushort) (Database.FindFirstCommandSlot(this, classId) + charaWork.commandBorder);
}
EquipAbility(classId, commandId, hotbarSlot, printMessage);
}
//Add commandId to classId's hotbar at hotbarSlot.
//If classId is not the current class, do it in the database
//hotbarSlot is 32-indexed
//hotbarSlot starts at 32
public void EquipAbility(byte classId, uint commandId, ushort hotbarSlot, bool printMessage = true)
{
var ability = Server.GetWorldManager().GetBattleCommand(commandId);
uint trueCommandId = commandId | 0xA0F00000;
uint trueCommandId = 0xA0F00000 + commandId;
ushort lowHotbarSlot = (ushort)(hotbarSlot - charaWork.commandBorder);
ushort maxRecastTime = (ushort)ability.recastTimeSeconds;
ushort maxRecastTime = (ushort)(ability != null ? ability.maxRecastTimeSeconds : 5);
uint recastEnd = Utils.UnixTimeStampUTC() + maxRecastTime;
List<ushort> slotsToUpdate = new List<ushort>();
@ -1889,6 +1890,7 @@ namespace FFXIVClassic_Map_Server.Actors
//hotbarSlot 1 and 2 are 32-indexed.
public void SwapAbilities(ushort hotbarSlot1, ushort hotbarSlot2)
{
//0 indexed hotbar slots for saving to database and recast timers
uint lowHotbarSlot1 = (ushort)(hotbarSlot1 - charaWork.commandBorder);
uint lowHotbarSlot2 = (ushort)(hotbarSlot2 - charaWork.commandBorder);
@ -1906,10 +1908,12 @@ namespace FFXIVClassic_Map_Server.Actors
charaWork.command[hotbarSlot2] = commandId;
charaWork.parameterTemp.maxCommandRecastTime[lowHotbarSlot2] = recastMax;
charaWork.parameterSave.commandSlot_recastTime[lowHotbarSlot2] = recastEnd;
//Save changes
Database.EquipAbility(this, charaWork.parameterSave.state_mainSkill[0], (ushort)(lowHotbarSlot1), charaWork.command[hotbarSlot1], charaWork.parameterSave.commandSlot_recastTime[lowHotbarSlot1]);
//Save changes to both slots
Database.EquipAbility(this, GetCurrentClassOrJob(), (ushort)(lowHotbarSlot1), 0xA0F00000 ^ charaWork.command[hotbarSlot1], charaWork.parameterSave.commandSlot_recastTime[lowHotbarSlot1]);
Database.EquipAbility(this, GetCurrentClassOrJob(), (ushort)(lowHotbarSlot2), 0xA0F00000 ^ charaWork.command[hotbarSlot2], charaWork.parameterSave.commandSlot_recastTime[lowHotbarSlot2]);
//Update slots on client
List<ushort> slotsToUpdate = new List<ushort>();
slotsToUpdate.Add(hotbarSlot1);
slotsToUpdate.Add(hotbarSlot2);
@ -1926,7 +1930,7 @@ namespace FFXIVClassic_Map_Server.Actors
slotsToUpdate.Add(trueHotbarSlot);
if(printMessage)
SendGameMessage(Server.GetWorldManager().GetActor(), 30604, 0x20, 0, commandId ^ 0xA0F00000);
SendGameMessage(Server.GetWorldManager().GetActor(), 30604, 0x20, 0, 0xA0F00000 ^ commandId);
UpdateHotbar(slotsToUpdate);
}
@ -1952,10 +1956,10 @@ namespace FFXIVClassic_Map_Server.Actors
return firstSlot;
}
private void UpdateHotbarTimer(uint commandId, uint recastTimeSeconds)
private void UpdateHotbarTimer(uint commandId, uint recastTimeMs)
{
ushort slot = FindFirstCommandSlotById(commandId);
charaWork.parameterSave.commandSlot_recastTime[slot - charaWork.commandBorder] = Utils.UnixTimeStampUTC(DateTime.Now.AddSeconds(recastTimeSeconds));
charaWork.parameterSave.commandSlot_recastTime[slot - charaWork.commandBorder] = Utils.UnixTimeStampUTC(DateTime.Now.AddMilliseconds(recastTimeMs));
var slots = new List<ushort>();
slots.Add(slot);
UpdateRecastTimers(slots);
@ -2123,7 +2127,7 @@ namespace FFXIVClassic_Map_Server.Actors
SendGameMessage(Server.GetWorldManager().GetActor(), 32539, 0x20, (uint)spell.id);
return false;
}
if (!IsValidTarget(target, spell.validTarget) || !spell.IsValidTarget(this, target))
if (!IsValidTarget(target, spell.mainTarget) || !spell.IsValidMainTarget(this, target))
{
// error packet is set in IsValidTarget
return false;
@ -2141,29 +2145,36 @@ namespace FFXIVClassic_Map_Server.Actors
SendGameMessage(Server.GetWorldManager().GetActor(), 32535, 0x20, (uint)skill.id);
return false;
}
if (target == null)
{
// Target does not exist.
SendGameMessage(Server.GetWorldManager().GetActor(), 32511, 0x20, (uint)skill.id);
return false;
}
if (Utils.Distance(positionX, positionY, positionZ, target.positionX, target.positionY, target.positionZ) > skill.range)
{
// The target is out of range.
SendGameMessage(Server.GetWorldManager().GetActor(), 32539, 0x20, (uint)skill.id);
return false;
}
if (!IsValidTarget(target, skill.validTarget) || !skill.IsValidTarget(this, target))
if (!IsValidTarget(target, skill.validTarget) || !skill.IsValidMainTarget(this, target))
{
// error packet is set in IsValidTarget
return false;
}
return true;
}
public override void OnAttack(State state, BattleAction action, ref BattleAction error)
{
var target = state.GetTarget();
base.OnAttack(state, action, ref error);
// todo: switch based on main weap (also probably move this anim assignment somewhere else)
action.animation = 0x19001000;
if (error == null)
@ -2171,42 +2182,39 @@ namespace FFXIVClassic_Map_Server.Actors
// melee attack animation
//action.animation = 0x19001000;
}
var target = state.GetTarget();
if (target is BattleNpc)
{
((BattleNpc)target).hateContainer.UpdateHate(this, action.amount);
((BattleNpc)target).hateContainer.UpdateHate(this, action.enmity);
}
LuaEngine.GetInstance().OnSignal("playerAttack");
}
public override void OnCast(State state, BattleAction[] actions, ref BattleAction[] errors)
public override void OnCast(State state, BattleAction[] actions, BattleCommand spell, ref BattleAction[] errors)
{
// todo: update hotbar timers to skill's recast time (also needs to be done on class change or equip crap)
base.OnCast(state, actions, ref errors);
var spell = ((MagicState)state).GetSpell();
base.OnCast(state, actions, spell, ref errors);
// todo: should just make a thing that updates the one slot cause this is dumb as hell
UpdateHotbarTimer(spell.id, spell.recastTimeSeconds);
LuaEngine.GetInstance().OnSignal("spellUse");
UpdateHotbarTimer(spell.id, spell.recastTimeMs);
//LuaEngine.GetInstance().OnSignal("spellUse");
}
public override void OnWeaponSkill(State state, BattleAction[] actions, ref BattleAction[] errors)
public override void OnWeaponSkill(State state, BattleAction[] actions, BattleCommand skill, ref BattleAction[] errors)
{
// todo: update hotbar timers to skill's recast time (also needs to be done on class change or equip crap)
base.OnWeaponSkill(state, actions, ref errors);
var skill = ((WeaponSkillState)state).GetWeaponSkill();
base.OnWeaponSkill(state, actions, skill, ref errors);
// todo: should just make a thing that updates the one slot cause this is dumb as hell
UpdateHotbarTimer(skill.id, skill.recastTimeSeconds);
UpdateHotbarTimer(skill.id, skill.recastTimeMs);
// todo: this really shouldnt be called on each ws?
lua.LuaEngine.CallLuaBattleFunction(this, "onWeaponSkill", this, state.GetTarget(), skill);
LuaEngine.GetInstance().OnSignal("weaponskillUse");
}
public override void OnAbility(State state, BattleAction[] actions, ref BattleAction[] errors)
public override void OnAbility(State state, BattleAction[] actions, BattleCommand ability, ref BattleAction[] errors)
{
base.OnAbility(state, actions, ref errors);
base.OnAbility(state, actions, ability, ref errors);
UpdateHotbarTimer(ability.id, ability.recastTimeMs);
LuaEngine.GetInstance().OnSignal("abilityUse");
}
@ -2307,6 +2315,7 @@ namespace FFXIVClassic_Map_Server.Actors
currentJob = jobId;
BroadcastPacket(SetCurrentJobPacket.BuildPacket(actorId, jobId), true);
Database.LoadHotbar(this);
SendCharaExpInfo();
}
//Gets the id of the player's current job. If they aren't a job, gets the id of their class
@ -2328,5 +2337,66 @@ namespace FFXIVClassic_Map_Server.Actors
updateFlags |= ActorUpdateFlags.HpTpMp;
}
public void SetCombos(int comboId1 = 0, int comboId2 = 0)
{
SetCombos(new int[] { comboId1, comboId2 });
}
public void SetCombos(int[] comboIds)
{
Array.Copy(comboIds, playerWork.comboNextCommandId, 2);
//If we're starting or continuing a combo chain, add the status effect and combo cost bonus
if (comboIds[0] != 0)
{
StatusEffect comboEffect = new StatusEffect(this, (uint) StatusEffectId.Combo, 1, 0, 13);
comboEffect.SetOverwritable(1);
statusEffects.AddStatusEffect(comboEffect, this, true);
playerWork.comboCostBonusRate = 1;
}
//Otherwise we're ending a combo, remove the status
else
{
statusEffects.RemoveStatusEffect(statusEffects.GetStatusEffectById((uint) StatusEffectId.Combo));
playerWork.comboCostBonusRate = 0;
}
ActorPropertyPacketUtil comboPropertyPacket = new ActorPropertyPacketUtil("playerWork/combo", this);
comboPropertyPacket.AddProperty($"playerWork.comboCostBonusRate");
comboPropertyPacket.AddProperty($"playerWork.comboNextCommandId[{0}]");
comboPropertyPacket.AddProperty($"playerWork.comboNextCommandId[{1}]");
QueuePackets(comboPropertyPacket.Done());
}
public override void CalculateBaseStats()
{
base.CalculateBaseStats();
//Add weapon property mod
var equip = GetEquipment();
var mainHandItem = equip.GetItemAtSlot(Equipment.SLOT_MAINHAND);
var damageAttribute = 0;
var attackDelay = 3000;
var hitCount = 1;
GetAttackDelayMs();
if (mainHandItem != null)
{
var mainHandWeapon = (Server.GetItemGamedata(mainHandItem.itemId) as WeaponItem);
damageAttribute = mainHandWeapon.damageAttributeType1;
attackDelay = (int) (mainHandWeapon.damageInterval * 1000);
hitCount = mainHandWeapon.frequency;
}
var hasShield = equip.GetItemAtSlot(Equipment.SLOT_OFFHAND) != null ? 1 : 0;
SetMod((uint)Modifier.HasShield, hasShield);
SetMod((uint)Modifier.AttackType, damageAttribute);
SetMod((uint)Modifier.AttackDelay, attackDelay);
SetMod((uint)Modifier.HitCount, hitCount);
}
public void SetCurrentJob(ushort jobId)
{
currentJob = jobId;
BroadcastPacket(SetCurrentJobPacket.BuildPacket(actorId, jobId), true);
}
}
}

View file

@ -17,8 +17,9 @@ namespace FFXIVClassic_Map_Server.actors.group
public MonsterParty(ulong groupIndex, uint[] initialMonsterMembers)
: base(groupIndex)
{
for (int i = 0; i < initialMonsterMembers.Length; i++)
monsterMembers.Add(initialMonsterMembers[i]);
if(initialMonsterMembers != null)
for (int i = 0; i < initialMonsterMembers.Length; i++)
monsterMembers.Add(initialMonsterMembers[i]);
}
public void AddMember(uint memberId)

View file

@ -81,6 +81,8 @@ namespace FFXIVClassic_Map_Server.actors.group
{
members.Remove(memberId);
SendGroupPacketsAll(members);
if (members.Count == 0)
Server.GetWorldManager().NoMembersInParty(this);
}
}
}