Ported .Net Core commits:

hondacrx:
- Initial commit: Switch to .Net Core 2.0
- Fix build and removed not needed files
Fabi:
- Updated solution platforms.
- Changed folder structure.
- Change library target framework to netstandard2.0.
- Updated solution platforms again...
- Removed windows specific kernel32 function usage (Ctrl-C handler).
This commit is contained in:
Fabian
2017-10-26 17:23:44 +02:00
parent 227702e19c
commit a3dc7b3f48
844 changed files with 26064 additions and 1824 deletions
@@ -0,0 +1,125 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Game.Entities;
using System;
namespace Game.Movement
{
public class ConfusedGenerator<T> : MovementGeneratorMedium<T> where T : Unit
{
public ConfusedGenerator()
{
i_nextMoveTime = new TimeTracker();
}
public override void DoInitialize(T owner)
{
owner.AddUnitState(UnitState.Confused);
owner.SetFlag(UnitFields.Flags, UnitFlags.Confused);
owner.GetPosition(out i_x, out i_y, out i_z);
if (!owner.IsAlive() || owner.IsStopped())
return;
owner.StopMoving();
owner.AddUnitState(UnitState.ConfusedMove);
}
public override void DoFinalize(T owner)
{
if (owner.IsTypeId(TypeId.Player))
{
owner.RemoveFlag(UnitFields.Flags, UnitFlags.Confused);
owner.ClearUnitState(UnitState.Confused | UnitState.ConfusedMove);
owner.StopMoving();
}
else if (owner.IsTypeId(TypeId.Unit))
{
owner.RemoveFlag(UnitFields.Flags, UnitFlags.Confused);
owner.ClearUnitState(UnitState.Confused | UnitState.ConfusedMove);
if (owner.GetVictim())
owner.SetTarget(owner.GetVictim().GetGUID());
}
}
public override void DoReset(T owner)
{
i_nextMoveTime.Reset(0);
if (!owner.IsAlive() || owner.IsStopped())
return;
owner.StopMoving();
owner.AddUnitState(UnitState.Confused | UnitState.ConfusedMove);
}
public override bool DoUpdate(T owner, uint time_diff)
{
if (owner.HasUnitState(UnitState.Root | UnitState.Stunned | UnitState.Distracted))
return true;
if (i_nextMoveTime.Passed())
{
// currently moving, update location
owner.AddUnitState(UnitState.ConfusedMove);
if (owner.moveSpline.Finalized())
i_nextMoveTime.Reset(RandomHelper.IRand(800, 1500));
}
else
{
// waiting for next move
i_nextMoveTime.Update(time_diff);
if (i_nextMoveTime.Passed())
{
// start moving
owner.AddUnitState(UnitState.ConfusedMove);
float dest = (float)(4.0f * RandomHelper.NextDouble() - 2.0f);
Position pos = new Position(i_x, i_y, i_z);
owner.MovePositionToFirstCollision(ref pos, dest, 0.0f);
PathGenerator path = new PathGenerator(owner);
path.SetPathLengthLimit(30.0f);
bool result = path.CalculatePath(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ());
if (!result || path.GetPathType().HasAnyFlag(PathType.NoPath))
{
i_nextMoveTime.Reset(100);
return true;
}
MoveSplineInit init = new MoveSplineInit(owner);
init.MovebyPath(path.GetPath());
init.SetWalk(true);
init.Launch();
}
}
return true;
}
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Confused;
}
TimeTracker i_nextMoveTime;
float i_x, i_y, i_z;
}
}
@@ -0,0 +1,223 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Game.Entities;
using System;
namespace Game.Movement
{
public class FleeingGenerator<T> : MovementGeneratorMedium<T> where T : Unit
{
public const float MIN_QUIET_DISTANCE = 28.0f;
public const float MAX_QUIET_DISTANCE = 43.0f;
public FleeingGenerator(ObjectGuid fright)
{
i_frightGUID = fright;
i_nextCheckTime = new TimeTracker();
}
void _setTargetLocation(T owner)
{
if (owner == null)
return;
if (owner.HasUnitState(UnitState.Root | UnitState.Stunned))
return;
if (owner.HasUnitState(UnitState.Casting) && !owner.CanMoveDuringChannel())
{
owner.CastStop();
return;
}
owner.AddUnitState(UnitState.FleeingMove);
float x, y, z;
_getPoint(owner, out x, out y, out z);
Position mypos = owner.GetPosition();
bool isInLOS = Global.VMapMgr.isInLineOfSight(owner.GetMapId(), mypos.posX, mypos.posY, mypos.posZ + 2.0f, x, y, z + 2.0f);
if (!isInLOS)
{
i_nextCheckTime.Reset(200);
return;
}
PathGenerator path = new PathGenerator(owner);
path.SetPathLengthLimit(30.0f);
bool result = path.CalculatePath(x, y, z);
if (!result || path.GetPathType().HasAnyFlag(PathType.NoPath))
{
i_nextCheckTime.Reset(100);
return;
}
MoveSplineInit init = new MoveSplineInit(owner);
init.MovebyPath(path.GetPath());
init.SetWalk(false);
int traveltime = init.Launch();
i_nextCheckTime.Reset(traveltime + RandomHelper.URand(800, 1500));
}
void _getPoint(T owner, out float x, out float y, out float z)
{
float dist_from_caster, angle_to_caster;
Unit fright = Global.ObjAccessor.GetUnit(owner, i_frightGUID);
if (fright != null)
{
dist_from_caster = fright.GetDistance(owner);
if (dist_from_caster > 0.2f)
angle_to_caster = fright.GetAngle(owner);
else
angle_to_caster = RandomHelper.FRand(0, 2 * MathFunctions.PI);
}
else
{
dist_from_caster = 0.0f;
angle_to_caster = RandomHelper.FRand(0, 2 * MathFunctions.PI);
}
float dist, angle;
if (dist_from_caster < MIN_QUIET_DISTANCE)
{
dist = RandomHelper.FRand(0.4f, 1.3f) * (MIN_QUIET_DISTANCE - dist_from_caster);
angle = angle_to_caster + RandomHelper.FRand(-MathFunctions.PI / 8, MathFunctions.PI / 8);
}
else if (dist_from_caster > MAX_QUIET_DISTANCE)
{
dist = RandomHelper.FRand(0.4f, 1.0f) * (MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE);
angle = -angle_to_caster + RandomHelper.FRand(-MathFunctions.PI / 4, MathFunctions.PI / 4);
}
else // we are inside quiet range
{
dist = RandomHelper.FRand(0.6f, 1.2f) * (MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE);
angle = RandomHelper.FRand(0, 2 * MathFunctions.PI);
}
Position pos = owner.GetFirstCollisionPosition(dist, angle);
x = pos.posX;
y = pos.posY;
z = pos.posZ;
}
public override void DoInitialize(T owner)
{
if (owner == null)
return;
owner.SetFlag(UnitFields.Flags, UnitFlags.Fleeing);
owner.AddUnitState(UnitState.Fleeing | UnitState.FleeingMove);
_setTargetLocation(owner);
}
public override void DoFinalize(T owner)
{
if (owner.IsTypeId(TypeId.Player))
{
owner.RemoveFlag(UnitFields.Flags, UnitFlags.Fleeing);
owner.ClearUnitState(UnitState.Fleeing | UnitState.FleeingMove);
owner.StopMoving();
}
else
{
owner.RemoveFlag(UnitFields.Flags, UnitFlags.Fleeing);
owner.ClearUnitState(UnitState.Fleeing | UnitState.FleeingMove);
if (owner.GetVictim() != null)
owner.SetTarget(owner.GetVictim().GetGUID());
}
}
public override void DoReset(T owner)
{
DoInitialize(owner);
}
public override bool DoUpdate(T owner, uint time_diff)
{
if (owner == null || !owner.IsAlive())
return false;
if (owner.HasUnitState(UnitState.Root | UnitState.Stunned))
{
owner.ClearUnitState(UnitState.FleeingMove);
return true;
}
i_nextCheckTime.Update(time_diff);
if (i_nextCheckTime.Passed() && owner.moveSpline.Finalized())
_setTargetLocation(owner);
return true;
}
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Fleeing;
}
ObjectGuid i_frightGUID;
TimeTracker i_nextCheckTime;
}
public class TimedFleeingGenerator : FleeingGenerator<Creature>
{
public TimedFleeingGenerator(ObjectGuid fright, uint time) : base(fright)
{
i_totalFleeTime = new TimeTracker(time);
}
public override void Finalize(Unit owner)
{
owner.RemoveFlag(UnitFields.Flags, UnitFlags.Fleeing);
owner.ClearUnitState(UnitState.Fleeing | UnitState.FleeingMove);
Unit victim = owner.GetVictim();
if (victim != null)
{
if (owner.IsAlive())
{
owner.AttackStop();
owner.ToCreature().GetAI().AttackStart(victim);
}
}
}
public override bool Update(Unit owner, uint time_diff)
{
if (!owner.IsAlive())
return false;
if (owner.HasUnitState(UnitState.Root | UnitState.Stunned))
{
owner.ClearUnitState(UnitState.FleeingMove);
return true;
}
i_totalFleeTime.Update(time_diff);
if (i_totalFleeTime.Passed())
return false;
// This calls grant-parent Update method hiden by FleeingMovementGenerator.Update(Creature &, uint32) version
// This is done instead of casting Unit& to Creature& and call parent method, then we can use Unit directly
return base.Update(owner, time_diff);
}
TimeTracker i_totalFleeTime;
}
}
@@ -0,0 +1,85 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Game.Entities;
using Game.Movement;
namespace Game.AI
{
public class HomeMovementGenerator<T> : MovementGeneratorMedium<T> where T : Creature
{
public override void DoInitialize(T owner)
{
SetTargetLocation(owner);
}
public override void DoFinalize(T owner)
{
if (arrived)
{
owner.ClearUnitState(UnitState.Evade);
owner.SetWalk(true);
owner.LoadCreaturesAddon();
owner.GetAI().JustReachedHome();
owner.SetSpawnHealth();
}
}
public override void DoReset(T owner) { }
public override bool DoUpdate(T owner, uint time_diff)
{
arrived = skipToHome || owner.moveSpline.Finalized();
return !arrived;
}
void SetTargetLocation(T owner)
{
if (owner.HasUnitState(UnitState.Root | UnitState.Stunned | UnitState.Distracted))
{ // if we are ROOT/STUNNED/DISTRACTED even after aura clear, finalize on next update - otherwise we would get stuck in evade
skipToHome = true;
return;
}
MoveSplineInit init = new MoveSplineInit(owner);
float x, y, z, o;
// at apply we can select more nice return points base at current movegen
if (owner.GetMotionMaster().empty() || !owner.GetMotionMaster().top().GetResetPosition(owner, out x, out y, out z))
{
owner.GetHomePosition(out x, out y, out z, out o);
init.SetFacing(o);
}
init.MoveTo(x, y, z);
init.SetWalk(false);
init.Launch();
skipToHome = false;
arrived = false;
owner.ClearUnitState(UnitState.AllState & ~(UnitState.Evade | UnitState.IgnorePathfinding));
}
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Home;
}
bool arrived;
bool skipToHome;
}
}
@@ -0,0 +1,159 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Game.Entities;
namespace Game.Movement
{
public class IdleMovementGenerator : IMovementGenerator
{
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Idle;
}
public bool isActive { get; set; }
public override void Reset(Unit owner)
{
if (!owner.isStopped())
owner.StopMoving();
}
public override void Initialize(Unit owner)
{
Reset(owner);
}
public override void Finalize(Unit owner)
{
}
public override bool Update(Unit owner, uint time_diff)
{
return true;
}
}
public class RotateMovementGenerator : IMovementGenerator
{
public RotateMovementGenerator(uint time, RotateDirection direction)
{
m_duration = time;
m_maxDuration = time;
m_direction = direction;
}
public override void Finalize(Unit owner)
{
owner.ClearUnitState(UnitState.Rotating);
if (owner.IsTypeId(TypeId.Unit))
owner.ToCreature().GetAI().MovementInform(MovementGeneratorType.Rotate, 0);
}
public override void Initialize(Unit owner)
{
if (!owner.IsStopped())
owner.StopMoving();
if (owner.GetVictim())
owner.SetInFront(owner.GetVictim());
owner.AddUnitState(UnitState.Rotating);
owner.AttackStop();
}
public override bool Update(Unit owner, uint time_diff)
{
float angle = owner.GetOrientation();
angle += time_diff * MathFunctions.TwoPi / m_maxDuration * (m_direction == RotateDirection.Left ? 1.0f : -1.0f);
angle = MathFunctions.wrap(angle, 0.0f, MathFunctions.TwoPi);
owner.SetOrientation(angle); // UpdateSplinePosition does not set orientation with UNIT_STATE_ROTATING
owner.SetFacingTo(angle); // Send spline movement to clients
if (m_duration > time_diff)
m_duration -= time_diff;
else
return false;
return true;
}
public override void Reset(Unit owner) { }
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.Rotate; }
uint m_duration, m_maxDuration;
RotateDirection m_direction;
}
public class DistractMovementGenerator : IMovementGenerator
{
public DistractMovementGenerator(uint timer)
{
m_timer = timer;
}
public override void Finalize(Unit owner)
{
owner.ClearUnitState(UnitState.Distracted);
// If this is a creature, then return orientation to original position (for idle movement creatures)
if (owner.IsTypeId(TypeId.Unit))
{
float angle = owner.ToCreature().GetHomePosition().GetOrientation();
owner.SetFacingTo(angle);
}
}
public override void Initialize(Unit owner)
{
// Distracted creatures stand up if not standing
if (!owner.IsStandState())
owner.SetStandState(UnitStandStateType.Stand);
owner.AddUnitState(UnitState.Distracted);
}
public override bool Update(Unit owner, uint time_diff)
{
if (time_diff > m_timer)
return false;
m_timer -= time_diff;
return true;
}
public override void Reset(Unit owner) { }
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.Distract; }
uint m_timer;
}
public class AssistanceDistractMovementGenerator : DistractMovementGenerator
{
public AssistanceDistractMovementGenerator(uint timer) : base(timer) { }
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.AssistanceDistract; }
public override void Finalize(Unit owner)
{
owner.ClearUnitState(UnitState.Distracted);
owner.ToCreature().SetReactState(ReactStates.Aggressive);
}
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Framework.Dynamic;
using Game.Entities;
namespace Game.Movement
{
public abstract class IMovementGenerator
{
public abstract void Finalize(Unit owner);
public abstract void Initialize(Unit owner);
public abstract void Reset(Unit owner);
public abstract bool Update(Unit owner, uint time_diff);
public abstract MovementGeneratorType GetMovementGeneratorType();
public virtual void unitSpeedChanged() { }
// used by Evade code for select point to evade with expected restart default movement
public virtual bool GetResetPosition(Unit u, out float x, out float y, out float z)
{
x = y = z = 0.0f;
return false;
}
}
public abstract class MovementGeneratorMedium<T> : IMovementGenerator where T : Unit
{
public override void Initialize(Unit owner)
{
DoInitialize((T)owner);
isActive = true;
}
public override void Finalize(Unit owner)
{
DoFinalize((T)owner);
}
public override void Reset(Unit owner)
{
DoReset((T)owner);
}
public override bool Update(Unit owner, uint time_diff)
{
return DoUpdate((T)owner, time_diff);
}
public bool isActive { get; set; }
public abstract void DoInitialize(T owner);
public abstract void DoFinalize(T owner);
public abstract void DoReset(T owner);
public abstract bool DoUpdate(T owner, uint time_diff);
}
public class FollowerReference : Reference<Unit, TargetedMovementGeneratorBase>
{
public override void targetObjectBuildLink()
{
getTarget().addFollower(this);
}
public override void targetObjectDestroyLink()
{
getTarget().removeFollower(this);
}
public override void sourceObjectDestroyLink()
{
GetSource().stopFollowing();
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,207 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Game.Entities;
namespace Game.Movement
{
public class PointMovementGenerator<T> : MovementGeneratorMedium<T> where T : Unit
{
public PointMovementGenerator(ulong _id, float _x, float _y, float _z, bool _generatePath, float _speed = 0.0f, Unit faceTarget = null, SpellEffectExtraData spellEffectExtraData = null)
{
id = _id;
i_x = _x;
i_y = _y;
i_z = _z;
speed = _speed;
i_faceTarget = faceTarget;
i_spellEffectExtra = spellEffectExtraData;
m_generatePath = _generatePath;
i_recalculateSpeed = false;
}
public override void DoInitialize(T owner)
{
if (!owner.IsStopped())
owner.StopMoving();
owner.AddUnitState(UnitState.Roaming | UnitState.RoamingMove);
if (id == EventId.ChargePrepath)
return;
MoveSplineInit init = new MoveSplineInit(owner);
init.MoveTo(i_x, i_y, i_z, m_generatePath);
if (speed > 0.0f)
init.SetVelocity(speed);
if (i_faceTarget)
init.SetFacing(i_faceTarget);
if (i_spellEffectExtra != null)
init.SetSpellEffectExtraData(i_spellEffectExtra);
init.Launch();
// Call for creature group update
Creature creature = owner.ToCreature();
if (creature != null)
if (creature.GetFormation() != null && creature.GetFormation().getLeader() == creature)
creature.GetFormation().LeaderMoveTo(i_x, i_y, i_z);
}
public override bool DoUpdate(T owner, uint time_diff)
{
if (owner == null)
return false;
if (owner.HasUnitState(UnitState.Root | UnitState.Stunned))
{
owner.ClearUnitState(UnitState.RoamingMove);
return true;
}
owner.AddUnitState(UnitState.RoamingMove);
if (id != EventId.ChargePrepath && i_recalculateSpeed && !owner.moveSpline.Finalized())
{
i_recalculateSpeed = false;
MoveSplineInit init = new MoveSplineInit(owner);
init.MoveTo(i_x, i_y, i_z, m_generatePath);
if (speed > 0.0f) // Default value for point motion type is 0.0, if 0.0 spline will use GetSpeed on unit
init.SetVelocity(speed);
init.Launch();
// Call for creature group update
Creature creature = owner.ToCreature();
if (creature != null)
if (creature.GetFormation() != null && creature.GetFormation().getLeader() == creature)
creature.GetFormation().LeaderMoveTo(i_x, i_y, i_z);
}
return !owner.moveSpline.Finalized();
}
public override void DoFinalize(T owner)
{
if (owner.HasUnitState(UnitState.Charging))
owner.ClearUnitState(UnitState.Roaming | UnitState.RoamingMove);
if (owner.moveSpline.Finalized())
MovementInform(owner);
}
public override void DoReset(T owner)
{
if (!owner.IsStopped())
owner.StopMoving();
owner.AddUnitState(UnitState.Roaming | UnitState.RoamingMove);
}
public void MovementInform(T unit)
{
if (!unit.IsTypeId(TypeId.Unit))
return;
if (unit.ToCreature().GetAI() != null)
unit.ToCreature().GetAI().MovementInform(MovementGeneratorType.Point, (uint)id);
}
public override void unitSpeedChanged()
{
i_recalculateSpeed = true;
}
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Point;
}
ulong id;
float i_x, i_y, i_z;
float speed;
Unit i_faceTarget;
SpellEffectExtraData i_spellEffectExtra;
bool m_generatePath;
bool i_recalculateSpeed;
}
public class AssistanceMovementGenerator : PointMovementGenerator<Creature>
{
public AssistanceMovementGenerator(float _x, float _y, float _z) : base(0, _x, _y, _z, true) { }
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.Assistance; }
public override void Finalize(Unit owner)
{
owner.ToCreature().SetNoCallAssistance(false);
owner.ToCreature().CallAssistance();
if (owner.IsAlive())
owner.GetMotionMaster().MoveSeekAssistanceDistract(WorldConfig.GetUIntValue(WorldCfg.CreatureFamilyAssistanceDelay));
}
}
// Does almost nothing - just doesn't allows previous movegen interrupt current effect.
public class EffectMovementGenerator : IMovementGenerator
{
public EffectMovementGenerator(uint Id, uint arrivalSpellId = 0, ObjectGuid arrivalSpellTargetGuid = default(ObjectGuid))
{
_Id = Id;
_arrivalSpellId = arrivalSpellId;
_arrivalSpellTargetGuid = arrivalSpellTargetGuid;
}
public override void Finalize(Unit unit)
{
if (_arrivalSpellId != 0)
unit.CastSpell(Global.ObjAccessor.GetUnit(unit, _arrivalSpellTargetGuid), _arrivalSpellId, true);
if (!unit.IsTypeId(TypeId.Unit))
return;
// Need restore previous movement since we have no proper states system
if (unit.IsAlive() && !unit.HasUnitState(UnitState.Confused | UnitState.Fleeing))
{
Unit victim = unit.GetVictim();
if (victim != null)
unit.GetMotionMaster().MoveChase(victim);
else
unit.GetMotionMaster().Initialize();
}
if (unit.ToCreature().GetAI() != null)
unit.ToCreature().GetAI().MovementInform(MovementGeneratorType.Effect, _Id);
}
public override bool Update(Unit owner, uint time_diff)
{
return !owner.moveSpline.Finalized();
}
public override void Initialize(Unit owner) { }
public override void Reset(Unit owner) { }
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.Effect; }
uint _Id;
uint _arrivalSpellId;
ObjectGuid _arrivalSpellTargetGuid;
}
}
@@ -0,0 +1,179 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Game.Entities;
using Game.Maps;
using System;
namespace Game.Movement
{
public class RandomMovementGenerator<T> : MovementGeneratorMedium<T> where T : Creature
{
public RandomMovementGenerator(float spawn_dist = 0.0f)
{
i_nextMoveTime = new TimeTrackerSmall();
wander_distance = spawn_dist;
}
TimeTrackerSmall i_nextMoveTime;
float wander_distance;
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Random;
}
public override void DoInitialize(T creature)
{
if (!creature.IsAlive())
return;
if (wander_distance == 0)
wander_distance = creature.GetRespawnRadius();
if (wander_distance == 0)//Temp fix
wander_distance = 50.0f;
creature.AddUnitState(UnitState.Roaming | UnitState.RoamingMove);
_setRandomLocation(creature);
}
public override void DoFinalize(T creature)
{
creature.ClearUnitState(UnitState.Roaming | UnitState.RoamingMove);
creature.SetWalk(false);
}
public override void DoReset(T creature)
{
DoInitialize(creature);
}
public override bool DoUpdate(T creature, uint diff)
{
if (!creature || !creature.IsAlive())
return false;
if (creature.HasUnitState(UnitState.Root | UnitState.Stunned | UnitState.Distracted))
{
i_nextMoveTime.Reset(0); // Expire the timer
creature.ClearUnitState(UnitState.RoamingMove);
return true;
}
if (creature.moveSpline.Finalized())
{
i_nextMoveTime.Update((int)diff);
if (i_nextMoveTime.Passed())
_setRandomLocation(creature);
}
return true;
}
public void _setRandomLocation(T creature)
{
if (creature.HasUnitState(UnitState.Casting) && !creature.CanMoveDuringChannel())
{
creature.CastStop();
return;
}
float respX, respY, respZ, respO, destX, destY, destZ, travelDistZ;
creature.GetHomePosition(out respX, out respY, out respZ, out respO);
Map map = creature.GetMap();
bool is_air_ok = creature.CanFly();
float angle = (float)(RandomHelper.NextDouble() * MathFunctions.TwoPi);
float range = (float)(RandomHelper.NextDouble() * wander_distance);
float distanceX = (float)(range * Math.Cos(angle));
float distanceY = (float)(range * Math.Sin(angle));
destX = respX + distanceX;
destY = respY + distanceY;
// prevent invalid coordinates generation
GridDefines.NormalizeMapCoord(ref destX);
GridDefines.NormalizeMapCoord(ref destY);
travelDistZ = range; // sin^2+cos^2=1, so travelDistZ=range^2; no need for sqrt below
if (is_air_ok) // 3D system above ground and above water (flying mode)
{
// Limit height change
float distanceZ = (float)(RandomHelper.NextDouble() * travelDistZ / 2.0f);
destZ = respZ + distanceZ;
float levelZ = map.GetWaterOrGroundLevel(creature.GetPhases(), destX, destY, destZ - 2.5f);
// Problem here, we must fly above the ground and water, not under. Let's try on next tick
if (levelZ >= destZ)
return;
}
else // 2D only
{
// 10.0 is the max that vmap high can check (MAX_CAN_FALL_DISTANCE)
travelDistZ = travelDistZ >= 10.0f ? 10.0f : travelDistZ;
// The fastest way to get an accurate result 90% of the time.
// Better result can be obtained like 99% accuracy with a ray light, but the cost is too high and the code is too long.
destZ = map.GetHeight(creature.GetPhases(), destX, destY, respZ + travelDistZ - 2.0f, false);
if (Math.Abs(destZ - respZ) > travelDistZ) // Map check
{
// Vmap Horizontal or above
destZ = map.GetHeight(creature.GetPhases(), destX, destY, respZ - 2.0f, true);
if (Math.Abs(destZ - respZ) > travelDistZ)
{
// Vmap Higher
destZ = map.GetHeight(creature.GetPhases(), destX, destY, respZ + travelDistZ - 2.0f, true);
// let's forget this bad coords where a z cannot be find and retry at next tick
if (Math.Abs(destZ - respZ) > travelDistZ)
return;
}
}
}
if (is_air_ok)
i_nextMoveTime.Reset(0);
else
{
if (RandomHelper.randChance(50))
i_nextMoveTime.Reset(RandomHelper.IRand(5000, 10000));
else
i_nextMoveTime.Reset(RandomHelper.IRand(50, 400));
}
creature.AddUnitState(UnitState.RoamingMove);
if (destZ < 25f)
{
}
MoveSplineInit init = new MoveSplineInit(creature);
init.MoveTo(destX, destY, destZ);
init.SetWalk(true);
init.Launch();
//Call for creature group update
if (creature.GetFormation() != null && creature.GetFormation().getLeader() == creature)
creature.GetFormation().LeaderMoveTo(destX, destY, destZ);
}
public virtual bool GetResetPosition(Creature creature, float x, float y, float z) { return false; }
}
}
@@ -0,0 +1,186 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Framework.GameMath;
using Game.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace Game.Movement
{
public class SplineChainMovementGenerator : IMovementGenerator
{
public SplineChainMovementGenerator(uint id, List<SplineChainLink> chain, bool walk = false)
{
_id = id;
_chain = chain;
_chainSize = (byte)chain.Count;
_walk = walk;
}
public SplineChainMovementGenerator(SplineChainResumeInfo info)
{
_id = info.PointID;
_chain = info.Chain;
_chainSize = (byte)info.Chain.Count;
_walk = info.IsWalkMode;
finished = info.SplineIndex >= info.Chain.Count;
_nextIndex = info.SplineIndex;
_nextFirstWP = info.PointIndex;
_msToNext = info.TimeToNext;
}
uint SendPathSpline(Unit me, List<Vector3> wp)
{
int numWp = wp.Count;
Contract.Assert(numWp > 1, "Every path must have source & destination");
MoveSplineInit init = new MoveSplineInit(me);
if (numWp > 2)
init.MovebyPath(wp.ToArray());
else
init.MoveTo(wp[1], false, true);
init.SetWalk(_walk);
return (uint)init.Launch();
}
void SendSplineFor(Unit me, int index, uint toNext)
{
Contract.Assert(index < _chainSize);
Log.outDebug(LogFilter.Movement, "{0}: Sending spline for {1}.", me.GetGUID().ToString(), index);
SplineChainLink thisLink = _chain[index];
uint actualDuration = SendPathSpline(me, thisLink.Points);
if (actualDuration != thisLink.ExpectedDuration)
{
Log.outDebug(LogFilter.Movement, "{0}: Sent spline for {1}, duration is {2} ms. Expected was {3} ms (delta {4} ms). Adjusting.", me.GetGUID().ToString(), index, actualDuration, thisLink.ExpectedDuration, actualDuration - thisLink.ExpectedDuration);
toNext = (uint)(actualDuration / thisLink.ExpectedDuration * toNext);
}
else
{
Log.outDebug(LogFilter.Movement, "{0}: Sent spline for {1}, duration is {2} ms.", me.GetGUID().ToString(), index, actualDuration);
}
}
public override void Initialize(Unit me)
{
if (_chainSize != 0)
{
if (_nextFirstWP != 0) // this is a resumed movegen that has to start with a partial spline
{
if (finished)
return;
SplineChainLink thisLink = _chain[_nextIndex];
if (_nextFirstWP >= thisLink.Points.Count)
{
Log.outError(LogFilter.Movement, "{0}: Attempted to resume spline chain from invalid resume state ({1}, {2}).", me.GetGUID().ToString(), _nextIndex, _nextFirstWP);
_nextFirstWP = (byte)(thisLink.Points.Count - 1);
}
List<Vector3> partial = new List<Vector3>();
partial.AddRange(thisLink.Points.Skip(_nextFirstWP - 1).ToArray());
SendPathSpline(me, partial);
Log.outDebug(LogFilter.Movement, "{0}: Resumed spline chain generator from resume state.", me.GetGUID().ToString());
++_nextIndex;
if (_msToNext == 0)
_msToNext = 1;
_nextFirstWP = 0;
}
else
{
_msToNext = Math.Max(_chain[_nextIndex].TimeToNext, 1u);
SendSplineFor(me, _nextIndex, _msToNext);
++_nextIndex;
if (_nextIndex >= _chainSize)
_msToNext = 0;
}
}
else
{
Log.outError(LogFilter.Movement, "SplineChainMovementGenerator.Initialize - empty spline chain passed for {0}.", me.GetGUID().ToString());
}
}
public override void Finalize(Unit me)
{
if (!finished)
return;
Creature cMe = me.ToCreature();
if (cMe && cMe.IsAIEnabled)
cMe.GetAI().MovementInform(MovementGeneratorType.SplineChain, _id);
}
public override bool Update(Unit me, uint diff)
{
if (finished)
return false;
// _msToNext being zero here means we're on the final spline
if (_msToNext == 0)
{
finished = me.moveSpline.Finalized();
return !finished;
}
if (_msToNext <= diff)
{
// Send next spline
Log.outDebug(LogFilter.Movement, "{0}: Should send spline {1} ({2} ms late).", me.GetGUID().ToString(), _nextIndex, diff - _msToNext);
_msToNext = Math.Max(_chain[_nextIndex].TimeToNext, 1u);
SendSplineFor(me, _nextIndex, _msToNext);
++_nextIndex;
if (_nextIndex >= _chainSize)
{
// We have reached the final spline, once it finalizes we should also finalize the movegen (start checking on next update)
_msToNext = 0;
return true;
}
}
else
_msToNext -= diff;
return true;
}
SplineChainResumeInfo GetResumeInfo(Unit me)
{
if (_nextIndex == 0)
return new SplineChainResumeInfo(_id, _chain, _walk, 0, 0, _msToNext);
if (me.moveSpline.Finalized())
{
if (_nextIndex < _chainSize)
return new SplineChainResumeInfo(_id, _chain, _walk, _nextIndex, 0, 1u);
else
return new SplineChainResumeInfo();
}
return new SplineChainResumeInfo(_id, _chain, _walk, (byte)(_nextIndex - 1), (byte)(me.moveSpline._currentSplineIdx()), _msToNext);
}
public override void Reset(Unit owner) { }
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.SplineChain; }
uint _id;
List<SplineChainLink> _chain = new List<SplineChainLink>();
byte _chainSize;
bool _walk;
bool finished;
byte _nextIndex;
byte _nextFirstWP; // only used for resuming
uint _msToNext;
}
}
@@ -0,0 +1,401 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Framework.GameMath;
using Game.Entities;
using System;
namespace Game.Movement
{
public interface TargetedMovementGeneratorBase
{
FollowerReference reftarget { get; set; }
void stopFollowing();
}
public abstract class TargetedMovementGeneratorMedium<T, D> : MovementGeneratorMedium<T>, TargetedMovementGeneratorBase where T : Unit
{
public FollowerReference reftarget { get; set; }
public Unit target
{
get { return reftarget.getTarget(); }
}
public void stopFollowing() { }
public TargetedMovementGeneratorMedium(Unit _target, float _offset = 0, float _angle = 0)
{
reftarget = new FollowerReference();
reftarget.link(_target, this);
recheckDistance = new TimeTrackerSmall();
offset = _offset;
angle = _angle;
recalculateTravel = false;
targetReached = false;
}
public override bool DoUpdate(T owner, uint time_diff)
{
if (!reftarget.isValid() || !target.IsInWorld)
return false;
if (owner == null || !owner.IsAlive())
return false;
if (owner.HasUnitState(UnitState.NotMove))
{
_clearUnitStateMove(owner);
return true;
}
// prevent movement while casting spells with cast time or channel time
if (owner.HasUnitState(UnitState.Casting) && !owner.CanMoveDuringChannel())
{
if (!owner.isStopped())
owner.StopMoving();
return true;
}
// prevent crash after creature killed pet
if (_lostTarget(owner))
{
_clearUnitStateMove(owner);
return true;
}
bool targetMoved = false;
recheckDistance.Update((int)time_diff);
if (recheckDistance.Passed())
{
recheckDistance.Reset(100);
//More distance let have better performance, less distance let have more sensitive reaction at target move.
float allowed_dist = 0.0f;// owner.GetCombatReach() + WorldConfig.GetFloatValue(WorldCfg.RateTargetPosRecalculationRange);
if (owner.IsPet() && (owner.GetCharmerOrOwnerGUID() == target.GetGUID()))
allowed_dist = 1.0f; // pet following owner
else
allowed_dist = owner.GetCombatReach() + WorldConfig.GetFloatValue(WorldCfg.RateTargetPosRecalculationRange);
Vector3 dest = owner.moveSpline.FinalDestination();
if (owner.moveSpline.onTransport)
{
float o = 0;
ITransport transport = owner.GetDirectTransport();
if (transport != null)
transport.CalculatePassengerPosition(ref dest.X, ref dest.Y, ref dest.Z, ref o);
}
// First check distance
if (owner.IsTypeId(TypeId.Unit) && (owner.ToCreature().CanFly() || owner.ToCreature().CanSwim()))
targetMoved = !target.IsWithinDist3d(dest.X, dest.Y, dest.Z, allowed_dist);
else
targetMoved = !target.IsWithinDist2d(dest.X, dest.Y, allowed_dist);
// then, if the target is in range, check also Line of Sight.
if (!targetMoved)
targetMoved = !target.IsWithinLOSInMap(owner);
}
if (recalculateTravel || targetMoved)
_setTargetLocation(owner, targetMoved);
if (owner.moveSpline.Finalized())
{
MovementInform(owner);
if (angle == 0.0f && !owner.HasInArc(0.01f, target))
owner.SetInFront(target);
if (!targetReached)
{
targetReached = true;
_reachTarget(owner);
}
}
return true;
}
public override void unitSpeedChanged()
{
recalculateTravel = true;
}
public void _setTargetLocation(T owner, bool updateDestination)
{
if (!reftarget.isValid() || !target.IsInWorld)
return;
if (owner.HasUnitState(UnitState.NotMove))
return;
if (owner.HasUnitState(UnitState.Casting) && !owner.CanMoveDuringChannel())
return;
if (owner.IsTypeId(TypeId.Unit) && !target.isInAccessiblePlaceFor(owner.ToCreature()))
{
owner.ToCreature().SetCannotReachTarget(true);
return;
}
if (owner.IsTypeId(TypeId.Unit) && owner.ToCreature().IsFocusing(null, true))
return;
float x, y, z;
if (updateDestination || i_path == null)
{
if (offset == 0)
{
if (target.IsWithinDistInMap(owner, SharedConst.ContactDistance))
return;
// to nearest contact position
target.GetContactPoint(owner, out x, out y, out z);
}
else
{
float dist = 0;
float size = 0;
// Pets need special handling.
// We need to subtract GetObjectSize() because it gets added back further down the chain
// and that makes pets too far away. Subtracting it allows pets to properly
// be (GetCombatReach() + i_offset) away.
// Only applies when i_target is pet's owner otherwise pets and mobs end up
// doing a "dance" while fighting
if (owner.IsPet() && target.IsTypeId(TypeId.Player))
{
dist = 1.0f;// target.GetCombatReach();
size = 1.0f;// target.GetCombatReach() - target.GetObjectSize();
}
else
{
dist = offset + 1.0f;
size = owner.GetObjectSize();
}
if (target.IsWithinDistInMap(owner, dist))
return;
// to at i_offset distance from target and i_angle from target facing
target.GetClosePoint(out x, out y, out z, size, offset, angle);
}
}
else
{
// the destination has not changed, we just need to refresh the path (usually speed change)
var end = i_path.GetEndPosition();
x = end.X;
y = end.Y;
z = end.Z;
}
if (i_path == null)
i_path = new PathGenerator(owner);
// allow pets to use shortcut if no path found when following their master
bool forceDest = (owner.IsTypeId(TypeId.Unit) && owner.IsPet()
&& owner.HasUnitState(UnitState.Follow));
bool result = i_path.CalculatePath(x, y, z, forceDest);
if (!result && Convert.ToBoolean(i_path.GetPathType() & PathType.NoPath))
{
// Can't reach target
recalculateTravel = true;
if (owner.IsTypeId(TypeId.Unit))
owner.ToCreature().SetCannotReachTarget(true);
return;
}
_addUnitStateMove(owner);
targetReached = false;
recalculateTravel = false;
owner.AddUnitState(UnitState.Chase);
if (owner.IsTypeId(TypeId.Unit))
owner.ToCreature().SetCannotReachTarget(false);
MoveSplineInit init = new MoveSplineInit(owner);
init.MovebyPath(i_path.GetPath());
init.SetWalk(EnableWalking());
// Using the same condition for facing target as the one that is used for SetInFront on movement end
// - applies to ChaseMovementGenerator mostly
if (angle == 0.0f)
init.SetFacing(target);
init.Launch();
}
public void UpdateFinalDistance(float fDistance)
{
if (typeof(T) == typeof(Player))
return;
offset = fDistance;
recalculateTravel = true;
}
bool IsReachable() { return (i_path != null) ? Convert.ToBoolean(i_path.GetPathType() & PathType.Normal) : true; }
public abstract void MovementInform(T unit);
public abstract bool _lostTarget(T u);
public abstract void _clearUnitStateMove(T u);
public abstract void _addUnitStateMove(T u);
public abstract void _reachTarget(T owner);
public abstract bool EnableWalking();
public abstract void _updateSpeed(T u);
#region Fields
PathGenerator i_path;
TimeTrackerSmall recheckDistance;
float offset;
float angle;
public bool recalculateTravel;
bool targetReached;
#endregion
}
public class ChaseMovementGenerator<T> : TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T>> where T : Unit
{
public ChaseMovementGenerator(Unit target)
: base(target)
{
}
public ChaseMovementGenerator(Unit target, float offset, float angle)
: base(target, offset, angle)
{
}
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.Chase; }
public override void DoInitialize(T owner)
{
if (owner.IsTypeId(TypeId.Unit))
owner.SetWalk(false);
owner.AddUnitState(UnitState.Chase | UnitState.ChaseMove);
_setTargetLocation(owner, true);
}
public override void DoFinalize(T owner)
{
owner.ClearUnitState(UnitState.Chase | UnitState.ChaseMove);
}
public override void DoReset(T owner)
{
DoInitialize(owner);
}
public override bool _lostTarget(T u)
{
return u.GetVictim() != target;
}
public override void _clearUnitStateMove(T u)
{
u.ClearUnitState(UnitState.ChaseMove);
}
public override void _addUnitStateMove(T u)
{
u.AddUnitState(UnitState.ChaseMove);
}
public override bool EnableWalking() { return false; }
public override void _updateSpeed(T u) { }
public override void _reachTarget(T owner)
{
_clearUnitStateMove(owner);
if (owner.IsWithinMeleeRange(target))
owner.Attack(target, true);
if (owner.IsTypeId(TypeId.Unit))
owner.ToCreature().SetCannotReachTarget(false);
}
public override void MovementInform(T unit)
{
if (unit.IsTypeId(TypeId.Unit))
{
// Pass back the GUIDLow of the target. If it is pet's owner then PetAI will handle
if (unit.ToCreature().GetAI() != null)
unit.ToCreature().GetAI().MovementInform(MovementGeneratorType.Chase, (uint)target.GetGUID().GetCounter());
}
}
}
public class FollowMovementGenerator<T> : TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T>> where T : Unit
{
public FollowMovementGenerator(Unit target) : base(target) { }
public FollowMovementGenerator(Unit target, float offset, float angle) : base(target, offset, angle) { }
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Follow;
}
public override void _clearUnitStateMove(T u)
{
u.ClearUnitState(UnitState.FollowMove);
}
public override void _addUnitStateMove(T u)
{
u.AddUnitState(UnitState.FollowMove);
}
public override void DoReset(T owner)
{
DoInitialize(owner);
}
public override bool _lostTarget(T u) { return false; }
public override void _reachTarget(T u) { }
public override void DoInitialize(T owner)
{
owner.AddUnitState(UnitState.Follow | UnitState.FollowMove);
_updateSpeed(owner);
_setTargetLocation(owner, true);
}
public override void DoFinalize(T owner)
{
owner.ClearUnitState(UnitState.Follow | UnitState.FollowMove);
_updateSpeed(owner);
}
public override void MovementInform(T unit)
{
if (unit.IsTypeId(TypeId.Player))
return;
// Pass back the GUIDLow of the target. If it is pet's owner then PetAI will handle
if (unit.ToCreature().GetAI() != null)
unit.ToCreature().GetAI().MovementInform(MovementGeneratorType.Follow, (uint)target.GetGUID().GetCounter());
}
public override bool EnableWalking()
{
if (typeof(T) == typeof(Player))
return false;
else
return reftarget.isValid() && target.IsWalking();
}
public override void _updateSpeed(T owner)
{
if (owner.IsTypeId(TypeId.Player))
return;
if (!owner.IsPet() || !owner.IsInWorld || !reftarget.isValid() && target.GetGUID() != owner.GetOwnerGUID())
return;
owner.UpdateSpeed(UnitMoveType.Run);
owner.UpdateSpeed(UnitMoveType.Walk);
owner.UpdateSpeed(UnitMoveType.Swim);
}
}
}
@@ -0,0 +1,503 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Framework.Constants;
using Framework.GameMath;
using Game.DataStorage;
using Game.Entities;
using Game.Maps;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Game.Movement
{
public class WaypointMovementGenerator<T> : MovementGeneratorMedium<T> where T : Creature
{
const int FLIGHT_TRAVEL_UPDATE = 100;
const int TIMEDIFF_NEXT_WP = 250;
public WaypointMovementGenerator(uint pathid = 0, bool _repeating = true)
{
nextMoveTime = new TimeTrackerSmall(0);
isArrivalDone = false;
pathId = pathid;
repeating = _repeating;
}
public override void DoReset(T owner)
{
owner.AddUnitState(UnitState.Roaming | UnitState.RoamingMove);
StartMoveNow(owner);
}
public override void DoFinalize(T owner)
{
owner.ClearUnitState(UnitState.Roaming | UnitState.RoamingMove);
owner.SetWalk(false);
}
public override void DoInitialize(T owner)
{
LoadPath(owner);
owner.AddUnitState(UnitState.Roaming | UnitState.RoamingMove);
}
public override bool DoUpdate(T owner, uint time_diff)
{
// Waypoint movement can be switched on/off
// This is quite handy for escort quests and other stuff
if (owner.HasUnitState(UnitState.NotMove))
{
owner.ClearUnitState(UnitState.RoamingMove);
return true;
}
// prevent a crash at empty waypoint path.
if (path == null || path.Empty())
return false;
if (Stopped())
{
if (CanMove((int)time_diff))
return StartMove(owner);
}
else
{
if (owner.IsStopped())
Stop(WorldConfig.GetIntValue(WorldCfg.CreatureStopForPlayer));
else if (owner.moveSpline.Finalized())
{
OnArrived(owner);
return StartMove(owner);
}
}
return true;
}
void MovementInform(Creature creature)
{
if (creature.IsAIEnabled)
creature.GetAI().MovementInform(MovementGeneratorType.Waypoint, currentNode);
}
void Stop(int time)
{
nextMoveTime.Reset(time);
}
bool Stopped()
{
return !nextMoveTime.Passed();
}
bool CanMove(int diff)
{
nextMoveTime.Update(diff);
return nextMoveTime.Passed();
}
void StartMoveNow(Creature creature)
{
nextMoveTime.Reset(0);
StartMove(creature);
}
bool StartMove(Creature creature)
{
if (path == null || path.Empty())
return false;
if (Stopped())
return true;
bool transportPath = creature.GetTransport() != null;
if (isArrivalDone)
{
if ((currentNode == path.Count - 1) && !repeating) // If that's our last waypoint
{
float x = path[(int)currentNode].x;
float y = path[(int)currentNode].y;
float z = path[(int)currentNode].z;
float o = path[(int)currentNode].orientation;
if (!transportPath)
creature.SetHomePosition(x, y, z, o);
else
{
Transport trans = creature.GetTransport();
if (trans)
{
o -= trans.GetOrientation();
creature.SetTransportHomePosition(x, y, z, o);
trans.CalculatePassengerPosition(ref x, ref y, ref z, ref o);
creature.SetHomePosition(x, y, z, o);
}
else
transportPath = false;
// else if (vehicle) - this should never happen, vehicle offsets are const
}
creature.GetMotionMaster().Initialize();
return false;
}
currentNode = (uint)((currentNode + 1) % path.Count);
}
WaypointData node = path.LookupByIndex((int)currentNode);
isArrivalDone = false;
creature.AddUnitState(UnitState.RoamingMove);
MoveSplineInit init = new MoveSplineInit(creature);
Position formationDest = new Position(node.x, node.y, node.z);
//! If creature is on transport, we assume waypoints set in DB are already transport offsets
if (transportPath)
{
init.DisableTransportPathTransformations();
ITransport trans = creature.GetDirectTransport();
if (trans != null)
trans.CalculatePassengerPosition(ref formationDest.posX, ref formationDest.posY, ref formationDest.posZ, ref formationDest.Orientation);
}
init.MoveTo(formationDest.posX, formationDest.posY, formationDest.posZ);
//! Accepts angles such as 0.00001 and -0.00001, 0 must be ignored, default value in waypoint table
if (node.orientation != 0 && node.delay != 0)
init.SetFacing(formationDest.Orientation);
switch (node.movetype)
{
case WaypointMoveType.Land:
init.SetAnimation(AnimType.ToGround);
break;
case WaypointMoveType.Takeoff:
init.SetAnimation(AnimType.ToFly);
break;
case WaypointMoveType.Run:
init.SetWalk(false);
break;
case WaypointMoveType.Walk:
init.SetWalk(true);
break;
}
init.Launch();
//Call for creature group update
if (creature.GetFormation() != null && creature.GetFormation().getLeader() == creature)
{
creature.SetWalk(node.movetype != WaypointMoveType.Run);
creature.GetFormation().LeaderMoveTo(formationDest.posX, formationDest.posY, formationDest.posZ);
}
return true;
}
void LoadPath(Creature creature)
{
if (pathId == 0)
pathId = creature.GetWaypointPath();
path = Global.WaypointMgr.GetPath(pathId);
if (path == null)
{
// No movement found for entry
Log.outError(LogFilter.ScriptsAi, "WaypointMovementGenerator.LoadPath: creature {0} (Entry: {1} GUID: {2}) doesn't have waypoint path id: {3}", creature.GetName(), creature.GetEntry(), creature.GetGUID().ToString(), pathId);
return;
}
StartMoveNow(creature);
}
void OnArrived(Creature creature)
{
if (path == null || path.Empty())
return;
if (isArrivalDone)
return;
creature.ClearUnitState(UnitState.RoamingMove);
isArrivalDone = true;
var wpData = path.LookupByIndex((int)currentNode);
if (wpData.event_id != 0 && RandomHelper.IRand(0, 99) < wpData.event_chance)
{
Log.outDebug(LogFilter.Unit, "Creature movement start script {0} at point {1} for {2}.", wpData.event_id, currentNode, creature.GetGUID());
creature.GetMap().ScriptsStart(ScriptsType.Waypoint, wpData.event_id, creature, null);
}
// Inform script
MovementInform(creature);
creature.UpdateWaypointID(currentNode);
if (wpData.delay != 0)
{
creature.ClearUnitState(UnitState.RoamingMove);
Stop((int)wpData.delay);
}
}
public override MovementGeneratorType GetMovementGeneratorType()
{
return MovementGeneratorType.Waypoint;
}
TimeTrackerSmall nextMoveTime;
bool isArrivalDone;
uint pathId;
bool repeating;
List<WaypointData> path;
uint currentNode;
}
public class FlightPathMovementGenerator : MovementGeneratorMedium<Player>
{
public FlightPathMovementGenerator() { }
public void LoadPath(Player player, uint startNode = 0)
{
i_path.Clear();
i_currentNode = (int)startNode;
_pointsForPathSwitch.Clear();
var taxi = player.m_taxi.GetPath();
for (int src = 0, dst = 1; dst < taxi.Count; src = dst++)
{
uint path, cost;
Global.ObjectMgr.GetTaxiPath(taxi[src], taxi[dst], out path, out cost);
if (path > CliDB.TaxiPathNodesByPath.Keys.Max())
return;
var nodes = CliDB.TaxiPathNodesByPath[path];
if (!nodes.Empty())
{
TaxiPathNodeRecord start = nodes[0];
TaxiPathNodeRecord end = nodes[nodes.Length - 1];
bool passedPreviousSegmentProximityCheck = false;
for (uint i = 0; i < nodes.Length; ++i)
{
if (passedPreviousSegmentProximityCheck || src == 0 || i_path.Empty() || IsNodeIncludedInShortenedPath(i_path.Last(), nodes[i]))
{
if ((src == 0 || (IsNodeIncludedInShortenedPath(start, nodes[i]) && i >= 2)) &&
(dst == taxi.Count - 1 || (IsNodeIncludedInShortenedPath(end, nodes[i]) && i < nodes.Length - 1)))
{
passedPreviousSegmentProximityCheck = true;
i_path.Add(nodes[i]);
}
}
else
{
i_path.RemoveAt(i_path.Count - 1);
_pointsForPathSwitch[_pointsForPathSwitch.Count - 1].PathIndex -= 1;
}
}
}
_pointsForPathSwitch.Add(new TaxiNodeChangeInfo((uint)(i_path.Count - 1), (int)cost));
}
}
public override void DoInitialize(Player owner)
{
Reset(owner);
InitEndGridInfo();
}
public override void DoFinalize(Player owner)
{
// remove flag to prevent send object build movement packets for flight state and crash (movement generator already not at top of stack)
owner.ClearUnitState(UnitState.InFlight);
owner.Dismount();
owner.RemoveFlag(UnitFields.Flags, UnitFlags.RemoveClientControl | UnitFlags.TaxiFlight);
if (owner.m_taxi.empty())
{
owner.getHostileRefManager().setOnlineOfflineState(true);
// update z position to ground and orientation for landing point
// this prevent cheating with landing point at lags
// when client side flight end early in comparison server side
owner.StopMoving();
}
owner.RemoveFlag(PlayerFields.Flags, PlayerFlags.TaxiBenchmark);
}
public override void DoReset(Player owner)
{
owner.getHostileRefManager().setOnlineOfflineState(false);
owner.AddUnitState(UnitState.InFlight);
owner.SetFlag(UnitFields.Flags, UnitFlags.RemoveClientControl | UnitFlags.TaxiFlight);
MoveSplineInit init = new MoveSplineInit(owner);
uint end = GetPathAtMapEnd();
init.args.path = new Vector3[end];
for (int i = i_currentNode; i != end; ++i)
{
Vector3 vertice = new Vector3(i_path[i].Loc.X, i_path[i].Loc.Y, i_path[i].Loc.Z);
init.args.path[i] = vertice;
}
init.SetFirstPointId(i_currentNode);
init.SetFly();
init.SetSmooth();
init.SetUncompressed();
init.SetWalk(true);
init.SetVelocity(30.0f);
init.Launch();
}
public override bool DoUpdate(Player player, uint time_diff)
{
uint pointId = (uint)player.moveSpline.currentPathIdx();
if (pointId > i_currentNode)
{
bool departureEvent = true;
do
{
DoEventIfAny(player, i_path[i_currentNode], departureEvent);
while (!_pointsForPathSwitch.Empty() && _pointsForPathSwitch[0].PathIndex <= i_currentNode)
{
_pointsForPathSwitch.RemoveAt(0);
player.m_taxi.NextTaxiDestination();
if (!_pointsForPathSwitch.Empty())
{
player.UpdateCriteria(CriteriaTypes.GoldSpentForTravelling, (uint)_pointsForPathSwitch[0].Cost);
player.ModifyMoney(-_pointsForPathSwitch[0].Cost);
}
}
if (pointId == i_currentNode)
break;
if (i_currentNode == _preloadTargetNode)
PreloadEndGrid();
i_currentNode += (departureEvent ? 1 : 0);
departureEvent = !departureEvent;
}
while (true);
}
return i_currentNode < (i_path.Count - 1);
}
public void SetCurrentNodeAfterTeleport()
{
if (i_path.Empty() || i_currentNode >= i_path.Count)
return;
uint map0 = i_path[i_currentNode].MapID;
for (int i = i_currentNode + 1; i < i_path.Count; ++i)
{
if (i_path[i].MapID != map0)
{
i_currentNode = i;
return;
}
}
}
void DoEventIfAny(Player player, TaxiPathNodeRecord node, bool departure)
{
uint eventid = departure ? node.DepartureEventID : node.ArrivalEventID;
if (eventid != 0)
{
Log.outDebug(LogFilter.Scripts, "Taxi {0} event {1} of node {2} of path {3} for player {4}", departure ? "departure" : "arrival", eventid, node.NodeIndex, node.PathID, player.GetName());
player.GetMap().ScriptsStart(ScriptsType.Event, eventid, player, player);
}
}
bool GetResetPos(Player player, out float x, out float y, out float z)
{
TaxiPathNodeRecord node = i_path[i_currentNode];
x = node.Loc.X;
y = node.Loc.Y;
z = node.Loc.Z;
return true;
}
void InitEndGridInfo()
{
int nodeCount = i_path.Count; //! Number of nodes in path.
_endMapId = i_path[nodeCount - 1].MapID; //! MapId of last node
_preloadTargetNode = (uint)nodeCount - 3;
_endGridX = i_path[nodeCount - 1].Loc.X;
_endGridY = i_path[nodeCount - 1].Loc.Y;
}
void PreloadEndGrid()
{
// used to preload the final grid where the flightmaster is
Map endMap = Global.MapMgr.FindBaseNonInstanceMap(_endMapId);
// Load the grid
if (endMap != null)
{
Log.outInfo(LogFilter.Server, "Preloading grid ({0}, {1}) for map {2} at node index {3}/{4}", _endGridX, _endGridY, _endMapId, _preloadTargetNode, i_path.Count - 1);
endMap.LoadGrid(_endGridX, _endGridY);
}
else
Log.outInfo(LogFilter.Server, "Unable to determine map to preload flightmaster grid");
}
uint GetPathAtMapEnd()
{
if (i_currentNode >= i_path.Count)
return (uint)i_path.Count;
uint curMapId = i_path[i_currentNode].MapID;
for (int i = i_currentNode; i < i_path.Count; ++i)
{
if (i_path[i].MapID != curMapId)
return (uint)i;
}
return (uint)i_path.Count;
}
bool IsNodeIncludedInShortenedPath(TaxiPathNodeRecord p1, TaxiPathNodeRecord p2)
{
return p1.MapID != p2.MapID || Math.Pow(p1.Loc.X - p2.Loc.X, 2) + Math.Pow(p1.Loc.Y - p2.Loc.Y, 2) > (40.0f * 40.0f);
}
public override MovementGeneratorType GetMovementGeneratorType() { return MovementGeneratorType.Flight; }
public List<TaxiPathNodeRecord> GetPath() { return i_path; }
bool HasArrived() { return (i_currentNode >= i_path.Count); }
public void SkipCurrentNode() { ++i_currentNode; }
public uint GetCurrentNode() { return (uint)i_currentNode; }
float _endGridX; //! X coord of last node location
float _endGridY; //! Y coord of last node location
uint _endMapId; //! map Id of last node location
uint _preloadTargetNode; //! node index where preloading starts
int i_currentNode;
List<TaxiPathNodeRecord> i_path = new List<TaxiPathNodeRecord>();
List<TaxiNodeChangeInfo> _pointsForPathSwitch = new List<TaxiNodeChangeInfo>(); //! node indexes and costs where TaxiPath changes
class TaxiNodeChangeInfo
{
public TaxiNodeChangeInfo(uint pathIndex, int cost)
{
PathIndex = pathIndex;
Cost = cost;
}
public uint PathIndex;
public int Cost;
}
}
}