Core: SOme code cleanup, more to follow.

This commit is contained in:
hondacrx
2021-03-20 22:48:48 -04:00
parent 62f554f2e0
commit 62ec699ec6
318 changed files with 5080 additions and 5125 deletions
+9 -14
View File
@@ -99,14 +99,12 @@ namespace Game.AI
public static IMovementGenerator SelectMovementAI(Creature creature) public static IMovementGenerator SelectMovementAI(Creature creature)
{ {
switch (creature.DefaultMovementType) return creature.DefaultMovementType switch
{ {
case MovementGeneratorType.Random: MovementGeneratorType.Random => new RandomMovementGenerator(),
return new RandomMovementGenerator(); MovementGeneratorType.Waypoint => new WaypointMovementGenerator(),
case MovementGeneratorType.Waypoint: _ => null,
return new WaypointMovementGenerator(); };
}
return null;
} }
public static GameObjectAI SelectGameObjectAI(GameObject go) public static GameObjectAI SelectGameObjectAI(GameObject go)
@@ -116,14 +114,11 @@ namespace Game.AI
if (scriptedAI != null) if (scriptedAI != null)
return scriptedAI; return scriptedAI;
switch (go.GetAIName()) return go.GetAIName() switch
{ {
case "GameObjectAI": "SmartGameObjectAI" => new SmartGameObjectAI(go),
default: _ => new GameObjectAI(go),
return new GameObjectAI(go); };
case "SmartGameObjectAI":
return new SmartGameObjectAI(go);
}
} }
} }
} }
+2 -2
View File
@@ -21,6 +21,8 @@ namespace Game.AI
{ {
public class AreaTriggerAI public class AreaTriggerAI
{ {
protected AreaTrigger at;
public AreaTriggerAI(AreaTrigger a) public AreaTriggerAI(AreaTrigger a)
{ {
at = a; at = a;
@@ -49,8 +51,6 @@ namespace Game.AI
// Called when the AreaTrigger is removed // Called when the AreaTrigger is removed
public virtual void OnRemove() { } public virtual void OnRemove() { }
protected AreaTrigger at;
} }
class NullAreaTriggerAI : AreaTriggerAI class NullAreaTriggerAI : AreaTriggerAI
+53 -53
View File
@@ -23,13 +23,15 @@ namespace Game.AI
{ {
public class CombatAI : CreatureAI public class CombatAI : CreatureAI
{ {
public List<uint> Spells = new();
public CombatAI(Creature c) : base(c) { } public CombatAI(Creature c) : base(c) { }
public override void InitializeAI() public override void InitializeAI()
{ {
for (var i = 0; i < SharedConst.MaxCreatureSpells; ++i) for (var i = 0; i < SharedConst.MaxCreatureSpells; ++i)
if (me.m_spells[i] != 0 && Global.SpellMgr.HasSpellInfo(me.m_spells[i], me.GetMap().GetDifficultyID())) if (me.m_spells[i] != 0 && Global.SpellMgr.HasSpellInfo(me.m_spells[i], me.GetMap().GetDifficultyID()))
spells.Add(me.m_spells[i]); Spells.Add(me.m_spells[i]);
base.InitializeAI(); base.InitializeAI();
} }
@@ -41,7 +43,7 @@ namespace Game.AI
public override void JustDied(Unit killer) public override void JustDied(Unit killer)
{ {
foreach (var id in spells) foreach (var id in Spells)
{ {
AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID()); AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID());
if (info.condition == AICondition.Die) if (info.condition == AICondition.Die)
@@ -51,7 +53,7 @@ namespace Game.AI
public override void EnterCombat(Unit victim) public override void EnterCombat(Unit victim)
{ {
foreach (var id in spells) foreach (var id in Spells)
{ {
AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID()); AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID());
if (info.condition == AICondition.Aggro) if (info.condition == AICondition.Aggro)
@@ -86,8 +88,6 @@ namespace Game.AI
{ {
_events.RescheduleEvent(spellId, unTimeMs); _events.RescheduleEvent(spellId, unTimeMs);
} }
public List<uint> spells = new List<uint>();
} }
public class AggressorAI : CreatureAI public class AggressorAI : CreatureAI
@@ -105,41 +105,43 @@ namespace Game.AI
public class CasterAI : CombatAI public class CasterAI : CombatAI
{ {
float _attackDist;
public CasterAI(Creature c) public CasterAI(Creature c)
: base(c) : base(c)
{ {
m_attackDist = SharedConst.MeleeRange; _attackDist = SharedConst.MeleeRange;
} }
public override void InitializeAI() public override void InitializeAI()
{ {
base.InitializeAI(); base.InitializeAI();
m_attackDist = 30.0f; _attackDist = 30.0f;
foreach (var id in spells) foreach (var id in Spells)
{ {
AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID()); AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID());
if (info.condition == AICondition.Combat && m_attackDist > info.maxRange) if (info.condition == AICondition.Combat && _attackDist > info.maxRange)
m_attackDist = info.maxRange; _attackDist = info.maxRange;
} }
if (m_attackDist == 30.0f) if (_attackDist == 30.0f)
m_attackDist = SharedConst.MeleeRange; _attackDist = SharedConst.MeleeRange;
} }
public override void AttackStart(Unit victim) public override void AttackStart(Unit victim)
{ {
AttackStartCaster(victim, m_attackDist); AttackStartCaster(victim, _attackDist);
} }
public override void EnterCombat(Unit victim) public override void EnterCombat(Unit victim)
{ {
if (spells.Empty()) if (Spells.Empty())
return; return;
int spell = (int)(RandomHelper.Rand32() % spells.Count); int spell = (int)(RandomHelper.Rand32() % Spells.Count);
uint count = 0; uint count = 0;
foreach (var id in spells) foreach (var id in Spells)
{ {
AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID()); AISpellInfoType info = GetAISpellInfo(id, me.GetMap().GetDifficultyID());
if (info.condition == AICondition.Aggro) if (info.condition == AICondition.Aggro)
@@ -149,7 +151,7 @@ namespace Game.AI
uint cooldown = info.realCooldown; uint cooldown = info.realCooldown;
if (count == spell) if (count == spell)
{ {
DoCast(spells[spell]); DoCast(Spells[spell]);
cooldown += (uint)me.GetCurrentSpellCastTime(id); cooldown += (uint)me.GetCurrentSpellCastTime(id);
} }
_events.ScheduleEvent(id, cooldown); _events.ScheduleEvent(id, cooldown);
@@ -182,23 +184,22 @@ namespace Game.AI
_events.ScheduleEvent(spellId, (casttime != 0 ? casttime : 500) + info.realCooldown); _events.ScheduleEvent(spellId, (casttime != 0 ? casttime : 500) + info.realCooldown);
} }
} }
float m_attackDist;
} }
public class ArcherAI : CreatureAI public class ArcherAI : CreatureAI
{ {
public ArcherAI(Creature c) float _minRange;
: base(c)
public ArcherAI(Creature c) : base(c)
{ {
if (me.m_spells[0] == 0) if (me.m_spells[0] == 0)
Log.outError(LogFilter.ScriptsAi, "ArcherAI set for creature (entry = {0}) with spell1=0. AI will do nothing", me.GetEntry()); Log.outError(LogFilter.ScriptsAi, "ArcherAI set for creature (entry = {0}) with spell1=0. AI will do nothing", me.GetEntry());
var spellInfo = Global.SpellMgr.GetSpellInfo(me.m_spells[0], me.GetMap().GetDifficultyID()); var spellInfo = Global.SpellMgr.GetSpellInfo(me.m_spells[0], me.GetMap().GetDifficultyID());
m_minRange = spellInfo != null ? spellInfo.GetMinRange(false) : 0; _minRange = spellInfo != null ? spellInfo.GetMinRange(false) : 0;
if (m_minRange == 0) if (_minRange == 0)
m_minRange = SharedConst.MeleeRange; _minRange = SharedConst.MeleeRange;
me.m_CombatDistance = spellInfo != null ? spellInfo.GetMaxRange(false) : 0; me.m_CombatDistance = spellInfo != null ? spellInfo.GetMaxRange(false) : 0;
me.m_SightDistance = me.m_CombatDistance; me.m_SightDistance = me.m_CombatDistance;
} }
@@ -208,7 +209,7 @@ namespace Game.AI
if (who == null) if (who == null)
return; return;
if (me.IsWithinCombatRange(who, m_minRange)) if (me.IsWithinCombatRange(who, _minRange))
{ {
if (me.Attack(who, true) && !who.IsFlying()) if (me.Attack(who, true) && !who.IsFlying())
me.GetMotionMaster().MoveChase(who); me.GetMotionMaster().MoveChase(who);
@@ -222,22 +223,23 @@ namespace Game.AI
if (who.IsFlying()) if (who.IsFlying())
me.GetMotionMaster().MoveIdle(); me.GetMotionMaster().MoveIdle();
} }
public override void UpdateAI(uint diff) public override void UpdateAI(uint diff)
{ {
if (!UpdateVictim()) if (!UpdateVictim())
return; return;
if (!me.IsWithinCombatRange(me.GetVictim(), m_minRange)) if (!me.IsWithinCombatRange(me.GetVictim(), _minRange))
DoSpellAttackIfReady(me.m_spells[0]); DoSpellAttackIfReady(me.m_spells[0]);
else else
DoMeleeAttackIfReady(); DoMeleeAttackIfReady();
} }
float m_minRange;
} }
public class TurretAI : CreatureAI public class TurretAI : CreatureAI
{ {
float _minRange;
public TurretAI(Creature c) public TurretAI(Creature c)
: base(c) : base(c)
{ {
@@ -245,7 +247,7 @@ namespace Game.AI
Log.outError(LogFilter.Server, "TurretAI set for creature (entry = {0}) with spell1=0. AI will do nothing", me.GetEntry()); Log.outError(LogFilter.Server, "TurretAI set for creature (entry = {0}) with spell1=0. AI will do nothing", me.GetEntry());
var spellInfo = Global.SpellMgr.GetSpellInfo(me.m_spells[0], me.GetMap().GetDifficultyID()); var spellInfo = Global.SpellMgr.GetSpellInfo(me.m_spells[0], me.GetMap().GetDifficultyID());
m_minRange = spellInfo != null ? spellInfo.GetMinRange(false) : 0; _minRange = spellInfo != null ? spellInfo.GetMinRange(false) : 0;
me.m_CombatDistance = spellInfo != null ? spellInfo.GetMaxRange(false) : 0; me.m_CombatDistance = spellInfo != null ? spellInfo.GetMaxRange(false) : 0;
me.m_SightDistance = me.m_CombatDistance; me.m_SightDistance = me.m_CombatDistance;
} }
@@ -254,7 +256,7 @@ namespace Game.AI
{ {
// todo use one function to replace it // todo use one function to replace it
if (!me.IsWithinCombatRange(me.GetVictim(), me.m_CombatDistance) if (!me.IsWithinCombatRange(me.GetVictim(), me.m_CombatDistance)
|| (m_minRange != 0 && me.IsWithinCombatRange(me.GetVictim(), m_minRange))) || (_minRange != 0 && me.IsWithinCombatRange(me.GetVictim(), _minRange)))
return false; return false;
return true; return true;
} }
@@ -272,8 +274,6 @@ namespace Game.AI
DoSpellAttackIfReady(me.m_spells[0]); DoSpellAttackIfReady(me.m_spells[0]);
} }
float m_minRange;
} }
public class VehicleAI : CreatureAI public class VehicleAI : CreatureAI
@@ -281,27 +281,32 @@ namespace Game.AI
const int VEHICLE_CONDITION_CHECK_TIME = 1000; const int VEHICLE_CONDITION_CHECK_TIME = 1000;
const int VEHICLE_DISMISS_TIME = 5000; const int VEHICLE_DISMISS_TIME = 5000;
bool _hasConditions;
uint _conditionsTimer;
bool _doDismiss;
uint _dismissTimer;
public VehicleAI(Creature creature) : base(creature) public VehicleAI(Creature creature) : base(creature)
{ {
m_ConditionsTimer = VEHICLE_CONDITION_CHECK_TIME; _conditionsTimer = VEHICLE_CONDITION_CHECK_TIME;
LoadConditions(); LoadConditions();
m_DoDismiss = false; _doDismiss = false;
m_DismissTimer = VEHICLE_DISMISS_TIME; _dismissTimer = VEHICLE_DISMISS_TIME;
} }
public override void UpdateAI(uint diff) public override void UpdateAI(uint diff)
{ {
CheckConditions(diff); CheckConditions(diff);
if (m_DoDismiss) if (_doDismiss)
{ {
if (m_DismissTimer < diff) if (_dismissTimer < diff)
{ {
m_DoDismiss = false; _doDismiss = false;
me.DespawnOrUnsummon(); me.DespawnOrUnsummon();
} }
else else
m_DismissTimer -= diff; _dismissTimer -= diff;
} }
} }
@@ -311,25 +316,25 @@ namespace Game.AI
public override void OnCharmed(bool apply) public override void OnCharmed(bool apply)
{ {
if (!me.GetVehicleKit().IsVehicleInUse() && !apply && m_HasConditions)//was used and has conditions if (!me.GetVehicleKit().IsVehicleInUse() && !apply && _hasConditions)//was used and has conditions
m_DoDismiss = true;//needs reset _doDismiss = true;//needs reset
else if (apply) else if (apply)
m_DoDismiss = false;//in use again _doDismiss = false;//in use again
m_DismissTimer = VEHICLE_DISMISS_TIME;//reset timer _dismissTimer = VEHICLE_DISMISS_TIME;//reset timer
} }
void LoadConditions() void LoadConditions()
{ {
m_HasConditions = Global.ConditionMgr.HasConditionsForNotGroupedEntry(ConditionSourceType.CreatureTemplateVehicle, me.GetEntry()); _hasConditions = Global.ConditionMgr.HasConditionsForNotGroupedEntry(ConditionSourceType.CreatureTemplateVehicle, me.GetEntry());
} }
void CheckConditions(uint diff) void CheckConditions(uint diff)
{ {
if (!m_HasConditions) if (!_hasConditions)
return; return;
if (m_ConditionsTimer <= diff) if (_conditionsTimer <= diff)
{ {
Vehicle vehicleKit = me.GetVehicleKit(); Vehicle vehicleKit = me.GetVehicleKit();
if (vehicleKit) if (vehicleKit)
@@ -352,16 +357,11 @@ namespace Game.AI
} }
} }
m_ConditionsTimer = VEHICLE_CONDITION_CHECK_TIME; _conditionsTimer = VEHICLE_CONDITION_CHECK_TIME;
} }
else else
m_ConditionsTimer -= diff; _conditionsTimer -= diff;
} }
bool m_HasConditions;
uint m_ConditionsTimer;
bool m_DoDismiss;
uint m_DismissTimer;
} }
public class ReactorAI : CreatureAI public class ReactorAI : CreatureAI
+33 -32
View File
@@ -27,10 +27,20 @@ namespace Game.AI
{ {
public class CreatureAI : UnitAI public class CreatureAI : UnitAI
{ {
bool _moveInLineOfSightLocked;
List<AreaBoundary> _boundary = new();
bool _negateBoundary;
protected new Creature me;
protected EventMap _events = new();
protected TaskScheduler _scheduler = new();
protected InstanceScript _instanceScript;
public CreatureAI(Creature _creature) : base(_creature) public CreatureAI(Creature _creature) : base(_creature)
{ {
me = _creature; me = _creature;
MoveInLineOfSight_locked = false; _moveInLineOfSightLocked = false;
} }
public override void OnCharmed(bool apply) public override void OnCharmed(bool apply)
@@ -109,12 +119,12 @@ namespace Game.AI
public virtual void MoveInLineOfSight_Safe(Unit who) public virtual void MoveInLineOfSight_Safe(Unit who)
{ {
if (MoveInLineOfSight_locked) if (_moveInLineOfSightLocked)
return; return;
MoveInLineOfSight_locked = true; _moveInLineOfSightLocked = true;
MoveInLineOfSight(who); MoveInLineOfSight(who);
MoveInLineOfSight_locked = false; _moveInLineOfSightLocked = false;
} }
public virtual void MoveInLineOfSight(Unit who) public virtual void MoveInLineOfSight(Unit who)
@@ -126,7 +136,7 @@ namespace Game.AI
me.EngageWithTarget(who); me.EngageWithTarget(who);
} }
void _OnOwnerCombatInteraction(Unit target) void OnOwnerCombatInteraction(Unit target)
{ {
if (target == null || !me.IsAlive()) if (target == null || !me.IsAlive())
return; return;
@@ -165,7 +175,7 @@ namespace Game.AI
if (!_EnterEvadeMode(why)) if (!_EnterEvadeMode(why))
return; return;
Log.outDebug( LogFilter.Unit, "Creature {0} enters evade mode.", me.GetEntry()); Log.outDebug(LogFilter.Unit, "Creature {0} enters evade mode.", me.GetEntry());
if (me.GetVehicle() == null) // otherwise me will be in evade mode forever if (me.GetVehicle() == null) // otherwise me will be in evade mode forever
{ {
@@ -190,7 +200,7 @@ namespace Game.AI
me.GetVehicleKit().Reset(true); me.GetVehicleKit().Reset(true);
} }
void SetGazeOn(Unit target) public void SetGazeOn(Unit target)
{ {
if (me.IsValidAttackTarget(target) && target != me.GetVictim()) if (me.IsValidAttackTarget(target) && target != me.GetVictim())
{ {
@@ -276,9 +286,9 @@ namespace Game.AI
if (_boundary.Empty()) if (_boundary.Empty())
return CypherStrings.CreatureMovementNotBounded; return CypherStrings.CreatureMovementNotBounded;
List<KeyValuePair<int, int>> Q = new List<KeyValuePair<int, int>>(); List<KeyValuePair<int, int>> Q = new();
List<KeyValuePair<int, int>> alreadyChecked = new List<KeyValuePair<int, int>>(); List<KeyValuePair<int, int>> alreadyChecked = new();
List<KeyValuePair<int, int>> outOfBounds = new List<KeyValuePair<int, int>>(); List<KeyValuePair<int, int>> outOfBounds = new();
Position startPosition = owner.GetPosition(); Position startPosition = owner.GetPosition();
if (!CheckBoundary(startPosition)) // fall back to creature position if (!CheckBoundary(startPosition)) // fall back to creature position
@@ -309,7 +319,7 @@ namespace Game.AI
} }
if (!alreadyChecked.Contains(next)) // never check a coordinate twice if (!alreadyChecked.Contains(next)) // never check a coordinate twice
{ {
Position nextPos = new Position(startPosition.GetPositionX() + next.Key * SharedConst.BoundaryVisualizeStepSize, startPosition.GetPositionY() + next.Value * SharedConst.BoundaryVisualizeStepSize, startPosition.GetPositionZ()); Position nextPos = new(startPosition.GetPositionX() + next.Key * SharedConst.BoundaryVisualizeStepSize, startPosition.GetPositionY() + next.Value * SharedConst.BoundaryVisualizeStepSize, startPosition.GetPositionZ());
if (CheckBoundary(nextPos)) if (CheckBoundary(nextPos))
Q.Add(next); Q.Add(next);
else else
@@ -390,7 +400,7 @@ namespace Game.AI
return true; return true;
} }
public void SetBoundary(List<AreaBoundary> boundary, bool negateBoundaries = false) public void SetBoundary(List<AreaBoundary> boundary, bool negateBoundaries = false)
{ {
_boundary = boundary; _boundary = boundary;
@@ -408,8 +418,8 @@ namespace Game.AI
public virtual void JustDied(Unit killer) { } public virtual void JustDied(Unit killer) { }
// Called when the creature kills a unit // Called when the creature kills a unit
public virtual void KilledUnit(Unit victim) {} public virtual void KilledUnit(Unit victim) { }
// Called when the creature summon successfully other creature // Called when the creature summon successfully other creature
public virtual void JustSummoned(Creature summon) { } public virtual void JustSummoned(Creature summon) { }
public virtual void IsSummonedBy(Unit summoner) { } public virtual void IsSummonedBy(Unit summoner) { }
@@ -430,11 +440,11 @@ namespace Game.AI
public virtual void JustUnregisteredAreaTrigger(AreaTrigger areaTrigger) { } public virtual void JustUnregisteredAreaTrigger(AreaTrigger areaTrigger) { }
// Called when hit by a spell // Called when hit by a spell
public virtual void SpellHit(Unit caster, SpellInfo spell) {} public virtual void SpellHit(Unit caster, SpellInfo spell) { }
// Called when spell hits a target // Called when spell hits a target
public virtual void SpellHitTarget(Unit target, SpellInfo spell) {} public virtual void SpellHitTarget(Unit target, SpellInfo spell) { }
public virtual bool IsEscorted() { return false; } public virtual bool IsEscorted() { return false; }
// Called when creature appears in the world (spawn, respawn, grid load etc...) // Called when creature appears in the world (spawn, respawn, grid load etc...)
@@ -450,18 +460,18 @@ namespace Game.AI
// Called at reaching home after evade // Called at reaching home after evade
public virtual void JustReachedHome() { } public virtual void JustReachedHome() { }
// Called at text emote receive from player // Called at text emote receive from player
public virtual void ReceiveEmote(Player player, TextEmotes emoteId) { } public virtual void ReceiveEmote(Player player, TextEmotes emoteId) { }
// Called when owner takes damage // Called when owner takes damage
public virtual void OwnerAttackedBy(Unit attacker) { _OnOwnerCombatInteraction(attacker); } public virtual void OwnerAttackedBy(Unit attacker) { OnOwnerCombatInteraction(attacker); }
// Called when owner attacks something // Called when owner attacks something
public virtual void OwnerAttacked(Unit target) { _OnOwnerCombatInteraction(target); } public virtual void OwnerAttacked(Unit target) { OnOwnerCombatInteraction(target); }
// called when the corpse of this creature gets removed // called when the corpse of this creature gets removed
public virtual void CorpseRemoved(long respawnDelay) {} public virtual void CorpseRemoved(long respawnDelay) { }
public virtual void PassengerBoarded(Unit passenger, sbyte seatId, bool apply) { } public virtual void PassengerBoarded(Unit passenger, sbyte seatId, bool apply) { }
@@ -481,18 +491,9 @@ namespace Game.AI
/// </summary> /// </summary>
/// <param name="onlyIfActive"></param> /// <param name="onlyIfActive"></param>
/// <returns></returns> /// <returns></returns>
public virtual bool IsEscortNPC(bool onlyIfActive) { return false; } public virtual bool IsEscortNPC(bool onlyIfActive) { return false; }
List<AreaBoundary> GetBoundary() { return _boundary; }
bool MoveInLineOfSight_locked; public List<AreaBoundary> GetBoundary() { return _boundary; }
protected new Creature me;
List<AreaBoundary> _boundary = new List<AreaBoundary>();
bool _negateBoundary;
protected EventMap _events = new EventMap();
protected TaskScheduler _scheduler = new TaskScheduler();
protected InstanceScript _instance;
} }
public struct AISpellInfoType public struct AISpellInfoType
+6 -6
View File
@@ -15,15 +15,20 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using Framework.Constants;
using Framework.Dynamic; using Framework.Dynamic;
using Game.Entities; using Game.Entities;
using Game.Spells; using Game.Spells;
using Framework.Constants;
namespace Game.AI namespace Game.AI
{ {
public class GameObjectAI public class GameObjectAI
{ {
protected TaskScheduler _scheduler;
protected EventMap _events;
public GameObject me;
public GameObjectAI(GameObject gameObject) public GameObjectAI(GameObject gameObject)
{ {
me = gameObject; me = gameObject;
@@ -93,10 +98,5 @@ namespace Game.AI
public virtual void OnStateChanged(GameObjectState state) { } public virtual void OnStateChanged(GameObjectState state) { }
public virtual void EventInform(uint eventId) { } public virtual void EventInform(uint eventId) { }
public virtual void SpellHit(Unit unit, SpellInfo spellInfo) { } public virtual void SpellHit(Unit unit, SpellInfo spellInfo) { }
protected TaskScheduler _scheduler;
protected EventMap _events;
public GameObject me;
} }
} }
+21 -24
View File
@@ -26,14 +26,15 @@ namespace Game.AI
{ {
public class PetAI : CreatureAI public class PetAI : CreatureAI
{ {
List<ObjectGuid> _allySet = new();
uint _updateAlliesTimer;
public PetAI(Creature c) : base(c) public PetAI(Creature c) : base(c)
{ {
i_tracker = new TimeTracker(5000);
UpdateAllies(); UpdateAllies();
} }
bool _needToStop() bool NeedToStop()
{ {
// This is needed for charmed creatures, as once their target was reset other effects can trigger threat // This is needed for charmed creatures, as once their target was reset other effects can trigger threat
if (me.IsCharmed() && me.GetVictim() == me.GetCharmer()) if (me.IsCharmed() && me.GetVictim() == me.GetCharmer())
@@ -48,7 +49,7 @@ namespace Game.AI
return !me.IsValidAttackTarget(me.GetVictim()); return !me.IsValidAttackTarget(me.GetVictim());
} }
void _stopAttack() void StopAttack()
{ {
if (!me.IsAlive()) if (!me.IsAlive())
{ {
@@ -74,11 +75,11 @@ namespace Game.AI
Unit owner = me.GetCharmerOrOwner(); Unit owner = me.GetCharmerOrOwner();
if (m_updateAlliesTimer <= diff) if (_updateAlliesTimer <= diff)
// UpdateAllies self set update timer // UpdateAllies self set update timer
UpdateAllies(); UpdateAllies();
else else
m_updateAlliesTimer -= diff; _updateAlliesTimer -= diff;
if (me.GetVictim() && me.GetVictim().IsAlive()) if (me.GetVictim() && me.GetVictim().IsAlive())
{ {
@@ -90,10 +91,10 @@ namespace Game.AI
return; return;
} }
if (_needToStop()) if (NeedToStop())
{ {
Log.outDebug(LogFilter.Server, "Pet AI stopped attacking [{0}]", me.GetGUID().ToString()); Log.outDebug(LogFilter.Server, "Pet AI stopped attacking [{0}]", me.GetGUID().ToString());
_stopAttack(); StopAttack();
return; return;
} }
@@ -129,7 +130,7 @@ namespace Game.AI
// Autocast (casted only in combat or persistent spells in any state) // Autocast (casted only in combat or persistent spells in any state)
if (!me.HasUnitState(UnitState.Casting)) if (!me.HasUnitState(UnitState.Casting))
{ {
List<Tuple<Unit, Spell>> targetSpellStore = new List<Tuple<Unit, Spell>>(); List<Tuple<Unit, Spell>> targetSpellStore = new();
for (byte i = 0; i < me.GetPetAutoSpellSize(); ++i) for (byte i = 0; i < me.GetPetAutoSpellSize(); ++i)
{ {
@@ -157,7 +158,7 @@ namespace Game.AI
continue; continue;
} }
Spell spell = new Spell(me, spellInfo, TriggerCastFlags.None); Spell spell = new(me, spellInfo, TriggerCastFlags.None);
bool spellUsed = false; bool spellUsed = false;
// Some spells can target enemy or friendly (DK Ghoul's Leap) // Some spells can target enemy or friendly (DK Ghoul's Leap)
@@ -185,7 +186,7 @@ namespace Game.AI
// No enemy, check friendly // No enemy, check friendly
if (!spellUsed) if (!spellUsed)
{ {
foreach (var tar in m_AllySet) foreach (var tar in _allySet)
{ {
Unit ally = Global.ObjAccessor.GetUnit(me, tar); Unit ally = Global.ObjAccessor.GetUnit(me, tar);
@@ -208,7 +209,7 @@ namespace Game.AI
} }
else if (me.GetVictim() && CanAIAttack(me.GetVictim()) && spellInfo.CanBeUsedInCombat()) else if (me.GetVictim() && CanAIAttack(me.GetVictim()) && spellInfo.CanBeUsedInCombat())
{ {
Spell spell = new Spell(me, spellInfo, TriggerCastFlags.None); Spell spell = new(me, spellInfo, TriggerCastFlags.None);
if (spell.CanAutoCast(me.GetVictim())) if (spell.CanAutoCast(me.GetVictim()))
targetSpellStore.Add(Tuple.Create(me.GetVictim(), spell)); targetSpellStore.Add(Tuple.Create(me.GetVictim(), spell));
else else
@@ -226,7 +227,7 @@ namespace Game.AI
targetSpellStore.RemoveAt(index); targetSpellStore.RemoveAt(index);
SpellCastTargets targets = new SpellCastTargets(); SpellCastTargets targets = new();
targets.SetUnitTarget(target); targets.SetUnitTarget(target);
spell.Prepare(targets); spell.Prepare(targets);
@@ -245,7 +246,7 @@ namespace Game.AI
void UpdateAllies() void UpdateAllies()
{ {
m_updateAlliesTimer = 10 * Time.InMilliseconds; // update friendly targets every 10 seconds, lesser checks increase performance _updateAlliesTimer = 10 * Time.InMilliseconds; // update friendly targets every 10 seconds, lesser checks increase performance
Unit owner = me.GetCharmerOrOwner(); Unit owner = me.GetCharmerOrOwner();
if (!owner) if (!owner)
@@ -257,15 +258,15 @@ namespace Game.AI
group = player.GetGroup(); group = player.GetGroup();
//only pet and owner/not in group.ok //only pet and owner/not in group.ok
if (m_AllySet.Count == 2 && !group) if (_allySet.Count == 2 && !group)
return; return;
//owner is in group; group members filled in already (no raid . subgroupcount = whole count) //owner is in group; group members filled in already (no raid . subgroupcount = whole count)
if (group && !group.IsRaidGroup() && m_AllySet.Count == (group.GetMembersCount() + 2)) if (group && !group.IsRaidGroup() && _allySet.Count == (group.GetMembersCount() + 2))
return; return;
m_AllySet.Clear(); _allySet.Clear();
m_AllySet.Add(me.GetGUID()); _allySet.Add(me.GetGUID());
if (group) //add group if (group) //add group
{ {
for (GroupReference refe = group.GetFirstMember(); refe != null; refe = refe.Next()) for (GroupReference refe = group.GetFirstMember(); refe != null; refe = refe.Next())
@@ -277,11 +278,11 @@ namespace Game.AI
if (target.GetGUID() == owner.GetGUID()) if (target.GetGUID() == owner.GetGUID())
continue; continue;
m_AllySet.Add(target.GetGUID()); _allySet.Add(target.GetGUID());
} }
} }
else //remove group else //remove group
m_AllySet.Add(owner.GetGUID()); _allySet.Add(owner.GetGUID());
} }
public override void KilledUnit(Unit victim) public override void KilledUnit(Unit victim)
@@ -639,9 +640,5 @@ namespace Game.AI
public override void MoveInLineOfSight(Unit who) { } public override void MoveInLineOfSight(Unit who) { }
public override void MoveInLineOfSight_Safe(Unit who) { } public override void MoveInLineOfSight_Safe(Unit who) { }
public override void EnterEvadeMode(EvadeReason why) { } public override void EnterEvadeMode(EvadeReason why) { }
TimeTracker i_tracker;
List<ObjectGuid> m_AllySet = new List<ObjectGuid>();
uint m_updateAlliesTimer;
} }
} }
+6 -6
View File
@@ -23,9 +23,11 @@ namespace Game.AI
{ {
public class TotemAI : CreatureAI public class TotemAI : CreatureAI
{ {
ObjectGuid _victimGuid;
public TotemAI(Creature c) : base(c) public TotemAI(Creature c) : base(c)
{ {
i_victimGuid = ObjectGuid.Empty; _victimGuid = ObjectGuid.Empty;
} }
public override void EnterEvadeMode(EvadeReason why) public override void EnterEvadeMode(EvadeReason why)
@@ -51,7 +53,7 @@ namespace Game.AI
// SpellModOp.Range not applied in this place just because not existence range mods for attacking totems // SpellModOp.Range not applied in this place just because not existence range mods for attacking totems
Unit victim = !i_victimGuid.IsEmpty() ? Global.ObjAccessor.GetUnit(me, i_victimGuid) : null; Unit victim = !_victimGuid.IsEmpty() ? Global.ObjAccessor.GetUnit(me, _victimGuid) : null;
// Search victim if no, not attackable, or out of range, or friendly (possible in case duel end) // Search victim if no, not attackable, or out of range, or friendly (possible in case duel end)
if (victim == null || !victim.IsTargetableForAttack() || !me.IsWithinDistInMap(victim, max_range) || if (victim == null || !victim.IsTargetableForAttack() || !me.IsWithinDistInMap(victim, max_range) ||
@@ -67,15 +69,13 @@ namespace Game.AI
if (victim != null) if (victim != null)
{ {
// remember // remember
i_victimGuid = victim.GetGUID(); _victimGuid = victim.GetGUID();
// attack // attack
me.CastSpell(victim, me.ToTotem().GetSpell()); me.CastSpell(victim, me.ToTotem().GetSpell());
} }
else else
i_victimGuid.Clear(); _victimGuid.Clear();
} }
ObjectGuid i_victimGuid;
} }
} }
+39 -46
View File
@@ -27,6 +27,10 @@ namespace Game.AI
{ {
public class UnitAI public class UnitAI
{ {
static Dictionary<(uint id, Difficulty difficulty), AISpellInfoType> _aiSpellInfo = new();
protected Unit me { get; private set; }
public UnitAI(Unit _unit) public UnitAI(Unit _unit)
{ {
me = _unit; me = _unit;
@@ -59,7 +63,7 @@ namespace Game.AI
void SortByDistance(List<Unit> targets, bool ascending) void SortByDistance(List<Unit> targets, bool ascending)
{ {
targets.Sort(new ObjectDistanceOrderPred(me, true)); targets.Sort(new ObjectDistanceOrderPred(me, ascending));
} }
public void DoMeleeAttackIfReady() public void DoMeleeAttackIfReady()
@@ -145,18 +149,12 @@ namespace Game.AI
if (targetList.Empty()) if (targetList.Empty())
return null; return null;
switch (targetType) return targetType switch
{ {
case SelectAggroTarget.MaxThreat: SelectAggroTarget.MaxThreat or SelectAggroTarget.MinThreat or SelectAggroTarget.MaxDistance or SelectAggroTarget.MinDistance => targetList[0],
case SelectAggroTarget.MinThreat: SelectAggroTarget.Random => targetList.SelectRandom(),
case SelectAggroTarget.MaxDistance: _ => null,
case SelectAggroTarget.MinDistance: };
return targetList[0];
case SelectAggroTarget.Random:
return targetList.SelectRandom();
default:
return null;
}
} }
/// <summary> /// <summary>
@@ -287,7 +285,7 @@ namespace Game.AI
bool playerOnly = spellInfo.HasAttribute(SpellAttr3.OnlyTargetPlayers); bool playerOnly = spellInfo.HasAttribute(SpellAttr3.OnlyTargetPlayers);
float range = spellInfo.GetMaxRange(false); float range = spellInfo.GetMaxRange(false);
DefaultTargetSelector targetSelector = new DefaultTargetSelector(me, range, playerOnly, true, -(int)spellId); DefaultTargetSelector targetSelector = new(me, range, playerOnly, true, -(int)spellId);
if (!spellInfo.HasAuraInterruptFlag(SpellAuraInterruptFlags.NotVictim) if (!spellInfo.HasAuraInterruptFlag(SpellAuraInterruptFlags.NotVictim)
&& targetSelector.Invoke(me.GetVictim())) && targetSelector.Invoke(me.GetVictim()))
target = me.GetVictim(); target = me.GetVictim();
@@ -334,7 +332,7 @@ namespace Game.AI
Global.SpellMgr.ForEachSpellInfo(spellInfo => Global.SpellMgr.ForEachSpellInfo(spellInfo =>
{ {
AISpellInfoType AIInfo = new AISpellInfoType(); AISpellInfoType AIInfo = new();
if (spellInfo.HasAttribute(SpellAttr0.CastableWhileDead)) if (spellInfo.HasAttribute(SpellAttr0.CastableWhileDead))
AIInfo.condition = AICondition.Die; AIInfo.condition = AICondition.Die;
else if (spellInfo.IsPassive() || spellInfo.GetDuration() == -1) else if (spellInfo.IsPassive() || spellInfo.GetDuration() == -1)
@@ -461,7 +459,7 @@ namespace Game.AI
AIInfo.Effects |= 1 << ((int)SelectEffect.Aura - 1); AIInfo.Effects |= 1 << ((int)SelectEffect.Aura - 1);
} }
AISpellInfo[(spellInfo.Id, spellInfo.Difficulty)] = AIInfo; _aiSpellInfo[(spellInfo.Id, spellInfo.Difficulty)] = AIInfo;
}); });
} }
@@ -471,16 +469,16 @@ namespace Game.AI
public virtual void InitializeAI() public virtual void InitializeAI()
{ {
if (!me.IsDead()) if (!me.IsDead())
Reset(); Reset();
} }
public virtual void Reset() { } public virtual void Reset() { }
public virtual void OnCharmed(bool apply) { } public virtual void OnCharmed(bool apply) { }
public virtual bool ShouldSparWith(Unit target) { return false; } public virtual bool ShouldSparWith(Unit target) { return false; }
public virtual void DoAction(int action) { } public virtual void DoAction(int action) { }
public virtual uint GetData(uint id = 0) { return 0; } public virtual uint GetData(uint id = 0) { return 0; }
public virtual void SetData(uint id, uint value) { } public virtual void SetData(uint id, uint value) { }
@@ -491,7 +489,7 @@ namespace Game.AI
public virtual void DamageTaken(Unit attacker, ref uint damage) { } public virtual void DamageTaken(Unit attacker, ref uint damage) { }
public virtual void HealReceived(Unit by, uint addhealth) { } public virtual void HealReceived(Unit by, uint addhealth) { }
public virtual void HealDone(Unit to, uint addhealth) { } public virtual void HealDone(Unit to, uint addhealth) { }
public virtual void SpellInterrupted(uint spellId, uint unTimeMs) {} public virtual void SpellInterrupted(uint spellId, uint unTimeMs) { }
/// <summary> /// <summary>
/// Called when a player opens a gossip dialog with the creature. /// Called when a player opens a gossip dialog with the creature.
@@ -522,11 +520,10 @@ namespace Game.AI
} }
public virtual void QuestReward(Player player, Quest quest, LootItemType type, uint opt) { } public virtual void QuestReward(Player player, Quest quest, LootItemType type, uint opt) { }
/// <summary>
/// <summary> /// Called when a game event starts or ends
/// Called when a game event starts or ends /// </summary>
/// </summary> public virtual void OnGameEvent(bool start, ushort eventId) { }
public virtual void OnGameEvent(bool start, ushort eventId) { }
// Called when the dialog status between a player and the creature is requested. // Called when the dialog status between a player and the creature is requested.
public virtual QuestGiverStatus GetDialogStatus(Player player) { return QuestGiverStatus.ScriptedDefault; } public virtual QuestGiverStatus GetDialogStatus(Player player) { return QuestGiverStatus.ScriptedDefault; }
@@ -539,14 +536,10 @@ namespace Game.AI
public virtual void WaypointPathEnded(uint nodeId, uint pathId) { } public virtual void WaypointPathEnded(uint nodeId, uint pathId) { }
public AISpellInfoType GetAISpellInfo(uint spellId, Difficulty difficulty) public static AISpellInfoType GetAISpellInfo(uint spellId, Difficulty difficulty)
{ {
return AISpellInfo.LookupByKey((spellId, difficulty)); return _aiSpellInfo.LookupByKey((spellId, difficulty));
} }
public static Dictionary<(uint id, Difficulty difficulty), AISpellInfoType> AISpellInfo = new Dictionary<(uint id, Difficulty difficulty), AISpellInfoType>();
protected Unit me { get; private set; }
} }
public enum SelectAggroTarget public enum SelectAggroTarget
@@ -623,6 +616,9 @@ namespace Game.AI
// todo Add more checks from Spell.CheckCast // todo Add more checks from Spell.CheckCast
public class SpellTargetSelector : ICheck<Unit> public class SpellTargetSelector : ICheck<Unit>
{ {
Unit _caster;
SpellInfo _spellInfo;
public SpellTargetSelector(Unit caster, uint spellId) public SpellTargetSelector(Unit caster, uint spellId)
{ {
_caster = caster; _caster = caster;
@@ -694,9 +690,6 @@ namespace Game.AI
return true; return true;
} }
Unit _caster;
SpellInfo _spellInfo;
} }
// Very simple target selector, will just skip main target // Very simple target selector, will just skip main target
@@ -704,6 +697,9 @@ namespace Game.AI
// because tank will not be in the temporary list // because tank will not be in the temporary list
public class NonTankTargetSelector : ICheck<Unit> public class NonTankTargetSelector : ICheck<Unit>
{ {
Unit _source;
bool _playerOnly;
public NonTankTargetSelector(Unit source, bool playerOnly = true) public NonTankTargetSelector(Unit source, bool playerOnly = true)
{ {
_source = source; _source = source;
@@ -724,14 +720,16 @@ namespace Game.AI
return target != _source.GetVictim(); return target != _source.GetVictim();
} }
Unit _source;
bool _playerOnly;
} }
// Simple selector for units using mana // Simple selector for units using mana
class PowerUsersSelector : ICheck<Unit> class PowerUsersSelector : ICheck<Unit>
{ {
Unit _me;
PowerType _power;
float _dist;
bool _playerOnly;
public PowerUsersSelector(Unit unit, PowerType power, float dist, bool playerOnly) public PowerUsersSelector(Unit unit, PowerType power, float dist, bool playerOnly)
{ {
_me = unit; _me = unit;
@@ -759,15 +757,15 @@ namespace Game.AI
return true; return true;
} }
Unit _me;
PowerType _power;
float _dist;
bool _playerOnly;
} }
class FarthestTargetSelector : ICheck<Unit> class FarthestTargetSelector : ICheck<Unit>
{ {
Unit _me;
float _dist;
bool _playerOnly;
bool _inLos;
public FarthestTargetSelector(Unit unit, float dist, bool playerOnly, bool inLos) public FarthestTargetSelector(Unit unit, float dist, bool playerOnly, bool inLos)
{ {
_me = unit; _me = unit;
@@ -792,10 +790,5 @@ namespace Game.AI
return true; return true;
} }
Unit _me;
float _dist;
bool _playerOnly;
bool _inLos;
} }
} }
+32 -44
View File
@@ -389,6 +389,11 @@ namespace Game.AI
public class PlayerAI : UnitAI public class PlayerAI : UnitAI
{ {
protected new Player me;
uint _selfSpec;
bool _isSelfHealer;
bool _isSelfRangedAttacker;
public PlayerAI(Player player) : base(player) public PlayerAI(Player player) : base(player)
{ {
me = player; me = player;
@@ -402,29 +407,17 @@ namespace Game.AI
if (!who) if (!who)
return false; return false;
switch (who.GetClass()) return who.GetClass() switch
{ {
case Class.Warrior: Class.Paladin => who.GetPrimarySpecialization() == (uint)TalentSpecialization.PaladinHoly,
case Class.Hunter: Class.Priest => who.GetPrimarySpecialization() == (uint)TalentSpecialization.PriestDiscipline || who.GetPrimarySpecialization() == (uint)TalentSpecialization.PriestHoly,
case Class.Rogue: Class.Shaman => who.GetPrimarySpecialization() == (uint)TalentSpecialization.ShamanRestoration,
case Class.Deathknight: Class.Monk => who.GetPrimarySpecialization() == (uint)TalentSpecialization.MonkMistweaver,
case Class.Mage: Class.Druid => who.GetPrimarySpecialization() == (uint)TalentSpecialization.DruidRestoration,
case Class.Warlock: _ => false,
case Class.DemonHunter: };
default:
return false;
case Class.Paladin:
return who.GetPrimarySpecialization() == (uint)TalentSpecialization.PaladinHoly;
case Class.Priest:
return who.GetPrimarySpecialization() == (uint)TalentSpecialization.PriestDiscipline || who.GetPrimarySpecialization() == (uint)TalentSpecialization.PriestHoly;
case Class.Shaman:
return who.GetPrimarySpecialization() == (uint)TalentSpecialization.ShamanRestoration;
case Class.Monk:
return who.GetPrimarySpecialization() == (uint)TalentSpecialization.MonkMistweaver;
case Class.Druid:
return who.GetPrimarySpecialization() == (uint)TalentSpecialization.DruidRestoration;
}
} }
bool IsPlayerRangedAttacker(Player who) bool IsPlayerRangedAttacker(Player who)
{ {
if (!who) if (!who)
@@ -494,14 +487,14 @@ namespace Game.AI
if (me.GetSpellHistory().HasGlobalCooldown(spellInfo)) if (me.GetSpellHistory().HasGlobalCooldown(spellInfo))
return null; return null;
Spell spell = new Spell(me, spellInfo, TriggerCastFlags.None); Spell spell = new(me, spellInfo, TriggerCastFlags.None);
if (spell.CanAutoCast(target)) if (spell.CanAutoCast(target))
return Tuple.Create(spell, target); return Tuple.Create(spell, target);
return null; return null;
} }
Tuple<Spell, Unit> VerifySpellCast(uint spellId, SpellTarget target) public Tuple<Spell, Unit> VerifySpellCast(uint spellId, SpellTarget target)
{ {
Unit pTarget = null; Unit pTarget = null;
switch (target) switch (target)
@@ -558,7 +551,7 @@ namespace Game.AI
return selected; return selected;
} }
void VerifyAndPushSpellCast<T>(List<Tuple<Tuple<Spell, Unit>, uint>> spells, uint spellId, T target, uint weight) where T : Unit public void VerifyAndPushSpellCast<T>(List<Tuple<Tuple<Spell, Unit>, uint>> spells, uint spellId, T target, uint weight) where T : Unit
{ {
Tuple<Spell, Unit> spell = VerifySpellCast(spellId, target); Tuple<Spell, Unit> spell = VerifySpellCast(spellId, target);
if (spell != null) if (spell != null)
@@ -567,7 +560,7 @@ namespace Game.AI
public void DoCastAtTarget(Tuple<Spell, Unit> spell) public void DoCastAtTarget(Tuple<Spell, Unit> spell)
{ {
SpellCastTargets targets = new SpellCastTargets(); SpellCastTargets targets = new();
targets.SetUnitTarget(spell.Item2); targets.SetUnitTarget(spell.Item2);
spell.Item1.Prepare(targets); spell.Item1.Prepare(targets);
} }
@@ -621,10 +614,10 @@ namespace Game.AI
DoMeleeAttackIfReady(); DoMeleeAttackIfReady();
} }
void CancelAllShapeshifts() public void CancelAllShapeshifts()
{ {
List<AuraEffect> shapeshiftAuras = me.GetAuraEffectsByType(AuraType.ModShapeshift); List<AuraEffect> shapeshiftAuras = me.GetAuraEffectsByType(AuraType.ModShapeshift);
List<Aura> removableShapeshifts = new List<Aura>(); List<Aura> removableShapeshifts = new();
foreach (AuraEffect auraEff in shapeshiftAuras) foreach (AuraEffect auraEff in shapeshiftAuras)
{ {
Aura aura = auraEff.GetBase(); Aura aura = auraEff.GetBase();
@@ -654,22 +647,17 @@ namespace Game.AI
public override void OnCharmed(bool apply) { } public override void OnCharmed(bool apply) { }
// helper functions to determine player info // helper functions to determine player info
bool IsHealer(Player who = null) public bool IsHealer(Player who = null)
{ {
return (!who || who == me) ? _isSelfHealer : IsPlayerHealer(who); return (!who || who == me) ? _isSelfHealer : IsPlayerHealer(who);
} }
public bool IsRangedAttacker(Player who = null) { return (!who || who == me) ? _isSelfRangedAttacker : IsPlayerRangedAttacker(who); } public bool IsRangedAttacker(Player who = null) { return (!who || who == me) ? _isSelfRangedAttacker : IsPlayerRangedAttacker(who); }
uint GetSpec(Player who = null) { return (!who || who == me) ? _selfSpec : who.GetPrimarySpecialization(); } public uint GetSpec(Player who = null) { return (!who || who == me) ? _selfSpec : who.GetPrimarySpecialization(); }
void SetIsRangedAttacker(bool state) { _isSelfRangedAttacker = state; } // this allows overriding of the default ranged attacker detection public void SetIsRangedAttacker(bool state) { _isSelfRangedAttacker = state; } // this allows overriding of the default ranged attacker detection
public virtual Unit SelectAttackTarget() { return me.GetCharmer() ? me.GetCharmer().GetVictim() : null; } public virtual Unit SelectAttackTarget() { return me.GetCharmer() ? me.GetCharmer().GetVictim() : null; }
protected new Player me; public enum SpellTarget
uint _selfSpec;
bool _isSelfHealer;
bool _isSelfRangedAttacker;
enum SpellTarget
{ {
None, None,
Victim, Victim,
@@ -680,6 +668,13 @@ namespace Game.AI
class SimpleCharmedPlayerAI : PlayerAI class SimpleCharmedPlayerAI : PlayerAI
{ {
const float CASTER_CHASE_DISTANCE = 28.0f;
uint _castCheckTimer;
bool _chaseCloser;
bool _forceFacing;
bool _isFollowing;
public SimpleCharmedPlayerAI(Player player) : base(player) public SimpleCharmedPlayerAI(Player player) : base(player)
{ {
_castCheckTimer = 2500; _castCheckTimer = 2500;
@@ -710,7 +705,7 @@ namespace Game.AI
Tuple<Spell, Unit> SelectAppropriateCastForSpec() Tuple<Spell, Unit> SelectAppropriateCastForSpec()
{ {
List<Tuple<Tuple<Spell, Unit>, uint>> spells = new List<Tuple<Tuple<Spell, Unit>, uint>>(); List<Tuple<Tuple<Spell, Unit>, uint>> spells = new();
/* /*
switch (me.getClass()) switch (me.getClass())
{ {
@@ -1234,8 +1229,6 @@ namespace Game.AI
return SelectSpellCast(spells); return SelectSpellCast(spells);
} }
const float CASTER_CHASE_DISTANCE = 28.0f;
public override void UpdateAI(uint diff) public override void UpdateAI(uint diff)
{ {
Creature charmer = GetCharmer(); Creature charmer = GetCharmer();
@@ -1359,11 +1352,6 @@ namespace Game.AI
me.StopMoving(); me.StopMoving();
} }
} }
uint _castCheckTimer;
bool _chaseCloser;
bool _forceFacing;
bool _isFollowing;
} }
struct ValidTargetSelectPredicate : ICheck<Unit> struct ValidTargetSelectPredicate : ICheck<Unit>
+50 -60
View File
@@ -28,6 +28,10 @@ namespace Game.AI
{ {
public class ScriptedAI : CreatureAI public class ScriptedAI : CreatureAI
{ {
Difficulty _difficulty;
bool _isCombatMovementAllowed;
bool _isHeroic;
public ScriptedAI(Creature creature) : base(creature) public ScriptedAI(Creature creature) : base(creature)
{ {
_isCombatMovementAllowed = true; _isCombatMovementAllowed = true;
@@ -87,7 +91,7 @@ namespace Game.AI
} }
//Cast spell by spell info //Cast spell by spell info
void DoCastSpell(Unit target, SpellInfo spellInfo, bool triggered = false) public void DoCastSpell(Unit target, SpellInfo spellInfo, bool triggered = false)
{ {
if (target == null || me.IsNonMeleeSpellCast(false)) if (target == null || me.IsNonMeleeSpellCast(false))
return; return;
@@ -97,7 +101,7 @@ namespace Game.AI
} }
//Plays a sound to all nearby players //Plays a sound to all nearby players
public void DoPlaySoundToSet(WorldObject source, uint soundId) public static void DoPlaySoundToSet(WorldObject source, uint soundId)
{ {
if (source == null) if (source == null)
return; return;
@@ -268,7 +272,7 @@ namespace Game.AI
me.MonsterMoveWithSpeed(x, y, z, speed); me.MonsterMoveWithSpeed(x, y, z, speed);
} }
void DoTeleportTo(float[] position) public void DoTeleportTo(float[] position)
{ {
me.NearTeleportTo(position[0], position[1], position[2], position[3]); me.NearTeleportTo(position[0], position[1], position[2], position[3]);
} }
@@ -286,7 +290,7 @@ namespace Game.AI
me.GetGUID(), me.GetEntry(), unit.GetTypeId(), unit.GetGUID(), x, y, z, o); me.GetGUID(), me.GetEntry(), unit.GetTypeId(), unit.GetGUID(), x, y, z, o);
} }
void DoTeleportAll(float x, float y, float z, float o) public void DoTeleportAll(float x, float y, float z, float o)
{ {
Map map = me.GetMap(); Map map = me.GetMap();
if (!map.IsDungeon()) if (!map.IsDungeon())
@@ -310,9 +314,9 @@ namespace Game.AI
} }
//Returns a list of friendly CC'd units within range //Returns a list of friendly CC'd units within range
List<Creature> DoFindFriendlyCC(float range) public List<Creature> DoFindFriendlyCC(float range)
{ {
List<Creature> list = new List<Creature>(); List<Creature> list = new();
var u_check = new FriendlyCCedInRange(me, range); var u_check = new FriendlyCCedInRange(me, range);
var searcher = new CreatureListSearcher(me, list, u_check); var searcher = new CreatureListSearcher(me, list, u_check);
Cell.VisitAllObjects(me, searcher, range); Cell.VisitAllObjects(me, searcher, range);
@@ -323,7 +327,7 @@ namespace Game.AI
//Returns a list of all friendly units missing a specific buff within range //Returns a list of all friendly units missing a specific buff within range
public List<Creature> DoFindFriendlyMissingBuff(float range, uint spellId) public List<Creature> DoFindFriendlyMissingBuff(float range, uint spellId)
{ {
List<Creature> list = new List<Creature>(); List<Creature> list = new();
var u_check = new FriendlyMissingBuffInRange(me, range, spellId); var u_check = new FriendlyMissingBuffInRange(me, range, spellId);
var searcher = new CreatureListSearcher(me, list, u_check); var searcher = new CreatureListSearcher(me, list, u_check);
Cell.VisitAllObjects(me, searcher, range); Cell.VisitAllObjects(me, searcher, range);
@@ -332,7 +336,7 @@ namespace Game.AI
} }
//Return a player with at least minimumRange from me //Return a player with at least minimumRange from me
Player GetPlayerAtMinimumRange(float minimumRange) public Player GetPlayerAtMinimumRange(float minimumRange)
{ {
var check = new PlayerAtMinimumRangeAway(me, minimumRange); var check = new PlayerAtMinimumRangeAway(me, minimumRange);
var searcher = new PlayerSearcher(me, check); var searcher = new PlayerSearcher(me, check);
@@ -398,7 +402,7 @@ namespace Game.AI
return source.FindNearestCreature(entry, maxSearchRange, alive); return source.FindNearestCreature(entry, maxSearchRange, alive);
} }
public GameObject GetClosestGameObjectWithEntry(WorldObject source, uint entry, float maxSearchRange) public static GameObject GetClosestGameObjectWithEntry(WorldObject source, uint entry, float maxSearchRange)
{ {
return source.FindNearestGameObject(entry, maxSearchRange); return source.FindNearestGameObject(entry, maxSearchRange);
} }
@@ -429,50 +433,40 @@ namespace Game.AI
public T DungeonMode<T>(T normal5, T heroic10) public T DungeonMode<T>(T normal5, T heroic10)
{ {
switch (_difficulty) return _difficulty switch
{ {
case Difficulty.Normal: Difficulty.Normal => normal5,
return normal5; _ => heroic10,
case Difficulty.Heroic: };
default:
return heroic10;
}
} }
public T RaidMode<T>(T normal10, T normal25) public T RaidMode<T>(T normal10, T normal25)
{ {
switch (_difficulty) return _difficulty switch
{ {
case Difficulty.Raid10N: Difficulty.Raid10N => normal10,
return normal10; _ => normal25,
case Difficulty.Raid25N: };
default:
return normal25;
}
}
public T RaidMode<T>(T normal10, T normal25, T heroic10, T heroic25)
{
switch (_difficulty)
{
case Difficulty.Raid10N:
return normal10;
case Difficulty.Raid25N:
return normal25;
case Difficulty.Raid10HC:
return heroic10;
case Difficulty.Raid25HC:
default:
return heroic25;
}
} }
Difficulty _difficulty; public T RaidMode<T>(T normal10, T normal25, T heroic10, T heroic25)
bool _isCombatMovementAllowed; {
bool _isHeroic; return _difficulty switch
{
Difficulty.Raid10N => normal10,
Difficulty.Raid25N => normal25,
Difficulty.Raid10HC => heroic10,
_ => heroic25,
};
}
} }
public class BossAI : ScriptedAI public class BossAI : ScriptedAI
{ {
public InstanceScript instance;
public SummonList summons;
uint _bossId;
public BossAI(Creature creature, uint bossId) : base(creature) public BossAI(Creature creature, uint bossId) : base(creature)
{ {
instance = creature.GetInstanceScript(); instance = creature.GetInstanceScript();
@@ -615,14 +609,12 @@ namespace Game.AI
public override bool CanAIAttack(Unit victim) { return CheckBoundary(victim); } public override bool CanAIAttack(Unit victim) { return CheckBoundary(victim); }
public void _JustReachedHome() { me.SetActive(false); } public void _JustReachedHome() { me.SetActive(false); }
public InstanceScript instance;
public SummonList summons;
uint _bossId;
} }
public class WorldBossAI : ScriptedAI public class WorldBossAI : ScriptedAI
{ {
SummonList summons;
public WorldBossAI(Creature creature) : base(creature) public WorldBossAI(Creature creature) : base(creature)
{ {
summons = new SummonList(creature); summons = new SummonList(creature);
@@ -695,15 +687,15 @@ namespace Game.AI
public override void EnterCombat(Unit who) { _EnterCombat(); } public override void EnterCombat(Unit who) { _EnterCombat(); }
public override void JustDied(Unit killer) { _JustDied(); } public override void JustDied(Unit killer) { _JustDied(); }
SummonList summons;
} }
public class SummonList : List<ObjectGuid> public class SummonList : List<ObjectGuid>
{ {
Creature _me;
public SummonList(Creature creature) public SummonList(Creature creature)
{ {
me = creature; _me = creature;
} }
public void Summon(Creature summon) { Add(summon.GetGUID()); } public void Summon(Creature summon) { Add(summon.GetGUID()); }
@@ -712,7 +704,7 @@ namespace Game.AI
{ {
foreach (var id in this) foreach (var id in this)
{ {
Creature summon = ObjectAccessor.GetCreature(me, id); Creature summon = ObjectAccessor.GetCreature(_me, id);
if (summon && summon.IsAIEnabled && (entry == 0 || summon.GetEntry() == entry)) if (summon && summon.IsAIEnabled && (entry == 0 || summon.GetEntry() == entry))
{ {
summon.GetAI().DoZoneInCombat(null, maxRangeToNearestTarget); summon.GetAI().DoZoneInCombat(null, maxRangeToNearestTarget);
@@ -724,7 +716,7 @@ namespace Game.AI
{ {
foreach (var id in this) foreach (var id in this)
{ {
Creature summon = ObjectAccessor.GetCreature(me, id); Creature summon = ObjectAccessor.GetCreature(_me, id);
if (!summon) if (!summon)
Remove(id); Remove(id);
else if (summon.GetEntry() == entry) else if (summon.GetEntry() == entry)
@@ -739,7 +731,7 @@ namespace Game.AI
{ {
while (!this.Empty()) while (!this.Empty())
{ {
Creature summon = ObjectAccessor.GetCreature(me, this.FirstOrDefault()); Creature summon = ObjectAccessor.GetCreature(_me, this.FirstOrDefault());
RemoveAt(0); RemoveAt(0);
if (summon) if (summon)
summon.DespawnOrUnsummon(); summon.DespawnOrUnsummon();
@@ -762,7 +754,7 @@ namespace Game.AI
{ {
foreach (var id in this) foreach (var id in this)
{ {
if (!ObjectAccessor.GetCreature(me, id)) if (!ObjectAccessor.GetCreature(_me, id))
Remove(id); Remove(id);
} }
} }
@@ -770,7 +762,7 @@ namespace Game.AI
public void DoAction(int info, ICheck<ObjectGuid> predicate, ushort max = 0) public void DoAction(int info, ICheck<ObjectGuid> predicate, ushort max = 0)
{ {
// We need to use a copy of SummonList here, otherwise original SummonList would be modified // We need to use a copy of SummonList here, otherwise original SummonList would be modified
List<ObjectGuid> listCopy = new List<ObjectGuid>(this); List<ObjectGuid> listCopy = new(this);
listCopy.RandomResize(predicate.Invoke, max); listCopy.RandomResize(predicate.Invoke, max);
DoActionImpl(info, listCopy); DoActionImpl(info, listCopy);
} }
@@ -778,7 +770,7 @@ namespace Game.AI
public void DoAction(int info, Predicate<ObjectGuid> predicate, ushort max = 0) public void DoAction(int info, Predicate<ObjectGuid> predicate, ushort max = 0)
{ {
// We need to use a copy of SummonList here, otherwise original SummonList would be modified // We need to use a copy of SummonList here, otherwise original SummonList would be modified
List<ObjectGuid> listCopy = new List<ObjectGuid>(this); List<ObjectGuid> listCopy = new(this);
listCopy.RandomResize(predicate, max); listCopy.RandomResize(predicate, max);
DoActionImpl(info, listCopy); DoActionImpl(info, listCopy);
} }
@@ -787,7 +779,7 @@ namespace Game.AI
{ {
foreach (var id in this) foreach (var id in this)
{ {
Creature summon = ObjectAccessor.GetCreature(me, id); Creature summon = ObjectAccessor.GetCreature(_me, id);
if (summon && summon.GetEntry() == entry) if (summon && summon.GetEntry() == entry)
return true; return true;
} }
@@ -799,24 +791,22 @@ namespace Game.AI
{ {
foreach (var guid in summons) foreach (var guid in summons)
{ {
Creature summon = ObjectAccessor.GetCreature(me, guid); Creature summon = ObjectAccessor.GetCreature(_me, guid);
if (summon && summon.IsAIEnabled) if (summon && summon.IsAIEnabled)
summon.GetAI().DoAction(action); summon.GetAI().DoAction(action);
} }
} }
Creature me;
} }
public class EntryCheckPredicate : ICheck<ObjectGuid> public class EntryCheckPredicate : ICheck<ObjectGuid>
{ {
uint _entry;
public EntryCheckPredicate(uint entry) public EntryCheckPredicate(uint entry)
{ {
_entry = entry; _entry = entry;
} }
public bool Invoke(ObjectGuid guid) { return guid.GetEntry() == _entry; } public bool Invoke(ObjectGuid guid) { return guid.GetEntry() == _entry; }
uint _entry;
} }
} }
@@ -212,7 +212,7 @@ namespace Game.AI
Log.outDebug(LogFilter.Scripts, "EscortAI.UpdateAI: reached end of waypoints, despawning at end"); Log.outDebug(LogFilter.Scripts, "EscortAI.UpdateAI: reached end of waypoints, despawning at end");
if (_returnToStart) if (_returnToStart)
{ {
Position respawnPosition = new Position(); Position respawnPosition = new();
float orientation; float orientation;
me.GetRespawnPosition(out respawnPosition.posX, out respawnPosition.posY, out respawnPosition.posZ, out orientation); me.GetRespawnPosition(out respawnPosition.posX, out respawnPosition.posY, out respawnPosition.posZ, out orientation);
respawnPosition.SetOrientation(orientation); respawnPosition.SetOrientation(orientation);
@@ -338,7 +338,7 @@ namespace Game.AI
GridDefines.NormalizeMapCoord(ref x); GridDefines.NormalizeMapCoord(ref x);
GridDefines.NormalizeMapCoord(ref y); GridDefines.NormalizeMapCoord(ref y);
WaypointNode waypoint = new WaypointNode(); WaypointNode waypoint = new();
waypoint.id = id; waypoint.id = id;
waypoint.x = x; waypoint.x = x;
waypoint.y = y; waypoint.y = y;
+26 -26
View File
@@ -35,11 +35,17 @@ namespace Game.AI
class FollowerAI : ScriptedAI class FollowerAI : ScriptedAI
{ {
ObjectGuid _leaderGUID;
uint _updateFollowTimer;
FollowState _followState;
Quest _questForFollow; //normally we have a quest
public FollowerAI(Creature creature) : base(creature) public FollowerAI(Creature creature) : base(creature)
{ {
m_uiUpdateFollowTimer = 2500; _updateFollowTimer = 2500;
m_uiFollowState = FollowState.None; _followState = FollowState.None;
m_pQuestForFollow = null; _questForFollow = null;
} }
public override void AttackStart(Unit who) public override void AttackStart(Unit who)
@@ -124,7 +130,7 @@ namespace Game.AI
public override void JustDied(Unit killer) public override void JustDied(Unit killer)
{ {
if (!HasFollowState(FollowState.Inprogress) || m_uiLeaderGUID.IsEmpty() || m_pQuestForFollow == null) if (!HasFollowState(FollowState.Inprogress) || _leaderGUID.IsEmpty() || _questForFollow == null)
return; return;
// @todo need a better check for quests with time limit. // @todo need a better check for quests with time limit.
@@ -139,17 +145,17 @@ namespace Game.AI
Player member = groupRef.GetSource(); Player member = groupRef.GetSource();
if (member) if (member)
if (member.IsInMap(player)) if (member.IsInMap(player))
member.FailQuest(m_pQuestForFollow.Id); member.FailQuest(_questForFollow.Id);
} }
} }
else else
player.FailQuest(m_pQuestForFollow.Id); player.FailQuest(_questForFollow.Id);
} }
} }
public override void JustAppeared() public override void JustAppeared()
{ {
m_uiFollowState = FollowState.None; _followState = FollowState.None;
if (!IsCombatMovementAllowed()) if (!IsCombatMovementAllowed())
SetCombatMovement(true); SetCombatMovement(true);
@@ -191,7 +197,7 @@ namespace Game.AI
{ {
if (HasFollowState(FollowState.Inprogress) && !me.GetVictim()) if (HasFollowState(FollowState.Inprogress) && !me.GetVictim())
{ {
if (m_uiUpdateFollowTimer <= uiDiff) if (_updateFollowTimer <= uiDiff)
{ {
if (HasFollowState(FollowState.Complete) && !HasFollowState(FollowState.PostEvent)) if (HasFollowState(FollowState.Complete) && !HasFollowState(FollowState.PostEvent))
{ {
@@ -241,10 +247,10 @@ namespace Game.AI
return; return;
} }
m_uiUpdateFollowTimer = 1000; _updateFollowTimer = 1000;
} }
else else
m_uiUpdateFollowTimer -= uiDiff; _updateFollowTimer -= uiDiff;
} }
UpdateFollowerAI(uiDiff); UpdateFollowerAI(uiDiff);
@@ -275,7 +281,7 @@ namespace Game.AI
} }
} }
void StartFollow(Player player, uint factionForFollower = 0, Quest quest = null) public void StartFollow(Player player, uint factionForFollower = 0, Quest quest = null)
{ {
if (me.GetVictim()) if (me.GetVictim())
{ {
@@ -290,12 +296,12 @@ namespace Game.AI
} }
//set variables //set variables
m_uiLeaderGUID = player.GetGUID(); _leaderGUID = player.GetGUID();
if (factionForFollower != 0) if (factionForFollower != 0)
me.SetFaction(factionForFollower); me.SetFaction(factionForFollower);
m_pQuestForFollow = quest; _questForFollow = quest;
if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint) if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint)
{ {
@@ -311,12 +317,12 @@ namespace Game.AI
me.GetMotionMaster().MoveFollow(player, SharedConst.PetFollowDist, SharedConst.PetFollowAngle); me.GetMotionMaster().MoveFollow(player, SharedConst.PetFollowDist, SharedConst.PetFollowAngle);
Log.outDebug(LogFilter.Scripts, "FollowerAI start follow {0} ({1})", player.GetName(), m_uiLeaderGUID.ToString()); Log.outDebug(LogFilter.Scripts, "FollowerAI start follow {0} ({1})", player.GetName(), _leaderGUID.ToString());
} }
Player GetLeaderForFollower() Player GetLeaderForFollower()
{ {
Player player = Global.ObjAccessor.GetPlayer(me, m_uiLeaderGUID); Player player = Global.ObjAccessor.GetPlayer(me, _leaderGUID);
if (player) if (player)
{ {
if (player.IsAlive()) if (player.IsAlive())
@@ -332,7 +338,7 @@ namespace Game.AI
if (member && me.IsWithinDistInMap(member, 100.0f) && member.IsAlive()) if (member && me.IsWithinDistInMap(member, 100.0f) && member.IsAlive())
{ {
Log.outDebug(LogFilter.Scripts, "FollowerAI GetLeader changed and returned new leader."); Log.outDebug(LogFilter.Scripts, "FollowerAI GetLeader changed and returned new leader.");
m_uiLeaderGUID = member.GetGUID(); _leaderGUID = member.GetGUID();
return member; return member;
} }
} }
@@ -344,7 +350,7 @@ namespace Game.AI
return null; return null;
} }
void SetFollowComplete(bool bWithEndEvent = false) public void SetFollowComplete(bool bWithEndEvent = false)
{ {
if (me.HasUnitState(UnitState.Follow)) if (me.HasUnitState(UnitState.Follow))
{ {
@@ -366,15 +372,9 @@ namespace Game.AI
AddFollowState(FollowState.Complete); AddFollowState(FollowState.Complete);
} }
bool HasFollowState(FollowState uiFollowState) { return (m_uiFollowState & uiFollowState) != 0; } bool HasFollowState(FollowState uiFollowState) { return (_followState & uiFollowState) != 0; }
void AddFollowState(FollowState uiFollowState) { m_uiFollowState |= uiFollowState; } void AddFollowState(FollowState uiFollowState) { _followState |= uiFollowState; }
void RemoveFollowState(FollowState uiFollowState) { m_uiFollowState &= ~uiFollowState; } void RemoveFollowState(FollowState uiFollowState) { _followState &= ~uiFollowState; }
ObjectGuid m_uiLeaderGUID;
uint m_uiUpdateFollowTimer;
FollowState m_uiFollowState;
Quest m_pQuestForFollow; //normally we have a quest
} }
} }
+158 -158
View File
@@ -31,19 +31,61 @@ namespace Game.AI
const int SMART_ESCORT_MAX_PLAYER_DIST = 60; const int SMART_ESCORT_MAX_PLAYER_DIST = 60;
const int SMART_MAX_AID_DIST = SMART_ESCORT_MAX_PLAYER_DIST / 2; const int SMART_MAX_AID_DIST = SMART_ESCORT_MAX_PLAYER_DIST / 2;
public uint EscortQuestID;
SmartScript _script = new();
bool _isCharmed;
uint _followCreditType;
uint _followArrivedTimer;
uint _followCredit;
uint _followArrivedEntry;
ObjectGuid _followGuid;
float _followDist;
float _followAngle;
SmartEscortState _escortState;
uint _escortNPCFlags;
uint _escortInvokerCheckTimer;
WaypointPath _path;
uint _currentWaypointNode;
bool _waypointReached;
uint _waypointPauseTimer;
bool _waypointPauseForced;
bool _repeatWaypointPath;
bool _OOCReached;
bool _waypointPathEnded;
bool _run;
bool _evadeDisabled;
bool _canAutoAttack;
bool _canCombatMove;
uint _invincibilityHpLevel;
uint _despawnTime;
uint _respawnTime;
uint _despawnState;
// Vehicle conditions
bool _hasConditions;
uint _conditionsTimer;
// Gossip
bool _gossipReturn;
public SmartAI(Creature creature) : base(creature) public SmartAI(Creature creature) : base(creature)
{ {
_escortInvokerCheckTimer = 1000; _escortInvokerCheckTimer = 1000;
mRun = true; _run = true;
mCanAutoAttack = true; _canAutoAttack = true;
mCanCombatMove = true; _canCombatMove = true;
mHasConditions = Global.ConditionMgr.HasConditionsForNotGroupedEntry(ConditionSourceType.CreatureTemplateVehicle, creature.GetEntry()); _hasConditions = Global.ConditionMgr.HasConditionsForNotGroupedEntry(ConditionSourceType.CreatureTemplateVehicle, creature.GetEntry());
} }
bool IsAIControlled() bool IsAIControlled()
{ {
return !mIsCharmed; return !_isCharmed;
} }
public void StartPath(bool run = false, uint pathId = 0, bool repeat = false, Unit invoker = null, uint nodeId = 1) public void StartPath(bool run = false, uint pathId = 0, bool repeat = false, Unit invoker = null, uint nodeId = 1)
@@ -57,6 +99,8 @@ namespace Game.AI
if (HasEscortState(SmartEscortState.Escorting)) if (HasEscortState(SmartEscortState.Escorting))
StopPath(); StopPath();
SetRun(run);
if (pathId != 0) if (pathId != 0)
{ {
if (!LoadPath(pathId)) if (!LoadPath(pathId))
@@ -104,7 +148,7 @@ namespace Game.AI
{ {
GridDefines.NormalizeMapCoord(ref waypoint.x); GridDefines.NormalizeMapCoord(ref waypoint.x);
GridDefines.NormalizeMapCoord(ref waypoint.y); GridDefines.NormalizeMapCoord(ref waypoint.y);
waypoint.moveType = mRun ? WaypointMoveType.Run : WaypointMoveType.Walk; waypoint.moveType = _run ? WaypointMoveType.Run : WaypointMoveType.Walk;
} }
GetScript().SetPathId(entry); GetScript().SetPathId(entry);
@@ -118,8 +162,8 @@ namespace Game.AI
me.PauseMovement(delay, MovementSlot.Idle, forced); me.PauseMovement(delay, MovementSlot.Idle, forced);
if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint) if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint)
{ {
var waypointInfo = me.GetCurrentWaypointInfo(); var (nodeId, pathId) = me.GetCurrentWaypointInfo();
GetScript().ProcessEventsFor(SmartEvents.WaypointPaused, null, waypointInfo.nodeId, waypointInfo.pathId); GetScript().ProcessEventsFor(SmartEvents.WaypointPaused, null, nodeId, pathId);
} }
return; return;
} }
@@ -135,7 +179,7 @@ namespace Game.AI
if (forced) if (forced)
{ {
_waypointPauseForced = forced; _waypointPauseForced = forced;
SetRun(mRun); SetRun(_run);
me.PauseMovement(); me.PauseMovement();
me.SetHomePosition(me.GetPosition()); me.SetHomePosition(me.GetPosition());
} }
@@ -154,7 +198,7 @@ namespace Game.AI
if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint) if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint)
waypointInfo = me.GetCurrentWaypointInfo(); waypointInfo = me.GetCurrentWaypointInfo();
if (mDespawnState != 2) if (_despawnState != 2)
SetDespawnTime(despawnTime); SetDespawnTime(despawnTime);
me.GetMotionMaster().MoveIdle(); me.GetMotionMaster().MoveIdle();
@@ -166,16 +210,16 @@ namespace Game.AI
{ {
if (waypointInfo.Item1 != 0) if (waypointInfo.Item1 != 0)
GetScript().ProcessEventsFor(SmartEvents.WaypointEnded, null, waypointInfo.Item1, waypointInfo.Item2); GetScript().ProcessEventsFor(SmartEvents.WaypointEnded, null, waypointInfo.Item1, waypointInfo.Item2);
if (mDespawnState == 1) if (_despawnState == 1)
StartDespawn(); StartDespawn();
} }
return; return;
} }
if (quest != 0) if (quest != 0)
mEscortQuestID = quest; EscortQuestID = quest;
if (mDespawnState != 2) if (_despawnState != 2)
SetDespawnTime(despawnTime); SetDespawnTime(despawnTime);
me.GetMotionMaster().MoveIdle(); me.GetMotionMaster().MoveIdle();
@@ -198,16 +242,16 @@ namespace Game.AI
} }
List<WorldObject> targets = GetScript().GetStoredTargetList(SharedConst.SmartEscortTargets, me); List<WorldObject> targets = GetScript().GetStoredTargetList(SharedConst.SmartEscortTargets, me);
if (targets != null && mEscortQuestID != 0) if (targets != null && EscortQuestID != 0)
{ {
if (targets.Count == 1 && GetScript().IsPlayer(targets.First())) if (targets.Count == 1 && GetScript().IsPlayer(targets.First()))
{ {
Player player = targets.First().ToPlayer(); Player player = targets.First().ToPlayer();
if (!fail && player.IsAtGroupRewardDistance(me) && player.GetCorpse() == null) if (!fail && player.IsAtGroupRewardDistance(me) && player.GetCorpse() == null)
player.GroupEventHappens(mEscortQuestID, me); player.GroupEventHappens(EscortQuestID, me);
if (fail) if (fail)
player.FailQuest(mEscortQuestID); player.FailQuest(EscortQuestID);
Group group = player.GetGroup(); Group group = player.GetGroup();
if (group) if (group)
@@ -219,9 +263,9 @@ namespace Game.AI
continue; continue;
if (!fail && groupGuy.IsAtGroupRewardDistance(me) && !groupGuy.GetCorpse()) if (!fail && groupGuy.IsAtGroupRewardDistance(me) && !groupGuy.GetCorpse())
groupGuy.AreaExploredOrEventHappens(mEscortQuestID); groupGuy.AreaExploredOrEventHappens(EscortQuestID);
else if (fail) else if (fail)
groupGuy.FailQuest(mEscortQuestID); groupGuy.FailQuest(EscortQuestID);
} }
} }
} }
@@ -233,9 +277,9 @@ namespace Game.AI
{ {
Player player = obj.ToPlayer(); Player player = obj.ToPlayer();
if (!fail && player.IsAtGroupRewardDistance(me) && player.GetCorpse() == null) if (!fail && player.IsAtGroupRewardDistance(me) && player.GetCorpse() == null)
player.AreaExploredOrEventHappens(mEscortQuestID); player.AreaExploredOrEventHappens(EscortQuestID);
else if (fail) else if (fail)
player.FailQuest(mEscortQuestID); player.FailQuest(EscortQuestID);
} }
} }
} }
@@ -250,12 +294,12 @@ namespace Game.AI
if (_repeatWaypointPath) if (_repeatWaypointPath)
{ {
if (IsAIControlled()) if (IsAIControlled())
StartPath(mRun, GetScript().GetPathId(), _repeatWaypointPath); StartPath(_run, GetScript().GetPathId(), _repeatWaypointPath);
} }
else else
GetScript().SetPathId(0); GetScript().SetPathId(0);
if (mDespawnState == 1) if (_despawnState == 1)
StartDespawn(); StartDespawn();
} }
@@ -269,7 +313,7 @@ namespace Game.AI
_waypointReached = false; _waypointReached = false;
_waypointPauseTimer = 0; _waypointPauseTimer = 0;
SetRun(mRun); SetRun(_run);
me.ResumeMovement(); me.ResumeMovement();
} }
@@ -298,7 +342,7 @@ namespace Game.AI
if (!UpdateVictim()) if (!UpdateVictim())
return; return;
if (mCanAutoAttack) if (_canAutoAttack)
DoMeleeAttackIfReady(); DoMeleeAttackIfReady();
} }
@@ -382,7 +426,7 @@ namespace Game.AI
if (_currentWaypointNode == _path.nodes.Count) if (_currentWaypointNode == _path.nodes.Count)
_waypointPathEnded = true; _waypointPathEnded = true;
else else
SetRun(mRun); SetRun(_run);
} }
} }
@@ -411,7 +455,7 @@ namespace Game.AI
public override void EnterEvadeMode(EvadeReason why = EvadeReason.Other) public override void EnterEvadeMode(EvadeReason why = EvadeReason.Other)
{ {
if (mEvadeDisabled) if (_evadeDisabled)
{ {
GetScript().ProcessEventsFor(SmartEvents.Evade); GetScript().ProcessEventsFor(SmartEvents.Evade);
return; return;
@@ -430,7 +474,7 @@ namespace Game.AI
GetScript().ProcessEventsFor(SmartEvents.Evade); // must be after _EnterEvadeMode (spells, auras, ...) GetScript().ProcessEventsFor(SmartEvents.Evade); // must be after _EnterEvadeMode (spells, auras, ...)
SetRun(mRun); SetRun(_run);
Unit owner = me.GetCharmerOrOwner(); Unit owner = me.GetCharmerOrOwner();
if (owner != null) if (owner != null)
@@ -445,10 +489,10 @@ namespace Game.AI
} }
else else
{ {
Unit target = !mFollowGuid.IsEmpty() ? Global.ObjAccessor.GetUnit(me, mFollowGuid) : null; Unit target = !_followGuid.IsEmpty() ? Global.ObjAccessor.GetUnit(me, _followGuid) : null;
if (target) if (target)
{ {
me.GetMotionMaster().MoveFollow(target, mFollowDist, mFollowAngle); me.GetMotionMaster().MoveFollow(target, _followDist, _followAngle);
// evade is not cleared in MoveFollow, so we can't keep it // evade is not cleared in MoveFollow, so we can't keep it
me.ClearUnitState(UnitState.Evade); me.ClearUnitState(UnitState.Evade);
} }
@@ -526,9 +570,9 @@ namespace Game.AI
public override void JustAppeared() public override void JustAppeared()
{ {
mDespawnTime = 0; _despawnTime = 0;
mRespawnTime = 0; _respawnTime = 0;
mDespawnState = 0; _despawnState = 0;
_escortState = SmartEscortState.None; _escortState = SmartEscortState.None;
me.SetVisible(true); me.SetVisible(true);
@@ -539,13 +583,13 @@ namespace Game.AI
GetScript().OnReset(); GetScript().OnReset();
GetScript().ProcessEventsFor(SmartEvents.Respawn); GetScript().ProcessEventsFor(SmartEvents.Respawn);
mFollowGuid.Clear();//do not reset follower on Reset(), we need it after combat evade _followGuid.Clear();//do not reset follower on Reset(), we need it after combat evade
mFollowDist = 0; _followDist = 0;
mFollowAngle = 0; _followAngle = 0;
mFollowCredit = 0; _followCredit = 0;
mFollowArrivedTimer = 1000; _followArrivedTimer = 1000;
mFollowArrivedEntry = 0; _followArrivedEntry = 0;
mFollowCreditType = 0; _followCreditType = 0;
} }
public override void JustReachedHome() public override void JustReachedHome()
@@ -597,18 +641,18 @@ namespace Game.AI
if (!IsAIControlled()) if (!IsAIControlled())
{ {
if (who != null) if (who != null)
me.Attack(who, mCanAutoAttack); me.Attack(who, _canAutoAttack);
return; return;
} }
if (who != null && me.Attack(who, mCanAutoAttack)) if (who != null && me.Attack(who, _canAutoAttack))
{ {
me.GetMotionMaster().Clear(MovementSlot.Active); me.GetMotionMaster().Clear(MovementSlot.Active);
me.PauseMovement(); me.PauseMovement();
if (mCanCombatMove) if (_canCombatMove)
{ {
SetRun(mRun); SetRun(_run);
me.GetMotionMaster().MoveChase(who); me.GetMotionMaster().MoveChase(who);
} }
} }
@@ -631,8 +675,8 @@ namespace Game.AI
if (!IsAIControlled()) // don't allow players to use unkillable units if (!IsAIControlled()) // don't allow players to use unkillable units
return; return;
if (mInvincibilityHpLevel != 0 && (damage >= me.GetHealth() - mInvincibilityHpLevel)) if (_invincibilityHpLevel != 0 && (damage >= me.GetHealth() - _invincibilityHpLevel))
damage = (uint)(me.GetHealth() - mInvincibilityHpLevel); // damage should not be nullified, because of player damage req. damage = (uint)(me.GetHealth() - _invincibilityHpLevel); // damage should not be nullified, because of player damage req.
} }
public override void HealReceived(Unit by, uint addhealth) public override void HealReceived(Unit by, uint addhealth)
@@ -672,7 +716,7 @@ namespace Game.AI
public override void InitializeAI() public override void InitializeAI()
{ {
mScript.OnInitialize(me); _script.OnInitialize(me);
if (!me.IsDead()) if (!me.IsDead())
GetScript().OnReset(); GetScript().OnReset();
@@ -686,14 +730,14 @@ namespace Game.AI
EndPath(true); EndPath(true);
} }
mIsCharmed = apply; _isCharmed = apply;
if (!apply && !me.IsInEvadeMode()) if (!apply && !me.IsInEvadeMode())
{ {
if (_repeatWaypointPath) if (_repeatWaypointPath)
StartPath(mRun, GetScript().GetPathId(), true); StartPath(_run, GetScript().GetPathId(), true);
else else
me.SetWalk(!mRun); me.SetWalk(!_run);
Unit charmer = me.GetCharmer(); Unit charmer = me.GetCharmer();
if (charmer) if (charmer)
@@ -728,7 +772,7 @@ namespace Game.AI
public void SetRun(bool run) public void SetRun(bool run)
{ {
me.SetWalk(!run); me.SetWalk(!run);
mRun = run; _run = run;
} }
public void SetDisableGravity(bool disable = true) public void SetDisableGravity(bool disable = true)
@@ -748,7 +792,7 @@ namespace Game.AI
public void SetEvadeDisabled(bool disable) public void SetEvadeDisabled(bool disable)
{ {
mEvadeDisabled = disable; _evadeDisabled = disable;
} }
public override bool GossipHello(Player player) public override bool GossipHello(Player player)
@@ -782,10 +826,10 @@ namespace Game.AI
public void SetCombatMove(bool on) public void SetCombatMove(bool on)
{ {
if (mCanCombatMove == on) if (_canCombatMove == on)
return; return;
mCanCombatMove = on; _canCombatMove = on;
if (!IsAIControlled()) if (!IsAIControlled())
return; return;
@@ -794,7 +838,7 @@ namespace Game.AI
{ {
if (on && !me.HasReactState(ReactStates.Passive) && me.GetVictim() && me.GetMotionMaster().GetMotionSlotType(MovementSlot.Active) == MovementGeneratorType.Max) if (on && !me.HasReactState(ReactStates.Passive) && me.GetVictim() && me.GetMotionMaster().GetMotionSlotType(MovementSlot.Active) == MovementGeneratorType.Max)
{ {
SetRun(mRun); SetRun(_run);
me.GetMotionMaster().MoveChase(me.GetVictim()); me.GetMotionMaster().MoveChase(me.GetVictim());
} }
else if (!on && me.GetMotionMaster().GetMotionSlotType(MovementSlot.Active) == MovementGeneratorType.Chase) else if (!on && me.GetMotionMaster().GetMotionSlotType(MovementSlot.Active) == MovementGeneratorType.Chase)
@@ -810,39 +854,39 @@ namespace Game.AI
return; return;
} }
mFollowGuid = target.GetGUID(); _followGuid = target.GetGUID();
mFollowDist = dist; _followDist = dist;
mFollowAngle = angle; _followAngle = angle;
mFollowArrivedTimer = 1000; _followArrivedTimer = 1000;
mFollowCredit = credit; _followCredit = credit;
mFollowArrivedEntry = end; _followArrivedEntry = end;
mFollowCreditType = creditType; _followCreditType = creditType;
SetRun(mRun); SetRun(_run);
me.GetMotionMaster().MoveFollow(target, mFollowDist, mFollowAngle); me.GetMotionMaster().MoveFollow(target, _followDist, _followAngle);
} }
public void StopFollow(bool complete) public void StopFollow(bool complete)
{ {
mFollowGuid.Clear(); _followGuid.Clear();
mFollowDist = 0; _followDist = 0;
mFollowAngle = 0; _followAngle = 0;
mFollowCredit = 0; _followCredit = 0;
mFollowArrivedTimer = 1000; _followArrivedTimer = 1000;
mFollowArrivedEntry = 0; _followArrivedEntry = 0;
mFollowCreditType = 0; _followCreditType = 0;
me.StopMoving(); me.StopMoving();
me.GetMotionMaster().MoveIdle(); me.GetMotionMaster().MoveIdle();
if (!complete) if (!complete)
return; return;
Player player = Global.ObjAccessor.GetPlayer(me, mFollowGuid); Player player = Global.ObjAccessor.GetPlayer(me, _followGuid);
if (player != null) if (player != null)
{ {
if (mFollowCreditType == 0) if (_followCreditType == 0)
player.RewardPlayerAndGroupAtEvent(mFollowCredit, me); player.RewardPlayerAndGroupAtEvent(_followCredit, me);
else else
player.GroupEventHappens(mFollowCredit, me); player.GroupEventHappens(_followCredit, me);
} }
SetDespawnTime(5000); SetDespawnTime(5000);
@@ -853,7 +897,7 @@ namespace Game.AI
public void SetScript9(SmartScriptHolder e, uint entry, Unit invoker) public void SetScript9(SmartScriptHolder e, uint entry, Unit invoker)
{ {
if (invoker != null) if (invoker != null)
GetScript().mLastInvoker = invoker.GetGUID(); GetScript().LastInvoker = invoker.GetGUID();
GetScript().SetScript9(e, entry); GetScript().SetScript9(e, entry);
} }
@@ -872,10 +916,10 @@ namespace Game.AI
void CheckConditions(uint diff) void CheckConditions(uint diff)
{ {
if (!mHasConditions) if (!_hasConditions)
return; return;
if (mConditionsTimer <= diff) if (_conditionsTimer <= diff)
{ {
Vehicle vehicleKit = me.GetVehicleKit(); Vehicle vehicleKit = me.GetVehicleKit();
if (vehicleKit != null) if (vehicleKit != null)
@@ -898,10 +942,10 @@ namespace Game.AI
} }
} }
mConditionsTimer = 1000; _conditionsTimer = 1000;
} }
else else
mConditionsTimer -= diff; _conditionsTimer -= diff;
} }
void UpdatePath(uint diff) void UpdatePath(uint diff)
@@ -913,7 +957,7 @@ namespace Game.AI
{ {
if (!IsEscortInvokerInRange()) if (!IsEscortInvokerInRange())
{ {
StopPath(0, mEscortQuestID, true); StopPath(0, EscortQuestID, true);
// allow to properly hook out of range despawn action, which in most cases should perform the same operation as dying // allow to properly hook out of range despawn action, which in most cases should perform the same operation as dying
GetScript().ProcessEventsFor(SmartEvents.Death, me); GetScript().ProcessEventsFor(SmartEvents.Death, me);
@@ -957,123 +1001,83 @@ namespace Game.AI
void UpdateFollow(uint diff) void UpdateFollow(uint diff)
{ {
if (mFollowGuid.IsEmpty()) if (_followGuid.IsEmpty())
{ {
if (mFollowArrivedTimer < diff) if (_followArrivedTimer < diff)
{ {
if (me.FindNearestCreature(mFollowArrivedEntry, SharedConst.InteractionDistance, true)) if (me.FindNearestCreature(_followArrivedEntry, SharedConst.InteractionDistance, true))
{ {
StopFollow(true); StopFollow(true);
return; return;
} }
mFollowArrivedTimer = 1000; _followArrivedTimer = 1000;
} }
else else
mFollowArrivedTimer -= diff; _followArrivedTimer -= diff;
} }
} }
void UpdateDespawn(uint diff) void UpdateDespawn(uint diff)
{ {
if (mDespawnState <= 1 || mDespawnState > 3) if (_despawnState <= 1 || _despawnState > 3)
return; return;
if (mDespawnTime < diff) if (_despawnTime < diff)
{ {
if (mDespawnState == 2) if (_despawnState == 2)
{ {
me.SetVisible(false); me.SetVisible(false);
mDespawnTime = 5000; _despawnTime = 5000;
mDespawnState++; _despawnState++;
} }
else else
me.DespawnOrUnsummon(0, TimeSpan.FromSeconds(mRespawnTime)); me.DespawnOrUnsummon(0, TimeSpan.FromSeconds(_respawnTime));
} }
else else
mDespawnTime -= diff; _despawnTime -= diff;
} }
public override void Reset() public override void Reset()
{ {
if (!HasEscortState(SmartEscortState.Escorting))//dont mess up escort movement after combat if (!HasEscortState(SmartEscortState.Escorting))//dont mess up escort movement after combat
SetRun(mRun); SetRun(_run);
GetScript().OnReset(); GetScript().OnReset();
} }
public bool HasEscortState(SmartEscortState uiEscortState) { return (_escortState & uiEscortState) != 0; } public bool HasEscortState(SmartEscortState uiEscortState) { return (_escortState & uiEscortState) != 0; }
public void AddEscortState(SmartEscortState uiEscortState) { _escortState |= uiEscortState; } public void AddEscortState(SmartEscortState uiEscortState) { _escortState |= uiEscortState; }
public void RemoveEscortState(SmartEscortState uiEscortState) { _escortState &= ~uiEscortState; } public void RemoveEscortState(SmartEscortState uiEscortState) { _escortState &= ~uiEscortState; }
public void SetAutoAttack(bool on) { mCanAutoAttack = on; } public void SetAutoAttack(bool on) { _canAutoAttack = on; }
public bool CanCombatMove() { return mCanCombatMove; } public bool CanCombatMove() { return _canCombatMove; }
public SmartScript GetScript() { return mScript; } public SmartScript GetScript() { return _script; }
public void SetInvincibilityHpLevel(uint level) { mInvincibilityHpLevel = level; } public void SetInvincibilityHpLevel(uint level) { _invincibilityHpLevel = level; }
public void SetDespawnTime(uint t, uint r = 0) public void SetDespawnTime(uint t, uint r = 0)
{ {
mDespawnTime = t; _despawnTime = t;
mRespawnTime = r; _respawnTime = r;
mDespawnState = t != 0 ? 1 : 0u; _despawnState = t != 0 ? 1 : 0u;
} }
public void StartDespawn() { mDespawnState = 2; } public void StartDespawn() { _despawnState = 2; }
public void SetWPPauseTimer(uint time) { _waypointPauseTimer = time; } public void SetWPPauseTimer(uint time) { _waypointPauseTimer = time; }
public void SetGossipReturn(bool val) { _gossipReturn = val; } public void SetGossipReturn(bool val) { _gossipReturn = val; }
public uint mEscortQuestID;
SmartScript mScript = new SmartScript();
bool mIsCharmed;
uint mFollowCreditType;
uint mFollowArrivedTimer;
uint mFollowCredit;
uint mFollowArrivedEntry;
ObjectGuid mFollowGuid;
float mFollowDist;
float mFollowAngle;
SmartEscortState _escortState;
uint _escortNPCFlags;
uint _escortInvokerCheckTimer;
WaypointPath _path;
uint _currentWaypointNode;
bool _waypointReached;
uint _waypointPauseTimer;
bool _waypointPauseForced;
bool _repeatWaypointPath;
bool _OOCReached;
bool _waypointPathEnded;
bool mRun;
bool mEvadeDisabled;
bool mCanAutoAttack;
bool mCanCombatMove;
uint mInvincibilityHpLevel;
uint mDespawnTime;
uint mRespawnTime;
uint mDespawnState;
// Vehicle conditions
bool mHasConditions;
uint mConditionsTimer;
// Gossip
bool _gossipReturn;
} }
public class SmartGameObjectAI : GameObjectAI public class SmartGameObjectAI : GameObjectAI
{ {
public SmartGameObjectAI(GameObject g) : base(g) SmartScript _script = new();
{
mScript = new SmartScript(); // Gossip
} bool _gossipReturn;
public SmartGameObjectAI(GameObject g) : base(g) { }
public override void UpdateAI(uint diff) public override void UpdateAI(uint diff)
{ {
@@ -1142,7 +1146,7 @@ namespace Game.AI
public void SetScript9(SmartScriptHolder e, uint entry, Unit invoker) public void SetScript9(SmartScriptHolder e, uint entry, Unit invoker)
{ {
if (invoker != null) if (invoker != null)
GetScript().mLastInvoker = invoker.GetGUID(); GetScript().LastInvoker = invoker.GetGUID();
GetScript().SetScript9(e, entry); GetScript().SetScript9(e, entry);
} }
@@ -1168,16 +1172,13 @@ namespace Game.AI
public void SetGossipReturn(bool val) { _gossipReturn = val; } public void SetGossipReturn(bool val) { _gossipReturn = val; }
public SmartScript GetScript() { return mScript; } public SmartScript GetScript() { return _script; }
SmartScript mScript;
// Gossip
bool _gossipReturn;
} }
public class SmartAreaTriggerAI : AreaTriggerAI public class SmartAreaTriggerAI : AreaTriggerAI
{ {
SmartScript _script = new();
public SmartAreaTriggerAI(AreaTrigger areaTrigger) : base(areaTrigger) { } public SmartAreaTriggerAI(AreaTrigger areaTrigger) : base(areaTrigger) { }
public override void OnInitialize() public override void OnInitialize()
@@ -1198,13 +1199,12 @@ namespace Game.AI
public void SetScript9(SmartScriptHolder e, uint entry, Unit invoker) public void SetScript9(SmartScriptHolder e, uint entry, Unit invoker)
{ {
if (invoker) if (invoker)
GetScript().mLastInvoker = invoker.GetGUID(); GetScript().LastInvoker = invoker.GetGUID();
GetScript().SetScript9(e, entry); GetScript().SetScript9(e, entry);
} }
SmartScript GetScript() { return mScript; } public SmartScript GetScript() { return _script; }
SmartScript mScript;
} }
public enum SmartEscortState public enum SmartEscortState
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+18 -28
View File
@@ -16,6 +16,7 @@
*/ */
using Framework.Constants; using Framework.Constants;
using Framework.Cryptography;
using Framework.Database; using Framework.Database;
using Game.Accounts; using Game.Accounts;
using Game.Entities; using Game.Entities;
@@ -23,7 +24,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Framework.Cryptography;
namespace Game namespace Game
{ {
@@ -32,6 +32,9 @@ namespace Game
const int MaxAccountLength = 16; const int MaxAccountLength = 16;
const int MaxEmailLength = 64; const int MaxEmailLength = 64;
readonly Dictionary<uint, RBACPermission> _permissions = new();
readonly MultiMap<byte, uint> _defaultPermissions = new();
AccountManager() { } AccountManager() { }
public AccountOpResult CreateAccount(string username, string password, string email = "", uint bnetAccountId = 0, byte bnetIndex = 0) public AccountOpResult CreateAccount(string username, string password, string email = "", uint bnetAccountId = 0, byte bnetIndex = 0)
@@ -116,7 +119,7 @@ namespace Game
stmt.AddValue(0, accountId); stmt.AddValue(0, accountId);
DB.Characters.Execute(stmt); DB.Characters.Execute(stmt);
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_ACCOUNT); stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_ACCOUNT);
stmt.AddValue(0, accountId); stmt.AddValue(0, accountId);
@@ -170,12 +173,10 @@ namespace Game
stmt.AddValue(2, accountId); stmt.AddValue(2, accountId);
DB.Login.Execute(stmt); DB.Login.Execute(stmt);
{ stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON_LEGACY);
stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON_LEGACY); stmt.AddValue(0, CalculateShaPassHash(newUsername, newPassword));
stmt.AddValue(0, CalculateShaPassHash(newUsername, newPassword)); stmt.AddValue(1, accountId);
stmt.AddValue(1, accountId); DB.Login.Execute(stmt);
DB.Login.Execute(stmt);
}
return AccountOpResult.Ok; return AccountOpResult.Ok;
} }
@@ -198,12 +199,10 @@ namespace Game
stmt.AddValue(2, accountId); stmt.AddValue(2, accountId);
DB.Login.Execute(stmt); DB.Login.Execute(stmt);
{ stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON_LEGACY);
stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LOGON_LEGACY); stmt.AddValue(0, CalculateShaPassHash(username, newPassword));
stmt.AddValue(0, CalculateShaPassHash(username, newPassword)); stmt.AddValue(1, accountId);
stmt.AddValue(1, accountId); DB.Login.Execute(stmt);
DB.Login.Execute(stmt);
}
return AccountOpResult.Ok; return AccountOpResult.Ok;
} }
@@ -280,7 +279,7 @@ namespace Game
return false; return false;
} }
bool GetEmail(uint accountId, out string email) public bool GetEmail(uint accountId, out string email)
{ {
email = ""; email = "";
PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.GET_EMAIL_BY_ID); PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.GET_EMAIL_BY_ID);
@@ -339,7 +338,6 @@ namespace Game
return result.IsEmpty() ? 0 : (uint)result.Read<ulong>(0); return result.IsEmpty() ? 0 : (uint)result.Read<ulong>(0);
} }
[Obsolete]
string CalculateShaPassHash(string name, string password) string CalculateShaPassHash(string name, string password)
{ {
SHA1 sha = SHA1.Create(); SHA1 sha = SHA1.Create();
@@ -371,7 +369,8 @@ namespace Game
public void LoadRBAC() public void LoadRBAC()
{ {
ClearRBAC(); _permissions.Clear();
_defaultPermissions.Clear();
Log.outDebug(LogFilter.Rbac, "AccountMgr:LoadRBAC"); Log.outDebug(LogFilter.Rbac, "AccountMgr:LoadRBAC");
uint oldMSTime = Time.GetMSTime(); uint oldMSTime = Time.GetMSTime();
@@ -455,7 +454,7 @@ namespace Game
rbac.SetSecurityLevel(securityLevel); rbac.SetSecurityLevel(securityLevel);
PreparedStatement stmt; PreparedStatement stmt;
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
// Delete old security level from DB // Delete old security level from DB
if (realmId == -1) if (realmId == -1)
{ {
@@ -498,7 +497,7 @@ namespace Game
return false; return false;
} }
RBACData rbac = new RBACData(accountId, "", (int)realmId); RBACData rbac = new(accountId, "", (int)realmId);
rbac.LoadFromDB(); rbac.LoadFromDB();
bool hasPermission = rbac.HasPermission(permissionId); bool hasPermission = rbac.HasPermission(permissionId);
@@ -507,21 +506,12 @@ namespace Game
return hasPermission; return hasPermission;
} }
void ClearRBAC()
{
_permissions.Clear();
_defaultPermissions.Clear();
}
public List<uint> GetRBACDefaultPermissions(byte secLevel) public List<uint> GetRBACDefaultPermissions(byte secLevel)
{ {
return _defaultPermissions[secLevel]; return _defaultPermissions[secLevel];
} }
public Dictionary<uint, RBACPermission> GetRBACPermissionList() { return _permissions; } public Dictionary<uint, RBACPermission> GetRBACPermissionList() { return _permissions; }
Dictionary<uint, RBACPermission> _permissions = new Dictionary<uint, RBACPermission>();
MultiMap<byte, uint> _defaultPermissions = new MultiMap<byte, uint>();
} }
public enum AccountOpResult public enum AccountOpResult
+15 -16
View File
@@ -24,6 +24,14 @@ namespace Game.Accounts
{ {
public class RBACData public class RBACData
{ {
uint _id; // Account id
string _name; // Account name
int _realmId; // RealmId Affected
byte _secLevel; // Account SecurityLevel
List<uint> _grantedPerms = new(); // Granted permissions
List<uint> _deniedPerms = new(); // Denied permissions
List<uint> _globalPerms = new(); // Calculated permissions
public RBACData(uint id, string name, int realmId, byte secLevel = 255) public RBACData(uint id, string name, int realmId, byte secLevel = 255)
{ {
_id = id; _id = id;
@@ -224,7 +232,7 @@ namespace Game.Accounts
RemovePermissions(_globalPerms, revoked); RemovePermissions(_globalPerms, revoked);
} }
void AddPermissions(List<uint> permsFrom, List<uint> permsTo) public void AddPermissions(List<uint> permsFrom, List<uint> permsTo)
{ {
foreach (var id in permsFrom) foreach (var id in permsFrom)
permsTo.Add(id); permsTo.Add(id);
@@ -243,7 +251,7 @@ namespace Game.Accounts
void ExpandPermissions(List<uint> permissions) void ExpandPermissions(List<uint> permissions)
{ {
List<uint> toCheck = new List<uint>(permissions); List<uint> toCheck = new(permissions);
permissions.Clear(); permissions.Clear();
while (!toCheck.Empty()) while (!toCheck.Empty())
@@ -337,18 +345,14 @@ namespace Game.Accounts
{ {
_deniedPerms.Remove(permissionId); _deniedPerms.Remove(permissionId);
} }
uint _id; // Account id
string _name; // Account name
int _realmId; // RealmId Affected
byte _secLevel; // Account SecurityLevel
List<uint> _grantedPerms = new List<uint>(); // Granted permissions
List<uint> _deniedPerms = new List<uint>(); // Denied permissions
List<uint> _globalPerms = new List<uint>(); // Calculated permissions
} }
public class RBACPermission public class RBACPermission
{ {
uint _id; // id of the object
string _name; // name of the object
List<uint> _perms = new(); // Set of permissions
public RBACPermission(uint id = 0, string name = "") public RBACPermission(uint id = 0, string name = "")
{ {
_id = id; _id = id;
@@ -365,12 +369,7 @@ namespace Game.Accounts
// Adds a new linked Permission // Adds a new linked Permission
public void AddLinkedPermission(uint id) { _perms.Add(id); } public void AddLinkedPermission(uint id) { _perms.Add(id); }
// Removes a linked Permission // Removes a linked Permission
void RemoveLinkedPermission(uint id) { _perms.Remove(id); } public void RemoveLinkedPermission(uint id) { _perms.Remove(id); }
uint _id; // id of the object
string _name; // name of the object
List<uint> _perms = new List<uint>(); // Set of permissions
} }
public enum RBACCommandResult public enum RBACCommandResult
+60 -60
View File
@@ -35,6 +35,9 @@ namespace Game.Achievements
{ {
public class AchievementManager : CriteriaHandler public class AchievementManager : CriteriaHandler
{ {
protected Dictionary<uint, CompletedAchievementData> _completedAchievements = new();
protected uint _achievementPoints;
/// <summary> /// <summary>
/// called at player login. The player might have fulfilled some achievements when the achievement system wasn't working yet /// called at player login. The player might have fulfilled some achievements when the achievement system wasn't working yet
/// </summary> /// </summary>
@@ -193,13 +196,12 @@ namespace Game.Achievements
return achievement; return achievement;
return null; return null;
}; };
protected Dictionary<uint, CompletedAchievementData> _completedAchievements = new Dictionary<uint, CompletedAchievementData>();
protected uint _achievementPoints;
} }
public class PlayerAchievementMgr : AchievementManager public class PlayerAchievementMgr : AchievementManager
{ {
Player _owner;
public PlayerAchievementMgr(Player owner) public PlayerAchievementMgr(Player owner)
{ {
_owner = owner; _owner = owner;
@@ -211,7 +213,7 @@ namespace Game.Achievements
foreach (var iter in _completedAchievements) foreach (var iter in _completedAchievements)
{ {
AchievementDeleted achievementDeleted = new AchievementDeleted(); AchievementDeleted achievementDeleted = new();
achievementDeleted.AchievementID = iter.Key; achievementDeleted.AchievementID = iter.Key;
SendPacket(achievementDeleted); SendPacket(achievementDeleted);
} }
@@ -226,7 +228,7 @@ namespace Game.Achievements
public static void DeleteFromDB(ObjectGuid guid) public static void DeleteFromDB(ObjectGuid guid)
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHAR_ACHIEVEMENT); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHAR_ACHIEVEMENT);
stmt.AddValue(0, guid.GetCounter()); stmt.AddValue(0, guid.GetCounter());
@@ -252,7 +254,7 @@ namespace Game.Achievements
if (achievement == null) if (achievement == null)
continue; continue;
CompletedAchievementData ca = new CompletedAchievementData(); CompletedAchievementData ca = new();
ca.Date = achievementResult.Read<uint>(1); ca.Date = achievementResult.Read<uint>(1);
ca.Changed = false; ca.Changed = false;
@@ -299,7 +301,7 @@ namespace Game.Achievements
if (criteria.Entry.StartTimer != 0 && (date + criteria.Entry.StartTimer) < now) if (criteria.Entry.StartTimer != 0 && (date + criteria.Entry.StartTimer) < now)
continue; continue;
CriteriaProgress progress = new CriteriaProgress(); CriteriaProgress progress = new();
progress.Counter = counter; progress.Counter = counter;
progress.Date = date; progress.Date = date;
progress.PlayerGUID = _owner.GetGUID(); progress.PlayerGUID = _owner.GetGUID();
@@ -398,8 +400,8 @@ namespace Game.Achievements
public override void SendAllData(Player receiver) public override void SendAllData(Player receiver)
{ {
AllAccountCriteria allAccountCriteria = new AllAccountCriteria(); AllAccountCriteria allAccountCriteria = new();
AllAchievementData achievementData = new AllAchievementData(); AllAchievementData achievementData = new();
foreach (var pair in _completedAchievements) foreach (var pair in _completedAchievements)
{ {
@@ -407,7 +409,7 @@ namespace Game.Achievements
if (achievement == null) if (achievement == null)
continue; continue;
EarnedAchievement earned = new EarnedAchievement(); EarnedAchievement earned = new();
earned.Id = pair.Key; earned.Id = pair.Key;
earned.Date = pair.Value.Date; earned.Date = pair.Value.Date;
if (!achievement.Flags.HasAnyFlag(AchievementFlags.Account)) if (!achievement.Flags.HasAnyFlag(AchievementFlags.Account))
@@ -422,7 +424,7 @@ namespace Game.Achievements
{ {
Criteria criteria = Global.CriteriaMgr.GetCriteria(pair.Key); Criteria criteria = Global.CriteriaMgr.GetCriteria(pair.Key);
CriteriaProgressPkt progress = new CriteriaProgressPkt(); CriteriaProgressPkt progress = new();
progress.Id = pair.Key; progress.Id = pair.Key;
progress.Quantity = pair.Value.Counter; progress.Quantity = pair.Value.Counter;
progress.Player = pair.Value.PlayerGUID; progress.Player = pair.Value.PlayerGUID;
@@ -434,7 +436,7 @@ namespace Game.Achievements
if (criteria.FlagsCu.HasAnyFlag(CriteriaFlagsCu.Account)) if (criteria.FlagsCu.HasAnyFlag(CriteriaFlagsCu.Account))
{ {
CriteriaProgressPkt accountProgress = new CriteriaProgressPkt(); CriteriaProgressPkt accountProgress = new();
accountProgress.Id = pair.Key; accountProgress.Id = pair.Key;
accountProgress.Quantity = pair.Value.Counter; accountProgress.Quantity = pair.Value.Counter;
accountProgress.Player = _owner.GetSession().GetBattlenetAccountGUID(); accountProgress.Player = _owner.GetSession().GetBattlenetAccountGUID();
@@ -454,7 +456,7 @@ namespace Game.Achievements
public void SendAchievementInfo(Player receiver) public void SendAchievementInfo(Player receiver)
{ {
RespondInspectAchievements inspectedAchievements = new RespondInspectAchievements(); RespondInspectAchievements inspectedAchievements = new();
inspectedAchievements.Player = _owner.GetGUID(); inspectedAchievements.Player = _owner.GetGUID();
foreach (var pair in _completedAchievements) foreach (var pair in _completedAchievements)
@@ -463,7 +465,7 @@ namespace Game.Achievements
if (achievement == null) if (achievement == null)
continue; continue;
EarnedAchievement earned = new EarnedAchievement(); EarnedAchievement earned = new();
earned.Id = pair.Key; earned.Id = pair.Key;
earned.Date = pair.Value.Date; earned.Date = pair.Value.Date;
if (!achievement.Flags.HasAnyFlag(AchievementFlags.Account)) if (!achievement.Flags.HasAnyFlag(AchievementFlags.Account))
@@ -476,7 +478,7 @@ namespace Game.Achievements
foreach (var pair in _criteriaProgress) foreach (var pair in _criteriaProgress)
{ {
CriteriaProgressPkt progress = new CriteriaProgressPkt(); CriteriaProgressPkt progress = new();
progress.Id = pair.Key; progress.Id = pair.Key;
progress.Quantity = pair.Value.Counter; progress.Quantity = pair.Value.Counter;
progress.Player = pair.Value.PlayerGUID; progress.Player = pair.Value.PlayerGUID;
@@ -515,7 +517,7 @@ namespace Game.Achievements
Log.outDebug(LogFilter.Achievement, "PlayerAchievementMgr.CompletedAchievement({0}). {1}", achievement.Id, GetOwnerInfo()); Log.outDebug(LogFilter.Achievement, "PlayerAchievementMgr.CompletedAchievement({0}). {1}", achievement.Id, GetOwnerInfo());
CompletedAchievementData ca = new CompletedAchievementData(); CompletedAchievementData ca = new();
ca.Date = Time.UnixTime; ca.Date = Time.UnixTime;
ca.Changed = true; ca.Changed = true;
_completedAchievements[achievement.Id] = ca; _completedAchievements[achievement.Id] = ca;
@@ -552,7 +554,7 @@ namespace Game.Achievements
// mail // mail
if (reward.SenderCreatureId != 0) if (reward.SenderCreatureId != 0)
{ {
MailDraft draft = new MailDraft(reward.MailTemplateId); MailDraft draft = new(reward.MailTemplateId);
if (reward.MailTemplateId == 0) if (reward.MailTemplateId == 0)
{ {
@@ -574,7 +576,7 @@ namespace Game.Achievements
draft = new MailDraft(subject, text); draft = new MailDraft(subject, text);
} }
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
Item item = reward.ItemId != 0 ? Item.CreateItem(reward.ItemId, 1, ItemContext.None, _owner) : null; Item item = reward.ItemId != 0 ? Item.CreateItem(reward.ItemId, 1, ItemContext.None, _owner) : null;
if (item) if (item)
@@ -604,7 +606,7 @@ namespace Game.Achievements
{ {
if (criteria.FlagsCu.HasAnyFlag(CriteriaFlagsCu.Account)) if (criteria.FlagsCu.HasAnyFlag(CriteriaFlagsCu.Account))
{ {
AccountCriteriaUpdate criteriaUpdate = new AccountCriteriaUpdate(); AccountCriteriaUpdate criteriaUpdate = new();
criteriaUpdate.Progress.Id = criteria.Id; criteriaUpdate.Progress.Id = criteria.Id;
criteriaUpdate.Progress.Quantity = progress.Counter; criteriaUpdate.Progress.Quantity = progress.Counter;
criteriaUpdate.Progress.Player = _owner.GetSession().GetBattlenetAccountGUID(); criteriaUpdate.Progress.Player = _owner.GetSession().GetBattlenetAccountGUID();
@@ -619,7 +621,7 @@ namespace Game.Achievements
} }
else else
{ {
CriteriaUpdate criteriaUpdate = new CriteriaUpdate(); CriteriaUpdate criteriaUpdate = new();
criteriaUpdate.CriteriaID = criteria.Id; criteriaUpdate.CriteriaID = criteria.Id;
criteriaUpdate.Quantity = progress.Counter; criteriaUpdate.Quantity = progress.Counter;
@@ -638,7 +640,7 @@ namespace Game.Achievements
public override void SendCriteriaProgressRemoved(uint criteriaId) public override void SendCriteriaProgressRemoved(uint criteriaId)
{ {
CriteriaDeleted criteriaDeleted = new CriteriaDeleted(); CriteriaDeleted criteriaDeleted = new();
criteriaDeleted.CriteriaID = criteriaId; criteriaDeleted.CriteriaID = criteriaId;
SendPacket(criteriaDeleted); SendPacket(criteriaDeleted);
} }
@@ -656,7 +658,7 @@ namespace Game.Achievements
Guild guild = Global.GuildMgr.GetGuildById(_owner.GetGuildId()); Guild guild = Global.GuildMgr.GetGuildById(_owner.GetGuildId());
if (guild) if (guild)
{ {
BroadcastTextBuilder say_builder = new BroadcastTextBuilder(_owner, ChatMsg.GuildAchievement, (uint)BroadcastTextIds.AchivementEarned, _owner.GetGender(), _owner, achievement.Id); BroadcastTextBuilder say_builder = new(_owner, ChatMsg.GuildAchievement, (uint)BroadcastTextIds.AchivementEarned, _owner.GetGender(), _owner, achievement.Id);
var say_do = new LocalizedPacketDo(say_builder); var say_do = new LocalizedPacketDo(say_builder);
guild.BroadcastWorker(say_do, _owner); guild.BroadcastWorker(say_do, _owner);
} }
@@ -664,7 +666,7 @@ namespace Game.Achievements
if (achievement.Flags.HasAnyFlag(AchievementFlags.RealmFirstReach | AchievementFlags.RealmFirstKill)) if (achievement.Flags.HasAnyFlag(AchievementFlags.RealmFirstReach | AchievementFlags.RealmFirstKill))
{ {
// broadcast realm first reached // broadcast realm first reached
BroadcastAchievement serverFirstAchievement = new BroadcastAchievement(); BroadcastAchievement serverFirstAchievement = new();
serverFirstAchievement.Name = _owner.GetName(); serverFirstAchievement.Name = _owner.GetName();
serverFirstAchievement.PlayerGUID = _owner.GetGUID(); serverFirstAchievement.PlayerGUID = _owner.GetGUID();
serverFirstAchievement.AchievementID = achievement.Id; serverFirstAchievement.AchievementID = achievement.Id;
@@ -673,14 +675,14 @@ namespace Game.Achievements
// if player is in world he can tell his friends about new achievement // if player is in world he can tell his friends about new achievement
else if (_owner.IsInWorld) else if (_owner.IsInWorld)
{ {
BroadcastTextBuilder _builder = new BroadcastTextBuilder(_owner, ChatMsg.Achievement, (uint)BroadcastTextIds.AchivementEarned, _owner.GetGender(), _owner, achievement.Id); BroadcastTextBuilder _builder = new(_owner, ChatMsg.Achievement, (uint)BroadcastTextIds.AchivementEarned, _owner.GetGender(), _owner, achievement.Id);
var _localizer = new LocalizedPacketDo(_builder); var _localizer = new LocalizedPacketDo(_builder);
var _worker = new PlayerDistWorker(_owner, WorldConfig.GetFloatValue(WorldCfg.ListenRangeSay), _localizer); var _worker = new PlayerDistWorker(_owner, WorldConfig.GetFloatValue(WorldCfg.ListenRangeSay), _localizer);
Cell.VisitWorldObjects(_owner, _worker, WorldConfig.GetFloatValue(WorldCfg.ListenRangeSay)); Cell.VisitWorldObjects(_owner, _worker, WorldConfig.GetFloatValue(WorldCfg.ListenRangeSay));
} }
} }
AchievementEarned achievementEarned = new AchievementEarned(); AchievementEarned achievementEarned = new();
achievementEarned.Sender = _owner.GetGUID(); achievementEarned.Sender = _owner.GetGUID();
achievementEarned.Earner = _owner.GetGUID(); achievementEarned.Earner = _owner.GetGUID();
achievementEarned.EarnerNativeRealm = achievementEarned.EarnerVirtualRealm = Global.WorldMgr.GetVirtualRealmAddress(); achievementEarned.EarnerNativeRealm = achievementEarned.EarnerVirtualRealm = Global.WorldMgr.GetVirtualRealmAddress();
@@ -707,12 +709,12 @@ namespace Game.Achievements
{ {
return $"{_owner.GetGUID()} {_owner.GetName()}"; return $"{_owner.GetGUID()} {_owner.GetName()}";
} }
Player _owner;
} }
public class GuildAchievementMgr : AchievementManager public class GuildAchievementMgr : AchievementManager
{ {
Guild _owner;
public GuildAchievementMgr(Guild owner) public GuildAchievementMgr(Guild owner)
{ {
_owner = owner; _owner = owner;
@@ -725,7 +727,7 @@ namespace Game.Achievements
ObjectGuid guid = _owner.GetGUID(); ObjectGuid guid = _owner.GetGUID();
foreach (var iter in _completedAchievements) foreach (var iter in _completedAchievements)
{ {
GuildAchievementDeleted guildAchievementDeleted = new GuildAchievementDeleted(); GuildAchievementDeleted guildAchievementDeleted = new();
guildAchievementDeleted.AchievementID = iter.Key; guildAchievementDeleted.AchievementID = iter.Key;
guildAchievementDeleted.GuildGUID = guid; guildAchievementDeleted.GuildGUID = guid;
guildAchievementDeleted.TimeDeleted = Time.UnixTime; guildAchievementDeleted.TimeDeleted = Time.UnixTime;
@@ -739,7 +741,7 @@ namespace Game.Achievements
void DeleteFromDB(ObjectGuid guid) void DeleteFromDB(ObjectGuid guid)
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ALL_GUILD_ACHIEVEMENTS); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ALL_GUILD_ACHIEVEMENTS);
stmt.AddValue(0, guid.GetCounter()); stmt.AddValue(0, guid.GetCounter());
@@ -808,7 +810,7 @@ namespace Game.Achievements
if (criteria.Entry.StartTimer != 0 && date + criteria.Entry.StartTimer < now) if (criteria.Entry.StartTimer != 0 && date + criteria.Entry.StartTimer < now)
continue; continue;
CriteriaProgress progress = new CriteriaProgress(); CriteriaProgress progress = new();
progress.Counter = counter; progress.Counter = counter;
progress.Date = date; progress.Date = date;
progress.PlayerGUID = ObjectGuid.Create(HighGuid.Player, guidLow); progress.PlayerGUID = ObjectGuid.Create(HighGuid.Player, guidLow);
@@ -823,7 +825,7 @@ namespace Game.Achievements
public void SaveToDB(SQLTransaction trans) public void SaveToDB(SQLTransaction trans)
{ {
PreparedStatement stmt; PreparedStatement stmt;
StringBuilder guidstr = new StringBuilder(); StringBuilder guidstr = new();
foreach (var pair in _completedAchievements) foreach (var pair in _completedAchievements)
{ {
if (!pair.Value.Changed) if (!pair.Value.Changed)
@@ -869,7 +871,7 @@ namespace Game.Achievements
public override void SendAllData(Player receiver) public override void SendAllData(Player receiver)
{ {
AllGuildAchievements allGuildAchievements = new AllGuildAchievements(); AllGuildAchievements allGuildAchievements = new();
foreach (var pair in _completedAchievements) foreach (var pair in _completedAchievements)
{ {
@@ -877,7 +879,7 @@ namespace Game.Achievements
if (achievement == null) if (achievement == null)
continue; continue;
EarnedAchievement earned = new EarnedAchievement(); EarnedAchievement earned = new();
earned.Id = pair.Key; earned.Id = pair.Key;
earned.Date = pair.Value.Date; earned.Date = pair.Value.Date;
allGuildAchievements.Earned.Add(earned); allGuildAchievements.Earned.Add(earned);
@@ -888,7 +890,7 @@ namespace Game.Achievements
public void SendAchievementInfo(Player receiver, uint achievementId = 0) public void SendAchievementInfo(Player receiver, uint achievementId = 0)
{ {
GuildCriteriaUpdate guildCriteriaUpdate = new GuildCriteriaUpdate(); GuildCriteriaUpdate guildCriteriaUpdate = new();
AchievementRecord achievement = CliDB.AchievementStorage.LookupByKey(achievementId); AchievementRecord achievement = CliDB.AchievementStorage.LookupByKey(achievementId);
if (achievement != null) if (achievement != null)
{ {
@@ -902,7 +904,7 @@ namespace Game.Achievements
var progress = _criteriaProgress.LookupByKey(node.Criteria.Id); var progress = _criteriaProgress.LookupByKey(node.Criteria.Id);
if (progress != null) if (progress != null)
{ {
GuildCriteriaProgress guildCriteriaProgress = new GuildCriteriaProgress(); GuildCriteriaProgress guildCriteriaProgress = new();
guildCriteriaProgress.CriteriaID = node.Criteria.Id; guildCriteriaProgress.CriteriaID = node.Criteria.Id;
guildCriteriaProgress.DateCreated = 0; guildCriteriaProgress.DateCreated = 0;
guildCriteriaProgress.DateStarted = 0; guildCriteriaProgress.DateStarted = 0;
@@ -923,7 +925,7 @@ namespace Game.Achievements
public void SendAllTrackedCriterias(Player receiver, List<uint> trackedCriterias) public void SendAllTrackedCriterias(Player receiver, List<uint> trackedCriterias)
{ {
GuildCriteriaUpdate guildCriteriaUpdate = new GuildCriteriaUpdate(); GuildCriteriaUpdate guildCriteriaUpdate = new();
foreach (uint criteriaId in trackedCriterias) foreach (uint criteriaId in trackedCriterias)
{ {
@@ -931,7 +933,7 @@ namespace Game.Achievements
if (progress == null) if (progress == null)
continue; continue;
GuildCriteriaProgress guildCriteriaProgress = new GuildCriteriaProgress(); GuildCriteriaProgress guildCriteriaProgress = new();
guildCriteriaProgress.CriteriaID = criteriaId; guildCriteriaProgress.CriteriaID = criteriaId;
guildCriteriaProgress.DateCreated = 0; guildCriteriaProgress.DateCreated = 0;
guildCriteriaProgress.DateStarted = 0; guildCriteriaProgress.DateStarted = 0;
@@ -951,7 +953,7 @@ namespace Game.Achievements
var achievementData = _completedAchievements.LookupByKey(achievementId); var achievementData = _completedAchievements.LookupByKey(achievementId);
if (achievementData != null) if (achievementData != null)
{ {
GuildAchievementMembers guildAchievementMembers = new GuildAchievementMembers(); GuildAchievementMembers guildAchievementMembers = new();
guildAchievementMembers.GuildGUID = _owner.GetGUID(); guildAchievementMembers.GuildGUID = _owner.GetGUID();
guildAchievementMembers.AchievementID = achievementId; guildAchievementMembers.AchievementID = achievementId;
@@ -977,7 +979,7 @@ namespace Game.Achievements
} }
SendAchievementEarned(achievement); SendAchievementEarned(achievement);
CompletedAchievementData ca = new CompletedAchievementData(); CompletedAchievementData ca = new();
ca.Date = Time.UnixTime; ca.Date = Time.UnixTime;
ca.Changed = true; ca.Changed = true;
@@ -1013,9 +1015,9 @@ namespace Game.Achievements
public override void SendCriteriaUpdate(Criteria entry, CriteriaProgress progress, uint timeElapsed, bool timedCompleted) public override void SendCriteriaUpdate(Criteria entry, CriteriaProgress progress, uint timeElapsed, bool timedCompleted)
{ {
GuildCriteriaUpdate guildCriteriaUpdate = new GuildCriteriaUpdate(); GuildCriteriaUpdate guildCriteriaUpdate = new();
GuildCriteriaProgress guildCriteriaProgress = new GuildCriteriaProgress(); GuildCriteriaProgress guildCriteriaProgress = new();
guildCriteriaProgress.CriteriaID = entry.Id; guildCriteriaProgress.CriteriaID = entry.Id;
guildCriteriaProgress.DateCreated = 0; guildCriteriaProgress.DateCreated = 0;
guildCriteriaProgress.DateStarted = 0; guildCriteriaProgress.DateStarted = 0;
@@ -1031,7 +1033,7 @@ namespace Game.Achievements
public override void SendCriteriaProgressRemoved(uint criteriaId) public override void SendCriteriaProgressRemoved(uint criteriaId)
{ {
GuildCriteriaDeleted guildCriteriaDeleted = new GuildCriteriaDeleted(); GuildCriteriaDeleted guildCriteriaDeleted = new();
guildCriteriaDeleted.GuildGUID = _owner.GetGUID(); guildCriteriaDeleted.GuildGUID = _owner.GetGUID();
guildCriteriaDeleted.CriteriaID = criteriaId; guildCriteriaDeleted.CriteriaID = criteriaId;
SendPacket(guildCriteriaDeleted); SendPacket(guildCriteriaDeleted);
@@ -1042,7 +1044,7 @@ namespace Game.Achievements
if (achievement.Flags.HasAnyFlag(AchievementFlags.RealmFirstReach | AchievementFlags.RealmFirstKill)) if (achievement.Flags.HasAnyFlag(AchievementFlags.RealmFirstReach | AchievementFlags.RealmFirstKill))
{ {
// broadcast realm first reached // broadcast realm first reached
BroadcastAchievement serverFirstAchievement = new BroadcastAchievement(); BroadcastAchievement serverFirstAchievement = new();
serverFirstAchievement.Name = _owner.GetName(); serverFirstAchievement.Name = _owner.GetName();
serverFirstAchievement.PlayerGUID = _owner.GetGUID(); serverFirstAchievement.PlayerGUID = _owner.GetGUID();
serverFirstAchievement.AchievementID = achievement.Id; serverFirstAchievement.AchievementID = achievement.Id;
@@ -1050,7 +1052,7 @@ namespace Game.Achievements
Global.WorldMgr.SendGlobalMessage(serverFirstAchievement); Global.WorldMgr.SendGlobalMessage(serverFirstAchievement);
} }
GuildAchievementEarned guildAchievementEarned = new GuildAchievementEarned(); GuildAchievementEarned guildAchievementEarned = new();
guildAchievementEarned.AchievementID = achievement.Id; guildAchievementEarned.AchievementID = achievement.Id;
guildAchievementEarned.GuildGUID = _owner.GetGUID(); guildAchievementEarned.GuildGUID = _owner.GetGUID();
guildAchievementEarned.TimeEarned = Time.UnixTime; guildAchievementEarned.TimeEarned = Time.UnixTime;
@@ -1071,12 +1073,19 @@ namespace Game.Achievements
{ {
return $"Guild ID {_owner.GetId()} {_owner.GetName()}"; return $"Guild ID {_owner.GetId()} {_owner.GetName()}";
} }
Guild _owner;
} }
public class AchievementGlobalMgr : Singleton<AchievementGlobalMgr> public class AchievementGlobalMgr : Singleton<AchievementGlobalMgr>
{ {
// store achievements by referenced achievement id to speed up lookup
MultiMap<uint, AchievementRecord> _achievementListByReferencedId = new();
// store realm first achievements
Dictionary<uint /*achievementId*/, DateTime /*completionTime*/> _allCompletedAchievements = new();
Dictionary<uint, AchievementReward> _achievementRewards = new();
Dictionary<uint, AchievementRewardLocale> _achievementRewardLocales = new();
AchievementGlobalMgr() { } AchievementGlobalMgr() { }
public List<AchievementRecord> GetAchievementByReferencedId(uint id) public List<AchievementRecord> GetAchievementByReferencedId(uint id)
@@ -1217,7 +1226,7 @@ namespace Game.Achievements
continue; continue;
} }
AchievementReward reward = new AchievementReward(); AchievementReward reward = new();
reward.TitleId[0] = result.Read<uint>(1); reward.TitleId[0] = result.Read<uint>(1);
reward.TitleId[1] = result.Read<uint>(2); reward.TitleId[1] = result.Read<uint>(2);
reward.ItemId = result.Read<uint>(3); reward.ItemId = result.Read<uint>(3);
@@ -1332,7 +1341,7 @@ namespace Game.Achievements
continue; continue;
} }
AchievementRewardLocale data = new AchievementRewardLocale(); AchievementRewardLocale data = new();
Locale locale = localeName.ToEnum<Locale>(); Locale locale = localeName.ToEnum<Locale>();
if (!SharedConst.IsValidLocale(locale) || locale == Locale.enUS) if (!SharedConst.IsValidLocale(locale) || locale == Locale.enUS)
continue; continue;
@@ -1346,15 +1355,6 @@ namespace Game.Achievements
Log.outInfo(LogFilter.ServerLoading, "Loaded {0} achievement reward locale strings in {1} ms.", _achievementRewardLocales.Count, Time.GetMSTimeDiffToNow(oldMSTime)); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} achievement reward locale strings in {1} ms.", _achievementRewardLocales.Count, Time.GetMSTimeDiffToNow(oldMSTime));
} }
// store achievements by referenced achievement id to speed up lookup
MultiMap<uint, AchievementRecord> _achievementListByReferencedId = new MultiMap<uint, AchievementRecord>();
// store realm first achievements
Dictionary<uint /*achievementId*/, DateTime /*completionTime*/> _allCompletedAchievements = new Dictionary<uint, DateTime>();
Dictionary<uint, AchievementReward> _achievementRewards = new Dictionary<uint, AchievementReward>();
Dictionary<uint, AchievementRewardLocale> _achievementRewardLocales = new Dictionary<uint, AchievementRewardLocale>();
} }
public class AchievementReward public class AchievementReward
@@ -1369,14 +1369,14 @@ namespace Game.Achievements
public class AchievementRewardLocale public class AchievementRewardLocale
{ {
public StringArray Subject = new StringArray((int)Locale.Total); public StringArray Subject = new((int)Locale.Total);
public StringArray Body = new StringArray((int)Locale.Total); public StringArray Body = new((int)Locale.Total);
} }
public class CompletedAchievementData public class CompletedAchievementData
{ {
public long Date; public long Date;
public List<ObjectGuid> CompletingPlayers = new List<ObjectGuid>(); public List<ObjectGuid> CompletingPlayers = new();
public bool Changed; public bool Changed;
} }
} }
+100 -100
View File
@@ -37,6 +37,9 @@ namespace Game.Achievements
{ {
public class CriteriaHandler public class CriteriaHandler
{ {
protected Dictionary<uint, CriteriaProgress> _criteriaProgress = new();
Dictionary<uint, uint /*ms time left*/> _timeCriteriaTrees = new();
public virtual void Reset() public virtual void Reset()
{ {
foreach (var iter in _criteriaProgress) foreach (var iter in _criteriaProgress)
@@ -2599,13 +2602,28 @@ namespace Game.Achievements
public virtual string GetOwnerInfo() { return ""; } public virtual string GetOwnerInfo() { return ""; }
public virtual List<Criteria> GetCriteriaByType(CriteriaTypes type, uint asset) { return null; } public virtual List<Criteria> GetCriteriaByType(CriteriaTypes type, uint asset) { return null; }
protected Dictionary<uint, CriteriaProgress> _criteriaProgress = new Dictionary<uint, CriteriaProgress>();
Dictionary<uint, uint /*ms time left*/> _timeCriteriaTrees = new Dictionary<uint, uint>();
} }
public class CriteriaManager : Singleton<CriteriaManager> public class CriteriaManager : Singleton<CriteriaManager>
{ {
Dictionary<uint, CriteriaDataSet> _criteriaDataMap = new();
Dictionary<uint, CriteriaTree> _criteriaTrees = new();
Dictionary<uint, Criteria> _criteria = new();
Dictionary<uint, ModifierTreeNode> _criteriaModifiers = new();
MultiMap<uint, CriteriaTree> _criteriaTreeByCriteria = new();
// store criterias by type to speed up lookup
MultiMap<CriteriaTypes, Criteria> _criteriasByType = new();
MultiMap<uint, Criteria>[] _criteriasByAsset = new MultiMap<uint, Criteria>[(int)CriteriaTypes.TotalTypes];
MultiMap<CriteriaTypes, Criteria> _guildCriteriasByType = new();
MultiMap<CriteriaTypes, Criteria> _scenarioCriteriasByType = new();
MultiMap<CriteriaTypes, Criteria> _questObjectiveCriteriasByType = new();
MultiMap<CriteriaTimedTypes, Criteria> _criteriasByTimedType = new();
MultiMap<int, Criteria>[] _criteriasByFailEvent = new MultiMap<int, Criteria>[(int)CriteriaCondition.Max];
CriteriaManager() CriteriaManager()
{ {
for (var i = 0; i < (int)CriteriaTypes.TotalTypes; ++i) for (var i = 0; i < (int)CriteriaTypes.TotalTypes; ++i)
@@ -2625,7 +2643,7 @@ namespace Game.Achievements
// Load modifier tree nodes // Load modifier tree nodes
foreach (var tree in CliDB.ModifierTreeStorage.Values) foreach (var tree in CliDB.ModifierTreeStorage.Values)
{ {
ModifierTreeNode node = new ModifierTreeNode(); ModifierTreeNode node = new();
node.Entry = tree; node.Entry = tree;
_criteriaModifiers[node.Entry.Id] = node; _criteriaModifiers[node.Entry.Id] = node;
} }
@@ -2667,19 +2685,19 @@ namespace Game.Achievements
{ {
uint oldMSTime = Time.GetMSTime(); uint oldMSTime = Time.GetMSTime();
Dictionary<uint /*criteriaTreeID*/, AchievementRecord> achievementCriteriaTreeIds = new Dictionary<uint, AchievementRecord>(); Dictionary<uint /*criteriaTreeID*/, AchievementRecord> achievementCriteriaTreeIds = new();
foreach (AchievementRecord achievement in CliDB.AchievementStorage.Values) foreach (AchievementRecord achievement in CliDB.AchievementStorage.Values)
if (achievement.CriteriaTree != 0) if (achievement.CriteriaTree != 0)
achievementCriteriaTreeIds[achievement.CriteriaTree] = achievement; achievementCriteriaTreeIds[achievement.CriteriaTree] = achievement;
Dictionary<uint, ScenarioStepRecord> scenarioCriteriaTreeIds = new Dictionary<uint, ScenarioStepRecord>(); Dictionary<uint, ScenarioStepRecord> scenarioCriteriaTreeIds = new();
foreach (ScenarioStepRecord scenarioStep in CliDB.ScenarioStepStorage.Values) foreach (ScenarioStepRecord scenarioStep in CliDB.ScenarioStepStorage.Values)
{ {
if (scenarioStep.CriteriaTreeId != 0) if (scenarioStep.CriteriaTreeId != 0)
scenarioCriteriaTreeIds[scenarioStep.CriteriaTreeId] = scenarioStep; scenarioCriteriaTreeIds[scenarioStep.CriteriaTreeId] = scenarioStep;
} }
Dictionary<uint /*criteriaTreeID*/, QuestObjective> questObjectiveCriteriaTreeIds = new Dictionary<uint, QuestObjective>(); Dictionary<uint /*criteriaTreeID*/, QuestObjective> questObjectiveCriteriaTreeIds = new();
foreach (var pair in Global.ObjectMgr.GetQuestTemplates()) foreach (var pair in Global.ObjectMgr.GetQuestTemplates())
{ {
foreach (QuestObjective objective in pair.Value.Objectives) foreach (QuestObjective objective in pair.Value.Objectives)
@@ -2702,7 +2720,7 @@ namespace Game.Achievements
if (achievement == null && scenarioStep == null && questObjective == null) if (achievement == null && scenarioStep == null && questObjective == null)
continue; continue;
CriteriaTree criteriaTree = new CriteriaTree(); CriteriaTree criteriaTree = new();
criteriaTree.Id = tree.Id; criteriaTree.Id = tree.Id;
criteriaTree.Achievement = achievement; criteriaTree.Achievement = achievement;
criteriaTree.ScenarioStep = scenarioStep; criteriaTree.ScenarioStep = scenarioStep;
@@ -2742,7 +2760,7 @@ namespace Game.Achievements
if (treeList.Empty()) if (treeList.Empty())
continue; continue;
Criteria criteria = new Criteria(); Criteria criteria = new();
criteria.Id = criteriaEntry.Id; criteria.Id = criteriaEntry.Id;
criteria.Entry = criteriaEntry; criteria.Entry = criteriaEntry;
criteria.Modifier = _criteriaModifiers.LookupByKey(criteriaEntry.ModifierTreeId); criteria.Modifier = _criteriaModifiers.LookupByKey(criteriaEntry.ModifierTreeId);
@@ -2863,13 +2881,13 @@ namespace Game.Achievements
scriptId = Global.ObjectMgr.GetScriptId(scriptName); scriptId = Global.ObjectMgr.GetScriptId(scriptName);
} }
CriteriaData data = new CriteriaData(dataType, result.Read<uint>(2), result.Read<uint>(3), scriptId); CriteriaData data = new(dataType, result.Read<uint>(2), result.Read<uint>(3), scriptId);
if (!data.IsValid(criteria)) if (!data.IsValid(criteria))
continue; continue;
// this will allocate empty data set storage // this will allocate empty data set storage
CriteriaDataSet dataSet = new CriteriaDataSet(); CriteriaDataSet dataSet = new();
dataSet.SetCriteriaId(criteria_id); dataSet.SetCriteriaId(criteria_id);
// add real data only for not NONE data types // add real data only for not NONE data types
@@ -3012,30 +3030,12 @@ namespace Game.Achievements
func(tree); func(tree);
} }
Dictionary<uint, CriteriaDataSet> _criteriaDataMap = new Dictionary<uint, CriteriaDataSet>();
Dictionary<uint, CriteriaTree> _criteriaTrees = new Dictionary<uint, CriteriaTree>();
Dictionary<uint, Criteria> _criteria = new Dictionary<uint, Criteria>();
Dictionary<uint, ModifierTreeNode> _criteriaModifiers = new Dictionary<uint, ModifierTreeNode>();
MultiMap<uint, CriteriaTree> _criteriaTreeByCriteria = new MultiMap<uint, CriteriaTree>();
// store criterias by type to speed up lookup
MultiMap<CriteriaTypes, Criteria> _criteriasByType = new MultiMap<CriteriaTypes, Criteria>();
MultiMap<uint, Criteria>[] _criteriasByAsset = new MultiMap<uint, Criteria>[(int)CriteriaTypes.TotalTypes];
MultiMap<CriteriaTypes, Criteria> _guildCriteriasByType = new MultiMap<CriteriaTypes, Criteria>();
MultiMap<CriteriaTypes, Criteria> _scenarioCriteriasByType = new MultiMap<CriteriaTypes, Criteria>();
MultiMap<CriteriaTypes, Criteria> _questObjectiveCriteriasByType = new MultiMap<CriteriaTypes, Criteria>();
MultiMap<CriteriaTimedTypes, Criteria> _criteriasByTimedType = new MultiMap<CriteriaTimedTypes, Criteria>();
MultiMap<int, Criteria>[] _criteriasByFailEvent = new MultiMap<int, Criteria>[(int)CriteriaCondition.Max];
} }
public class ModifierTreeNode public class ModifierTreeNode
{ {
public ModifierTreeRecord Entry; public ModifierTreeRecord Entry;
public List<ModifierTreeNode> Children = new List<ModifierTreeNode>(); public List<ModifierTreeNode> Children = new();
} }
public class Criteria public class Criteria
@@ -3054,7 +3054,7 @@ namespace Game.Achievements
public ScenarioStepRecord ScenarioStep; public ScenarioStepRecord ScenarioStep;
public QuestObjective QuestObjective; public QuestObjective QuestObjective;
public Criteria Criteria; public Criteria Criteria;
public List<CriteriaTree> Children = new List<CriteriaTree>(); public List<CriteriaTree> Children = new();
} }
public class CriteriaProgress public class CriteriaProgress
@@ -3067,7 +3067,67 @@ namespace Game.Achievements
[StructLayout(LayoutKind.Explicit)] [StructLayout(LayoutKind.Explicit)]
public class CriteriaData public class CriteriaData
{ {
[FieldOffset(0)]
public CriteriaDataType DataType;
[FieldOffset(4)]
public CreatureStruct Creature;
[FieldOffset(4)]
public ClassRaceStruct ClassRace;
[FieldOffset(4)]
public HealthStruct Health;
[FieldOffset(4)]
public AuraStruct Aura;
[FieldOffset(4)]
public ValueStruct Value;
[FieldOffset(4)]
public LevelStruct Level;
[FieldOffset(4)]
public GenderStruct Gender;
[FieldOffset(4)]
public MapPlayersStruct MapPlayers;
[FieldOffset(4)]
public TeamStruct TeamId;
[FieldOffset(4)]
public DrunkStruct Drunk;
[FieldOffset(4)]
public HolidayStruct Holiday;
[FieldOffset(4)]
public BgLossTeamScoreStruct BattlegroundScore;
[FieldOffset(4)]
public EquippedItemStruct EquippedItem;
[FieldOffset(4)]
public MapIdStruct MapId;
[FieldOffset(4)]
public KnownTitleStruct KnownTitle;
[FieldOffset(4)]
public GameEventStruct GameEvent;
[FieldOffset(4)]
public ItemQualityStruct itemQuality;
[FieldOffset(4)]
public RawStruct Raw;
[FieldOffset(12)]
public uint ScriptId;
public CriteriaData() public CriteriaData()
{ {
DataType = CriteriaDataType.None; DataType = CriteriaDataType.None;
@@ -3452,66 +3512,6 @@ namespace Game.Achievements
return false; return false;
} }
[FieldOffset(0)]
public CriteriaDataType DataType;
[FieldOffset(4)]
public CreatureStruct Creature;
[FieldOffset(4)]
public ClassRaceStruct ClassRace;
[FieldOffset(4)]
public HealthStruct Health;
[FieldOffset(4)]
public AuraStruct Aura;
[FieldOffset(4)]
public ValueStruct Value;
[FieldOffset(4)]
public LevelStruct Level;
[FieldOffset(4)]
public GenderStruct Gender;
[FieldOffset(4)]
public MapPlayersStruct MapPlayers;
[FieldOffset(4)]
public TeamStruct TeamId;
[FieldOffset(4)]
public DrunkStruct Drunk;
[FieldOffset(4)]
public HolidayStruct Holiday;
[FieldOffset(4)]
public BgLossTeamScoreStruct BattlegroundScore;
[FieldOffset(4)]
public EquippedItemStruct EquippedItem;
[FieldOffset(4)]
public MapIdStruct MapId;
[FieldOffset(4)]
public KnownTitleStruct KnownTitle;
[FieldOffset(4)]
public GameEventStruct GameEvent;
[FieldOffset(4)]
public ItemQualityStruct itemQuality;
[FieldOffset(4)]
public RawStruct Raw;
[FieldOffset(12)]
public uint ScriptId;
#region Structs #region Structs
// criteria_data_TYPE_NONE = 0 (no data) // criteria_data_TYPE_NONE = 0 (no data)
// criteria_data_TYPE_T_CREATURE = 1 // criteria_data_TYPE_T_CREATURE = 1
@@ -3618,21 +3618,21 @@ namespace Game.Achievements
} }
public class CriteriaDataSet public class CriteriaDataSet
{ {
public void Add(CriteriaData data) { storage.Add(data); } uint _criteriaId;
List<CriteriaData> _storage = new();
public void Add(CriteriaData data) { _storage.Add(data); }
public bool Meets(Player source, Unit target, uint miscValue = 0, uint miscValue2 = 0) public bool Meets(Player source, Unit target, uint miscValue = 0, uint miscValue2 = 0)
{ {
foreach (var data in storage) foreach (var data in _storage)
if (!data.Meets(criteria_id, source, target, miscValue, miscValue2)) if (!data.Meets(_criteriaId, source, target, miscValue, miscValue2))
return false; return false;
return true; return true;
} }
public void SetCriteriaId(uint id) { criteria_id = id; } public void SetCriteriaId(uint id) { _criteriaId = id; }
uint criteria_id;
List<CriteriaData> storage = new List<CriteriaData>();
} }
} }
+6 -6
View File
@@ -136,7 +136,7 @@ namespace Game.Arenas
//Player.RemovePetitionsAndSigns(playerGuid, GetArenaType()); //Player.RemovePetitionsAndSigns(playerGuid, GetArenaType());
// Feed data to the struct // Feed data to the struct
ArenaTeamMember newMember = new ArenaTeamMember(); ArenaTeamMember newMember = new();
newMember.Name = playerName; newMember.Name = playerName;
newMember.Guid = playerGuid; newMember.Guid = playerGuid;
newMember.Class = (byte)playerClass; newMember.Class = (byte)playerClass;
@@ -211,7 +211,7 @@ namespace Game.Arenas
if (arenaTeamId > teamId) if (arenaTeamId > teamId)
break; break;
ArenaTeamMember newMember = new ArenaTeamMember(); ArenaTeamMember newMember = new();
newMember.Guid = ObjectGuid.Create(HighGuid.Player, result.Read<ulong>(1)); newMember.Guid = ObjectGuid.Create(HighGuid.Player, result.Read<ulong>(1));
newMember.WeekGames = result.Read<ushort>(2); newMember.WeekGames = result.Read<ushort>(2);
newMember.WeekWins = result.Read<ushort>(3); newMember.WeekWins = result.Read<ushort>(3);
@@ -341,7 +341,7 @@ namespace Game.Arenas
DelMember(Members.FirstOrDefault().Guid, false); DelMember(Members.FirstOrDefault().Guid, false);
// Update database // Update database
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ARENA_TEAM); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ARENA_TEAM);
stmt.AddValue(0, teamId); stmt.AddValue(0, teamId);
@@ -364,7 +364,7 @@ namespace Game.Arenas
DelMember(Members.First().Guid, false); DelMember(Members.First().Guid, false);
// Update database // Update database
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ARENA_TEAM); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ARENA_TEAM);
stmt.AddValue(0, teamId); stmt.AddValue(0, teamId);
@@ -692,7 +692,7 @@ namespace Game.Arenas
// Save team and member stats to db // Save team and member stats to db
// Called after a match has ended or when calculating arena_points // Called after a match has ended or when calculating arena_points
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ARENA_TEAM_STATS); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ARENA_TEAM_STATS);
stmt.AddValue(0, stats.Rating); stmt.AddValue(0, stats.Rating);
@@ -808,7 +808,7 @@ namespace Game.Arenas
byte BorderStyle; // border image id byte BorderStyle; // border image id
uint BorderColor; // ARGB format uint BorderColor; // ARGB format
List<ArenaTeamMember> Members = new List<ArenaTeamMember>(); List<ArenaTeamMember> Members = new();
ArenaTeamStats stats; ArenaTeamStats stats;
} }
+2 -2
View File
@@ -101,7 +101,7 @@ namespace Game.Arenas
uint count = 0; uint count = 0;
do do
{ {
ArenaTeam newArenaTeam = new ArenaTeam(); ArenaTeam newArenaTeam = new();
if (!newArenaTeam.LoadArenaTeamFromDB(result) || !newArenaTeam.LoadMembersFromDB(result2)) if (!newArenaTeam.LoadArenaTeamFromDB(result) || !newArenaTeam.LoadMembersFromDB(result2))
{ {
@@ -123,6 +123,6 @@ namespace Game.Arenas
public Dictionary<uint, ArenaTeam> GetArenaTeamMap() { return ArenaTeamStorage; } public Dictionary<uint, ArenaTeam> GetArenaTeamMap() { return ArenaTeamStorage; }
uint NextArenaTeamId; uint NextArenaTeamId;
Dictionary<uint, ArenaTeam> ArenaTeamStorage = new Dictionary<uint, ArenaTeam>(); Dictionary<uint, ArenaTeam> ArenaTeamStorage = new();
} }
} }
+50 -50
View File
@@ -41,13 +41,13 @@ namespace Game
AuctionHouseObject mNeutralAuctions; AuctionHouseObject mNeutralAuctions;
AuctionHouseObject mGoblinAuctions; AuctionHouseObject mGoblinAuctions;
Dictionary<ObjectGuid, PlayerPendingAuctions> _pendingAuctionsByPlayer = new Dictionary<ObjectGuid, PlayerPendingAuctions>(); Dictionary<ObjectGuid, PlayerPendingAuctions> _pendingAuctionsByPlayer = new();
Dictionary<ObjectGuid, Item> _itemsByGuid = new Dictionary<ObjectGuid, Item>(); Dictionary<ObjectGuid, Item> _itemsByGuid = new();
uint _replicateIdGenerator; uint _replicateIdGenerator;
Dictionary<ObjectGuid, PlayerThrottleObject> _playerThrottleObjects = new Dictionary<ObjectGuid, PlayerThrottleObject>(); Dictionary<ObjectGuid, PlayerThrottleObject> _playerThrottleObjects = new();
DateTime _playerThrottleObjectsCleanupTime; DateTime _playerThrottleObjectsCleanupTime;
AuctionManager() AuctionManager()
@@ -164,8 +164,8 @@ namespace Game
// data needs to be at first place for Item.LoadFromDB // data needs to be at first place for Item.LoadFromDB
uint count = 0; uint count = 0;
MultiMap<uint, Item> itemsByAuction = new MultiMap<uint, Item>(); MultiMap<uint, Item> itemsByAuction = new();
MultiMap<uint, ObjectGuid> biddersByAuction = new MultiMap<uint, ObjectGuid>(); MultiMap<uint, ObjectGuid> biddersByAuction = new();
do do
{ {
@@ -215,10 +215,10 @@ namespace Game
result = DB.Characters.Query(DB.Characters.GetPreparedStatement(CharStatements.SEL_AUCTIONS)); result = DB.Characters.Query(DB.Characters.GetPreparedStatement(CharStatements.SEL_AUCTIONS));
if (!result.IsEmpty()) if (!result.IsEmpty())
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
do do
{ {
AuctionPosting auction = new AuctionPosting(); AuctionPosting auction = new();
auction.Id = result.Read<uint>(0); auction.Id = result.Read<uint>(0);
uint auctionHouseId = result.Read<uint>(1); uint auctionHouseId = result.Read<uint>(1);
@@ -343,7 +343,7 @@ namespace Game
// expire auctions we cannot afford // expire auctions we cannot afford
if (auctionIndex < playerPendingAuctions.Auctions.Count) if (auctionIndex < playerPendingAuctions.Auctions.Count)
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
do do
{ {
@@ -385,7 +385,7 @@ namespace Game
// Expire any auctions that we couldn't get a deposit for // Expire any auctions that we couldn't get a deposit for
Log.outWarn(LogFilter.Auctionhouse, $"Player {playerGUID} was offline, unable to retrieve deposit!"); Log.outWarn(LogFilter.Auctionhouse, $"Player {playerGUID} was offline, unable to retrieve deposit!");
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
foreach (PendingAuctionInfo pendingAuction in pair.Value.Auctions) foreach (PendingAuctionInfo pendingAuction in pair.Value.Auctions)
{ {
AuctionPosting auction = GetAuctionsById(pendingAuction.AuctionHouseId).GetAuction(pendingAuction.AuctionId); AuctionPosting auction = GetAuctionsById(pendingAuction.AuctionHouseId).GetAuction(pendingAuction.AuctionId);
@@ -517,7 +517,7 @@ namespace Game
class PlayerPendingAuctions class PlayerPendingAuctions
{ {
public List<PendingAuctionInfo> Auctions = new List<PendingAuctionInfo>(); public List<PendingAuctionInfo> Auctions = new();
public int LastAuctionsSize; public int LastAuctionsSize;
} }
@@ -677,7 +677,7 @@ namespace Game
_itemsByAuctionId[auction.Id] = auction; _itemsByAuctionId[auction.Id] = auction;
AuctionPosting.Sorter insertSorter = new AuctionPosting.Sorter(Locale.enUS, new AuctionSortDef[] { new AuctionSortDef(AuctionHouseSortOrder.Price, false) }, 1); AuctionPosting.Sorter insertSorter = new(Locale.enUS, new AuctionSortDef[] { new AuctionSortDef(AuctionHouseSortOrder.Price, false) }, 1);
var auctionIndex = bucket.Auctions.BinarySearch(auction, insertSorter); var auctionIndex = bucket.Auctions.BinarySearch(auction, insertSorter);
if (auctionIndex < 0) if (auctionIndex < 0)
auctionIndex = ~auctionIndex; auctionIndex = ~auctionIndex;
@@ -786,7 +786,7 @@ namespace Game
if (_itemsByAuctionId.Empty()) if (_itemsByAuctionId.Empty())
return; return;
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
foreach (var auction in _itemsByAuctionId.Values.ToList()) foreach (var auction in _itemsByAuctionId.Values.ToList())
{ {
@@ -822,8 +822,8 @@ namespace Game
public void BuildListBuckets(AuctionListBucketsResult listBucketsResult, Player player, string name, byte minLevel, byte maxLevel, AuctionHouseFilterMask filters, Optional<AuctionSearchClassFilters> classFilters, public void BuildListBuckets(AuctionListBucketsResult listBucketsResult, Player player, string name, byte minLevel, byte maxLevel, AuctionHouseFilterMask filters, Optional<AuctionSearchClassFilters> classFilters,
byte[] knownPetBits, int knownPetBitsCount, byte maxKnownPetLevel, uint offset, AuctionSortDef[] sorts, int sortCount) byte[] knownPetBits, int knownPetBitsCount, byte maxKnownPetLevel, uint offset, AuctionSortDef[] sorts, int sortCount)
{ {
List<uint> knownAppearanceIds = new List<uint>(); List<uint> knownAppearanceIds = new();
BitArray knownPetSpecies = new BitArray(knownPetBits); BitArray knownPetSpecies = new(knownPetBits);
// prepare uncollected filter for more efficient searches // prepare uncollected filter for more efficient searches
if (filters.HasFlag(AuctionHouseFilterMask.UncollectedOnly)) if (filters.HasFlag(AuctionHouseFilterMask.UncollectedOnly))
{ {
@@ -957,7 +957,7 @@ namespace Game
foreach (AuctionsBucketData resultBucket in builder.GetResultRange()) foreach (AuctionsBucketData resultBucket in builder.GetResultRange())
{ {
BucketInfo bucketInfo = new BucketInfo(); BucketInfo bucketInfo = new();
resultBucket.BuildBucketInfo(bucketInfo, player); resultBucket.BuildBucketInfo(bucketInfo, player);
listBucketsResult.Buckets.Add(bucketInfo); listBucketsResult.Buckets.Add(bucketInfo);
} }
@@ -967,7 +967,7 @@ namespace Game
public void BuildListBuckets(AuctionListBucketsResult listBucketsResult, Player player, AuctionBucketKey[] keys, int keysCount, AuctionSortDef[] sorts, int sortCount) public void BuildListBuckets(AuctionListBucketsResult listBucketsResult, Player player, AuctionBucketKey[] keys, int keysCount, AuctionSortDef[] sorts, int sortCount)
{ {
List<AuctionsBucketData> buckets = new List<AuctionsBucketData>(); List<AuctionsBucketData> buckets = new();
for (int i = 0; i < keysCount; ++i) for (int i = 0; i < keysCount; ++i)
{ {
var bucketData = _buckets.LookupByKey(new AuctionsBucketKey(keys[i])); var bucketData = _buckets.LookupByKey(new AuctionsBucketKey(keys[i]));
@@ -975,12 +975,12 @@ namespace Game
buckets.Add(bucketData); buckets.Add(bucketData);
} }
AuctionsBucketData.Sorter sorter = new AuctionsBucketData.Sorter(player.GetSession().GetSessionDbcLocale(), sorts, sortCount); AuctionsBucketData.Sorter sorter = new(player.GetSession().GetSessionDbcLocale(), sorts, sortCount);
buckets.Sort(sorter); buckets.Sort(sorter);
foreach (AuctionsBucketData resultBucket in buckets) foreach (AuctionsBucketData resultBucket in buckets)
{ {
BucketInfo bucketInfo = new BucketInfo(); BucketInfo bucketInfo = new();
resultBucket.BuildBucketInfo(bucketInfo, player); resultBucket.BuildBucketInfo(bucketInfo, player);
listBucketsResult.Buckets.Add(bucketInfo); listBucketsResult.Buckets.Add(bucketInfo);
} }
@@ -991,7 +991,7 @@ namespace Game
public void BuildListBiddedItems(AuctionListBiddedItemsResult listBidderItemsResult, Player player, uint offset, AuctionSortDef[] sorts, int sortCount) public void BuildListBiddedItems(AuctionListBiddedItemsResult listBidderItemsResult, Player player, uint offset, AuctionSortDef[] sorts, int sortCount)
{ {
// always full list // always full list
List<AuctionPosting> auctions = new List<AuctionPosting>(); List<AuctionPosting> auctions = new();
foreach (var auctionId in _playerBidderAuctions.LookupByKey(player.GetGUID())) foreach (var auctionId in _playerBidderAuctions.LookupByKey(player.GetGUID()))
{ {
AuctionPosting auction = _itemsByAuctionId.LookupByKey(auctionId); AuctionPosting auction = _itemsByAuctionId.LookupByKey(auctionId);
@@ -999,12 +999,12 @@ namespace Game
auctions.Add(auction); auctions.Add(auction);
} }
AuctionPosting.Sorter sorter = new AuctionPosting.Sorter(player.GetSession().GetSessionDbcLocale(), sorts, sortCount); AuctionPosting.Sorter sorter = new(player.GetSession().GetSessionDbcLocale(), sorts, sortCount);
auctions.Sort(sorter); auctions.Sort(sorter);
foreach (var resultAuction in auctions) foreach (var resultAuction in auctions)
{ {
AuctionItem auctionItem = new AuctionItem(); AuctionItem auctionItem = new();
resultAuction.BuildAuctionItem(auctionItem, true, true, true, false); resultAuction.BuildAuctionItem(auctionItem, true, true, true, false);
listBidderItemsResult.Items.Add(auctionItem); listBidderItemsResult.Items.Add(auctionItem);
} }
@@ -1030,7 +1030,7 @@ namespace Game
foreach (AuctionPosting resultAuction in builder.GetResultRange()) foreach (AuctionPosting resultAuction in builder.GetResultRange())
{ {
AuctionItem auctionItem = new AuctionItem(); AuctionItem auctionItem = new();
resultAuction.BuildAuctionItem(auctionItem, false, false, resultAuction.OwnerAccount != player.GetSession().GetAccountGUID(), resultAuction.Bidder.IsEmpty()); resultAuction.BuildAuctionItem(auctionItem, false, false, resultAuction.OwnerAccount != player.GetSession().GetAccountGUID(), resultAuction.Bidder.IsEmpty());
listItemsResult.Items.Add(auctionItem); listItemsResult.Items.Add(auctionItem);
} }
@@ -1058,7 +1058,7 @@ namespace Game
foreach (AuctionPosting resultAuction in builder.GetResultRange()) foreach (AuctionPosting resultAuction in builder.GetResultRange())
{ {
AuctionItem auctionItem = new AuctionItem(); AuctionItem auctionItem = new();
resultAuction.BuildAuctionItem(auctionItem, false, true, resultAuction.OwnerAccount != player.GetSession().GetAccountGUID(), resultAuction.BuildAuctionItem(auctionItem, false, true, resultAuction.OwnerAccount != player.GetSession().GetAccountGUID(),
resultAuction.Bidder.IsEmpty()); resultAuction.Bidder.IsEmpty());
@@ -1071,7 +1071,7 @@ namespace Game
public void BuildListOwnedItems(AuctionListOwnedItemsResult listOwnerItemsResult, Player player, uint offset, AuctionSortDef[] sorts, int sortCount) public void BuildListOwnedItems(AuctionListOwnedItemsResult listOwnerItemsResult, Player player, uint offset, AuctionSortDef[] sorts, int sortCount)
{ {
// always full list // always full list
List<AuctionPosting> auctions = new List<AuctionPosting>(); List<AuctionPosting> auctions = new();
foreach (var auctionId in _playerOwnedAuctions.LookupByKey(player.GetGUID())) foreach (var auctionId in _playerOwnedAuctions.LookupByKey(player.GetGUID()))
{ {
AuctionPosting auction = _itemsByAuctionId.LookupByKey(auctionId); AuctionPosting auction = _itemsByAuctionId.LookupByKey(auctionId);
@@ -1079,12 +1079,12 @@ namespace Game
auctions.Add(auction); auctions.Add(auction);
} }
AuctionPosting.Sorter sorter = new AuctionPosting.Sorter(player.GetSession().GetSessionDbcLocale(), sorts, sortCount); AuctionPosting.Sorter sorter = new(player.GetSession().GetSessionDbcLocale(), sorts, sortCount);
auctions.Sort(sorter); auctions.Sort(sorter);
foreach (var resultAuction in auctions) foreach (var resultAuction in auctions)
{ {
AuctionItem auctionItem = new AuctionItem(); AuctionItem auctionItem = new();
resultAuction.BuildAuctionItem(auctionItem, true, true, false, false); resultAuction.BuildAuctionItem(auctionItem, true, true, false, false);
listOwnerItemsResult.Items.Add(auctionItem); listOwnerItemsResult.Items.Add(auctionItem);
} }
@@ -1118,7 +1118,7 @@ namespace Game
var keyIndex = _itemsByAuctionId.IndexOfKey(cursor); var keyIndex = _itemsByAuctionId.IndexOfKey(cursor);
foreach (var pair in _itemsByAuctionId.Skip(keyIndex)) foreach (var pair in _itemsByAuctionId.Skip(keyIndex))
{ {
AuctionItem auctionItem = new AuctionItem(); AuctionItem auctionItem = new();
pair.Value.BuildAuctionItem(auctionItem, false, true, true, pair.Value.Bidder.IsEmpty()); pair.Value.BuildAuctionItem(auctionItem, false, true, true, pair.Value.Bidder.IsEmpty());
replicateResponse.Items.Add(auctionItem); replicateResponse.Items.Add(auctionItem);
if (--count == 0) if (--count == 0)
@@ -1197,7 +1197,7 @@ namespace Game
ulong totalPrice = 0; ulong totalPrice = 0;
uint remainingQuantity = quantity; uint remainingQuantity = quantity;
List<AuctionPosting> auctions = new List<AuctionPosting>(); List<AuctionPosting> auctions = new();
for (var i = 0; i < bucketItr.Auctions.Count;) for (var i = 0; i < bucketItr.Auctions.Count;)
{ {
AuctionPosting auction = bucketItr.Auctions[i++]; AuctionPosting auction = bucketItr.Auctions[i++];
@@ -1238,14 +1238,14 @@ namespace Game
return false; return false;
} }
Optional<ObjectGuid> uniqueSeller = new Optional<ObjectGuid>(); Optional<ObjectGuid> uniqueSeller = new();
// prepare items // prepare items
List<MailedItemsBatch> items = new List<MailedItemsBatch>(); List<MailedItemsBatch> items = new();
items.Add(new MailedItemsBatch()); items.Add(new MailedItemsBatch());
remainingQuantity = quantity; remainingQuantity = quantity;
List<int> removedItemsFromAuction = new List<int>(); List<int> removedItemsFromAuction = new();
for (var i = 0; i < bucketItr.Auctions.Count;) for (var i = 0; i < bucketItr.Auctions.Count;)
{ {
@@ -1323,7 +1323,7 @@ namespace Game
foreach (MailedItemsBatch batch in items) foreach (MailedItemsBatch batch in items)
{ {
MailDraft mail = new MailDraft(Global.AuctionHouseMgr.BuildCommodityAuctionMailSubject(AuctionMailType.Won, itemId, batch.Quantity), MailDraft mail = new(Global.AuctionHouseMgr.BuildCommodityAuctionMailSubject(AuctionMailType.Won, itemId, batch.Quantity),
Global.AuctionHouseMgr.BuildAuctionWonMailBody(uniqueSeller.Value, batch.TotalPrice, batch.Quantity)); Global.AuctionHouseMgr.BuildAuctionWonMailBody(uniqueSeller.Value, batch.TotalPrice, batch.Quantity));
for (int i = 0; i < batch.ItemsCount; ++i) for (int i = 0; i < batch.ItemsCount; ++i)
@@ -1340,7 +1340,7 @@ namespace Game
mail.SendMailTo(trans, player, new MailSender(this), MailCheckMask.Copied); mail.SendMailTo(trans, player, new MailSender(this), MailCheckMask.Copied);
} }
AuctionWonNotification packet = new AuctionWonNotification(); AuctionWonNotification packet = new();
packet.Info.Initialize(auctions[0], items[0].Items[0]); packet.Info.Initialize(auctions[0], items[0].Items[0]);
player.SendPacket(packet); player.SendPacket(packet);
@@ -1373,7 +1373,7 @@ namespace Game
{ {
if (oldBidder) if (oldBidder)
{ {
AuctionOutbidNotification packet = new AuctionOutbidNotification(); AuctionOutbidNotification packet = new();
packet.BidAmount = newBidAmount; packet.BidAmount = newBidAmount;
packet.MinIncrement = AuctionPosting.CalculateMinIncrement(newBidAmount); packet.MinIncrement = AuctionPosting.CalculateMinIncrement(newBidAmount);
packet.Info.AuctionID = auction.Id; packet.Info.AuctionID = auction.Id;
@@ -1427,7 +1427,7 @@ namespace Game
// receiver exist // receiver exist
if ((bidder != null || bidderAccId != 0))// && !sAuctionBotConfig.IsBotChar(auction.Bidder)) if ((bidder != null || bidderAccId != 0))// && !sAuctionBotConfig.IsBotChar(auction.Bidder))
{ {
MailDraft mail = new MailDraft(Global.AuctionHouseMgr.BuildItemAuctionMailSubject(AuctionMailType.Won, auction), MailDraft mail = new(Global.AuctionHouseMgr.BuildItemAuctionMailSubject(AuctionMailType.Won, auction),
Global.AuctionHouseMgr.BuildAuctionWonMailBody(auction.Owner, auction.BidAmount, auction.BuyoutOrUnitPrice)); Global.AuctionHouseMgr.BuildAuctionWonMailBody(auction.Owner, auction.BidAmount, auction.BuyoutOrUnitPrice));
// set owner to bidder (to prevent delete item with sender char deleting) // set owner to bidder (to prevent delete item with sender char deleting)
@@ -1444,7 +1444,7 @@ namespace Game
if (bidder) if (bidder)
{ {
AuctionWonNotification packet = new AuctionWonNotification(); AuctionWonNotification packet = new();
packet.Info.Initialize(auction, auction.Items[0]); packet.Info.Initialize(auction, auction.Items[0]);
bidder.SendPacket(packet); bidder.SendPacket(packet);
@@ -1502,7 +1502,7 @@ namespace Game
int itemIndex = 0; int itemIndex = 0;
while (itemIndex < auction.Items.Count) while (itemIndex < auction.Items.Count)
{ {
MailDraft mail = new MailDraft(Global.AuctionHouseMgr.BuildItemAuctionMailSubject(AuctionMailType.Expired, auction), ""); MailDraft mail = new(Global.AuctionHouseMgr.BuildItemAuctionMailSubject(AuctionMailType.Expired, auction), "");
for (int i = 0; i < SharedConst.MaxMailItems && itemIndex < auction.Items.Count; ++i, ++itemIndex) for (int i = 0; i < SharedConst.MaxMailItems && itemIndex < auction.Items.Count; ++i, ++itemIndex)
mail.AddItem(auction.Items[itemIndex]); mail.AddItem(auction.Items[itemIndex]);
@@ -1523,7 +1523,7 @@ namespace Game
int itemIndex = 0; int itemIndex = 0;
while (itemIndex < auction.Items.Count) while (itemIndex < auction.Items.Count)
{ {
MailDraft draft = new MailDraft(Global.AuctionHouseMgr.BuildItemAuctionMailSubject(AuctionMailType.Cancelled, auction), ""); MailDraft draft = new(Global.AuctionHouseMgr.BuildItemAuctionMailSubject(AuctionMailType.Cancelled, auction), "");
for (int i = 0; i < SharedConst.MaxMailItems && itemIndex < auction.Items.Count; ++i, ++itemIndex) for (int i = 0; i < SharedConst.MaxMailItems && itemIndex < auction.Items.Count; ++i, ++itemIndex)
draft.AddItem(auction.Items[itemIndex]); draft.AddItem(auction.Items[itemIndex]);
@@ -1552,7 +1552,7 @@ namespace Game
// owner exist (online or offline) // owner exist (online or offline)
if ((owner || Global.CharacterCacheStorage.HasCharacterCacheEntry(auction.Owner)))// && !sAuctionBotConfig.IsBotChar(auction.Owner)) if ((owner || Global.CharacterCacheStorage.HasCharacterCacheEntry(auction.Owner)))// && !sAuctionBotConfig.IsBotChar(auction.Owner))
{ {
ByteBuffer tempBuffer = new ByteBuffer(); ByteBuffer tempBuffer = new();
tempBuffer.WritePackedTime(GameTime.GetGameTime() + WorldConfig.GetIntValue(WorldCfg.MailDeliveryDelay)); tempBuffer.WritePackedTime(GameTime.GetGameTime() + WorldConfig.GetIntValue(WorldCfg.MailDeliveryDelay));
uint eta = tempBuffer.ReadUInt32(); uint eta = tempBuffer.ReadUInt32();
@@ -1593,16 +1593,16 @@ namespace Game
AuctionHouseRecord _auctionHouse; AuctionHouseRecord _auctionHouse;
SortedList<uint, AuctionPosting> _itemsByAuctionId = new SortedList<uint, AuctionPosting>(); // ordered for replicate SortedList<uint, AuctionPosting> _itemsByAuctionId = new(); // ordered for replicate
SortedDictionary<AuctionsBucketKey, AuctionsBucketData> _buckets = new SortedDictionary<AuctionsBucketKey, AuctionsBucketData>();// ordered for search by itemid only SortedDictionary<AuctionsBucketKey, AuctionsBucketData> _buckets = new();// ordered for search by itemid only
Dictionary<ObjectGuid, CommodityQuote> _commodityQuotes = new Dictionary<ObjectGuid, CommodityQuote>(); Dictionary<ObjectGuid, CommodityQuote> _commodityQuotes = new();
MultiMap<ObjectGuid, uint> _playerOwnedAuctions = new MultiMap<ObjectGuid, uint>(); MultiMap<ObjectGuid, uint> _playerOwnedAuctions = new();
MultiMap<ObjectGuid, uint> _playerBidderAuctions = new MultiMap<ObjectGuid, uint>(); MultiMap<ObjectGuid, uint> _playerBidderAuctions = new();
// Map of throttled players for GetAll, and throttle expiry time // Map of throttled players for GetAll, and throttle expiry time
// Stored here, rather than player object to maintain persistence after logout // Stored here, rather than player object to maintain persistence after logout
Dictionary<ObjectGuid, PlayerReplicateThrottleData> _replicateThrottleMap = new Dictionary<ObjectGuid, PlayerReplicateThrottleData>(); Dictionary<ObjectGuid, PlayerReplicateThrottleData> _replicateThrottleMap = new();
} }
public class AuctionPosting public class AuctionPosting
@@ -1610,7 +1610,7 @@ namespace Game
public uint Id; public uint Id;
public AuctionsBucketData Bucket; public AuctionsBucketData Bucket;
public List<Item> Items = new List<Item>(); public List<Item> Items = new();
public ObjectGuid Owner; public ObjectGuid Owner;
public ObjectGuid OwnerAccount; public ObjectGuid OwnerAccount;
public ObjectGuid Bidder; public ObjectGuid Bidder;
@@ -1621,7 +1621,7 @@ namespace Game
public DateTime StartTime = DateTime.MinValue; public DateTime StartTime = DateTime.MinValue;
public DateTime EndTime = DateTime.MinValue; public DateTime EndTime = DateTime.MinValue;
public List<ObjectGuid> BidderHistory = new List<ObjectGuid>(); public List<ObjectGuid> BidderHistory = new();
public bool IsCommodity() public bool IsCommodity()
{ {
@@ -1674,7 +1674,7 @@ namespace Game
SocketedGem gemData = Items[0].m_itemData.Gems[i]; SocketedGem gemData = Items[0].m_itemData.Gems[i];
if (gemData.ItemId != 0) if (gemData.ItemId != 0)
{ {
ItemGemData gem = new ItemGemData(); ItemGemData gem = new();
gem.Slot = i; gem.Slot = i;
gem.Item = new ItemInstance(gemData); gem.Item = new ItemInstance(gemData);
auctionItem.Gems.Add(gem); auctionItem.Gems.Add(gem);
@@ -1802,7 +1802,7 @@ namespace Game
public byte MaxBattlePetLevel = 0; public byte MaxBattlePetLevel = 0;
public string[] FullName = new string[(int)Locale.Total]; public string[] FullName = new string[(int)Locale.Total];
public List<AuctionPosting> Auctions = new List<AuctionPosting>(); public List<AuctionPosting> Auctions = new();
public void BuildBucketInfo(BucketInfo bucketInfo, Player player) public void BuildBucketInfo(BucketInfo bucketInfo, Player player)
{ {
@@ -2004,7 +2004,7 @@ namespace Game
uint _offset; uint _offset;
IComparer<T> _sorter; IComparer<T> _sorter;
AuctionHouseResultLimits _maxResults; AuctionHouseResultLimits _maxResults;
List<T> _items = new List<T>(); List<T> _items = new();
bool _hasMoreResults; bool _hasMoreResults;
public AuctionsResultBuilder(uint offset, IComparer<T> sorter, AuctionHouseResultLimits maxResults) public AuctionsResultBuilder(uint offset, IComparer<T> sorter, AuctionHouseResultLimits maxResults)
+8 -8
View File
@@ -471,7 +471,7 @@ namespace Game.BattleFields
public void SendUpdateWorldState(uint variable, uint value, bool hidden = false) public void SendUpdateWorldState(uint variable, uint value, bool hidden = false)
{ {
UpdateWorldState worldstate = new UpdateWorldState(); UpdateWorldState worldstate = new();
worldstate.VariableID = variable; worldstate.VariableID = variable;
worldstate.Value = (int)value; worldstate.Value = (int)value;
worldstate.Hidden = hidden; worldstate.Hidden = hidden;
@@ -654,7 +654,7 @@ namespace Game.BattleFields
public void SendAreaSpiritHealerQuery(Player player, ObjectGuid guid) public void SendAreaSpiritHealerQuery(Player player, ObjectGuid guid)
{ {
AreaSpiritHealerTime areaSpiritHealerTime = new AreaSpiritHealerTime(); AreaSpiritHealerTime areaSpiritHealerTime = new();
areaSpiritHealerTime.HealerGuid = guid; areaSpiritHealerTime.HealerGuid = guid;
areaSpiritHealerTime.TimeLeft = m_LastResurectTimer;// resurrect every 30 seconds areaSpiritHealerTime.TimeLeft = m_LastResurectTimer;// resurrect every 30 seconds
@@ -807,7 +807,7 @@ namespace Game.BattleFields
protected uint m_DefenderTeam; protected uint m_DefenderTeam;
// Map of the objectives belonging to this OutdoorPvP // Map of the objectives belonging to this OutdoorPvP
Dictionary<uint, BfCapturePoint> m_capturePoints = new Dictionary<uint, BfCapturePoint>(); Dictionary<uint, BfCapturePoint> m_capturePoints = new();
// Players info maps // Players info maps
protected List<ObjectGuid>[] m_players = new List<ObjectGuid>[2]; // Players in zone protected List<ObjectGuid>[] m_players = new List<ObjectGuid>[2]; // Players in zone
@@ -835,7 +835,7 @@ namespace Game.BattleFields
uint m_uiKickAfkPlayersTimer; // Timer for check Afk in war uint m_uiKickAfkPlayersTimer; // Timer for check Afk in war
// Graveyard variables // Graveyard variables
protected List<BfGraveyard> m_GraveyardList = new List<BfGraveyard>(); // Vector witch contain the different GY of the battle protected List<BfGraveyard> m_GraveyardList = new(); // Vector witch contain the different GY of the battle
uint m_LastResurectTimer; // Timer for resurect player every 30 sec uint m_LastResurectTimer; // Timer for resurect player every 30 sec
protected uint m_StartGroupingTimer; // Timer for invite players in area 15 minute before start battle protected uint m_StartGroupingTimer; // Timer for invite players in area 15 minute before start battle
@@ -843,8 +843,8 @@ namespace Game.BattleFields
List<ObjectGuid>[] m_Groups = new List<ObjectGuid>[2]; // Contain different raid group List<ObjectGuid>[] m_Groups = new List<ObjectGuid>[2]; // Contain different raid group
Dictionary<int, ulong> m_Data64 = new Dictionary<int, ulong>(); Dictionary<int, ulong> m_Data64 = new();
protected Dictionary<int, uint> m_Data32 = new Dictionary<int, uint>(); protected Dictionary<int, uint> m_Data32 = new();
} }
public class BfGraveyard public class BfGraveyard
@@ -992,7 +992,7 @@ namespace Game.BattleFields
uint m_ControlTeam; uint m_ControlTeam;
uint m_GraveyardId; uint m_GraveyardId;
ObjectGuid[] m_SpiritGuide = new ObjectGuid[SharedConst.BGTeamsCount]; ObjectGuid[] m_SpiritGuide = new ObjectGuid[SharedConst.BGTeamsCount];
List<ObjectGuid> m_ResurrectQueue = new List<ObjectGuid>(); List<ObjectGuid> m_ResurrectQueue = new();
protected BattleField m_Bf; protected BattleField m_Bf;
} }
@@ -1143,7 +1143,7 @@ namespace Game.BattleFields
} }
} }
List<Unit> players = new List<Unit>(); List<Unit> players = new();
var checker = new AnyPlayerInObjectRangeCheck(capturePoint, radius); var checker = new AnyPlayerInObjectRangeCheck(capturePoint, radius);
var searcher = new PlayerListSearcher(capturePoint, players, checker); var searcher = new PlayerListSearcher(capturePoint, players, checker);
Cell.VisitWorldObjects(capturePoint, searcher, radius); Cell.VisitWorldObjects(capturePoint, searcher, radius);
@@ -145,10 +145,10 @@ namespace Game.BattleFields
// contains all initiated battlefield events // contains all initiated battlefield events
// used when initing / cleaning up // used when initing / cleaning up
List<BattleField> _battlefieldSet = new List<BattleField>(); List<BattleField> _battlefieldSet = new();
// maps the zone ids to an battlefield event // maps the zone ids to an battlefield event
// used in player event handling // used in player event handling
Dictionary<uint, BattleField> _battlefieldMap = new Dictionary<uint, BattleField>(); Dictionary<uint, BattleField> _battlefieldMap = new();
// update interval // update interval
uint _updateTimer; uint _updateTimer;
} }
+10 -10
View File
@@ -85,7 +85,7 @@ namespace Game.BattleFields
foreach (var gy in WGConst.WGGraveYard) foreach (var gy in WGConst.WGGraveYard)
{ {
BfGraveyardWG graveyard = new BfGraveyardWG(this); BfGraveyardWG graveyard = new(this);
// When between games, the graveyard is controlled by the defending team // When between games, the graveyard is controlled by the defending team
if (gy.StartControl == TeamId.Neutral) if (gy.StartControl == TeamId.Neutral)
@@ -101,7 +101,7 @@ namespace Game.BattleFields
// Spawn workshop creatures and gameobjects // Spawn workshop creatures and gameobjects
for (byte i = 0; i < WGConst.MaxWorkshops; i++) for (byte i = 0; i < WGConst.MaxWorkshops; i++)
{ {
WGWorkshop workshop = new WGWorkshop(this, i); WGWorkshop workshop = new(this, i);
if (i < WGWorkshopIds.Ne) if (i < WGWorkshopIds.Ne)
workshop.GiveControlTo(GetAttackerTeam(), true); workshop.GiveControlTo(GetAttackerTeam(), true);
else else
@@ -129,7 +129,7 @@ namespace Game.BattleFields
GameObject go = SpawnGameObject(build.Entry, build.Pos, build.Rot); GameObject go = SpawnGameObject(build.Entry, build.Pos, build.Rot);
if (go) if (go)
{ {
BfWGGameObjectBuilding b = new BfWGGameObjectBuilding(this, build.BuildingType, build.WorldState); BfWGGameObjectBuilding b = new(this, build.BuildingType, build.WorldState);
b.Init(go); b.Init(go);
if (!IsEnabled() && go.GetEntry() == WGGameObjects.VaultGate) if (!IsEnabled() && go.GetEntry() == WGGameObjects.VaultGate)
go.SetDestructibleState(GameObjectDestructibleState.Destroyed); go.SetDestructibleState(GameObjectDestructibleState.Destroyed);
@@ -551,7 +551,7 @@ namespace Game.BattleFields
{ {
if (workshop.GetId() == workshopId) if (workshop.GetId() == workshopId)
{ {
WintergraspCapturePoint capturePoint = new WintergraspCapturePoint(this, GetAttackerTeam()); WintergraspCapturePoint capturePoint = new(this, GetAttackerTeam());
capturePoint.SetCapturePointData(go); capturePoint.SetCapturePointData(go);
capturePoint.LinkToWorkshop(workshop); capturePoint.LinkToWorkshop(workshop);
@@ -782,7 +782,7 @@ namespace Game.BattleFields
void SendInitWorldStatesTo(Player player) void SendInitWorldStatesTo(Player player)
{ {
InitWorldStates packet = new InitWorldStates(); InitWorldStates packet = new();
packet.AreaID = m_ZoneId; packet.AreaID = m_ZoneId;
packet.MapID = m_MapId; packet.MapID = m_MapId;
packet.SubareaID = 0; packet.SubareaID = 0;
@@ -1028,13 +1028,13 @@ namespace Game.BattleFields
bool m_isRelicInteractible; bool m_isRelicInteractible;
List<WGWorkshop> Workshops = new List<WGWorkshop>(); List<WGWorkshop> Workshops = new();
List<ObjectGuid>[] DefenderPortalList = new List<ObjectGuid>[SharedConst.BGTeamsCount]; List<ObjectGuid>[] DefenderPortalList = new List<ObjectGuid>[SharedConst.BGTeamsCount];
List<BfWGGameObjectBuilding> BuildingsInZone = new List<BfWGGameObjectBuilding>(); List<BfWGGameObjectBuilding> BuildingsInZone = new();
List<ObjectGuid>[] m_vehicles = new List<ObjectGuid>[SharedConst.BGTeamsCount]; List<ObjectGuid>[] m_vehicles = new List<ObjectGuid>[SharedConst.BGTeamsCount];
List<ObjectGuid> CanonList = new List<ObjectGuid>(); List<ObjectGuid> CanonList = new();
int m_tenacityTeam; int m_tenacityTeam;
uint m_tenacityStack; uint m_tenacityStack;
@@ -1476,8 +1476,8 @@ namespace Game.BattleFields
// Creature associations // Creature associations
List<ObjectGuid>[] m_CreatureBottomList = new List<ObjectGuid>[SharedConst.BGTeamsCount]; List<ObjectGuid>[] m_CreatureBottomList = new List<ObjectGuid>[SharedConst.BGTeamsCount];
List<ObjectGuid>[] m_CreatureTopList = new List<ObjectGuid>[SharedConst.BGTeamsCount]; List<ObjectGuid>[] m_CreatureTopList = new List<ObjectGuid>[SharedConst.BGTeamsCount];
List<ObjectGuid> m_TowerCannonBottomList = new List<ObjectGuid>(); List<ObjectGuid> m_TowerCannonBottomList = new();
List<ObjectGuid> m_TurretTopList = new List<ObjectGuid>(); List<ObjectGuid> m_TurretTopList = new();
} }
class WGWorkshop class WGWorkshop
@@ -45,10 +45,10 @@ namespace Game.BattleFields
public static uint[] ClockWorldState = { 3781, 4354 }; public static uint[] ClockWorldState = { 3781, 4354 };
public static uint[] WintergraspFaction = { 1732, 1735, 35 }; public static uint[] WintergraspFaction = { 1732, 1735, 35 };
public static Position WintergraspStalkerPos = new Position(4948.985f, 2937.789f, 550.5172f, 1.815142f); public static Position WintergraspStalkerPos = new(4948.985f, 2937.789f, 550.5172f, 1.815142f);
public static Position RelicPos = new Position(5440.379f, 2840.493f, 430.2816f, -1.832595f); public static Position RelicPos = new(5440.379f, 2840.493f, 430.2816f, -1.832595f);
public static Quaternion RelicRot = new Quaternion(0.0f, 0.0f, -0.7933531f, 0.6087617f); public static Quaternion RelicRot = new(0.0f, 0.0f, -0.7933531f, 0.6087617f);
//Destructible (Wall, Tower..) //Destructible (Wall, Tower..)
public static WintergraspBuildingSpawnData[] WGGameObjectBuilding = public static WintergraspBuildingSpawnData[] WGGameObjectBuilding =
+25 -25
View File
@@ -187,7 +187,7 @@ namespace Game.BattleGrounds
{ {
m_LastPlayerPositionBroadcast = 0; m_LastPlayerPositionBroadcast = 0;
BattlegroundPlayerPositions playerPositions = new BattlegroundPlayerPositions(); BattlegroundPlayerPositions playerPositions = new();
for (var i =0; i < _playerPositions.Count; ++i) for (var i =0; i < _playerPositions.Count; ++i)
{ {
var playerPosition = _playerPositions[i]; var playerPosition = _playerPositions[i];
@@ -349,7 +349,7 @@ namespace Game.BattleGrounds
{ {
uint countdownMaxForBGType = IsArena() ? BattlegroundConst.ArenaCountdownMax : BattlegroundConst.BattlegroundCountdownMax; uint countdownMaxForBGType = IsArena() ? BattlegroundConst.ArenaCountdownMax : BattlegroundConst.BattlegroundCountdownMax;
StartTimer timer = new StartTimer(); StartTimer timer = new();
timer.Type = TimerType.Pvp; timer.Type = TimerType.Pvp;
timer.TimeRemaining = countdownMaxForBGType - (GetElapsedTime() / 1000); timer.TimeRemaining = countdownMaxForBGType - (GetElapsedTime() / 1000);
timer.TotalTime = countdownMaxForBGType; timer.TotalTime = countdownMaxForBGType;
@@ -568,8 +568,8 @@ namespace Game.BattleGrounds
return; return;
} }
BroadcastTextBuilder builder = new BroadcastTextBuilder(null, msgType, id, Gender.Male, target); BroadcastTextBuilder builder = new(null, msgType, id, Gender.Male, target);
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
BroadcastWorker(localizer); BroadcastWorker(localizer);
} }
@@ -634,7 +634,7 @@ namespace Game.BattleGrounds
public void UpdateWorldState(uint variable, uint value, bool hidden = false) public void UpdateWorldState(uint variable, uint value, bool hidden = false)
{ {
UpdateWorldState worldstate = new UpdateWorldState(); UpdateWorldState worldstate = new();
worldstate.VariableID = variable; worldstate.VariableID = variable;
worldstate.Value = (int)value; worldstate.Value = (int)value;
worldstate.Hidden = hidden; worldstate.Hidden = hidden;
@@ -643,7 +643,7 @@ namespace Game.BattleGrounds
public void UpdateWorldState(uint variable, bool value, bool hidden = false) public void UpdateWorldState(uint variable, bool value, bool hidden = false)
{ {
UpdateWorldState worldstate = new UpdateWorldState(); UpdateWorldState worldstate = new();
worldstate.VariableID = variable; worldstate.VariableID = variable;
worldstate.Value = value ? 1 : 0; worldstate.Value = value ? 1 : 0;
worldstate.Hidden = hidden; worldstate.Hidden = hidden;
@@ -699,7 +699,7 @@ namespace Game.BattleGrounds
//we must set it this way, because end time is sent in packet! //we must set it this way, because end time is sent in packet!
SetRemainingTime(BattlegroundConst.AutocloseBattleground); SetRemainingTime(BattlegroundConst.AutocloseBattleground);
PVPMatchComplete pvpMatchComplete = new PVPMatchComplete(); PVPMatchComplete pvpMatchComplete = new();
pvpMatchComplete.Winner = (byte)GetWinner(); pvpMatchComplete.Winner = (byte)GetWinner();
pvpMatchComplete.Duration = (int)Math.Max(0, (GetElapsedTime() - (int)BattlegroundStartTimeIntervals.Delay2m) / Time.InMilliseconds); pvpMatchComplete.Duration = (int)Math.Max(0, (GetElapsedTime() - (int)BattlegroundStartTimeIntervals.Delay2m) / Time.InMilliseconds);
pvpMatchComplete.LogData.HasValue = true; pvpMatchComplete.LogData.HasValue = true;
@@ -905,7 +905,7 @@ namespace Game.BattleGrounds
Global.BattlegroundMgr.ScheduleQueueUpdate(0, bgQueueTypeId, GetBracketId()); Global.BattlegroundMgr.ScheduleQueueUpdate(0, bgQueueTypeId, GetBracketId());
} }
// Let others know // Let others know
BattlegroundPlayerLeft playerLeft = new BattlegroundPlayerLeft(); BattlegroundPlayerLeft playerLeft = new();
playerLeft.Guid = guid; playerLeft.Guid = guid;
SendPacketToTeam(team, playerLeft, player); SendPacketToTeam(team, playerLeft, player);
} }
@@ -989,7 +989,7 @@ namespace Game.BattleGrounds
ObjectGuid guid = player.GetGUID(); ObjectGuid guid = player.GetGUID();
Team team = player.GetBGTeam(); Team team = player.GetBGTeam();
BattlegroundPlayer bp = new BattlegroundPlayer(); BattlegroundPlayer bp = new();
bp.OfflineRemoveTime = 0; bp.OfflineRemoveTime = 0;
bp.Team = team; bp.Team = team;
bp.ActiveSpec = (int)player.GetPrimarySpecialization(); bp.ActiveSpec = (int)player.GetPrimarySpecialization();
@@ -999,11 +999,11 @@ namespace Game.BattleGrounds
UpdatePlayersCountByTeam(team, false); // +1 player UpdatePlayersCountByTeam(team, false); // +1 player
BattlegroundPlayerJoined playerJoined = new BattlegroundPlayerJoined(); BattlegroundPlayerJoined playerJoined = new();
playerJoined.Guid = player.GetGUID(); playerJoined.Guid = player.GetGUID();
SendPacketToTeam(team, playerJoined, player); SendPacketToTeam(team, playerJoined, player);
PVPMatchInitialize pvpMatchInitialize = new PVPMatchInitialize(); PVPMatchInitialize pvpMatchInitialize = new();
pvpMatchInitialize.MapID = GetMapId(); pvpMatchInitialize.MapID = GetMapId();
switch (GetStatus()) switch (GetStatus())
{ {
@@ -1057,7 +1057,7 @@ namespace Game.BattleGrounds
player.CastSpell(player, BattlegroundConst.SpellPreparation, true); // reduces all mana cost of spells. player.CastSpell(player, BattlegroundConst.SpellPreparation, true); // reduces all mana cost of spells.
uint countdownMaxForBGType = IsArena() ? BattlegroundConst.ArenaCountdownMax : BattlegroundConst.BattlegroundCountdownMax; uint countdownMaxForBGType = IsArena() ? BattlegroundConst.ArenaCountdownMax : BattlegroundConst.BattlegroundCountdownMax;
StartTimer timer = new StartTimer(); StartTimer timer = new();
timer.Type = TimerType.Pvp; timer.Type = TimerType.Pvp;
timer.TimeRemaining = countdownMaxForBGType - (GetElapsedTime() / 1000); timer.TimeRemaining = countdownMaxForBGType - (GetElapsedTime() / 1000);
timer.TotalTime = countdownMaxForBGType; timer.TotalTime = countdownMaxForBGType;
@@ -1346,7 +1346,7 @@ namespace Game.BattleGrounds
if (!map) if (!map)
return false; return false;
Quaternion rotation = new Quaternion(rotation0, rotation1, rotation2, rotation3); Quaternion rotation = new(rotation0, rotation1, rotation2, rotation3);
// Temporally add safety check for bad spawns and send log (object rotations need to be rechecked in sniff) // Temporally add safety check for bad spawns and send log (object rotations need to be rechecked in sniff)
if (rotation0 == 0 && rotation1 == 0 && rotation2 == 0 && rotation3 == 0) if (rotation0 == 0 && rotation1 == 0 && rotation2 == 0 && rotation3 == 0)
{ {
@@ -1485,7 +1485,7 @@ namespace Game.BattleGrounds
return null; return null;
} }
Position pos = new Position(x, y, z, o); Position pos = new(x, y, z, o);
Creature creature = Creature.CreateCreature(entry, map, pos); Creature creature = Creature.CreateCreature(entry, map, pos);
if (!creature) if (!creature)
@@ -1581,8 +1581,8 @@ namespace Game.BattleGrounds
if (entry == 0) if (entry == 0)
return; return;
CypherStringChatBuilder builder = new CypherStringChatBuilder(null, msgType, entry, source); CypherStringChatBuilder builder = new(null, msgType, entry, source);
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
BroadcastWorker(localizer); BroadcastWorker(localizer);
} }
@@ -1591,8 +1591,8 @@ namespace Game.BattleGrounds
if (entry == 0) if (entry == 0)
return; return;
CypherStringChatBuilder builder = new CypherStringChatBuilder(null, msgType, entry, source, args); CypherStringChatBuilder builder = new(null, msgType, entry, source, args);
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
BroadcastWorker(localizer); BroadcastWorker(localizer);
} }
@@ -1724,7 +1724,7 @@ namespace Game.BattleGrounds
BlockMovement(player); BlockMovement(player);
PVPMatchStatisticsMessage pvpMatchStatistics = new PVPMatchStatisticsMessage(); PVPMatchStatisticsMessage pvpMatchStatistics = new();
BuildPvPLogDataPacket(out pvpMatchStatistics.Data); BuildPvPLogDataPacket(out pvpMatchStatistics.Data);
player.SendPacket(pvpMatchStatistics); player.SendPacket(pvpMatchStatistics);
} }
@@ -2025,11 +2025,11 @@ namespace Game.BattleGrounds
} }
#region Fields #region Fields
protected Dictionary<ObjectGuid, BattlegroundScore> PlayerScores = new Dictionary<ObjectGuid, BattlegroundScore>(); // Player scores protected Dictionary<ObjectGuid, BattlegroundScore> PlayerScores = new(); // Player scores
// Player lists, those need to be accessible by inherited classes // Player lists, those need to be accessible by inherited classes
Dictionary<ObjectGuid, BattlegroundPlayer> m_Players = new Dictionary<ObjectGuid, BattlegroundPlayer>(); Dictionary<ObjectGuid, BattlegroundPlayer> m_Players = new();
// Spirit Guide guid + Player list GUIDS // Spirit Guide guid + Player list GUIDS
MultiMap<ObjectGuid, ObjectGuid> m_ReviveQueue = new MultiMap<ObjectGuid, ObjectGuid>(); MultiMap<ObjectGuid, ObjectGuid> m_ReviveQueue = new();
// these are important variables used for starting messages // these are important variables used for starting messages
BattlegroundEventFlags m_Events; BattlegroundEventFlags m_Events;
@@ -2071,8 +2071,8 @@ namespace Game.BattleGrounds
uint m_LastPlayerPositionBroadcast; uint m_LastPlayerPositionBroadcast;
// Player lists // Player lists
List<ObjectGuid> m_ResurrectQueue = new List<ObjectGuid>(); // Player GUID List<ObjectGuid> m_ResurrectQueue = new(); // Player GUID
List<ObjectGuid> m_OfflineQueue = new List<ObjectGuid>(); // Player GUID List<ObjectGuid> m_OfflineQueue = new(); // Player GUID
// Invited counters are useful for player invitation to BG - do not allow, if BG is started to one faction to have 2 more players than another faction // Invited counters are useful for player invitation to BG - do not allow, if BG is started to one faction to have 2 more players than another faction
// Invited counters will be changed only when removing already invited player from queue, removing player from Battleground and inviting player to BG // Invited counters will be changed only when removing already invited player from queue, removing player from Battleground and inviting player to BG
@@ -2099,7 +2099,7 @@ namespace Game.BattleGrounds
BattlegroundTemplate _battlegroundTemplate; BattlegroundTemplate _battlegroundTemplate;
PvpDifficultyRecord _pvpDifficultyEntry; PvpDifficultyRecord _pvpDifficultyEntry;
List<BattlegroundPlayerPosition> _playerPositions = new List<BattlegroundPlayerPosition>(); List<BattlegroundPlayerPosition> _playerPositions = new();
#endregion #endregion
} }
@@ -85,7 +85,7 @@ namespace Game.BattleGrounds
// update scheduled queues // update scheduled queues
if (!m_QueueUpdateScheduler.Empty()) if (!m_QueueUpdateScheduler.Empty())
{ {
List<ScheduledQueueUpdate> scheduled = new List<ScheduledQueueUpdate>(); List<ScheduledQueueUpdate> scheduled = new();
Extensions.Swap(ref scheduled, ref m_QueueUpdateScheduler); Extensions.Swap(ref scheduled, ref m_QueueUpdateScheduler);
for (byte i = 0; i < scheduled.Count; i++) for (byte i = 0; i < scheduled.Count; i++)
@@ -379,7 +379,7 @@ namespace Game.BattleGrounds
continue; continue;
} }
BattlegroundTemplate bgTemplate = new BattlegroundTemplate(); BattlegroundTemplate bgTemplate = new();
bgTemplate.Id = bgTypeId; bgTemplate.Id = bgTypeId;
float dist = result.Read<float>(3); float dist = result.Read<float>(3);
bgTemplate.MaxStartDistSq = dist * dist; bgTemplate.MaxStartDistSq = dist * dist;
@@ -439,7 +439,7 @@ namespace Game.BattleGrounds
if (bgTemplate == null) if (bgTemplate == null)
return; return;
BattlefieldList battlefieldList = new BattlefieldList(); BattlefieldList battlefieldList = new();
battlefieldList.BattlemasterGuid = guid; battlefieldList.BattlemasterGuid = guid;
battlefieldList.BattlemasterListID = (int)bgTypeId; battlefieldList.BattlemasterListID = (int)bgTypeId;
battlefieldList.MinLevel = bgTemplate.GetMinLevel(); battlefieldList.MinLevel = bgTemplate.GetMinLevel();
@@ -471,7 +471,7 @@ namespace Game.BattleGrounds
if (time == 0xFFFFFFFF) if (time == 0xFFFFFFFF)
time = 0; time = 0;
AreaSpiritHealerTime areaSpiritHealerTime = new AreaSpiritHealerTime(); AreaSpiritHealerTime areaSpiritHealerTime = new();
areaSpiritHealerTime.HealerGuid = guid; areaSpiritHealerTime.HealerGuid = guid;
areaSpiritHealerTime.TimeLeft = time; areaSpiritHealerTime.TimeLeft = time;
@@ -556,7 +556,7 @@ namespace Game.BattleGrounds
public void ScheduleQueueUpdate(uint arenaMatchmakerRating, BattlegroundQueueTypeId bgQueueTypeId, BattlegroundBracketId bracket_id) public void ScheduleQueueUpdate(uint arenaMatchmakerRating, BattlegroundQueueTypeId bgQueueTypeId, BattlegroundBracketId bracket_id)
{ {
//we will use only 1 number created of bgTypeId and bracket_id //we will use only 1 number created of bgTypeId and bracket_id
ScheduledQueueUpdate scheduleId = new ScheduledQueueUpdate(arenaMatchmakerRating, bgQueueTypeId, bracket_id); ScheduledQueueUpdate scheduleId = new(arenaMatchmakerRating, bgQueueTypeId, bracket_id);
if (!m_QueueUpdateScheduler.Contains(scheduleId)) if (!m_QueueUpdateScheduler.Contains(scheduleId))
m_QueueUpdateScheduler.Add(scheduleId); m_QueueUpdateScheduler.Add(scheduleId);
} }
@@ -700,7 +700,7 @@ namespace Game.BattleGrounds
BattlegroundTemplate bgTemplate = GetBattlegroundTemplateByTypeId(bgTypeId); BattlegroundTemplate bgTemplate = GetBattlegroundTemplateByTypeId(bgTypeId);
if (bgTemplate != null) if (bgTemplate != null)
{ {
Dictionary<BattlegroundTypeId, float> selectionWeights = new Dictionary<BattlegroundTypeId, float>(); Dictionary<BattlegroundTypeId, float> selectionWeights = new();
foreach (var mapId in bgTemplate.BattlemasterEntry.MapId) foreach (var mapId in bgTemplate.BattlemasterEntry.MapId)
{ {
@@ -780,12 +780,12 @@ namespace Game.BattleGrounds
return _battlegroundMapTemplates.LookupByKey(mapId); return _battlegroundMapTemplates.LookupByKey(mapId);
} }
Dictionary<BattlegroundTypeId, BattlegroundData> bgDataStore = new Dictionary<BattlegroundTypeId, BattlegroundData>(); Dictionary<BattlegroundTypeId, BattlegroundData> bgDataStore = new();
Dictionary<BattlegroundQueueTypeId, BattlegroundQueue> m_BattlegroundQueues = new Dictionary<BattlegroundQueueTypeId, BattlegroundQueue>(); Dictionary<BattlegroundQueueTypeId, BattlegroundQueue> m_BattlegroundQueues = new();
MultiMap<BattlegroundQueueTypeId, Battleground> m_BGFreeSlotQueue = new MultiMap<BattlegroundQueueTypeId, Battleground>(); MultiMap<BattlegroundQueueTypeId, Battleground> m_BGFreeSlotQueue = new();
Dictionary<uint, BattlegroundTypeId> mBattleMastersMap = new Dictionary<uint, BattlegroundTypeId>(); Dictionary<uint, BattlegroundTypeId> mBattleMastersMap = new();
Dictionary<BattlegroundTypeId, BattlegroundTemplate> _battlegroundTemplates = new Dictionary<BattlegroundTypeId, BattlegroundTemplate>(); Dictionary<BattlegroundTypeId, BattlegroundTemplate> _battlegroundTemplates = new();
Dictionary<uint, BattlegroundTemplate> _battlegroundMapTemplates = new Dictionary<uint, BattlegroundTemplate>(); Dictionary<uint, BattlegroundTemplate> _battlegroundMapTemplates = new();
struct ScheduledQueueUpdate struct ScheduledQueueUpdate
{ {
@@ -820,7 +820,7 @@ namespace Game.BattleGrounds
return ArenaMatchmakerRating.GetHashCode() ^ QueueId.GetHashCode() ^ BracketId.GetHashCode(); return ArenaMatchmakerRating.GetHashCode() ^ QueueId.GetHashCode() ^ BracketId.GetHashCode();
} }
} }
List<ScheduledQueueUpdate> m_QueueUpdateScheduler = new List<ScheduledQueueUpdate>(); List<ScheduledQueueUpdate> m_QueueUpdateScheduler = new();
uint m_NextRatedArenaUpdate; uint m_NextRatedArenaUpdate;
uint m_UpdateTimer; uint m_UpdateTimer;
bool m_ArenaTesting; bool m_ArenaTesting;
@@ -835,7 +835,7 @@ namespace Game.BattleGrounds
m_ClientBattlegroundIds[i] = new List<uint>(); m_ClientBattlegroundIds[i] = new List<uint>();
} }
public Dictionary<uint, Battleground> m_Battlegrounds = new Dictionary<uint, Battleground>(); public Dictionary<uint, Battleground> m_Battlegrounds = new();
public List<uint>[] m_ClientBattlegroundIds = new List<uint>[(int)BattlegroundBracketId.Max]; public List<uint>[] m_ClientBattlegroundIds = new List<uint>[(int)BattlegroundBracketId.Max];
public Battleground Template; public Battleground Template;
} }
@@ -62,7 +62,7 @@ namespace Game.BattleGrounds
BattlegroundBracketId bracketId = bracketEntry.GetBracketId(); BattlegroundBracketId bracketId = bracketEntry.GetBracketId();
// create new ginfo // create new ginfo
GroupQueueInfo ginfo = new GroupQueueInfo(); GroupQueueInfo ginfo = new();
ginfo.BgTypeId = BgTypeId; ginfo.BgTypeId = BgTypeId;
ginfo.ArenaType = ArenaType; ginfo.ArenaType = ArenaType;
ginfo.ArenaTeamId = arenateamid; ginfo.ArenaTeamId = arenateamid;
@@ -105,7 +105,7 @@ namespace Game.BattleGrounds
if (!member) if (!member)
continue; // this should never happen continue; // this should never happen
PlayerQueueInfo pl_info = new PlayerQueueInfo(); PlayerQueueInfo pl_info = new();
pl_info.LastOnlineTime = lastOnlineTime; pl_info.LastOnlineTime = lastOnlineTime;
pl_info.GroupInfo = ginfo; pl_info.GroupInfo = ginfo;
@@ -116,7 +116,7 @@ namespace Game.BattleGrounds
} }
else else
{ {
PlayerQueueInfo pl_info = new PlayerQueueInfo(); PlayerQueueInfo pl_info = new();
pl_info.LastOnlineTime = lastOnlineTime; pl_info.LastOnlineTime = lastOnlineTime;
pl_info.GroupInfo = ginfo; pl_info.GroupInfo = ginfo;
@@ -409,10 +409,10 @@ namespace Game.BattleGrounds
player.SetInviteForBattlegroundQueueType(bgQueueTypeId, ginfo.IsInvitedToBGInstanceGUID); player.SetInviteForBattlegroundQueueType(bgQueueTypeId, ginfo.IsInvitedToBGInstanceGUID);
// create remind invite events // create remind invite events
BGQueueInviteEvent inviteEvent = new BGQueueInviteEvent(player.GetGUID(), ginfo.IsInvitedToBGInstanceGUID, bgTypeId, ginfo.ArenaType, ginfo.RemoveInviteTime); BGQueueInviteEvent inviteEvent = new(player.GetGUID(), ginfo.IsInvitedToBGInstanceGUID, bgTypeId, ginfo.ArenaType, ginfo.RemoveInviteTime);
m_events.AddEvent(inviteEvent, m_events.CalculateTime(BattlegroundConst.InvitationRemindTime)); m_events.AddEvent(inviteEvent, m_events.CalculateTime(BattlegroundConst.InvitationRemindTime));
// create automatic remove events // create automatic remove events
BGQueueRemoveEvent removeEvent = new BGQueueRemoveEvent(player.GetGUID(), ginfo.IsInvitedToBGInstanceGUID, bgQueueTypeId, ginfo.RemoveInviteTime); BGQueueRemoveEvent removeEvent = new(player.GetGUID(), ginfo.IsInvitedToBGInstanceGUID, bgQueueTypeId, ginfo.RemoveInviteTime);
m_events.AddEvent(removeEvent, m_events.CalculateTime(BattlegroundConst.InviteAcceptWaitTime)); m_events.AddEvent(removeEvent, m_events.CalculateTime(BattlegroundConst.InviteAcceptWaitTime));
uint queueSlot = player.GetBattlegroundQueueIndex(bgQueueTypeId); uint queueSlot = player.GetBattlegroundQueueIndex(bgQueueTypeId);
@@ -968,7 +968,7 @@ namespace Game.BattleGrounds
BattlegroundQueueTypeId m_queueId; BattlegroundQueueTypeId m_queueId;
Dictionary<ObjectGuid, PlayerQueueInfo> m_QueuedPlayers = new Dictionary<ObjectGuid, PlayerQueueInfo>(); Dictionary<ObjectGuid, PlayerQueueInfo> m_QueuedPlayers = new();
/// <summary> /// <summary>
/// This two dimensional array is used to store All queued groups /// This two dimensional array is used to store All queued groups
@@ -986,7 +986,7 @@ namespace Game.BattleGrounds
uint[][] m_SumOfWaitTimes = new uint[SharedConst.BGTeamsCount][]; uint[][] m_SumOfWaitTimes = new uint[SharedConst.BGTeamsCount][];
// Event handler // Event handler
EventSystem m_events = new EventSystem(); EventSystem m_events = new();
SelectionPool[] m_SelectionPools = new SelectionPool[SharedConst.BGTeamsCount]; SelectionPool[] m_SelectionPools = new SelectionPool[SharedConst.BGTeamsCount];
// class to select and invite groups to bg // class to select and invite groups to bg
@@ -1042,7 +1042,7 @@ namespace Game.BattleGrounds
} }
public uint GetPlayerCount() { return PlayerCount; } public uint GetPlayerCount() { return PlayerCount; }
public List<GroupQueueInfo> SelectedGroups = new List<GroupQueueInfo>(); public List<GroupQueueInfo> SelectedGroups = new();
uint PlayerCount; uint PlayerCount;
} }
@@ -1142,7 +1142,7 @@ namespace Game.BattleGrounds
/// </summary> /// </summary>
public class GroupQueueInfo public class GroupQueueInfo
{ {
public Dictionary<ObjectGuid, PlayerQueueInfo> Players = new Dictionary<ObjectGuid, PlayerQueueInfo>(); // player queue info map public Dictionary<ObjectGuid, PlayerQueueInfo> Players = new(); // player queue info map
public Team Team; // Player team (ALLIANCE/HORDE) public Team Team; // Player team (ALLIANCE/HORDE)
public BattlegroundTypeId BgTypeId; // Battleground type id public BattlegroundTypeId BgTypeId; // Battleground type id
public bool IsRated; // rated public bool IsRated; // rated
@@ -636,7 +636,7 @@ namespace Game.BattleGrounds.Zones
int teamIndex = GetTeamIndexByTeamId(player.GetTeam()); int teamIndex = GetTeamIndexByTeamId(player.GetTeam());
// Is there any occupied node for this team? // Is there any occupied node for this team?
List<byte> nodes = new List<byte>(); List<byte> nodes = new();
for (byte i = 0; i < ABBattlegroundNodes.DynamicNodesCount; ++i) for (byte i = 0; i < ABBattlegroundNodes.DynamicNodesCount; ++i)
if (m_Nodes[i] == ABNodeStatus.Occupied + teamIndex) if (m_Nodes[i] == ABNodeStatus.Occupied + teamIndex)
nodes.Add(i); nodes.Add(i);
@@ -298,7 +298,7 @@ namespace Game.BattleGrounds.Zones
Player p = Global.ObjAccessor.FindPlayer(pair.Key); Player p = Global.ObjAccessor.FindPlayer(pair.Key);
if (p) if (p)
{ {
UpdateData data = new UpdateData(p.GetMapId()); UpdateData data = new(p.GetMapId());
GetBGObject(i).BuildValuesUpdateBlockForPlayer(data, p); GetBGObject(i).BuildValuesUpdateBlockForPlayer(data, p);
UpdateObject pkt; UpdateObject pkt;
@@ -1029,7 +1029,7 @@ namespace Game.BattleGrounds.Zones
{ {
if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty() || !BgObjects[SAObjectTypes.BoatTwo].IsEmpty()) if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty() || !BgObjects[SAObjectTypes.BoatTwo].IsEmpty())
{ {
UpdateData transData = new UpdateData(player.GetMapId()); UpdateData transData = new(player.GetMapId());
if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty()) if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty())
GetBGObject(SAObjectTypes.BoatOne).BuildCreateUpdateBlockForPlayer(transData, player); GetBGObject(SAObjectTypes.BoatOne).BuildCreateUpdateBlockForPlayer(transData, player);
@@ -1046,7 +1046,7 @@ namespace Game.BattleGrounds.Zones
{ {
if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty() || !BgObjects[SAObjectTypes.BoatTwo].IsEmpty()) if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty() || !BgObjects[SAObjectTypes.BoatTwo].IsEmpty())
{ {
UpdateData transData = new UpdateData(player.GetMapId()); UpdateData transData = new(player.GetMapId());
if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty()) if (!BgObjects[SAObjectTypes.BoatOne].IsEmpty())
GetBGObject(SAObjectTypes.BoatOne).BuildOutOfRangeUpdateBlock(transData); GetBGObject(SAObjectTypes.BoatOne).BuildOutOfRangeUpdateBlock(transData);
if (!BgObjects[SAObjectTypes.BoatTwo].IsEmpty()) if (!BgObjects[SAObjectTypes.BoatTwo].IsEmpty())
@@ -1143,7 +1143,7 @@ namespace Game.BattleGrounds.Zones
bool SignaledRoundTwoHalfMin; bool SignaledRoundTwoHalfMin;
// for know if second round has been init // for know if second round has been init
bool InitSecondRound; bool InitSecondRound;
Dictionary<uint/*id*/, uint/*timer*/> DemoliserRespawnList = new Dictionary<uint, uint>(); Dictionary<uint/*id*/, uint/*timer*/> DemoliserRespawnList = new();
// Achievement: Defense of the Ancients // Achievement: Defense of the Ancients
bool _gateDestroyed; bool _gateDestroyed;
+17 -17
View File
@@ -33,7 +33,7 @@ namespace Game.BattlePets
_owner = owner; _owner = owner;
for (byte i = 0; i < SharedConst.MaxPetBattleSlots; ++i) for (byte i = 0; i < SharedConst.MaxPetBattleSlots; ++i)
{ {
BattlePetSlot slot = new BattlePetSlot(); BattlePetSlot slot = new();
slot.Index = i; slot.Index = i;
_slots.Add(slot); _slots.Add(slot);
} }
@@ -157,7 +157,7 @@ namespace Game.BattlePets
continue; continue;
} }
BattlePet pet = new BattlePet(); BattlePet pet = new();
pet.PacketInfo.Guid = ObjectGuid.Create(HighGuid.BattlePet, petsResult.Read<ulong>(0)); pet.PacketInfo.Guid = ObjectGuid.Create(HighGuid.BattlePet, petsResult.Read<ulong>(0));
pet.PacketInfo.Species = species; pet.PacketInfo.Species = species;
pet.PacketInfo.Breed = petsResult.Read<ushort>(2); pet.PacketInfo.Breed = petsResult.Read<ushort>(2);
@@ -277,7 +277,7 @@ namespace Game.BattlePets
if (battlePetSpecies == null) // should never happen if (battlePetSpecies == null) // should never happen
return; return;
BattlePet pet = new BattlePet(); BattlePet pet = new();
pet.PacketInfo.Guid = ObjectGuid.Create(HighGuid.BattlePet, Global.ObjectMgr.GetGenerator(HighGuid.BattlePet).Generate()); pet.PacketInfo.Guid = ObjectGuid.Create(HighGuid.BattlePet, Global.ObjectMgr.GetGenerator(HighGuid.BattlePet).Generate());
pet.PacketInfo.Species = species; pet.PacketInfo.Species = species;
pet.PacketInfo.CreatureID = creatureId; pet.PacketInfo.CreatureID = creatureId;
@@ -293,7 +293,7 @@ namespace Game.BattlePets
_pets[pet.PacketInfo.Guid.GetCounter()] = pet; _pets[pet.PacketInfo.Guid.GetCounter()] = pet;
List<BattlePet> updates = new List<BattlePet>(); List<BattlePet> updates = new();
updates.Add(pet); updates.Add(pet);
SendUpdates(updates, true); SendUpdates(updates, true);
@@ -326,7 +326,7 @@ namespace Game.BattlePets
_slots[slot].Locked = false; _slots[slot].Locked = false;
PetBattleSlotUpdates updates = new PetBattleSlotUpdates(); PetBattleSlotUpdates updates = new();
updates.Slots.Add(_slots[slot]); updates.Slots.Add(_slots[slot]);
updates.AutoSlotted = false; // what's this? updates.AutoSlotted = false; // what's this?
updates.NewSlot = true; // causes the "new slot unlocked" bubble to appear updates.NewSlot = true; // causes the "new slot unlocked" bubble to appear
@@ -349,7 +349,7 @@ namespace Game.BattlePets
if (pet == null) if (pet == null)
return; return;
List<ItemPosCount> dest = new List<ItemPosCount>(); List<ItemPosCount> dest = new();
if (_owner.GetPlayer().CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, SharedConst.BattlePetCageItemId, 1) != InventoryResult.Ok) if (_owner.GetPlayer().CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, SharedConst.BattlePetCageItemId, 1) != InventoryResult.Ok)
return; return;
@@ -368,7 +368,7 @@ namespace Game.BattlePets
RemovePet(guid); RemovePet(guid);
BattlePetDeleted deletePet = new BattlePetDeleted(); BattlePetDeleted deletePet = new();
deletePet.PetGuid = guid; deletePet.PetGuid = guid;
_owner.SendPacket(deletePet); _owner.SendPacket(deletePet);
} }
@@ -377,7 +377,7 @@ namespace Game.BattlePets
{ {
// TODO: After each Pet Battle, any injured companion will automatically // TODO: After each Pet Battle, any injured companion will automatically
// regain 50 % of the damage that was taken during combat // regain 50 % of the damage that was taken during combat
List<BattlePet> updates = new List<BattlePet>(); List<BattlePet> updates = new();
foreach (var pet in _pets.Values) foreach (var pet in _pets.Values)
{ {
@@ -425,7 +425,7 @@ namespace Game.BattlePets
public void SendJournal() public void SendJournal()
{ {
BattlePetJournal battlePetJournal = new BattlePetJournal(); BattlePetJournal battlePetJournal = new();
battlePetJournal.Trap = _trapLevel; battlePetJournal.Trap = _trapLevel;
foreach (var pet in _pets) foreach (var pet in _pets)
@@ -438,7 +438,7 @@ namespace Game.BattlePets
void SendUpdates(List<BattlePet> pets, bool petAdded) void SendUpdates(List<BattlePet> pets, bool petAdded)
{ {
BattlePetUpdates updates = new BattlePetUpdates(); BattlePetUpdates updates = new();
foreach (var pet in pets) foreach (var pet in pets)
updates.Pets.Add(pet.PacketInfo); updates.Pets.Add(pet.PacketInfo);
@@ -448,7 +448,7 @@ namespace Game.BattlePets
public void SendError(BattlePetError error, uint creatureId) public void SendError(BattlePetError error, uint creatureId)
{ {
BattlePetErrorPacket battlePetError = new BattlePetErrorPacket(); BattlePetErrorPacket battlePetError = new();
battlePetError.Result = error; battlePetError.Result = error;
battlePetError.CreatureID = creatureId; battlePetError.CreatureID = creatureId;
_owner.SendPacket(battlePetError); _owner.SendPacket(battlePetError);
@@ -462,13 +462,13 @@ namespace Game.BattlePets
WorldSession _owner; WorldSession _owner;
ushort _trapLevel; ushort _trapLevel;
Dictionary<ulong, BattlePet> _pets = new Dictionary<ulong, BattlePet>(); Dictionary<ulong, BattlePet> _pets = new();
List<BattlePetSlot> _slots = new List<BattlePetSlot>(); List<BattlePetSlot> _slots = new();
static Dictionary<uint, Dictionary<BattlePetState, int>> _battlePetBreedStates = new Dictionary<uint, Dictionary<BattlePetState, int>>(); static Dictionary<uint, Dictionary<BattlePetState, int>> _battlePetBreedStates = new();
static Dictionary<uint, Dictionary<BattlePetState, int>> _battlePetSpeciesStates = new Dictionary<uint, Dictionary<BattlePetState, int>>(); static Dictionary<uint, Dictionary<BattlePetState, int>> _battlePetSpeciesStates = new();
static MultiMap<uint, byte> _availableBreedsPerSpecies = new MultiMap<uint, byte>(); static MultiMap<uint, byte> _availableBreedsPerSpecies = new();
static Dictionary<uint, byte> _defaultQualityPerSpecies = new Dictionary<uint, byte>(); static Dictionary<uint, byte> _defaultQualityPerSpecies = new();
public class BattlePet public class BattlePet
{ {
+1 -1
View File
@@ -38,7 +38,7 @@ namespace Game.BlackMarket
Chance = fields.Read<float>(6); Chance = fields.Read<float>(6);
var bonusListIDsTok = new StringArray(fields.Read<string>(7), ' '); var bonusListIDsTok = new StringArray(fields.Read<string>(7), ' ');
List<uint> bonusListIDs = new List<uint>(); List<uint> bonusListIDs = new();
if (!bonusListIDsTok.IsEmpty()) if (!bonusListIDsTok.IsEmpty())
{ {
foreach (string token in bonusListIDsTok) foreach (string token in bonusListIDsTok)
+10 -10
View File
@@ -44,7 +44,7 @@ namespace Game.BlackMarket
do do
{ {
BlackMarketTemplate templ = new BlackMarketTemplate(); BlackMarketTemplate templ = new();
if (!templ.LoadFromDB(result.GetFields())) // Add checks if (!templ.LoadFromDB(result.GetFields())) // Add checks
continue; continue;
@@ -72,10 +72,10 @@ namespace Game.BlackMarket
_lastUpdate = Time.UnixTime; //Set update time before loading _lastUpdate = Time.UnixTime; //Set update time before loading
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
do do
{ {
BlackMarketEntry auction = new BlackMarketEntry(); BlackMarketEntry auction = new();
if (!auction.LoadFromDB(result.GetFields())) if (!auction.LoadFromDB(result.GetFields()))
{ {
@@ -99,7 +99,7 @@ namespace Game.BlackMarket
public void Update(bool updateTime = false) public void Update(bool updateTime = false)
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
long now = Time.UnixTime; long now = Time.UnixTime;
foreach (var entry in _auctions.Values) foreach (var entry in _auctions.Values)
{ {
@@ -118,7 +118,7 @@ namespace Game.BlackMarket
public void RefreshAuctions() public void RefreshAuctions()
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
// Delete completed auctions // Delete completed auctions
foreach (var pair in _auctions) foreach (var pair in _auctions)
{ {
@@ -132,7 +132,7 @@ namespace Game.BlackMarket
DB.Characters.CommitTransaction(trans); DB.Characters.CommitTransaction(trans);
trans = new SQLTransaction(); trans = new SQLTransaction();
List<BlackMarketTemplate> templates = new List<BlackMarketTemplate>(); List<BlackMarketTemplate> templates = new();
foreach (var pair in _templates) foreach (var pair in _templates)
{ {
if (GetAuctionByID(pair.Value.MarketID) != null) if (GetAuctionByID(pair.Value.MarketID) != null)
@@ -147,7 +147,7 @@ namespace Game.BlackMarket
foreach (BlackMarketTemplate templat in templates) foreach (BlackMarketTemplate templat in templates)
{ {
BlackMarketEntry entry = new BlackMarketEntry(); BlackMarketEntry entry = new();
entry.Initialize(templat.MarketID, (uint)templat.Duration); entry.Initialize(templat.MarketID, (uint)templat.Duration);
entry.SaveToDB(trans); entry.SaveToDB(trans);
AddAuction(entry); AddAuction(entry);
@@ -170,7 +170,7 @@ namespace Game.BlackMarket
{ {
BlackMarketTemplate templ = pair.Value.GetTemplate(); BlackMarketTemplate templ = pair.Value.GetTemplate();
BlackMarketItem item = new BlackMarketItem(); BlackMarketItem item = new();
item.MarketID = pair.Value.GetMarketId(); item.MarketID = pair.Value.GetMarketId();
item.SellerNPC = templ.SellerNPC; item.SellerNPC = templ.SellerNPC;
item.Item = templ.Item; item.Item = templ.Item;
@@ -302,8 +302,8 @@ namespace Game.BlackMarket
public long GetLastUpdate() { return _lastUpdate; } public long GetLastUpdate() { return _lastUpdate; }
Dictionary<uint, BlackMarketEntry> _auctions = new Dictionary<uint, BlackMarketEntry>(); Dictionary<uint, BlackMarketEntry> _auctions = new();
Dictionary<uint, BlackMarketTemplate> _templates = new Dictionary<uint, BlackMarketTemplate>(); Dictionary<uint, BlackMarketTemplate> _templates = new();
long _lastUpdate; long _lastUpdate;
} }
} }
+3 -3
View File
@@ -10,8 +10,8 @@ namespace Game.Cache
{ {
public class CharacterCache : Singleton<CharacterCache> public class CharacterCache : Singleton<CharacterCache>
{ {
Dictionary<ObjectGuid, CharacterCacheEntry> _characterCacheStore = new Dictionary<ObjectGuid, CharacterCacheEntry>(); Dictionary<ObjectGuid, CharacterCacheEntry> _characterCacheStore = new();
Dictionary<string, CharacterCacheEntry> _characterCacheByNameStore = new Dictionary<string, CharacterCacheEntry>(); Dictionary<string, CharacterCacheEntry> _characterCacheByNameStore = new();
CharacterCache() { } CharacterCache() { }
@@ -76,7 +76,7 @@ namespace Game.Cache
if (race.HasValue) if (race.HasValue)
characterCacheEntry.RaceId = (Race)race.Value; characterCacheEntry.RaceId = (Race)race.Value;
InvalidatePlayer invalidatePlayer = new InvalidatePlayer(); InvalidatePlayer invalidatePlayer = new();
invalidatePlayer.Guid = guid; invalidatePlayer.Guid = guid;
Global.WorldMgr.SendGlobalMessage(invalidatePlayer); Global.WorldMgr.SendGlobalMessage(invalidatePlayer);
+21 -21
View File
@@ -64,7 +64,7 @@ namespace Game
if (flags.HasAnyFlag(CalendarFlags.GuildEvent) || flags.HasAnyFlag(CalendarFlags.WithoutInvites)) if (flags.HasAnyFlag(CalendarFlags.GuildEvent) || flags.HasAnyFlag(CalendarFlags.WithoutInvites))
guildID = Global.CharacterCacheStorage.GetCharacterGuildIdByGuid(ownerGUID); guildID = Global.CharacterCacheStorage.GetCharacterGuildIdByGuid(ownerGUID);
CalendarEvent calendarEvent = new CalendarEvent(eventID, ownerGUID, guildID, type, textureID, date, flags, title, description, lockDate); CalendarEvent calendarEvent = new(eventID, ownerGUID, guildID, type, textureID, date, flags, title, description, lockDate);
_events.Add(calendarEvent); _events.Add(calendarEvent);
_maxEventId = Math.Max(_maxEventId, eventID); _maxEventId = Math.Max(_maxEventId, eventID);
@@ -93,7 +93,7 @@ namespace Game
CalendarModerationRank rank = (CalendarModerationRank)result.Read<byte>(6); CalendarModerationRank rank = (CalendarModerationRank)result.Read<byte>(6);
string note = result.Read<string>(7); string note = result.Read<string>(7);
CalendarInvite invite = new CalendarInvite(inviteId, eventId, invitee, senderGUID, responseTime, status, rank, note); CalendarInvite invite = new(inviteId, eventId, invitee, senderGUID, responseTime, status, rank, note);
_invites.Add(eventId, invite); _invites.Add(eventId, invite);
_maxInviteId = Math.Max(_maxInviteId, inviteId); _maxInviteId = Math.Max(_maxInviteId, inviteId);
@@ -148,9 +148,9 @@ namespace Game
SendCalendarEventRemovedAlert(calendarEvent); SendCalendarEventRemovedAlert(calendarEvent);
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt; PreparedStatement stmt;
MailDraft mail = new MailDraft(calendarEvent.BuildCalendarMailSubject(remover), calendarEvent.BuildCalendarMailBody()); MailDraft mail = new(calendarEvent.BuildCalendarMailSubject(remover), calendarEvent.BuildCalendarMailBody());
var eventInvites = _invites[eventId]; var eventInvites = _invites[eventId];
for (int i = 0; i < eventInvites.Count; ++i) for (int i = 0; i < eventInvites.Count; ++i)
@@ -196,7 +196,7 @@ namespace Game
if (calendarInvite == null) if (calendarInvite == null)
return; return;
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CALENDAR_INVITE); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CALENDAR_INVITE);
stmt.AddValue(0, calendarInvite.InviteId); stmt.AddValue(0, calendarInvite.InviteId);
trans.Append(stmt); trans.Append(stmt);
@@ -217,7 +217,7 @@ namespace Game
public void UpdateEvent(CalendarEvent calendarEvent) public void UpdateEvent(CalendarEvent calendarEvent)
{ {
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.REP_CALENDAR_EVENT); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.REP_CALENDAR_EVENT);
stmt.AddValue(0, calendarEvent.EventId); stmt.AddValue(0, calendarEvent.EventId);
stmt.AddValue(1, calendarEvent.OwnerGuid.GetCounter()); stmt.AddValue(1, calendarEvent.OwnerGuid.GetCounter());
@@ -331,7 +331,7 @@ namespace Game
public List<CalendarEvent> GetPlayerEvents(ObjectGuid guid) public List<CalendarEvent> GetPlayerEvents(ObjectGuid guid)
{ {
List<CalendarEvent> events = new List<CalendarEvent>(); List<CalendarEvent> events = new();
foreach (var pair in _invites) foreach (var pair in _invites)
{ {
@@ -360,7 +360,7 @@ namespace Game
public List<CalendarInvite> GetPlayerInvites(ObjectGuid guid) public List<CalendarInvite> GetPlayerInvites(ObjectGuid guid)
{ {
List<CalendarInvite> invites = new List<CalendarInvite>(); List<CalendarInvite> invites = new();
foreach (var calendarEvent in _invites.Values) foreach (var calendarEvent in _invites.Values)
{ {
@@ -402,7 +402,7 @@ namespace Game
uint level = player ? player.GetLevel() : Global.CharacterCacheStorage.GetCharacterLevelByGuid(invitee); uint level = player ? player.GetLevel() : Global.CharacterCacheStorage.GetCharacterLevelByGuid(invitee);
CalendarInviteAdded packet = new CalendarInviteAdded(); CalendarInviteAdded packet = new();
packet.EventID = calendarEvent != null ? calendarEvent.EventId : 0; packet.EventID = calendarEvent != null ? calendarEvent.EventId : 0;
packet.InviteGuid = invitee; packet.InviteGuid = invitee;
packet.InviteID = calendarEvent != null ? invite.InviteId : 0; packet.InviteID = calendarEvent != null ? invite.InviteId : 0;
@@ -427,7 +427,7 @@ namespace Game
public void SendCalendarEventUpdateAlert(CalendarEvent calendarEvent, long originalDate) public void SendCalendarEventUpdateAlert(CalendarEvent calendarEvent, long originalDate)
{ {
CalendarEventUpdatedAlert packet = new CalendarEventUpdatedAlert(); CalendarEventUpdatedAlert packet = new();
packet.ClearPending = true; // FIXME packet.ClearPending = true; // FIXME
packet.Date = calendarEvent.Date; packet.Date = calendarEvent.Date;
packet.Description = calendarEvent.Description; packet.Description = calendarEvent.Description;
@@ -444,7 +444,7 @@ namespace Game
public void SendCalendarEventStatus(CalendarEvent calendarEvent, CalendarInvite invite) public void SendCalendarEventStatus(CalendarEvent calendarEvent, CalendarInvite invite)
{ {
CalendarInviteStatusPacket packet = new CalendarInviteStatusPacket(); CalendarInviteStatusPacket packet = new();
packet.ClearPending = true; // FIXME packet.ClearPending = true; // FIXME
packet.Date = calendarEvent.Date; packet.Date = calendarEvent.Date;
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
@@ -458,7 +458,7 @@ namespace Game
void SendCalendarEventRemovedAlert(CalendarEvent calendarEvent) void SendCalendarEventRemovedAlert(CalendarEvent calendarEvent)
{ {
CalendarEventRemovedAlert packet = new CalendarEventRemovedAlert(); CalendarEventRemovedAlert packet = new();
packet.ClearPending = true; // FIXME packet.ClearPending = true; // FIXME
packet.Date = calendarEvent.Date; packet.Date = calendarEvent.Date;
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
@@ -468,7 +468,7 @@ namespace Game
void SendCalendarEventInviteRemove(CalendarEvent calendarEvent, CalendarInvite invite, uint flags) void SendCalendarEventInviteRemove(CalendarEvent calendarEvent, CalendarInvite invite, uint flags)
{ {
CalendarInviteRemoved packet = new CalendarInviteRemoved(); CalendarInviteRemoved packet = new();
packet.ClearPending = true; // FIXME packet.ClearPending = true; // FIXME
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
packet.Flags = flags; packet.Flags = flags;
@@ -479,7 +479,7 @@ namespace Game
public void SendCalendarEventModeratorStatusAlert(CalendarEvent calendarEvent, CalendarInvite invite) public void SendCalendarEventModeratorStatusAlert(CalendarEvent calendarEvent, CalendarInvite invite)
{ {
CalendarModeratorStatus packet = new CalendarModeratorStatus(); CalendarModeratorStatus packet = new();
packet.ClearPending = true; // FIXME packet.ClearPending = true; // FIXME
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
packet.InviteGuid = invite.InviteeGuid; packet.InviteGuid = invite.InviteeGuid;
@@ -490,7 +490,7 @@ namespace Game
void SendCalendarEventInviteAlert(CalendarEvent calendarEvent, CalendarInvite invite) void SendCalendarEventInviteAlert(CalendarEvent calendarEvent, CalendarInvite invite)
{ {
CalendarInviteAlert packet = new CalendarInviteAlert(); CalendarInviteAlert packet = new();
packet.Date = calendarEvent.Date; packet.Date = calendarEvent.Date;
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
packet.EventName = calendarEvent.Title; packet.EventName = calendarEvent.Title;
@@ -528,7 +528,7 @@ namespace Game
List<CalendarInvite> eventInviteeList = _invites[calendarEvent.EventId]; List<CalendarInvite> eventInviteeList = _invites[calendarEvent.EventId];
CalendarSendEvent packet = new CalendarSendEvent(); CalendarSendEvent packet = new();
packet.Date = calendarEvent.Date; packet.Date = calendarEvent.Date;
packet.Description = calendarEvent.Description; packet.Description = calendarEvent.Description;
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
@@ -551,7 +551,7 @@ namespace Game
uint inviteeLevel = invitee ? invitee.GetLevel() : Global.CharacterCacheStorage.GetCharacterLevelByGuid(inviteeGuid); uint inviteeLevel = invitee ? invitee.GetLevel() : Global.CharacterCacheStorage.GetCharacterLevelByGuid(inviteeGuid);
ulong inviteeGuildId = invitee ? invitee.GetGuildId() : Global.CharacterCacheStorage.GetCharacterGuildIdByGuid(inviteeGuid); ulong inviteeGuildId = invitee ? invitee.GetGuildId() : Global.CharacterCacheStorage.GetCharacterGuildIdByGuid(inviteeGuid);
CalendarEventInviteInfo inviteInfo = new CalendarEventInviteInfo(); CalendarEventInviteInfo inviteInfo = new();
inviteInfo.Guid = inviteeGuid; inviteInfo.Guid = inviteeGuid;
inviteInfo.Level = (byte)inviteeLevel; inviteInfo.Level = (byte)inviteeLevel;
inviteInfo.Status = calendarInvite.Status; inviteInfo.Status = calendarInvite.Status;
@@ -572,7 +572,7 @@ namespace Game
Player player = Global.ObjAccessor.FindPlayer(guid); Player player = Global.ObjAccessor.FindPlayer(guid);
if (player) if (player)
{ {
CalendarInviteRemovedAlert packet = new CalendarInviteRemovedAlert(); CalendarInviteRemovedAlert packet = new();
packet.Date = calendarEvent.Date; packet.Date = calendarEvent.Date;
packet.EventID = calendarEvent.EventId; packet.EventID = calendarEvent.EventId;
packet.Flags = calendarEvent.Flags; packet.Flags = calendarEvent.Flags;
@@ -594,7 +594,7 @@ namespace Game
Player player = Global.ObjAccessor.FindPlayer(guid); Player player = Global.ObjAccessor.FindPlayer(guid);
if (player) if (player)
{ {
CalendarCommandResult packet = new CalendarCommandResult(); CalendarCommandResult packet = new();
packet.Command = 1; // FIXME packet.Command = 1; // FIXME
packet.Result = err; packet.Result = err;
@@ -635,8 +635,8 @@ namespace Game
List<CalendarEvent> _events; List<CalendarEvent> _events;
MultiMap<ulong, CalendarInvite> _invites; MultiMap<ulong, CalendarInvite> _invites;
List<ulong> _freeEventIds = new List<ulong>(); List<ulong> _freeEventIds = new();
List<ulong> _freeInviteIds = new List<ulong>(); List<ulong> _freeInviteIds = new();
ulong _maxEventId; ulong _maxEventId;
ulong _maxInviteId; ulong _maxInviteId;
} }
+51 -51
View File
@@ -81,7 +81,7 @@ namespace Game.Chat
var tokens = new StringArray(bannedList, ' '); var tokens = new StringArray(bannedList, ' ');
for (var i = 0; i < tokens.Length; ++i) for (var i = 0; i < tokens.Length; ++i)
{ {
ObjectGuid bannedGuid = new ObjectGuid(); ObjectGuid bannedGuid = new();
if (ulong.TryParse(tokens[i].Substring(0, 16), out ulong highguid) && ulong.TryParse(tokens[i].Substring(16), out ulong lowguid)) if (ulong.TryParse(tokens[i].Substring(0, 16), out ulong highguid) && ulong.TryParse(tokens[i].Substring(16), out ulong lowguid))
bannedGuid.SetRawValue(highguid, lowguid); bannedGuid.SetRawValue(highguid, lowguid);
@@ -219,7 +219,7 @@ namespace Game.Chat
bool newChannel = _playersStore.Empty(); bool newChannel = _playersStore.Empty();
PlayerInfo playerInfo = new PlayerInfo(); PlayerInfo playerInfo = new();
playerInfo.SetInvisible(!player.IsGMVisible()); playerInfo.SetInvisible(!player.IsGMVisible());
_playersStore[guid] = playerInfo; _playersStore[guid] = playerInfo;
@@ -328,7 +328,7 @@ namespace Game.Chat
if (!IsOn(good)) if (!IsOn(good))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
@@ -336,7 +336,7 @@ namespace Game.Chat
PlayerInfo info = _playersStore.LookupByKey(good); PlayerInfo info = _playersStore.LookupByKey(good);
if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator)) if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotModeratorAppend()); ChannelNameBuilder builder = new(this, new NotModeratorAppend());
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
@@ -345,7 +345,7 @@ namespace Game.Chat
ObjectGuid victim = bad ? bad.GetGUID() : ObjectGuid.Empty; ObjectGuid victim = bad ? bad.GetGUID() : ObjectGuid.Empty;
if (victim.IsEmpty() || !IsOn(victim)) if (victim.IsEmpty() || !IsOn(victim))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerNotFoundAppend(badname)); ChannelNameBuilder builder = new(this, new PlayerNotFoundAppend(badname));
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
@@ -354,7 +354,7 @@ namespace Game.Chat
if (!player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator) && changeowner && good != _ownerGuid) if (!player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator) && changeowner && good != _ownerGuid)
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotOwnerAppend()); ChannelNameBuilder builder = new(this, new NotOwnerAppend());
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
@@ -366,14 +366,14 @@ namespace Game.Chat
if (!player.GetSession().HasPermission(RBACPermissions.SilentlyJoinChannel)) if (!player.GetSession().HasPermission(RBACPermissions.SilentlyJoinChannel))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerBannedAppend(good, victim)); ChannelNameBuilder builder = new(this, new PlayerBannedAppend(good, victim));
SendToAll(builder); SendToAll(builder);
} }
} }
else if (!player.GetSession().HasPermission(RBACPermissions.SilentlyJoinChannel)) else if (!player.GetSession().HasPermission(RBACPermissions.SilentlyJoinChannel))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerKickedAppend(good, victim)); ChannelNameBuilder builder = new(this, new PlayerKickedAppend(good, victim));
SendToAll(builder); SendToAll(builder);
} }
@@ -393,7 +393,7 @@ namespace Game.Chat
if (!IsOn(good)) if (!IsOn(good))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
@@ -401,7 +401,7 @@ namespace Game.Chat
PlayerInfo info = _playersStore.LookupByKey(good); PlayerInfo info = _playersStore.LookupByKey(good);
if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator)) if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotModeratorAppend()); ChannelNameBuilder builder = new(this, new NotModeratorAppend());
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
@@ -411,14 +411,14 @@ namespace Game.Chat
if (victim.IsEmpty() || !IsBanned(victim)) if (victim.IsEmpty() || !IsBanned(victim))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerNotFoundAppend(badname)); ChannelNameBuilder builder = new(this, new PlayerNotFoundAppend(badname));
SendToOne(builder, good); SendToOne(builder, good);
return; return;
} }
_bannedStore.Remove(victim); _bannedStore.Remove(victim);
ChannelNameBuilder builder1 = new ChannelNameBuilder(this, new PlayerUnbannedAppend(good, victim)); ChannelNameBuilder builder1 = new(this, new PlayerUnbannedAppend(good, victim));
SendToAll(builder1); SendToAll(builder1);
UpdateChannelInDB(); UpdateChannelInDB();
@@ -430,7 +430,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -438,14 +438,14 @@ namespace Game.Chat
PlayerInfo info = _playersStore.LookupByKey(guid); PlayerInfo info = _playersStore.LookupByKey(guid);
if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator)) if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotModeratorAppend()); ChannelNameBuilder builder = new(this, new NotModeratorAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
_channelPassword = pass; _channelPassword = pass;
ChannelNameBuilder builder1 = new ChannelNameBuilder(this, new PasswordChangedAppend(guid)); ChannelNameBuilder builder1 = new(this, new PasswordChangedAppend(guid));
SendToAll(builder1); SendToAll(builder1);
UpdateChannelInDB(); UpdateChannelInDB();
@@ -457,7 +457,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -465,7 +465,7 @@ namespace Game.Chat
PlayerInfo info = _playersStore.LookupByKey(guid); PlayerInfo info = _playersStore.LookupByKey(guid);
if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator)) if (!info.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotModeratorAppend()); ChannelNameBuilder builder = new(this, new NotModeratorAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -481,14 +481,14 @@ namespace Game.Chat
(!player.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel) || (!player.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel) ||
!newp.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel)))) !newp.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel))))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerNotFoundAppend(p2n)); ChannelNameBuilder builder = new(this, new PlayerNotFoundAppend(p2n));
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
if (_ownerGuid == victim && _ownerGuid != guid) if (_ownerGuid == victim && _ownerGuid != guid)
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotOwnerAppend()); ChannelNameBuilder builder = new(this, new NotOwnerAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -518,13 +518,13 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
if (!player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator) && guid != _ownerGuid) if (!player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator) && guid != _ownerGuid)
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotOwnerAppend()); ChannelNameBuilder builder = new(this, new NotOwnerAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -537,7 +537,7 @@ namespace Game.Chat
(!player.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel) || (!player.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel) ||
!newp.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel)))) !newp.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel))))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerNotFoundAppend(newname)); ChannelNameBuilder builder = new(this, new PlayerNotFoundAppend(newname));
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -551,12 +551,12 @@ namespace Game.Chat
ObjectGuid guid = player.GetGUID(); ObjectGuid guid = player.GetGUID();
if (IsOn(guid)) if (IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new ChannelOwnerAppend(this, _ownerGuid)); ChannelNameBuilder builder = new(this, new ChannelOwnerAppend(this, _ownerGuid));
SendToOne(builder, guid); SendToOne(builder, guid);
} }
else else
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
} }
} }
@@ -567,7 +567,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -575,7 +575,7 @@ namespace Game.Chat
string channelName = GetName(player.GetSession().GetSessionDbcLocale()); string channelName = GetName(player.GetSession().GetSessionDbcLocale());
Log.outDebug(LogFilter.ChatSystem, "SMSG_CHANNEL_LIST {0} Channel: {1}", player.GetSession().GetPlayerInfo(), channelName); Log.outDebug(LogFilter.ChatSystem, "SMSG_CHANNEL_LIST {0} Channel: {1}", player.GetSession().GetPlayerInfo(), channelName);
ChannelListResponse list = new ChannelListResponse(); ChannelListResponse list = new();
list.Display = true; // always true? list.Display = true; // always true?
list.Channel = channelName; list.Channel = channelName;
list.ChannelFlags = GetFlags(); list.ChannelFlags = GetFlags();
@@ -605,7 +605,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -613,7 +613,7 @@ namespace Game.Chat
PlayerInfo playerInfo = _playersStore.LookupByKey(guid); PlayerInfo playerInfo = _playersStore.LookupByKey(guid);
if (!playerInfo.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator)) if (!playerInfo.IsModerator() && !player.GetSession().HasPermission(RBACPermissions.ChangeChannelNotModerator))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotModeratorAppend()); ChannelNameBuilder builder = new(this, new NotModeratorAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -622,12 +622,12 @@ namespace Game.Chat
if (_announceEnabled) if (_announceEnabled)
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new AnnouncementsOnAppend(guid)); ChannelNameBuilder builder = new(this, new AnnouncementsOnAppend(guid));
SendToAll(builder); SendToAll(builder);
} }
else else
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new AnnouncementsOffAppend(guid)); ChannelNameBuilder builder = new(this, new AnnouncementsOffAppend(guid));
SendToAll(builder); SendToAll(builder);
} }
@@ -645,7 +645,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -653,7 +653,7 @@ namespace Game.Chat
PlayerInfo playerInfo = _playersStore.LookupByKey(guid); PlayerInfo playerInfo = _playersStore.LookupByKey(guid);
if (playerInfo.IsMuted()) if (playerInfo.IsMuted())
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new MutedAppend()); ChannelNameBuilder builder = new(this, new MutedAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -669,7 +669,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
NotMemberAppend appender; NotMemberAppend appender;
ChannelNameBuilder builder = new ChannelNameBuilder(this, appender); ChannelNameBuilder builder = new(this, appender);
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -678,7 +678,7 @@ namespace Game.Chat
if (playerInfo.IsMuted()) if (playerInfo.IsMuted())
{ {
MutedAppend appender; MutedAppend appender;
ChannelNameBuilder builder = new ChannelNameBuilder(this, appender); ChannelNameBuilder builder = new(this, appender);
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -692,7 +692,7 @@ namespace Game.Chat
if (!IsOn(guid)) if (!IsOn(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new NotMemberAppend()); ChannelNameBuilder builder = new(this, new NotMemberAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -700,14 +700,14 @@ namespace Game.Chat
Player newp = Global.ObjAccessor.FindPlayerByName(newname); Player newp = Global.ObjAccessor.FindPlayerByName(newname);
if (!newp || !newp.IsGMVisible()) if (!newp || !newp.IsGMVisible())
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerNotFoundAppend(newname)); ChannelNameBuilder builder = new(this, new PlayerNotFoundAppend(newname));
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
if (IsBanned(newp.GetGUID())) if (IsBanned(newp.GetGUID()))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerInviteBannedAppend(newname)); ChannelNameBuilder builder = new(this, new PlayerInviteBannedAppend(newname));
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
@@ -716,25 +716,25 @@ namespace Game.Chat
(!player.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel) || (!player.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel) ||
!newp.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel))) !newp.GetSession().HasPermission(RBACPermissions.TwoSideInteractionChannel)))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new InviteWrongFactionAppend()); ChannelNameBuilder builder = new(this, new InviteWrongFactionAppend());
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
if (IsOn(newp.GetGUID())) if (IsOn(newp.GetGUID()))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new PlayerAlreadyMemberAppend(newp.GetGUID())); ChannelNameBuilder builder = new(this, new PlayerAlreadyMemberAppend(newp.GetGUID()));
SendToOne(builder, guid); SendToOne(builder, guid);
return; return;
} }
if (!newp.GetSocial().HasIgnore(guid)) if (!newp.GetSocial().HasIgnore(guid))
{ {
ChannelNameBuilder builder = new ChannelNameBuilder(this, new InviteAppend(guid)); ChannelNameBuilder builder = new(this, new InviteAppend(guid));
SendToOne(builder, newp.GetGUID()); SendToOne(builder, newp.GetGUID());
} }
ChannelNameBuilder builder1 = new ChannelNameBuilder(this, new PlayerInvitedAppend(newp.GetName())); ChannelNameBuilder builder1 = new(this, new PlayerInvitedAppend(newp.GetName()));
SendToOne(builder1, guid); SendToOne(builder1, guid);
} }
@@ -759,12 +759,12 @@ namespace Game.Chat
playerInfo.SetModerator(true); playerInfo.SetModerator(true);
playerInfo.SetOwner(true); playerInfo.SetOwner(true);
ChannelNameBuilder builder = new ChannelNameBuilder(this, new ModeChangeAppend(_ownerGuid, oldFlag, GetPlayerFlags(_ownerGuid))); ChannelNameBuilder builder = new(this, new ModeChangeAppend(_ownerGuid, oldFlag, GetPlayerFlags(_ownerGuid)));
SendToAll(builder); SendToAll(builder);
if (exclaim) if (exclaim)
{ {
ChannelNameBuilder ownerChangedBuilder = new ChannelNameBuilder(this, new OwnerChangedAppend(_ownerGuid)); ChannelNameBuilder ownerChangedBuilder = new(this, new OwnerChangedAppend(_ownerGuid));
SendToAll(ownerChangedBuilder); SendToAll(ownerChangedBuilder);
} }
@@ -811,7 +811,7 @@ namespace Game.Chat
ChannelMemberFlags oldFlag = _playersStore[guid].GetFlags(); ChannelMemberFlags oldFlag = _playersStore[guid].GetFlags();
playerInfo.SetModerator(set); playerInfo.SetModerator(set);
ChannelNameBuilder builder = new ChannelNameBuilder(this, new ModeChangeAppend(guid, oldFlag, playerInfo.GetFlags())); ChannelNameBuilder builder = new(this, new ModeChangeAppend(guid, oldFlag, playerInfo.GetFlags()));
SendToAll(builder); SendToAll(builder);
} }
} }
@@ -827,14 +827,14 @@ namespace Game.Chat
ChannelMemberFlags oldFlag = _playersStore[guid].GetFlags(); ChannelMemberFlags oldFlag = _playersStore[guid].GetFlags();
playerInfo.SetMuted(set); playerInfo.SetMuted(set);
ChannelNameBuilder builder = new ChannelNameBuilder(this, new ModeChangeAppend(guid, oldFlag, playerInfo.GetFlags())); ChannelNameBuilder builder = new(this, new ModeChangeAppend(guid, oldFlag, playerInfo.GetFlags()));
SendToAll(builder); SendToAll(builder);
} }
} }
void SendToAll(MessageBuilder builder, ObjectGuid guid = default) void SendToAll(MessageBuilder builder, ObjectGuid guid = default)
{ {
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
foreach (var pair in _playersStore) foreach (var pair in _playersStore)
{ {
@@ -847,7 +847,7 @@ namespace Game.Chat
void SendToAllButOne(MessageBuilder builder, ObjectGuid who) void SendToAllButOne(MessageBuilder builder, ObjectGuid who)
{ {
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
foreach (var pair in _playersStore) foreach (var pair in _playersStore)
{ {
@@ -862,7 +862,7 @@ namespace Game.Chat
void SendToOne(MessageBuilder builder, ObjectGuid who) void SendToOne(MessageBuilder builder, ObjectGuid who)
{ {
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
Player player = Global.ObjAccessor.FindConnectedPlayer(who); Player player = Global.ObjAccessor.FindConnectedPlayer(who);
if (player) if (player)
@@ -871,7 +871,7 @@ namespace Game.Chat
void SendToAllWithAddon(MessageBuilder builder, string addonPrefix, ObjectGuid guid = default) void SendToAllWithAddon(MessageBuilder builder, string addonPrefix, ObjectGuid guid = default)
{ {
LocalizedPacketDo localizer = new LocalizedPacketDo(builder); LocalizedPacketDo localizer = new(builder);
foreach (var pair in _playersStore) foreach (var pair in _playersStore)
{ {
@@ -931,8 +931,8 @@ namespace Game.Chat
ObjectGuid _ownerGuid; ObjectGuid _ownerGuid;
string _channelName; string _channelName;
string _channelPassword; string _channelPassword;
Dictionary<ObjectGuid, PlayerInfo> _playersStore = new Dictionary<ObjectGuid, PlayerInfo>(); Dictionary<ObjectGuid, PlayerInfo> _playersStore = new();
List<ObjectGuid> _bannedStore = new List<ObjectGuid>(); List<ObjectGuid> _bannedStore = new();
AreaTableRecord _zoneEntry; AreaTableRecord _zoneEntry;
@@ -43,7 +43,7 @@ namespace Game.Chat
// LocalizedPacketDo sends client DBC locale, we need to get available to server locale // LocalizedPacketDo sends client DBC locale, we need to get available to server locale
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
ChannelNotify data = new ChannelNotify(); ChannelNotify data = new();
data.Type = _modifier.GetNotificationType(); data.Type = _modifier.GetNotificationType();
data.Channel = _source.GetName(localeIdx); data.Channel = _source.GetName(localeIdx);
_modifier.Append(data); _modifier.Append(data);
@@ -65,7 +65,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
ChannelNotifyJoined notify = new ChannelNotifyJoined(); ChannelNotifyJoined notify = new();
//notify.ChannelWelcomeMsg = ""; //notify.ChannelWelcomeMsg = "";
notify.ChatChannelID = (int)_source.GetChannelId(); notify.ChatChannelID = (int)_source.GetChannelId();
//notify.InstanceID = 0; //notify.InstanceID = 0;
@@ -90,7 +90,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
ChannelNotifyLeft notify = new ChannelNotifyLeft(); ChannelNotifyLeft notify = new();
notify.Channel = _source.GetName(localeIdx); notify.Channel = _source.GetName(localeIdx);
notify.ChatChannelID = _source.GetChannelId(); notify.ChatChannelID = _source.GetChannelId();
notify.Suspended = _suspended; notify.Suspended = _suspended;
@@ -115,7 +115,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
ChatPkt packet = new ChatPkt(); ChatPkt packet = new();
Player player = Global.ObjAccessor.FindConnectedPlayer(_guid); Player player = Global.ObjAccessor.FindConnectedPlayer(_guid);
if (player) if (player)
packet.Initialize(ChatMsg.Channel, _lang, player, player, _what, 0, _source.GetName(localeIdx)); packet.Initialize(ChatMsg.Channel, _lang, player, player, _what, 0, _source.GetName(localeIdx));
@@ -150,7 +150,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
ChatPkt packet = new ChatPkt(); ChatPkt packet = new();
Player player = Global.ObjAccessor.FindConnectedPlayer(_guid); Player player = Global.ObjAccessor.FindConnectedPlayer(_guid);
if (player) if (player)
packet.Initialize(ChatMsg.Channel, _lang, player, player, _what, 0, _source.GetName(localeIdx), Locale.enUS, _prefix); packet.Initialize(ChatMsg.Channel, _lang, player, player, _what, 0, _source.GetName(localeIdx), Locale.enUS, _prefix);
@@ -183,7 +183,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
UserlistAdd userlistAdd = new UserlistAdd(); UserlistAdd userlistAdd = new();
userlistAdd.AddedUserGUID = _guid; userlistAdd.AddedUserGUID = _guid;
userlistAdd.ChannelFlags = _source.GetFlags(); userlistAdd.ChannelFlags = _source.GetFlags();
userlistAdd.UserFlags = _source.GetPlayerFlags(_guid); userlistAdd.UserFlags = _source.GetPlayerFlags(_guid);
@@ -208,7 +208,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
UserlistUpdate userlistUpdate = new UserlistUpdate(); UserlistUpdate userlistUpdate = new();
userlistUpdate.UpdatedUserGUID = _guid; userlistUpdate.UpdatedUserGUID = _guid;
userlistUpdate.ChannelFlags = _source.GetFlags(); userlistUpdate.ChannelFlags = _source.GetFlags();
userlistUpdate.UserFlags = _source.GetPlayerFlags(_guid); userlistUpdate.UserFlags = _source.GetPlayerFlags(_guid);
@@ -233,7 +233,7 @@ namespace Game.Chat
{ {
Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale); Locale localeIdx = Global.WorldMgr.GetAvailableDbcLocale(locale);
UserlistRemove userlistRemove = new UserlistRemove(); UserlistRemove userlistRemove = new();
userlistRemove.RemovedUserGUID = _guid; userlistRemove.RemovedUserGUID = _guid;
userlistRemove.ChannelFlags = _source.GetFlags(); userlistRemove.ChannelFlags = _source.GetFlags();
userlistRemove.ChannelID = _source.GetChannelId(); userlistRemove.ChannelID = _source.GetChannelId();
+9 -9
View File
@@ -67,7 +67,7 @@ namespace Game.Chat
if (channel != null) if (channel != null)
return channel; return channel;
Channel newChannel = new Channel(channelGuid, channelId, _team, zoneEntry); Channel newChannel = new(channelGuid, channelId, _team, zoneEntry);
_channels[channelGuid] = newChannel; _channels[channelGuid] = newChannel;
return newChannel; return newChannel;
} }
@@ -77,7 +77,7 @@ namespace Game.Chat
if (channel != null) if (channel != null)
return channel; return channel;
Channel newChannel = new Channel(CreateCustomChannelGuid(), name, _team); Channel newChannel = new(CreateCustomChannelGuid(), name, _team);
_customChannels[name.ToLower()] = newChannel; _customChannels[name.ToLower()] = newChannel;
return newChannel; return newChannel;
} }
@@ -135,7 +135,7 @@ namespace Game.Chat
public static void SendNotOnChannelNotify(Player player, string name) public static void SendNotOnChannelNotify(Player player, string name)
{ {
ChannelNotify notify = new ChannelNotify(); ChannelNotify notify = new();
notify.Type = ChatNotify.NotMemberNotice; notify.Type = ChatNotify.NotMemberNotice;
notify.Channel = name; notify.Channel = name;
player.SendPacket(notify); player.SendPacket(notify);
@@ -148,7 +148,7 @@ namespace Game.Chat
high |= (ulong)Global.WorldMgr.GetRealmId().Index << 42; high |= (ulong)Global.WorldMgr.GetRealmId().Index << 42;
high |= (ulong)(_team == Team.Alliance ? 3 : 5) << 4; high |= (ulong)(_team == Team.Alliance ? 3 : 5) << 4;
ObjectGuid channelGuid = new ObjectGuid(); ObjectGuid channelGuid = new();
channelGuid.SetRawValue(high, _guidGenerator.Generate()); channelGuid.SetRawValue(high, _guidGenerator.Generate());
return channelGuid; return channelGuid;
} }
@@ -171,17 +171,17 @@ namespace Game.Chat
high |= (ulong)(zoneId) << 10; high |= (ulong)(zoneId) << 10;
high |= (ulong)(_team == Team.Alliance ? 3 : 5) << 4; high |= (ulong)(_team == Team.Alliance ? 3 : 5) << 4;
ObjectGuid channelGuid = new ObjectGuid(); ObjectGuid channelGuid = new();
channelGuid.SetRawValue(high, channelId); channelGuid.SetRawValue(high, channelId);
return channelGuid; return channelGuid;
} }
Dictionary<string, Channel> _customChannels = new Dictionary<string, Channel>(); Dictionary<string, Channel> _customChannels = new();
Dictionary<ObjectGuid, Channel> _channels = new Dictionary<ObjectGuid, Channel>(); Dictionary<ObjectGuid, Channel> _channels = new();
Team _team; Team _team;
ObjectGuidGenerator _guidGenerator; ObjectGuidGenerator _guidGenerator;
static ChannelManager allianceChannelMgr = new ChannelManager(Team.Alliance); static ChannelManager allianceChannelMgr = new(Team.Alliance);
static ChannelManager hordeChannelMgr = new ChannelManager(Team.Horde); static ChannelManager hordeChannelMgr = new(Team.Horde);
} }
} }
+9 -9
View File
@@ -73,7 +73,7 @@ namespace Game.Chat
public bool ExecuteCommandInTable(ICollection<ChatCommand> table, string text, string fullcmd) public bool ExecuteCommandInTable(ICollection<ChatCommand> table, string text, string fullcmd)
{ {
StringArguments args = new StringArguments(text); StringArguments args = new(text);
string cmd = args.NextString(); string cmd = args.NextString();
foreach (var command in table) foreach (var command in table)
@@ -170,7 +170,7 @@ namespace Game.Chat
public bool ShowHelpForCommand(ICollection<ChatCommand> table, string text) public bool ShowHelpForCommand(ICollection<ChatCommand> table, string text)
{ {
StringArguments args = new StringArguments(text); StringArguments args = new(text);
if (!args.Empty()) if (!args.Empty())
{ {
string cmd = args.NextString(); string cmd = args.NextString();
@@ -626,8 +626,8 @@ namespace Game.Chat
return null; return null;
Player pl = _session.GetPlayer(); Player pl = _session.GetPlayer();
NearestGameObjectCheck check = new NearestGameObjectCheck(pl); NearestGameObjectCheck check = new(pl);
GameObjectLastSearcher searcher = new GameObjectLastSearcher(pl, check); GameObjectLastSearcher searcher = new(pl, check);
Cell.VisitGridObjects(pl, searcher, MapConst.SizeofGrids); Cell.VisitGridObjects(pl, searcher, MapConst.SizeofGrids);
return searcher.GetTarget(); return searcher.GetTarget();
} }
@@ -764,7 +764,7 @@ namespace Game.Chat
if (escapeCharacters) if (escapeCharacters)
str.Replace("|", "||"); str.Replace("|", "||");
ChatPkt messageChat = new ChatPkt(); ChatPkt messageChat = new();
var lines = new StringArray(str, "\n", "\r"); var lines = new StringArray(str, "\n", "\r");
for (var i = 0; i < lines.Length; ++i) for (var i = 0; i < lines.Length; ++i)
@@ -782,7 +782,7 @@ namespace Game.Chat
public void SendGlobalSysMessage(string str) public void SendGlobalSysMessage(string str)
{ {
// Chat output // Chat output
ChatPkt data = new ChatPkt(); ChatPkt data = new();
data.Initialize(ChatMsg.System, Language.Universal, null, null, str); data.Initialize(ChatMsg.System, Language.Universal, null, null, str);
Global.WorldMgr.SendGlobalMessage(data); Global.WorldMgr.SendGlobalMessage(data);
} }
@@ -790,7 +790,7 @@ namespace Game.Chat
public void SendGlobalGMSysMessage(string str) public void SendGlobalGMSysMessage(string str)
{ {
// Chat output // Chat output
ChatPkt data = new ChatPkt(); ChatPkt data = new();
data.Initialize(ChatMsg.System, Language.Universal, null, null, str); data.Initialize(ChatMsg.System, Language.Universal, null, null, str);
Global.WorldMgr.SendGlobalGMMessage(data); Global.WorldMgr.SendGlobalGMMessage(data);
} }
@@ -893,7 +893,7 @@ namespace Game.Chat
void Send(string msg) void Send(string msg)
{ {
ChatPkt chat = new ChatPkt(); ChatPkt chat = new();
chat.Initialize(ChatMsg.Whisper, Language.Addon, GetSession().GetPlayer(), GetSession().GetPlayer(), msg, 0, "", Locale.enUS, PREFIX); chat.Initialize(ChatMsg.Whisper, Language.Addon, GetSession().GetPlayer(), GetSession().GetPlayer(), msg, 0, "", Locale.enUS, PREFIX);
GetSession().SendPacket(chat); GetSession().SendPacket(chat);
} }
@@ -919,7 +919,7 @@ namespace Game.Chat
if (!hadAck) if (!hadAck)
SendAck(); SendAck();
StringBuilder msg = new StringBuilder("m"); StringBuilder msg = new("m");
msg.Append(echo, 0, 4); msg.Append(echo, 0, 4);
string body = str; string body = str;
if (escapeCharacters) if (escapeCharacters)
+3 -3
View File
@@ -71,7 +71,7 @@ namespace Game.Chat
static bool SetDataForCommandInTable(ICollection<ChatCommand> table, string text, uint permission, string help, string fullcommand) static bool SetDataForCommandInTable(ICollection<ChatCommand> table, string text, uint permission, string help, string fullcommand)
{ {
StringArguments args = new StringArguments(text); StringArguments args = new(text);
string cmd = args.NextString().ToLower(); string cmd = args.NextString().ToLower();
foreach (var command in table) foreach (var command in table)
@@ -140,7 +140,7 @@ namespace Game.Chat
return _commands.Values; return _commands.Values;
} }
static SortedDictionary<string, ChatCommand> _commands = new SortedDictionary<string, ChatCommand>(); static SortedDictionary<string, ChatCommand> _commands = new();
} }
public delegate bool HandleCommandDelegate(StringArguments args, CommandHandler handler); public delegate bool HandleCommandDelegate(StringArguments args, CommandHandler handler);
@@ -192,6 +192,6 @@ namespace Game.Chat
public bool AllowConsole; public bool AllowConsole;
public HandleCommandDelegate Handler; public HandleCommandDelegate Handler;
public string Help; public string Help;
public List<ChatCommand> ChildCommands = new List<ChatCommand>(); public List<ChatCommand> ChildCommands = new();
} }
} }
+1 -1
View File
@@ -57,7 +57,7 @@ namespace Game.Chat
return false; return false;
} }
ArenaTeam arena = new ArenaTeam(); ArenaTeam arena = new();
if (!arena.Create(target.GetGUID(), type, name, 4293102085, 101, 4293253939, 4, 4284049911)) if (!arena.Create(target.GetGUID(), type, name, 4293102085, 101, 4293253939, 4, 4284049911))
{ {
@@ -415,7 +415,7 @@ namespace Game.Chat
string factionName = factionEntry != null ? factionEntry.Name[loc] : "#Not found#"; string factionName = factionEntry != null ? factionEntry.Name[loc] : "#Not found#";
ReputationRank rank = target.GetReputationMgr().GetRank(factionEntry); ReputationRank rank = target.GetReputationMgr().GetRank(factionEntry);
string rankName = handler.GetCypherString(ReputationMgr.ReputationRankStrIndex[(int)rank]); string rankName = handler.GetCypherString(ReputationMgr.ReputationRankStrIndex[(int)rank]);
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
if (handler.GetSession() != null) if (handler.GetSession() != null)
ss.AppendFormat("{0} - |cffffffff|Hfaction:{0}|h[{1} {2}]|h|r", faction.Id, factionName, loc); ss.AppendFormat("{0} - |cffffffff|Hfaction:{0}|h[{1} {2}]|h|r", faction.Id, factionName, loc);
else else
@@ -495,7 +495,7 @@ namespace Game.Chat
if (args.Empty()) if (args.Empty())
return false; return false;
List<DeletedInfo> foundList = new List<DeletedInfo>(); List<DeletedInfo> foundList = new();
if (!GetDeletedCharacterInfoList(foundList, args.NextString())) if (!GetDeletedCharacterInfoList(foundList, args.NextString()))
return false; return false;
@@ -518,7 +518,7 @@ namespace Game.Chat
[Command("list", RBACPermissions.CommandCharacterDeletedList, true)] [Command("list", RBACPermissions.CommandCharacterDeletedList, true)]
static bool HandleCharacterDeletedListCommand(StringArguments args, CommandHandler handler) static bool HandleCharacterDeletedListCommand(StringArguments args, CommandHandler handler)
{ {
List<DeletedInfo> foundList = new List<DeletedInfo>(); List<DeletedInfo> foundList = new();
if (!GetDeletedCharacterInfoList(foundList, args.NextString())) if (!GetDeletedCharacterInfoList(foundList, args.NextString()))
return false; return false;
@@ -545,7 +545,7 @@ namespace Game.Chat
string newCharName = args.NextString(); string newCharName = args.NextString();
uint newAccount = args.NextUInt32(); uint newAccount = args.NextUInt32();
List<DeletedInfo> foundList = new List<DeletedInfo>(); List<DeletedInfo> foundList = new();
if (!GetDeletedCharacterInfoList(foundList, searchString)) if (!GetDeletedCharacterInfoList(foundList, searchString))
return false; return false;
+7 -7
View File
@@ -542,7 +542,7 @@ namespace Game.Chat
target.DestroyForNearbyPlayers(); // Force new SMSG_UPDATE_OBJECT:CreateObject target.DestroyForNearbyPlayers(); // Force new SMSG_UPDATE_OBJECT:CreateObject
else else
{ {
MoveUpdate moveUpdate = new MoveUpdate(); MoveUpdate moveUpdate = new();
moveUpdate.Status = target.m_movementInfo; moveUpdate.Status = target.m_movementInfo;
target.SendMessageToSet(moveUpdate, true); target.SendMessageToSet(moveUpdate, true);
} }
@@ -775,7 +775,7 @@ namespace Game.Chat
return false; return false;
Map map = handler.GetSession().GetPlayer().GetMap(); Map map = handler.GetSession().GetPlayer().GetMap();
Position pos = new Position(x, y, z, o); Position pos = new(x, y, z, o);
Creature creature = Creature.CreateCreature(entry, map, pos, id); Creature creature = Creature.CreateCreature(entry, map, pos, id);
if (!creature) if (!creature)
@@ -1075,7 +1075,7 @@ namespace Game.Chat
string name = "test"; string name = "test";
byte code = args.NextByte(); byte code = args.NextByte();
ChannelNotify packet = new ChannelNotify(); ChannelNotify packet = new();
packet.Type = (ChatNotify)code; packet.Type = (ChatNotify)code;
packet.Channel = name; packet.Channel = name;
handler.GetSession().SendPacket(packet); handler.GetSession().SendPacket(packet);
@@ -1090,7 +1090,7 @@ namespace Game.Chat
string msg = "testtest"; string msg = "testtest";
byte type = args.NextByte(); byte type = args.NextByte();
ChatPkt data = new ChatPkt(); ChatPkt data = new();
data.Initialize((ChatMsg)type, Language.Universal, handler.GetSession().GetPlayer(), handler.GetSession().GetPlayer(), msg, 0, "chan"); data.Initialize((ChatMsg)type, Language.Universal, handler.GetSession().GetPlayer(), handler.GetSession().GetPlayer(), msg, 0, "chan");
handler.GetSession().SendPacket(data); handler.GetSession().SendPacket(data);
return true; return true;
@@ -1111,7 +1111,7 @@ namespace Game.Chat
static bool HandleDebugSendLargePacketCommand(StringArguments args, CommandHandler handler) static bool HandleDebugSendLargePacketCommand(StringArguments args, CommandHandler handler)
{ {
const string stuffingString = "This is a dummy string to push the packet's size beyond 128000 bytes. "; const string stuffingString = "This is a dummy string to push the packet's size beyond 128000 bytes. ";
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
while (ss.Length < 128000) while (ss.Length < 128000)
ss.Append(stuffingString); ss.Append(stuffingString);
handler.SendSysMessage(ss.ToString()); handler.SendSysMessage(ss.ToString());
@@ -1171,7 +1171,7 @@ namespace Game.Chat
if (args.Empty()) if (args.Empty())
return false; return false;
PhaseShift phaseShift = new PhaseShift(); PhaseShift phaseShift = new();
if (uint.TryParse(args.NextString(), out uint terrain)) if (uint.TryParse(args.NextString(), out uint terrain))
phaseShift.AddVisibleMapId(terrain, null); phaseShift.AddVisibleMapId(terrain, null);
@@ -1198,7 +1198,7 @@ namespace Game.Chat
int failArg1 = args.NextInt32(); int failArg1 = args.NextInt32();
int failArg2 = args.NextInt32(); int failArg2 = args.NextInt32();
CastFailed castFailed = new CastFailed(); CastFailed castFailed = new();
castFailed.CastID = ObjectGuid.Empty; castFailed.CastID = ObjectGuid.Empty;
castFailed.SpellID = 133; castFailed.SpellID = 133;
castFailed.Reason = (SpellCastResult)failNum; castFailed.Reason = (SpellCastResult)failNum;
@@ -366,7 +366,7 @@ namespace Game.Chat
Player player = handler.GetSession().GetPlayer(); Player player = handler.GetSession().GetPlayer();
List<WorldObject> creatureList = new List<WorldObject>(); List<WorldObject> creatureList = new();
if (!player.GetMap().SpawnGroupSpawn(groupId, ignoreRespawn, force, creatureList)) if (!player.GetMap().SpawnGroupSpawn(groupId, ignoreRespawn, force, creatureList))
{ {
handler.SendSysMessage(CypherStrings.SpawngroupBadgroup, groupId); handler.SendSysMessage(CypherStrings.SpawngroupBadgroup, groupId);
@@ -407,7 +407,7 @@ namespace Game.Chat
} }
else else
{ {
StringBuilder eventFilter = new StringBuilder(); StringBuilder eventFilter = new();
eventFilter.Append(" AND (eventEntry IS NULL "); eventFilter.Append(" AND (eventEntry IS NULL ");
bool initString = true; bool initString = true;
+1 -1
View File
@@ -45,7 +45,7 @@ namespace Game.Chat
return true; return true;
} }
Guild guild = new Guild(); Guild guild = new();
if (!guild.Create(target, guildname)) if (!guild.Create(target, guildname))
{ {
handler.SendSysMessage(CypherStrings.GuildNotCreated); handler.SendSysMessage(CypherStrings.GuildNotCreated);
+1 -1
View File
@@ -577,7 +577,7 @@ namespace Game.Chat.Commands
if (!args.Empty()) if (!args.Empty())
range = args.NextUInt32(); range = args.NextUInt32();
List<RespawnInfo> respawns = new List<RespawnInfo>(); List<RespawnInfo> respawns = new();
Locale locale = handler.GetSession().GetSessionDbcLocale(); Locale locale = handler.GetSession().GetSessionDbcLocale();
string stringOverdue = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsOverdue, locale); string stringOverdue = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsOverdue, locale);
string stringCreature = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsCreatures, locale); string stringCreature = Global.ObjectMgr.GetCypherString(CypherStrings.ListRespawnsCreatures, locale);
+5 -5
View File
@@ -267,7 +267,7 @@ namespace Game.Chat
// send faction in "id - [faction] rank reputation [visible] [at war] [own team] [unknown] [invisible] [inactive]" format // send faction in "id - [faction] rank reputation [visible] [at war] [own team] [unknown] [invisible] [inactive]" format
// or "id - [faction] [no reputation]" format // or "id - [faction] [no reputation]" format
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
if (handler.GetSession() != null) if (handler.GetSession() != null)
ss.AppendFormat("{0} - |cffffffff|Hfaction:{0}|h[{1}]|h|r", factionEntry.Id, name); ss.AppendFormat("{0} - |cffffffff|Hfaction:{0}|h[{1}]|h|r", factionEntry.Id, name);
else else
@@ -772,7 +772,7 @@ namespace Game.Chat
string namePart = args.NextString().ToLower(); string namePart = args.NextString().ToLower();
StringBuilder reply = new StringBuilder(); StringBuilder reply = new();
uint count = 0; uint count = 0;
bool limitReached = false; bool limitReached = false;
@@ -924,7 +924,7 @@ namespace Game.Chat
return true; return true;
} }
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
ss.Append(mapInfo.Id + " - [" + name + ']'); ss.Append(mapInfo.Id + " - [" + name + ']');
if (mapInfo.IsContinent()) if (mapInfo.IsContinent())
@@ -1141,7 +1141,7 @@ namespace Game.Chat
uint rank = learn && learnSpellInfo != null ? learnSpellInfo.GetRank() : spellInfo.GetRank(); uint rank = learn && learnSpellInfo != null ? learnSpellInfo.GetRank() : spellInfo.GetRank();
// send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format // send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
if (handler.GetSession() != null) if (handler.GetSession() != null)
ss.Append(spellInfo.Id + " - |cffffffff|Hspell:" + spellInfo.Id + "|h[" + name); ss.Append(spellInfo.Id + " - |cffffffff|Hspell:" + spellInfo.Id + "|h[" + name);
else else
@@ -1215,7 +1215,7 @@ namespace Game.Chat
uint rank = learn && learnSpellInfo != null ? learnSpellInfo.GetRank() : spellInfo.GetRank(); uint rank = learn && learnSpellInfo != null ? learnSpellInfo.GetRank() : spellInfo.GetRank();
// send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format // send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
if (handler.GetSession() != null) if (handler.GetSession() != null)
ss.Append(id + " - |cffffffff|Hspell:" + id + "|h[" + name); ss.Append(id + " - |cffffffff|Hspell:" + id + "|h[" + name);
else else
+6 -6
View File
@@ -62,7 +62,7 @@ namespace Game.Chat
player.GetPosition(out x, out y, out z); player.GetPosition(out x, out y, out z);
// path // path
PathGenerator path = new PathGenerator(target); PathGenerator path = new(target);
path.SetUseStraightPath(useStraightPath); path.SetUseStraightPath(useStraightPath);
bool result = path.CalculatePath(x, y, z, false, useStraightLine); bool result = path.CalculatePath(x, y, z, false, useStraightLine);
@@ -125,7 +125,7 @@ namespace Game.Chat
handler.SendSysMessage("Calc [{0:D2}, {1:D2}]", tilex, tiley); handler.SendSysMessage("Calc [{0:D2}, {1:D2}]", tilex, tiley);
// navmesh poly . navmesh tile location // navmesh poly . navmesh tile location
Detour.dtQueryFilter filter = new Detour.dtQueryFilter(); Detour.dtQueryFilter filter = new();
float[] nothing = new float[3]; float[] nothing = new float[3];
ulong polyRef = 0; ulong polyRef = 0;
if (Detour.dtStatusFailed(navmeshquery.findNearestPoly(location, extents, filter, ref polyRef, ref nothing))) if (Detour.dtStatusFailed(navmeshquery.findNearestPoly(location, extents, filter, ref polyRef, ref nothing)))
@@ -138,8 +138,8 @@ namespace Game.Chat
handler.SendSysMessage("Dt [??, ??] (invalid poly, probably no tile loaded)"); handler.SendSysMessage("Dt [??, ??] (invalid poly, probably no tile loaded)");
else else
{ {
Detour.dtMeshTile tile = new Detour.dtMeshTile(); Detour.dtMeshTile tile = new();
Detour.dtPoly poly = new Detour.dtPoly(); Detour.dtPoly poly = new();
if (Detour.dtStatusSucceed(navmesh.getTileAndPolyByRef(polyRef, ref tile, ref poly))) if (Detour.dtStatusSucceed(navmesh.getTileAndPolyByRef(polyRef, ref tile, ref poly)))
{ {
if (tile != null) if (tile != null)
@@ -231,7 +231,7 @@ namespace Game.Chat
WorldObject obj = handler.GetPlayer(); WorldObject obj = handler.GetPlayer();
// Get Creatures // Get Creatures
List<Unit> creatureList = new List<Unit>(); List<Unit> creatureList = new();
var go_check = new AnyUnitInObjectRangeCheck(obj, radius); var go_check = new AnyUnitInObjectRangeCheck(obj, radius);
var go_search = new UnitListSearcher(obj, creatureList, go_check); var go_search = new UnitListSearcher(obj, creatureList, go_check);
@@ -248,7 +248,7 @@ namespace Game.Chat
obj.GetPosition(out gx, out gy, out gz); obj.GetPosition(out gx, out gy, out gz);
foreach (var creature in creatureList) foreach (var creature in creatureList)
{ {
PathGenerator path = new PathGenerator(creature); PathGenerator path = new(creature);
path.CalculatePath(gx, gy, gz); path.CalculatePath(gx, gy, gz);
++paths; ++paths;
} }
+8 -8
View File
@@ -80,7 +80,7 @@ namespace Game.Chat
if (count == 0) if (count == 0)
count = 1; count = 1;
List<uint> bonusListIDs = new List<uint>(); List<uint> bonusListIDs = new();
var bonuses = args.NextString(); var bonuses = args.NextString();
// semicolon separated bonuslist ids (parse them after all arguments are extracted by strtok!) // semicolon separated bonuslist ids (parse them after all arguments are extracted by strtok!)
@@ -121,7 +121,7 @@ namespace Game.Chat
uint noSpaceForCount = 0; uint noSpaceForCount = 0;
// check space and find places // check space and find places
List<ItemPosCount> dest = new List<ItemPosCount>(); List<ItemPosCount> dest = new();
InventoryResult msg = playerTarget.CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, itemId, (uint)count, out noSpaceForCount); InventoryResult msg = playerTarget.CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, itemId, (uint)count, out noSpaceForCount);
if (msg != InventoryResult.Ok) // convert to possible store amount if (msg != InventoryResult.Ok) // convert to possible store amount
count -= (int)noSpaceForCount; count -= (int)noSpaceForCount;
@@ -175,7 +175,7 @@ namespace Game.Chat
return false; return false;
} }
List<uint> bonusListIDs = new List<uint>(); List<uint> bonusListIDs = new();
var bonuses = args.NextString(); var bonuses = args.NextString();
// semicolon separated bonuslist ids (parse them after all arguments are extracted by strtok!) // semicolon separated bonuslist ids (parse them after all arguments are extracted by strtok!)
@@ -203,7 +203,7 @@ namespace Game.Chat
if (template.Value.GetItemSet() == itemSetId) if (template.Value.GetItemSet() == itemSetId)
{ {
found = true; found = true;
List<ItemPosCount> dest = new List<ItemPosCount>(); List<ItemPosCount> dest = new();
InventoryResult msg = playerTarget.CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, template.Value.GetId(), 1); InventoryResult msg = playerTarget.CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, template.Value.GetId(), 1);
if (msg == InventoryResult.Ok) if (msg == InventoryResult.Ok)
{ {
@@ -565,7 +565,7 @@ namespace Game.Chat
// melee damage by specific school // melee damage by specific school
if (string.IsNullOrEmpty(spellStr)) if (string.IsNullOrEmpty(spellStr))
{ {
DamageInfo dmgInfo = new DamageInfo(attacker, target, damage_, null, schoolmask, DamageEffectType.SpellDirect, WeaponAttackType.BaseAttack); DamageInfo dmgInfo = new(attacker, target, damage_, null, schoolmask, DamageEffectType.SpellDirect, WeaponAttackType.BaseAttack);
attacker.CalcAbsorbResist(dmgInfo); attacker.CalcAbsorbResist(dmgInfo);
if (dmgInfo.GetDamage() == 0) if (dmgInfo.GetDamage() == 0)
@@ -591,7 +591,7 @@ namespace Game.Chat
if (spellInfo == null) if (spellInfo == null)
return false; return false;
SpellNonMeleeDamage damageInfo = new SpellNonMeleeDamage(attacker, target, spellInfo, new Networking.Packets.SpellCastVisual(spellInfo.GetSpellXSpellVisualId(attacker), 0), spellInfo.SchoolMask); SpellNonMeleeDamage damageInfo = new(attacker, target, spellInfo, new Networking.Packets.SpellCastVisual(spellInfo.GetSpellXSpellVisualId(attacker), 0), spellInfo.SchoolMask);
damageInfo.damage = damage_; damageInfo.damage = damage_;
attacker.DealDamageMods(damageInfo.target, ref damageInfo.damage, ref damageInfo.absorb); attacker.DealDamageMods(damageInfo.target, ref damageInfo.damage, ref damageInfo.absorb);
target.DealSpellDamage(damageInfo, true); target.DealSpellDamage(damageInfo, true);
@@ -886,7 +886,7 @@ namespace Game.Chat
} }
CellCoord cellCoord = GridDefines.ComputeCellCoord(obj.GetPositionX(), obj.GetPositionY()); CellCoord cellCoord = GridDefines.ComputeCellCoord(obj.GetPositionX(), obj.GetPositionY());
Cell cell = new Cell(cellCoord); Cell cell = new(cellCoord);
uint zoneId, areaId; uint zoneId, areaId;
obj.GetZoneAndAreaId(out zoneId, out areaId); obj.GetZoneAndAreaId(out zoneId, out areaId);
@@ -1957,7 +1957,7 @@ namespace Game.Chat
Cell.VisitGridObjects(player, worker, player.GetGridActivationRange()); Cell.VisitGridObjects(player, worker, player.GetGridActivationRange());
// Now handle any that had despawned, but had respawn time logged. // Now handle any that had despawned, but had respawn time logged.
List<RespawnInfo> data = new List<RespawnInfo>(); List<RespawnInfo> data = new();
player.GetMap().GetRespawnInfo(data, SpawnObjectTypeMask.All, 0); player.GetMap().GetRespawnInfo(data, SpawnObjectTypeMask.All, 0);
if (!data.Empty()) if (!data.Empty())
{ {
+4 -4
View File
@@ -191,8 +191,8 @@ namespace Game.Chat
if (handler.NeedReportToTarget(target)) if (handler.NeedReportToTarget(target))
target.SendSysMessage(CypherStrings.YoursSpellflatidChanged, handler.GetNameLink(), spellflatid, val, mark); target.SendSysMessage(CypherStrings.YoursSpellflatidChanged, handler.GetNameLink(), spellflatid, val, mark);
SetSpellModifier packet = new SetSpellModifier(ServerOpcodes.SetFlatSpellModifier); SetSpellModifier packet = new(ServerOpcodes.SetFlatSpellModifier);
SpellModifierInfo spellMod = new SpellModifierInfo(); SpellModifierInfo spellMod = new();
spellMod.ModIndex = op; spellMod.ModIndex = op;
SpellModifierData modData; SpellModifierData modData;
modData.ClassIndex = spellflatid; modData.ClassIndex = spellflatid;
@@ -601,7 +601,7 @@ namespace Game.Chat
Global.CharacterCacheStorage.UpdateCharacterGender(target.GetGUID(), (byte)gender); Global.CharacterCacheStorage.UpdateCharacterGender(target.GetGUID(), (byte)gender);
// Generate random customizations // Generate random customizations
List<ChrCustomizationChoice> customizations = new List<ChrCustomizationChoice>(); List<ChrCustomizationChoice> customizations = new();
var options = Global.DB2Mgr.GetCustomiztionOptions(target.GetRace(), gender); var options = Global.DB2Mgr.GetCustomiztionOptions(target.GetRace(), gender);
WorldSession worldSession = target.GetSession(); WorldSession worldSession = target.GetSession();
@@ -620,7 +620,7 @@ namespace Game.Chat
continue; continue;
ChrCustomizationChoiceRecord choiceEntry = choicesForOption[0]; ChrCustomizationChoiceRecord choiceEntry = choicesForOption[0];
ChrCustomizationChoice choice = new ChrCustomizationChoice(); ChrCustomizationChoice choice = new();
choice.ChrCustomizationOptionID = option.Id; choice.ChrCustomizationOptionID = option.Id;
choice.ChrCustomizationChoiceID = choiceEntry.Id; choice.ChrCustomizationChoiceID = choiceEntry.Id;
customizations.Add(choice); customizations.Add(choice);
+3 -3
View File
@@ -446,7 +446,7 @@ namespace Game.Chat
Player player = handler.GetSession().GetPlayer(); Player player = handler.GetSession().GetPlayer();
List<WorldObject> creatureList = new List<WorldObject>(); List<WorldObject> creatureList = new();
if (!player.GetMap().SpawnGroupSpawn(groupId, ignoreRespawn, force, creatureList)) if (!player.GetMap().SpawnGroupSpawn(groupId, ignoreRespawn, force, creatureList))
{ {
handler.SendSysMessage(CypherStrings.SpawngroupBadgroup, groupId); handler.SendSysMessage(CypherStrings.SpawngroupBadgroup, groupId);
@@ -719,7 +719,7 @@ namespace Game.Chat
uint vendor_entry = vendor.GetEntry(); uint vendor_entry = vendor.GetEntry();
VendorItem vItem = new VendorItem(); VendorItem vItem = new();
vItem.item = itemId; vItem.item = itemId;
vItem.maxcount = maxcount; vItem.maxcount = maxcount;
vItem.incrtime = incrtime; vItem.incrtime = incrtime;
@@ -807,7 +807,7 @@ namespace Game.Chat
return false; return false;
Player chr = handler.GetSession().GetPlayer(); Player chr = handler.GetSession().GetPlayer();
FormationInfo group_member = new FormationInfo(); FormationInfo group_member = new();
group_member.follow_angle = (creature.GetAngle(chr) - chr.GetOrientation()) * 180 / MathFunctions.PI; group_member.follow_angle = (creature.GetAngle(chr) - chr.GetOrientation()) * 180 / MathFunctions.PI;
group_member.follow_dist = (float)Math.Sqrt(Math.Pow(chr.GetPositionX() - creature.GetPositionX(), 2) + Math.Pow(chr.GetPositionY() - creature.GetPositionY(), 2)); group_member.follow_dist = (float)Math.Sqrt(Math.Pow(chr.GetPositionX() - creature.GetPositionX(), 2) + Math.Pow(chr.GetPositionY() - creature.GetPositionY(), 2));
group_member.leaderGUID = leaderGUID; group_member.leaderGUID = leaderGUID;
+1 -1
View File
@@ -52,7 +52,7 @@ namespace Game.Chat
} }
// Everything looks OK, create new pet // Everything looks OK, create new pet
Pet pet = new Pet(player, PetType.Hunter); Pet pet = new(player, PetType.Hunter);
if (!pet.CreateBaseAtCreature(creatureTarget)) if (!pet.CreateBaseAtCreature(creatureTarget))
{ {
handler.SendSysMessage("Error 1"); handler.SendSysMessage("Error 1");
+1 -1
View File
@@ -101,7 +101,7 @@ namespace Game.Chat
case QuestObjectiveType.Item: case QuestObjectiveType.Item:
{ {
uint curItemCount = player.GetItemCount((uint)obj.ObjectID, true); uint curItemCount = player.GetItemCount((uint)obj.ObjectID, true);
List<ItemPosCount> dest = new List<ItemPosCount>(); List<ItemPosCount> dest = new();
InventoryResult msg = player.CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, (uint)obj.ObjectID, (uint)(obj.Amount - curItemCount)); InventoryResult msg = player.CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, (uint)obj.ObjectID, (uint)(obj.Amount - curItemCount));
if (msg == InventoryResult.Ok) if (msg == InventoryResult.Ok)
{ {
+1 -1
View File
@@ -292,7 +292,7 @@ namespace Game.Chat.Commands
if (checkParams && handler.HasLowerSecurityAccount(null, accountId, true)) if (checkParams && handler.HasLowerSecurityAccount(null, accountId, true))
return null; return null;
RBACCommandData data = new RBACCommandData(); RBACCommandData data = new();
if (rdata == null) if (rdata == null)
{ {
+9 -9
View File
@@ -54,10 +54,10 @@ namespace Game.Chat.Commands
return false; return false;
// from console show not existed sender // from console show not existed sender
MailSender sender = new MailSender(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm); MailSender sender = new(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm);
// @todo Fix poor design // @todo Fix poor design
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
new MailDraft(subject, text) new MailDraft(subject, text)
.SendMailTo(trans, new MailReceiver(target, targetGuid.GetCounter()), sender); .SendMailTo(trans, new MailReceiver(target, targetGuid.GetCounter()), sender);
@@ -95,10 +95,10 @@ namespace Game.Chat.Commands
return false; return false;
// extract items // extract items
List<KeyValuePair<uint, uint>> items = new List<KeyValuePair<uint, uint>>(); List<KeyValuePair<uint, uint>> items = new();
// get all tail string // get all tail string
StringArguments tail = new StringArguments(args.NextString("")); StringArguments tail = new(args.NextString(""));
// get from tail next item str // get from tail next item str
StringArguments itemStr; StringArguments itemStr;
@@ -143,12 +143,12 @@ namespace Game.Chat.Commands
} }
// from console show not existed sender // from console show not existed sender
MailSender sender = new MailSender(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm); MailSender sender = new(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm);
// fill mail // fill mail
MailDraft draft = new MailDraft(subject, text); MailDraft draft = new(subject, text);
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
foreach (var pair in items) foreach (var pair in items)
{ {
@@ -202,9 +202,9 @@ namespace Game.Chat.Commands
return false; return false;
// from console show not existed sender // from console show not existed sender
MailSender sender = new MailSender(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm); MailSender sender = new(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm);
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
new MailDraft(subject, text) new MailDraft(subject, text)
.AddMoney((uint)money) .AddMoney((uint)money)
+2 -2
View File
@@ -90,7 +90,7 @@ namespace Game.Chat
return false; return false;
} }
GameTele tele = new GameTele(); GameTele tele = new();
tele.posX = player.GetPositionX(); tele.posX = player.GetPositionX();
tele.posY = player.GetPositionY(); tele.posY = player.GetPositionY();
tele.posZ = player.GetPositionZ(); tele.posZ = player.GetPositionZ();
@@ -232,7 +232,7 @@ namespace Game.Chat
if (!result.IsEmpty()) if (!result.IsEmpty())
{ {
WorldLocation loc = new WorldLocation(result.Read<ushort>(0), result.Read<float>(2), result.Read<float>(3), result.Read<float>(4), 0.0f); WorldLocation loc = new(result.Read<ushort>(0), result.Read<float>(2), result.Read<float>(3), result.Read<float>(4), 0.0f);
uint zoneId = result.Read<ushort>(1); uint zoneId = result.Read<ushort>(1);
Player.SavePositionInDB(loc, zoneId, targetGuid, null); Player.SavePositionInDB(loc, zoneId, targetGuid, null);
+3 -3
View File
@@ -760,7 +760,7 @@ namespace Game.Chat.Commands
Player chr = handler.GetSession().GetPlayer(); Player chr = handler.GetSession().GetPlayer();
Map map = chr.GetMap(); Map map = chr.GetMap();
Position pos = new Position(x, y, z, chr.GetOrientation()); Position pos = new(x, y, z, chr.GetOrientation());
Creature creature = Creature.CreateCreature(id, map, pos); Creature creature = Creature.CreateCreature(id, map, pos);
if (!creature) if (!creature)
@@ -826,7 +826,7 @@ namespace Game.Chat.Commands
Player chr = handler.GetSession().GetPlayer(); Player chr = handler.GetSession().GetPlayer();
Map map = chr.GetMap(); Map map = chr.GetMap();
Position pos = new Position(x, y, z, chr.GetOrientation()); Position pos = new(x, y, z, chr.GetOrientation());
Creature creature = Creature.CreateCreature(1, map, pos); Creature creature = Creature.CreateCreature(1, map, pos);
if (!creature) if (!creature)
@@ -881,7 +881,7 @@ namespace Game.Chat.Commands
Player chr = handler.GetSession().GetPlayer(); Player chr = handler.GetSession().GetPlayer();
Map map = chr.GetMap(); Map map = chr.GetMap();
Position pos = new Position(x, y, z, o); Position pos = new(x, y, z, o);
Creature creature = Creature.CreateCreature(1, map, pos); Creature creature = Creature.CreateCreature(1, map, pos);
if (!creature) if (!creature)
@@ -46,7 +46,7 @@ namespace Game.Collision
tempTree.Add(0); tempTree.Add(0);
// seed bbox // seed bbox
AABound gridBox = new AABound(); AABound gridBox = new();
gridBox.lo = bounds.Lo; gridBox.lo = bounds.Lo;
gridBox.hi = bounds.Hi; gridBox.hi = bounds.Hi;
AABound nodeBox = gridBox; AABound nodeBox = gridBox;
@@ -303,8 +303,8 @@ namespace Game.Collision
dat.primBound[i] = primitives[i].GetBounds(); dat.primBound[i] = primitives[i].GetBounds();
bounds.merge(dat.primBound[i]); bounds.merge(dat.primBound[i]);
} }
List<uint> tempTree = new List<uint>(); List<uint> tempTree = new();
BuildStats stats = new BuildStats(); BuildStats stats = new();
BuildHierarchy(tempTree, dat, stats); BuildHierarchy(tempTree, dat, stats);
objects = new uint[dat.numPrims]; objects = new uint[dat.numPrims];
@@ -322,7 +322,7 @@ namespace Game.Collision
float intervalMax = -1.0f; float intervalMax = -1.0f;
Vector3 org = r.Origin; Vector3 org = r.Origin;
Vector3 dir = r.Direction; Vector3 dir = r.Direction;
Vector3 invDir = new Vector3(); Vector3 invDir = new();
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
{ {
invDir[i] = 1.0f / dir[i]; invDir[i] = 1.0f / dir[i];
@@ -621,13 +621,13 @@ namespace Game.Collision
uint FloatToRawIntBits(float f) uint FloatToRawIntBits(float f)
{ {
FloatToIntConverter converter = new FloatToIntConverter(); FloatToIntConverter converter = new();
converter.FloatValue = f; converter.FloatValue = f;
return converter.IntValue; return converter.IntValue;
} }
float IntBitsToFloat(uint i) float IntBitsToFloat(uint i)
{ {
FloatToIntConverter converter = new FloatToIntConverter(); FloatToIntConverter converter = new();
converter.IntValue = i; converter.IntValue = i;
return converter.FloatValue; return converter.FloatValue;
} }
@@ -53,21 +53,21 @@ namespace Game.Collision
public void IntersectRay(Ray ray, WorkerCallback intersectCallback, ref float maxDist) public void IntersectRay(Ray ray, WorkerCallback intersectCallback, ref float maxDist)
{ {
Balance(); Balance();
MDLCallback temp_cb = new MDLCallback(intersectCallback, m_objects.ToArray(), (uint)m_objects.Count); MDLCallback temp_cb = new(intersectCallback, m_objects.ToArray(), (uint)m_objects.Count);
m_tree.IntersectRay(ray, temp_cb, ref maxDist, true); m_tree.IntersectRay(ray, temp_cb, ref maxDist, true);
} }
public void IntersectPoint(Vector3 point, WorkerCallback intersectCallback) public void IntersectPoint(Vector3 point, WorkerCallback intersectCallback)
{ {
Balance(); Balance();
MDLCallback callback = new MDLCallback(intersectCallback, m_objects.ToArray(), (uint)m_objects.Count); MDLCallback callback = new(intersectCallback, m_objects.ToArray(), (uint)m_objects.Count);
m_tree.IntersectPoint(point, callback); m_tree.IntersectPoint(point, callback);
} }
BIH m_tree = new BIH(); BIH m_tree = new();
List<T> m_objects = new List<T>(); List<T> m_objects = new();
Dictionary<T, uint> m_obj2Idx = new Dictionary<T, uint>(); Dictionary<T, uint> m_obj2Idx = new();
HashSet<T> m_objects_to_push = new HashSet<T>(); HashSet<T> m_objects_to_push = new();
int unbalanced_times; int unbalanced_times;
public class MDLCallback : WorkerCallback public class MDLCallback : WorkerCallback
+4 -4
View File
@@ -121,7 +121,7 @@ namespace Game.Collision
Vector3 e1 = points[(int)tri.idx1] - points[(int)tri.idx0]; Vector3 e1 = points[(int)tri.idx1] - points[(int)tri.idx0];
Vector3 e2 = points[(int)tri.idx2] - points[(int)tri.idx0]; Vector3 e2 = points[(int)tri.idx2] - points[(int)tri.idx0];
Vector3 p = new Vector3(ray.Direction.cross(e2)); Vector3 p = new(ray.Direction.cross(e2));
float a = e1.dot(p); float a = e1.dot(p);
if (Math.Abs(a) < EPS) if (Math.Abs(a) < EPS)
@@ -131,7 +131,7 @@ namespace Game.Collision
} }
float f = 1.0f / a; float f = 1.0f / a;
Vector3 s = new Vector3(ray.Origin - points[(int)tri.idx0]); Vector3 s = new(ray.Origin - points[(int)tri.idx0]);
float u = f * s.dot(p); float u = f * s.dot(p);
if ((u < 0.0f) || (u > 1.0f)) if ((u < 0.0f) || (u > 1.0f))
@@ -140,7 +140,7 @@ namespace Game.Collision
return false; return false;
} }
Vector3 q = new Vector3(s.cross(e1)); Vector3 q = new(s.cross(e1));
float v = f * ray.Direction.dot(q); float v = f * ray.Direction.dot(q);
if ((v < 0.0f) || ((u + v) > 1.0f)) if ((v < 0.0f) || ((u + v) > 1.0f))
@@ -205,7 +205,7 @@ namespace Game.Collision
} }
ModelInstance[] prims; ModelInstance[] prims;
public AreaInfo aInfo = new AreaInfo(); public AreaInfo aInfo = new();
} }
public class LocationInfoCallback : WorkerCallback public class LocationInfoCallback : WorkerCallback
+9 -9
View File
@@ -54,7 +54,7 @@ namespace Game.Collision
public bool GetIntersectionTime(Ray ray, Vector3 endPos, PhaseShift phaseShift, float maxDist) public bool GetIntersectionTime(Ray ray, Vector3 endPos, PhaseShift phaseShift, float maxDist)
{ {
float distance = maxDist; float distance = maxDist;
DynamicTreeIntersectionCallback callback = new DynamicTreeIntersectionCallback(phaseShift); DynamicTreeIntersectionCallback callback = new(phaseShift);
impl.IntersectRay(ray, callback, ref distance, endPos); impl.IntersectRay(ray, callback, ref distance, endPos);
if (callback.DidHit()) if (callback.DidHit())
maxDist = distance; maxDist = distance;
@@ -74,7 +74,7 @@ namespace Game.Collision
return false; return false;
} }
Vector3 dir = (endPos - startPos) / maxDist; // direction with length of 1 Vector3 dir = (endPos - startPos) / maxDist; // direction with length of 1
Ray ray = new Ray(startPos, dir); Ray ray = new(startPos, dir);
float dist = maxDist; float dist = maxDist;
if (GetIntersectionTime(ray, endPos, phaseShift, dist)) if (GetIntersectionTime(ray, endPos, phaseShift, dist))
{ {
@@ -106,8 +106,8 @@ namespace Game.Collision
if (!MathFunctions.fuzzyGt(maxDist, 0)) if (!MathFunctions.fuzzyGt(maxDist, 0))
return true; return true;
Ray r = new Ray(startPos, (endPos - startPos) / maxDist); Ray r = new(startPos, (endPos - startPos) / maxDist);
DynamicTreeIntersectionCallback callback = new DynamicTreeIntersectionCallback(phaseShift); DynamicTreeIntersectionCallback callback = new(phaseShift);
impl.IntersectRay(r, callback, ref maxDist, endPos); impl.IntersectRay(r, callback, ref maxDist, endPos);
return !callback.DidHit(); return !callback.DidHit();
@@ -115,9 +115,9 @@ namespace Game.Collision
public float GetHeight(float x, float y, float z, float maxSearchDist, PhaseShift phaseShift) public float GetHeight(float x, float y, float z, float maxSearchDist, PhaseShift phaseShift)
{ {
Vector3 v = new Vector3(x, y, z + 0.5f); Vector3 v = new(x, y, z + 0.5f);
Ray r = new Ray(v, new Vector3(0, 0, -1)); Ray r = new(v, new Vector3(0, 0, -1));
DynamicTreeIntersectionCallback callback = new DynamicTreeIntersectionCallback(phaseShift); DynamicTreeIntersectionCallback callback = new(phaseShift);
impl.IntersectZAllignedRay(r, callback, ref maxSearchDist); impl.IntersectZAllignedRay(r, callback, ref maxSearchDist);
if (callback.DidHit()) if (callback.DidHit())
@@ -133,8 +133,8 @@ namespace Game.Collision
rootId = 0; rootId = 0;
groupId = 0; groupId = 0;
Vector3 v = new Vector3(x, y, z + 0.5f); Vector3 v = new(x, y, z + 0.5f);
DynamicTreeAreaInfoCallback intersectionCallBack = new DynamicTreeAreaInfoCallback(phaseShift); DynamicTreeAreaInfoCallback intersectionCallBack = new(phaseShift);
impl.IntersectPoint(v, intersectionCallBack); impl.IntersectPoint(v, intersectionCallBack);
if (intersectionCallBack.GetAreaInfo().result) if (intersectionCallBack.GetAreaInfo().result)
{ {
+10 -10
View File
@@ -84,7 +84,7 @@ namespace Game.Collision
if (instanceTree == null) if (instanceTree == null)
{ {
string filename = VMapPath + GetMapFileName(mapId); string filename = VMapPath + GetMapFileName(mapId);
StaticMapTree newTree = new StaticMapTree(mapId); StaticMapTree newTree = new(mapId);
LoadResult treeInitResult = newTree.InitMap(filename); LoadResult treeInitResult = newTree.InitMap(filename);
if (treeInitResult != LoadResult.Success) if (treeInitResult != LoadResult.Success)
return treeInitResult; return treeInitResult;
@@ -232,7 +232,7 @@ namespace Game.Collision
var instanceTree = iInstanceMapTrees.LookupByKey(mapId); var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
if (instanceTree != null) if (instanceTree != null)
{ {
LocationInfo info = new LocationInfo(); LocationInfo info = new();
Vector3 pos = ConvertPositionToInternalRep(x, y, z); Vector3 pos = ConvertPositionToInternalRep(x, y, z);
if (instanceTree.GetLocationInfo(pos, info)) if (instanceTree.GetLocationInfo(pos, info))
{ {
@@ -265,7 +265,7 @@ namespace Game.Collision
var instanceTree = iInstanceMapTrees.LookupByKey(mapId); var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
if (instanceTree != null) if (instanceTree != null)
{ {
LocationInfo info = new LocationInfo(); LocationInfo info = new();
Vector3 pos = ConvertPositionToInternalRep(x, y, z); Vector3 pos = ConvertPositionToInternalRep(x, y, z);
if (instanceTree.GetLocationInfo(pos, info)) if (instanceTree.GetLocationInfo(pos, info))
{ {
@@ -292,7 +292,7 @@ namespace Game.Collision
var model = iLoadedModelFiles.LookupByKey(filename); var model = iLoadedModelFiles.LookupByKey(filename);
if (model == null) if (model == null)
{ {
WorldModel worldmodel = new WorldModel(); WorldModel worldmodel = new();
if (!worldmodel.ReadFile(VMapPath + filename)) if (!worldmodel.ReadFile(VMapPath + filename))
{ {
Log.outError(LogFilter.Server, "VMapManager: could not load '{0}'", filename); Log.outError(LogFilter.Server, "VMapManager: could not load '{0}'", filename);
@@ -347,7 +347,7 @@ namespace Game.Collision
Vector3 ConvertPositionToInternalRep(float x, float y, float z) Vector3 ConvertPositionToInternalRep(float x, float y, float z)
{ {
Vector3 pos = new Vector3(); Vector3 pos = new();
float mid = 0.5f * 64.0f * 533.33333333f; float mid = 0.5f * 64.0f * 533.33333333f;
pos.X = mid - x; pos.X = mid - x;
pos.Y = mid - y; pos.Y = mid - y;
@@ -368,14 +368,14 @@ namespace Game.Collision
public bool IsHeightCalcEnabled() { return _enableHeightCalc; } public bool IsHeightCalcEnabled() { return _enableHeightCalc; }
public bool IsMapLoadingEnabled() { return _enableLineOfSightCalc || _enableHeightCalc; } public bool IsMapLoadingEnabled() { return _enableLineOfSightCalc || _enableHeightCalc; }
Dictionary<string, ManagedModel> iLoadedModelFiles = new Dictionary<string, ManagedModel>(); Dictionary<string, ManagedModel> iLoadedModelFiles = new();
Dictionary<uint, StaticMapTree> iInstanceMapTrees = new Dictionary<uint, StaticMapTree>(); Dictionary<uint, StaticMapTree> iInstanceMapTrees = new();
MultiMap<uint, uint> iChildMapData = new MultiMap<uint, uint>(); MultiMap<uint, uint> iChildMapData = new();
Dictionary<uint, uint> iParentMapData = new Dictionary<uint, uint>(); Dictionary<uint, uint> iParentMapData = new();
bool _enableLineOfSightCalc; bool _enableLineOfSightCalc;
bool _enableHeightCalc; bool _enableHeightCalc;
object LoadedModelFilesLock = new object(); object LoadedModelFilesLock = new();
} }
public class ManagedModel public class ManagedModel
+17 -17
View File
@@ -64,7 +64,7 @@ namespace Game.Collision
if (!File.Exists(fname)) if (!File.Exists(fname))
return LoadResult.FileNotFound; return LoadResult.FileNotFound;
using (BinaryReader reader = new BinaryReader(new FileStream(fname, FileMode.Open, FileAccess.Read))) using (BinaryReader reader = new(new FileStream(fname, FileMode.Open, FileAccess.Read)))
{ {
var magic = reader.ReadStringFromChars(8); var magic = reader.ReadStringFromChars(8);
if (magic != MapConst.VMapMagic) if (magic != MapConst.VMapMagic)
@@ -120,7 +120,7 @@ namespace Game.Collision
if (fileResult.File != null) if (fileResult.File != null)
{ {
result = LoadResult.Success; result = LoadResult.Success;
using (BinaryReader reader = new BinaryReader(fileResult.File)) using (BinaryReader reader = new(fileResult.File))
{ {
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic) if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
result = LoadResult.VersionMismatch; result = LoadResult.VersionMismatch;
@@ -196,7 +196,7 @@ namespace Game.Collision
TileFileOpenResult fileResult = OpenMapTileFile(VMapManager.VMapPath, iMapID, tileX, tileY, vm); TileFileOpenResult fileResult = OpenMapTileFile(VMapManager.VMapPath, iMapID, tileX, tileY, vm);
if (fileResult.File != null) if (fileResult.File != null)
{ {
using (BinaryReader reader = new BinaryReader(fileResult.File)) using (BinaryReader reader = new(fileResult.File))
{ {
bool result = true; bool result = true;
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic) if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
@@ -240,7 +240,7 @@ namespace Game.Collision
static TileFileOpenResult OpenMapTileFile(string vmapPath, uint mapID, uint tileX, uint tileY, VMapManager vm) static TileFileOpenResult OpenMapTileFile(string vmapPath, uint mapID, uint tileX, uint tileY, VMapManager vm)
{ {
TileFileOpenResult result = new TileFileOpenResult(); TileFileOpenResult result = new();
result.Name = vmapPath + GetTileFileName(mapID, tileX, tileY); result.Name = vmapPath + GetTileFileName(mapID, tileX, tileY);
if (File.Exists(result.Name)) if (File.Exists(result.Name))
@@ -273,7 +273,7 @@ namespace Game.Collision
if (!File.Exists(fullname)) if (!File.Exists(fullname))
return LoadResult.FileNotFound; return LoadResult.FileNotFound;
using (BinaryReader reader = new BinaryReader(new FileStream(fullname, FileMode.Open, FileAccess.Read))) using (BinaryReader reader = new(new FileStream(fullname, FileMode.Open, FileAccess.Read)))
{ {
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic) if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
return LoadResult.VersionMismatch; return LoadResult.VersionMismatch;
@@ -283,7 +283,7 @@ namespace Game.Collision
if (stream == null) if (stream == null)
return LoadResult.FileNotFound; return LoadResult.FileNotFound;
using (BinaryReader reader = new BinaryReader(stream)) using (BinaryReader reader = new(stream))
{ {
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic) if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
return LoadResult.VersionMismatch; return LoadResult.VersionMismatch;
@@ -304,7 +304,7 @@ namespace Game.Collision
rootId = 0; rootId = 0;
groupId = 0; groupId = 0;
AreaInfoCallback intersectionCallBack = new AreaInfoCallback(iTreeValues); AreaInfoCallback intersectionCallBack = new(iTreeValues);
iTree.IntersectPoint(pos, intersectionCallBack); iTree.IntersectPoint(pos, intersectionCallBack);
if (intersectionCallBack.aInfo.result) if (intersectionCallBack.aInfo.result)
{ {
@@ -320,7 +320,7 @@ namespace Game.Collision
public bool GetLocationInfo(Vector3 pos, LocationInfo info) public bool GetLocationInfo(Vector3 pos, LocationInfo info)
{ {
LocationInfoCallback intersectionCallBack = new LocationInfoCallback(iTreeValues, info); LocationInfoCallback intersectionCallBack = new(iTreeValues, info);
iTree.IntersectPoint(pos, intersectionCallBack); iTree.IntersectPoint(pos, intersectionCallBack);
return intersectionCallBack.result; return intersectionCallBack.result;
} }
@@ -328,8 +328,8 @@ namespace Game.Collision
public float GetHeight(Vector3 pPos, float maxSearchDist) public float GetHeight(Vector3 pPos, float maxSearchDist)
{ {
float height = float.PositiveInfinity; float height = float.PositiveInfinity;
Vector3 dir = new Vector3(0, 0, -1); Vector3 dir = new(0, 0, -1);
Ray ray = new Ray(pPos, dir); // direction with length of 1 Ray ray = new(pPos, dir); // direction with length of 1
float maxDist = maxSearchDist; float maxDist = maxSearchDist;
if (GetIntersectionTime(ray, ref maxDist, false, ModelIgnoreFlags.Nothing)) if (GetIntersectionTime(ray, ref maxDist, false, ModelIgnoreFlags.Nothing))
height = pPos.Z - maxDist; height = pPos.Z - maxDist;
@@ -339,7 +339,7 @@ namespace Game.Collision
bool GetIntersectionTime(Ray pRay, ref float pMaxDist, bool pStopAtFirstHit, ModelIgnoreFlags ignoreFlags) bool GetIntersectionTime(Ray pRay, ref float pMaxDist, bool pStopAtFirstHit, ModelIgnoreFlags ignoreFlags)
{ {
float distance = pMaxDist; float distance = pMaxDist;
MapRayCallback intersectionCallBack = new MapRayCallback(iTreeValues, ignoreFlags); MapRayCallback intersectionCallBack = new(iTreeValues, ignoreFlags);
iTree.IntersectRay(pRay, intersectionCallBack, ref distance, pStopAtFirstHit); iTree.IntersectRay(pRay, intersectionCallBack, ref distance, pStopAtFirstHit);
if (intersectionCallBack.DidHit()) if (intersectionCallBack.DidHit())
pMaxDist = distance; pMaxDist = distance;
@@ -359,7 +359,7 @@ namespace Game.Collision
return false; return false;
} }
Vector3 dir = (pPos2 - pPos1) / maxDist; // direction with length of 1 Vector3 dir = (pPos2 - pPos1) / maxDist; // direction with length of 1
Ray ray = new Ray(pPos1, dir); Ray ray = new(pPos1, dir);
float dist = maxDist; float dist = maxDist;
if (GetIntersectionTime(ray, ref dist, false, ModelIgnoreFlags.Nothing)) if (GetIntersectionTime(ray, ref dist, false, ModelIgnoreFlags.Nothing))
{ {
@@ -403,7 +403,7 @@ namespace Game.Collision
if (maxDist < 1e-10f) if (maxDist < 1e-10f)
return true; return true;
// direction with length of 1 // direction with length of 1
Ray ray = new Ray(pos1, (pos2 - pos1) / maxDist); Ray ray = new(pos1, (pos2 - pos1) / maxDist);
if (GetIntersectionTime(ray, ref maxDist, true, ignoreFlags)) if (GetIntersectionTime(ray, ref maxDist, true, ignoreFlags))
return false; return false;
@@ -413,13 +413,13 @@ namespace Game.Collision
public int NumLoadedTiles() { return iLoadedTiles.Count; } public int NumLoadedTiles() { return iLoadedTiles.Count; }
uint iMapID; uint iMapID;
BIH iTree = new BIH(); BIH iTree = new();
ModelInstance[] iTreeValues; ModelInstance[] iTreeValues;
uint iNTreeValues; uint iNTreeValues;
Dictionary<uint, uint> iSpawnIndices = new Dictionary<uint, uint>(); Dictionary<uint, uint> iSpawnIndices = new();
Dictionary<uint, bool> iLoadedTiles = new Dictionary<uint, bool>(); Dictionary<uint, bool> iLoadedTiles = new();
Dictionary<uint, uint> iLoadedSpawns = new Dictionary<uint, uint>(); Dictionary<uint, uint> iLoadedSpawns = new();
} }
class TileFileOpenResult class TileFileOpenResult
@@ -25,7 +25,7 @@ namespace Game.Collision
{ {
public class StaticModelList public class StaticModelList
{ {
public static Dictionary<uint, GameobjectModelData> models = new Dictionary<uint, GameobjectModelData>(); public static Dictionary<uint, GameobjectModelData> models = new();
} }
public abstract class GameObjectModelOwnerBase public abstract class GameObjectModelOwnerBase
@@ -47,7 +47,7 @@ namespace Game.Collision
if (modelData == null) if (modelData == null)
return false; return false;
AxisAlignedBox mdl_box = new AxisAlignedBox(modelData.bound); AxisAlignedBox mdl_box = new(modelData.bound);
// ignore models with no bounds // ignore models with no bounds
if (mdl_box == AxisAlignedBox.Zero()) if (mdl_box == AxisAlignedBox.Zero())
{ {
@@ -69,7 +69,7 @@ namespace Game.Collision
iInvRot = iRotation.inverse(); iInvRot = iRotation.inverse();
// transform bounding box: // transform bounding box:
mdl_box = new AxisAlignedBox(mdl_box.Lo * iScale, mdl_box.Hi * iScale); mdl_box = new AxisAlignedBox(mdl_box.Lo * iScale, mdl_box.Hi * iScale);
AxisAlignedBox rotated_bounds = new AxisAlignedBox(); AxisAlignedBox rotated_bounds = new();
for (int i = 0; i < 8; ++i) for (int i = 0; i < 8; ++i)
rotated_bounds.merge(iRotation * mdl_box.corner(i)); rotated_bounds.merge(iRotation * mdl_box.corner(i));
@@ -81,7 +81,7 @@ namespace Game.Collision
public static GameObjectModel Create(GameObjectModelOwnerBase modelOwner) public static GameObjectModel Create(GameObjectModelOwnerBase modelOwner)
{ {
GameObjectModel mdl = new GameObjectModel(); GameObjectModel mdl = new();
if (!mdl.Initialize(modelOwner)) if (!mdl.Initialize(modelOwner))
return null; return null;
@@ -102,7 +102,7 @@ namespace Game.Collision
// child bounds are defined in object space: // child bounds are defined in object space:
Vector3 p = iInvRot * (ray.Origin - iPos) * iInvScale; Vector3 p = iInvRot * (ray.Origin - iPos) * iInvScale;
Ray modRay = new Ray(p, iInvRot * ray.Direction); Ray modRay = new(p, iInvRot * ray.Direction);
float distance = maxDist * iInvScale; float distance = maxDist * iInvScale;
bool hit = iModel.IntersectRay(modRay, ref distance, stopAtFirstHit, ignoreFlags); bool hit = iModel.IntersectRay(modRay, ref distance, stopAtFirstHit, ignoreFlags);
if (hit) if (hit)
@@ -149,7 +149,7 @@ namespace Game.Collision
if (it == null) if (it == null)
return false; return false;
AxisAlignedBox mdl_box = new AxisAlignedBox(it.bound); AxisAlignedBox mdl_box = new(it.bound);
// ignore models with no bounds // ignore models with no bounds
if (mdl_box == AxisAlignedBox.Zero()) if (mdl_box == AxisAlignedBox.Zero())
{ {
@@ -163,7 +163,7 @@ namespace Game.Collision
iInvRot = iRotation.inverse(); iInvRot = iRotation.inverse();
// transform bounding box: // transform bounding box:
mdl_box = new AxisAlignedBox(mdl_box.Lo * iScale, mdl_box.Hi * iScale); mdl_box = new AxisAlignedBox(mdl_box.Lo * iScale, mdl_box.Hi * iScale);
AxisAlignedBox rotated_bounds = new AxisAlignedBox(); AxisAlignedBox rotated_bounds = new();
for (int i = 0; i < 8; ++i) for (int i = 0; i < 8; ++i)
rotated_bounds.merge(iRotation * mdl_box.corner(i)); rotated_bounds.merge(iRotation * mdl_box.corner(i));
@@ -190,7 +190,7 @@ namespace Game.Collision
} }
try try
{ {
using (BinaryReader reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read))) using (BinaryReader reader = new(new FileStream(filename, FileMode.Open, FileAccess.Read)))
{ {
string magic = reader.ReadStringFromChars(8); string magic = reader.ReadStringFromChars(8);
if (magic != MapConst.VMapMagic) if (magic != MapConst.VMapMagic)
@@ -105,7 +105,7 @@ namespace Game.Collision
// child bounds are defined in object space: // child bounds are defined in object space:
Vector3 p = iInvRot * (pRay.Origin - iPos) * iInvScale; Vector3 p = iInvRot * (pRay.Origin - iPos) * iInvScale;
Ray modRay = new Ray(p, iInvRot * pRay.Direction); Ray modRay = new(p, iInvRot * pRay.Direction);
float distance = pMaxDist * iInvScale; float distance = pMaxDist * iInvScale;
bool hit = iModel.IntersectRay(modRay, ref distance, pStopAtFirstHit, ignoreFlags); bool hit = iModel.IntersectRay(modRay, ref distance, pStopAtFirstHit, ignoreFlags);
if (hit) if (hit)
+13 -13
View File
@@ -130,7 +130,7 @@ namespace Game.Collision
public static WmoLiquid ReadFromFile(BinaryReader reader) public static WmoLiquid ReadFromFile(BinaryReader reader)
{ {
WmoLiquid liquid = new WmoLiquid(); WmoLiquid liquid = new();
liquid.iTilesX = reader.ReadUInt32(); liquid.iTilesX = reader.ReadUInt32();
liquid.iTilesY = reader.ReadUInt32(); liquid.iTilesY = reader.ReadUInt32();
@@ -254,7 +254,7 @@ namespace Game.Collision
if (triangles.Empty()) if (triangles.Empty())
return false; return false;
GModelRayCallback callback = new GModelRayCallback(triangles, vertices); GModelRayCallback callback = new(triangles, vertices);
meshTree.IntersectRay(ray, callback, ref distance, stopAtFirstHit); meshTree.IntersectRay(ray, callback, ref distance, stopAtFirstHit);
return callback.hit; return callback.hit;
} }
@@ -267,7 +267,7 @@ namespace Game.Collision
Vector3 rPos = pos - 0.1f * down; Vector3 rPos = pos - 0.1f * down;
float dist = float.PositiveInfinity; float dist = float.PositiveInfinity;
Ray ray = new Ray(rPos, down); Ray ray = new(rPos, down);
bool hit = IntersectRay(ray, ref dist, false); bool hit = IntersectRay(ray, ref dist, false);
if (hit) if (hit)
z_dist = dist - 0.1f; z_dist = dist - 0.1f;
@@ -298,9 +298,9 @@ namespace Game.Collision
AxisAlignedBox iBound; AxisAlignedBox iBound;
uint iMogpFlags; uint iMogpFlags;
uint iGroupWMOID; uint iGroupWMOID;
List<Vector3> vertices = new List<Vector3>(); List<Vector3> vertices = new();
List<MeshTriangle> triangles = new List<MeshTriangle>(); List<MeshTriangle> triangles = new();
BIH meshTree = new BIH(); BIH meshTree = new();
WmoLiquid iLiquid; WmoLiquid iLiquid;
} }
@@ -326,7 +326,7 @@ namespace Game.Collision
if (groupModels.Count == 1) if (groupModels.Count == 1)
return groupModels[0].IntersectRay(ray, ref distance, stopAtFirstHit); return groupModels[0].IntersectRay(ray, ref distance, stopAtFirstHit);
WModelRayCallBack isc = new WModelRayCallBack(groupModels); WModelRayCallBack isc = new(groupModels);
groupTree.IntersectRay(ray, isc, ref distance, stopAtFirstHit); groupTree.IntersectRay(ray, isc, ref distance, stopAtFirstHit);
return isc.hit; return isc.hit;
} }
@@ -337,7 +337,7 @@ namespace Game.Collision
if (groupModels.Empty()) if (groupModels.Empty())
return false; return false;
WModelAreaCallback callback = new WModelAreaCallback(groupModels, down); WModelAreaCallback callback = new(groupModels, down);
groupTree.IntersectPoint(p, callback); groupTree.IntersectPoint(p, callback);
if (callback.hit != null) if (callback.hit != null)
{ {
@@ -357,7 +357,7 @@ namespace Game.Collision
if (groupModels.Empty()) if (groupModels.Empty())
return false; return false;
WModelAreaCallback callback = new WModelAreaCallback(groupModels, down); WModelAreaCallback callback = new(groupModels, down);
groupTree.IntersectPoint(p, callback); groupTree.IntersectPoint(p, callback);
if (callback.hit != null) if (callback.hit != null)
{ {
@@ -378,7 +378,7 @@ namespace Game.Collision
return false; return false;
} }
using (BinaryReader reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read))) using (BinaryReader reader = new(new FileStream(filename, FileMode.Open, FileAccess.Read)))
{ {
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic) if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
return false; return false;
@@ -396,7 +396,7 @@ namespace Game.Collision
uint count = reader.ReadUInt32(); uint count = reader.ReadUInt32();
for (var i = 0; i < count; ++i) for (var i = 0; i < count; ++i)
{ {
GroupModel group = new GroupModel(); GroupModel group = new();
group.ReadFromFile(reader); group.ReadFromFile(reader);
groupModels.Add(group); groupModels.Add(group);
} }
@@ -409,8 +409,8 @@ namespace Game.Collision
} }
} }
List<GroupModel> groupModels = new List<GroupModel>(); List<GroupModel> groupModels = new();
BIH groupTree = new BIH(); BIH groupTree = new();
uint RootWMOID; uint RootWMOID;
public uint Flags; public uint Flags;
} }
+2 -2
View File
@@ -89,7 +89,7 @@ namespace Game.Collision
public static Cell ComputeCell(float fx, float fy) public static Cell ComputeCell(float fx, float fy)
{ {
Cell c = new Cell(); Cell c = new();
c.x = (int)(fx * (1.0f / CELL_SIZE) + (CELL_NUMBER / 2f)); c.x = (int)(fx * (1.0f / CELL_SIZE) + (CELL_NUMBER / 2f));
c.y = (int)(fy * (1.0f / CELL_SIZE) + (CELL_NUMBER / 2f)); c.y = (int)(fy * (1.0f / CELL_SIZE) + (CELL_NUMBER / 2f));
return c; return c;
@@ -206,7 +206,7 @@ namespace Game.Collision
node.IntersectRay(ray, intersectCallback, ref max_dist); node.IntersectRay(ray, intersectCallback, ref max_dist);
} }
MultiMap<T, Node> memberTable = new MultiMap<T, Node>(); MultiMap<T, Node> memberTable = new();
Node[][] nodes = new Node[CELL_NUMBER][]; Node[][] nodes = new Node[CELL_NUMBER][];
} }
} }
+5 -5
View File
@@ -238,7 +238,7 @@ namespace Game.Combat
if (!IsOnline()) if (!IsOnline())
UpdateOnlineStatus(); UpdateOnlineStatus();
ThreatRefStatusChangeEvent Event = new ThreatRefStatusChangeEvent(UnitEventTypes.ThreatRefThreatChange, this, modThreat); ThreatRefStatusChangeEvent Event = new(UnitEventTypes.ThreatRefThreatChange, this, modThreat);
FireStatusChanged(Event); FireStatusChanged(Event);
if (IsValid() && modThreat > 0.0f) if (IsValid() && modThreat > 0.0f)
@@ -300,7 +300,7 @@ namespace Game.Combat
if (!iOnline) if (!iOnline)
SetAccessibleState(false); // if not online that not accessable as well SetAccessibleState(false); // if not online that not accessable as well
ThreatRefStatusChangeEvent Event = new ThreatRefStatusChangeEvent(UnitEventTypes.ThreatRefOnlineStatus, this); ThreatRefStatusChangeEvent Event = new(UnitEventTypes.ThreatRefOnlineStatus, this);
FireStatusChanged(Event); FireStatusChanged(Event);
} }
} }
@@ -311,7 +311,7 @@ namespace Game.Combat
{ {
iAccessible = isAccessible; iAccessible = isAccessible;
ThreatRefStatusChangeEvent Event = new ThreatRefStatusChangeEvent(UnitEventTypes.ThreatRefAccessibleStatus, this); ThreatRefStatusChangeEvent Event = new(UnitEventTypes.ThreatRefAccessibleStatus, this);
FireStatusChanged(Event); FireStatusChanged(Event);
} }
} }
@@ -321,7 +321,7 @@ namespace Game.Combat
{ {
Invalidate(); Invalidate();
ThreatRefStatusChangeEvent Event = new ThreatRefStatusChangeEvent(UnitEventTypes.ThreatRefRemoveFromList, this); ThreatRefStatusChangeEvent Event = new(UnitEventTypes.ThreatRefRemoveFromList, this);
FireStatusChanged(Event); FireStatusChanged(Event);
} }
@@ -366,7 +366,7 @@ namespace Game.Combat
iTempThreatModifier += threat; iTempThreatModifier += threat;
ThreatRefStatusChangeEvent Event = new ThreatRefStatusChangeEvent(UnitEventTypes.ThreatRefThreatChange, this, threat); ThreatRefStatusChangeEvent Event = new(UnitEventTypes.ThreatRefThreatChange, this, threat);
FireStatusChanged(Event); FireStatusChanged(Event);
} }
+1 -1
View File
@@ -521,7 +521,7 @@ namespace Game.Conditions
public string ToString(bool ext = false) public string ToString(bool ext = false)
{ {
StringBuilder ss = new StringBuilder(); StringBuilder ss = new();
ss.AppendFormat("[Condition SourceType: {0}", SourceType); ss.AppendFormat("[Condition SourceType: {0}", SourceType);
if (SourceType < ConditionSourceType.Max) if (SourceType < ConditionSourceType.Max)
ss.AppendFormat(" ({0})", Global.ConditionMgr.StaticSourceTypeData[(int)SourceType]); ss.AppendFormat(" ({0})", Global.ConditionMgr.StaticSourceTypeData[(int)SourceType]);
+18 -18
View File
@@ -38,7 +38,7 @@ namespace Game
if (conditions.Empty()) if (conditions.Empty())
return GridMapTypeMask.All; return GridMapTypeMask.All;
// groupId, typeMask // groupId, typeMask
Dictionary<uint, GridMapTypeMask> elseGroupSearcherTypeMasks = new Dictionary<uint, GridMapTypeMask>(); Dictionary<uint, GridMapTypeMask> elseGroupSearcherTypeMasks = new();
foreach (var i in conditions) foreach (var i in conditions)
{ {
// no point of having not loaded conditions in list // no point of having not loaded conditions in list
@@ -75,7 +75,7 @@ namespace Game
public bool IsObjectMeetToConditionList(ConditionSourceInfo sourceInfo, List<Condition> conditions) public bool IsObjectMeetToConditionList(ConditionSourceInfo sourceInfo, List<Condition> conditions)
{ {
// groupId, groupCheckPassed // groupId, groupCheckPassed
Dictionary<uint, bool> elseGroupStore = new Dictionary<uint, bool>(); Dictionary<uint, bool> elseGroupStore = new();
foreach (var condition in conditions) foreach (var condition in conditions)
{ {
Log.outDebug(LogFilter.Condition, "ConditionMgr.IsPlayerMeetToConditionList condType: {0} val1: {1}", condition.ConditionType, condition.ConditionValue1); Log.outDebug(LogFilter.Condition, "ConditionMgr.IsPlayerMeetToConditionList condType: {0} val1: {1}", condition.ConditionType, condition.ConditionValue1);
@@ -119,13 +119,13 @@ namespace Game
public bool IsObjectMeetToConditions(WorldObject obj, List<Condition> conditions) public bool IsObjectMeetToConditions(WorldObject obj, List<Condition> conditions)
{ {
ConditionSourceInfo srcInfo = new ConditionSourceInfo(obj); ConditionSourceInfo srcInfo = new(obj);
return IsObjectMeetToConditions(srcInfo, conditions); return IsObjectMeetToConditions(srcInfo, conditions);
} }
public bool IsObjectMeetToConditions(WorldObject obj1, WorldObject obj2, List<Condition> conditions) public bool IsObjectMeetToConditions(WorldObject obj1, WorldObject obj2, List<Condition> conditions)
{ {
ConditionSourceInfo srcInfo = new ConditionSourceInfo(obj1, obj2); ConditionSourceInfo srcInfo = new(obj1, obj2);
return IsObjectMeetToConditions(srcInfo, conditions); return IsObjectMeetToConditions(srcInfo, conditions);
} }
@@ -184,7 +184,7 @@ namespace Game
public bool IsObjectMeetingNotGroupedConditions(ConditionSourceType sourceType, uint entry, WorldObject target0, WorldObject target1 = null, WorldObject target2 = null) public bool IsObjectMeetingNotGroupedConditions(ConditionSourceType sourceType, uint entry, WorldObject target0, WorldObject target1 = null, WorldObject target2 = null)
{ {
ConditionSourceInfo conditionSource = new ConditionSourceInfo(target0, target1, target2); ConditionSourceInfo conditionSource = new(target0, target1, target2);
return IsObjectMeetingNotGroupedConditions(sourceType, entry, conditionSource); return IsObjectMeetingNotGroupedConditions(sourceType, entry, conditionSource);
} }
@@ -206,7 +206,7 @@ namespace Game
if (!conditions.Empty()) if (!conditions.Empty())
{ {
Log.outDebug(LogFilter.Condition, "GetConditionsForSpellClickEvent: found conditions for SpellClickEvent entry {0} spell {1}", creatureId, spellId); Log.outDebug(LogFilter.Condition, "GetConditionsForSpellClickEvent: found conditions for SpellClickEvent entry {0} spell {1}", creatureId, spellId);
ConditionSourceInfo sourceInfo = new ConditionSourceInfo(clicker, target); ConditionSourceInfo sourceInfo = new(clicker, target);
return IsObjectMeetToConditions(sourceInfo, conditions); return IsObjectMeetToConditions(sourceInfo, conditions);
} }
} }
@@ -237,7 +237,7 @@ namespace Game
if (!conditions.Empty()) if (!conditions.Empty())
{ {
Log.outDebug(LogFilter.Condition, "GetConditionsForVehicleSpell: found conditions for Vehicle entry {0} spell {1}", creatureId, spellId); Log.outDebug(LogFilter.Condition, "GetConditionsForVehicleSpell: found conditions for Vehicle entry {0} spell {1}", creatureId, spellId);
ConditionSourceInfo sourceInfo = new ConditionSourceInfo(player, vehicle); ConditionSourceInfo sourceInfo = new(player, vehicle);
return IsObjectMeetToConditions(sourceInfo, conditions); return IsObjectMeetToConditions(sourceInfo, conditions);
} }
} }
@@ -253,7 +253,7 @@ namespace Game
if (!conditions.Empty()) if (!conditions.Empty())
{ {
Log.outDebug(LogFilter.Condition, "GetConditionsForSmartEvent: found conditions for Smart Event entry or guid {0} eventId {1}", entryOrGuid, eventId); Log.outDebug(LogFilter.Condition, "GetConditionsForSmartEvent: found conditions for Smart Event entry or guid {0} eventId {1}", entryOrGuid, eventId);
ConditionSourceInfo sourceInfo = new ConditionSourceInfo(unit, baseObject); ConditionSourceInfo sourceInfo = new(unit, baseObject);
return IsObjectMeetToConditions(sourceInfo, conditions); return IsObjectMeetToConditions(sourceInfo, conditions);
} }
} }
@@ -269,7 +269,7 @@ namespace Game
if (!conditions.Empty()) if (!conditions.Empty())
{ {
Log.outDebug(LogFilter.Condition, "GetConditionsForNpcVendorEvent: found conditions for creature entry {0} item {1}", creatureId, itemId); Log.outDebug(LogFilter.Condition, "GetConditionsForNpcVendorEvent: found conditions for creature entry {0} item {1}", creatureId, itemId);
ConditionSourceInfo sourceInfo = new ConditionSourceInfo(player, vendor); ConditionSourceInfo sourceInfo = new(player, vendor);
return IsObjectMeetToConditions(sourceInfo, conditions); return IsObjectMeetToConditions(sourceInfo, conditions);
} }
} }
@@ -321,7 +321,7 @@ namespace Game
uint count = 0; uint count = 0;
do do
{ {
Condition cond = new Condition(); Condition cond = new();
int iSourceTypeOrReferenceId = result.Read<int>(0); int iSourceTypeOrReferenceId = result.Read<int>(0);
cond.SourceGroup = result.Read<uint>(1); cond.SourceGroup = result.Read<uint>(1);
cond.SourceEntry = result.Read<int>(2); cond.SourceEntry = result.Read<int>(2);
@@ -579,7 +579,7 @@ namespace Game
Global.SpellMgr.ForEachSpellInfoDifficulty((uint)cond.SourceEntry, spellInfo => Global.SpellMgr.ForEachSpellInfoDifficulty((uint)cond.SourceEntry, spellInfo =>
{ {
uint conditionEffMask = cond.SourceGroup; uint conditionEffMask = cond.SourceGroup;
List<uint> sharedMasks = new List<uint>(); List<uint> sharedMasks = new();
for (byte i = 0; i < SpellConst.MaxEffects; ++i) for (byte i = 0; i < SpellConst.MaxEffects; ++i)
{ {
SpellEffectInfo effect = spellInfo.GetEffect(i); SpellEffectInfo effect = spellInfo.GetEffect(i);
@@ -2167,7 +2167,7 @@ namespace Game
public static bool IsPlayerMeetingExpression(Player player, WorldStateExpressionRecord expression) public static bool IsPlayerMeetingExpression(Player player, WorldStateExpressionRecord expression)
{ {
ByteBuffer buffer = new ByteBuffer(expression.Expression.ToByteArray()); ByteBuffer buffer = new(expression.Expression.ToByteArray());
if (buffer.GetSize() == 0) if (buffer.GetSize() == 0)
return false; return false;
@@ -2387,12 +2387,12 @@ namespace Game
return false; return false;
} }
Dictionary<ConditionSourceType, MultiMap<uint, Condition>> ConditionStore = new Dictionary<ConditionSourceType, MultiMap<uint, Condition>>(); Dictionary<ConditionSourceType, MultiMap<uint, Condition>> ConditionStore = new();
MultiMap<uint, Condition> ConditionReferenceStore = new MultiMap<uint, Condition>(); MultiMap<uint, Condition> ConditionReferenceStore = new();
Dictionary<uint, MultiMap<uint, Condition>> VehicleSpellConditionStore = new Dictionary<uint, MultiMap<uint, Condition>>(); Dictionary<uint, MultiMap<uint, Condition>> VehicleSpellConditionStore = new();
Dictionary<uint, MultiMap<uint, Condition>> SpellClickEventConditionStore = new Dictionary<uint, MultiMap<uint, Condition>>(); Dictionary<uint, MultiMap<uint, Condition>> SpellClickEventConditionStore = new();
Dictionary<uint, MultiMap<uint, Condition>> NpcVendorConditionContainerStore = new Dictionary<uint, MultiMap<uint, Condition>>(); Dictionary<uint, MultiMap<uint, Condition>> NpcVendorConditionContainerStore = new();
Dictionary<Tuple<int, uint>, MultiMap<uint, Condition>> SmartEventConditionStore = new Dictionary<Tuple<int, uint>, MultiMap<uint, Condition>>(); Dictionary<Tuple<int, uint>, MultiMap<uint, Condition>> SmartEventConditionStore = new();
public string[] StaticSourceTypeData = public string[] StaticSourceTypeData =
{ {
+4 -4
View File
@@ -32,11 +32,11 @@ namespace Game
public class DisableData public class DisableData
{ {
public byte flags; public byte flags;
public List<uint> param0 = new List<uint>(); public List<uint> param0 = new();
public List<uint> param1 = new List<uint>(); public List<uint> param1 = new();
} }
Dictionary<DisableType, Dictionary<uint, DisableData>> m_DisableMap = new Dictionary<DisableType, Dictionary<uint, DisableData>>(); Dictionary<DisableType, Dictionary<uint, DisableData>> m_DisableMap = new();
public void LoadDisables() public void LoadDisables()
{ {
@@ -67,7 +67,7 @@ namespace Game
string params_0 = result.Read<string>(3); string params_0 = result.Read<string>(3);
string params_1 = result.Read<string>(4); string params_1 = result.Read<string>(4);
DisableData data = new DisableData(); DisableData data = new();
data.flags = flags; data.flags = flags;
switch (type) switch (type)
@@ -31,10 +31,10 @@ namespace Game.DataStorage
public void LoadAreaTriggerTemplates() public void LoadAreaTriggerTemplates()
{ {
uint oldMSTime = Time.GetMSTime(); uint oldMSTime = Time.GetMSTime();
MultiMap<uint, Vector2> verticesByAreaTrigger = new MultiMap<uint, Vector2>(); MultiMap<uint, Vector2> verticesByAreaTrigger = new();
MultiMap<uint, Vector2> verticesTargetByAreaTrigger = new MultiMap<uint, Vector2>(); MultiMap<uint, Vector2> verticesTargetByAreaTrigger = new();
MultiMap<uint, Vector3> splinesBySpellMisc = new MultiMap<uint, Vector3>(); MultiMap<uint, Vector3> splinesBySpellMisc = new();
MultiMap<AreaTriggerId, AreaTriggerAction> actionsByAreaTrigger = new MultiMap<AreaTriggerId, AreaTriggerAction>(); MultiMap<AreaTriggerId, AreaTriggerAction> actionsByAreaTrigger = new();
// 0 1 2 3 4 // 0 1 2 3 4
SQLResult templateActions = DB.World.Query("SELECT AreaTriggerId, IsServerSide, ActionType, ActionParam, TargetType FROM `areatrigger_template_actions`"); SQLResult templateActions = DB.World.Query("SELECT AreaTriggerId, IsServerSide, ActionType, ActionParam, TargetType FROM `areatrigger_template_actions`");
@@ -110,7 +110,7 @@ namespace Game.DataStorage
{ {
uint spellMiscId = splines.Read<uint>(0); uint spellMiscId = splines.Read<uint>(0);
Vector3 spline = new Vector3(splines.Read<float>(1), splines.Read<float>(2), splines.Read<float>(3)); Vector3 spline = new(splines.Read<float>(1), splines.Read<float>(2), splines.Read<float>(3));
splinesBySpellMisc.Add(spellMiscId, spline); splinesBySpellMisc.Add(spellMiscId, spline);
} }
@@ -127,7 +127,7 @@ namespace Game.DataStorage
{ {
do do
{ {
AreaTriggerTemplate areaTriggerTemplate = new AreaTriggerTemplate(); AreaTriggerTemplate areaTriggerTemplate = new();
areaTriggerTemplate.Id = new(templates.Read<uint>(0), templates.Read<byte>(1) == 1); areaTriggerTemplate.Id = new(templates.Read<uint>(0), templates.Read<byte>(1) == 1);
AreaTriggerTypes type = (AreaTriggerTypes)templates.Read<byte>(2); AreaTriggerTypes type = (AreaTriggerTypes)templates.Read<byte>(2);
@@ -172,7 +172,7 @@ namespace Game.DataStorage
{ {
do do
{ {
AreaTriggerMiscTemplate miscTemplate = new AreaTriggerMiscTemplate(); AreaTriggerMiscTemplate miscTemplate = new();
miscTemplate.MiscId = areatriggerSpellMiscs.Read<uint>(0); miscTemplate.MiscId = areatriggerSpellMiscs.Read<uint>(0);
uint areatriggerId = areatriggerSpellMiscs.Read<uint>(1); uint areatriggerId = areatriggerSpellMiscs.Read<uint>(1);
@@ -233,7 +233,7 @@ namespace Game.DataStorage
continue; continue;
} }
AreaTriggerOrbitInfo orbitInfo = new AreaTriggerOrbitInfo(); AreaTriggerOrbitInfo orbitInfo = new();
orbitInfo.StartDelay = circularMovementInfos.Read<uint>(1); orbitInfo.StartDelay = circularMovementInfos.Read<uint>(1);
orbitInfo.Radius = circularMovementInfos.Read<float>(2); orbitInfo.Radius = circularMovementInfos.Read<float>(2);
@@ -305,7 +305,7 @@ namespace Game.DataStorage
continue; continue;
} }
AreaTriggerSpawn spawn = new AreaTriggerSpawn(); AreaTriggerSpawn spawn = new();
spawn.SpawnId = spawnId; spawn.SpawnId = spawnId;
spawn.Id = areaTriggerId; spawn.Id = areaTriggerId;
spawn.Location = new WorldLocation(location); spawn.Location = new WorldLocation(location);
@@ -349,9 +349,9 @@ namespace Game.DataStorage
return _areaTriggerSpawnsBySpawnId.LookupByKey(spawnId); return _areaTriggerSpawnsBySpawnId.LookupByKey(spawnId);
} }
Dictionary<(uint mapId, uint cellId), SortedSet<ulong>> _areaTriggerSpawnsByLocation = new Dictionary<(uint mapId, uint cellId), SortedSet<ulong>>(); Dictionary<(uint mapId, uint cellId), SortedSet<ulong>> _areaTriggerSpawnsByLocation = new();
Dictionary<ulong, AreaTriggerSpawn> _areaTriggerSpawnsBySpawnId = new Dictionary<ulong, AreaTriggerSpawn>(); Dictionary<ulong, AreaTriggerSpawn> _areaTriggerSpawnsBySpawnId = new();
Dictionary<AreaTriggerId, AreaTriggerTemplate> _areaTriggerTemplateStore = new Dictionary<AreaTriggerId, AreaTriggerTemplate>(); Dictionary<AreaTriggerId, AreaTriggerTemplate> _areaTriggerTemplateStore = new();
Dictionary<uint, AreaTriggerMiscTemplate> _areaTriggerTemplateSpellMisc = new Dictionary<uint, AreaTriggerMiscTemplate>(); Dictionary<uint, AreaTriggerMiscTemplate> _areaTriggerTemplateSpellMisc = new();
} }
} }
@@ -30,7 +30,7 @@ namespace Game.DataStorage
uint oldMSTime = Time.GetMSTime(); uint oldMSTime = Time.GetMSTime();
_characterTemplateStore.Clear(); _characterTemplateStore.Clear();
MultiMap<uint, CharacterTemplateClass> characterTemplateClasses = new MultiMap<uint, CharacterTemplateClass>(); MultiMap<uint, CharacterTemplateClass> characterTemplateClasses = new();
SQLResult classesResult = DB.World.Query("SELECT TemplateId, FactionGroup, Class FROM character_template_class"); SQLResult classesResult = DB.World.Query("SELECT TemplateId, FactionGroup, Class FROM character_template_class");
if (!classesResult.IsEmpty()) if (!classesResult.IsEmpty())
{ {
@@ -71,7 +71,7 @@ namespace Game.DataStorage
do do
{ {
CharacterTemplate templ = new CharacterTemplate(); CharacterTemplate templ = new();
templ.TemplateSetId = templates.Read<uint>(0); templ.TemplateSetId = templates.Read<uint>(0);
templ.Name = templates.Read<string>(1); templ.Name = templates.Read<string>(1);
templ.Description = templates.Read<string>(2); templ.Description = templates.Read<string>(2);
@@ -101,7 +101,7 @@ namespace Game.DataStorage
return _characterTemplateStore.LookupByKey(templateId); return _characterTemplateStore.LookupByKey(templateId);
} }
Dictionary<uint, CharacterTemplate> _characterTemplateStore = new Dictionary<uint, CharacterTemplate>(); Dictionary<uint, CharacterTemplate> _characterTemplateStore = new();
} }
public struct CharacterTemplateClass public struct CharacterTemplateClass
+3 -3
View File
@@ -33,7 +33,7 @@ namespace Game.DataStorage
string db2Path = dataPath + "/dbc"; string db2Path = dataPath + "/dbc";
BitSet availableDb2Locales = new BitSet((int)Locale.Total); BitSet availableDb2Locales = new((int)Locale.Total);
foreach (var dir in Directory.GetDirectories(db2Path)) foreach (var dir in Directory.GetDirectories(db2Path))
{ {
Locale locale = Path.GetFileName(dir).ToEnum<Locale>(); Locale locale = Path.GetFileName(dir).ToEnum<Locale>();
@@ -698,8 +698,8 @@ namespace Game.DataStorage
public static byte[] OldContinentsNodesMask = new byte[PlayerConst.TaxiMaskSize]; public static byte[] OldContinentsNodesMask = new byte[PlayerConst.TaxiMaskSize];
public static byte[] HordeTaxiNodesMask = new byte[PlayerConst.TaxiMaskSize]; public static byte[] HordeTaxiNodesMask = new byte[PlayerConst.TaxiMaskSize];
public static byte[] AllianceTaxiNodesMask = new byte[PlayerConst.TaxiMaskSize]; public static byte[] AllianceTaxiNodesMask = new byte[PlayerConst.TaxiMaskSize];
public static Dictionary<uint, Dictionary<uint, TaxiPathBySourceAndDestination>> TaxiPathSetBySource = new Dictionary<uint, Dictionary<uint, TaxiPathBySourceAndDestination>>(); public static Dictionary<uint, Dictionary<uint, TaxiPathBySourceAndDestination>> TaxiPathSetBySource = new();
public static Dictionary<uint, TaxiPathNodeRecord[]> TaxiPathNodesByPath = new Dictionary<uint, TaxiPathNodeRecord[]>(); public static Dictionary<uint, TaxiPathNodeRecord[]> TaxiPathNodesByPath = new();
#endregion #endregion
#region Helper Methods #region Helper Methods
@@ -159,7 +159,7 @@ namespace Game.DataStorage
case TypeCode.Object: case TypeCode.Object:
if (type == typeof(LocalizedString)) if (type == typeof(LocalizedString))
{ {
LocalizedString locString = new LocalizedString(); LocalizedString locString = new();
locString[Global.WorldMgr.GetDefaultDbcLocale()] = result.Read<string>(dbIndex++); locString[Global.WorldMgr.GetDefaultDbcLocale()] = result.Read<string>(dbIndex++);
f.SetValue(obj, locString); f.SetValue(obj, locString);
@@ -37,7 +37,7 @@ namespace Game.DataStorage
public static DB6Storage<T> Read<T>(BitSet availableDb2Locales, string db2Path, string fileName, HotfixStatements preparedStatement, HotfixStatements preparedStatementLocale, ref uint loadedFileCount) where T : new() public static DB6Storage<T> Read<T>(BitSet availableDb2Locales, string db2Path, string fileName, HotfixStatements preparedStatement, HotfixStatements preparedStatementLocale, ref uint loadedFileCount) where T : new()
{ {
DB6Storage<T> storage = new DB6Storage<T>(); DB6Storage<T> storage = new();
if (!File.Exists(db2Path + fileName)) if (!File.Exists(db2Path + fileName))
{ {
@@ -45,7 +45,7 @@ namespace Game.DataStorage
return storage; return storage;
} }
DBReader reader = new DBReader(); DBReader reader = new();
using (var stream = new FileStream(db2Path + fileName, FileMode.Open)) using (var stream = new FileStream(db2Path + fileName, FileMode.Open))
{ {
if (!reader.Load(stream)) if (!reader.Load(stream))
@@ -118,7 +118,7 @@ namespace Game.DataStorage
{ {
if (ColumnMeta[i].CompressionType == DB2ColumnCompression.Common) if (ColumnMeta[i].CompressionType == DB2ColumnCompression.Common)
{ {
Dictionary<int, Value32> commonValues = new Dictionary<int, Value32>(); Dictionary<int, Value32> commonValues = new();
CommonData[i] = commonValues; CommonData[i] = commonValues;
for (int j = 0; j < ColumnMeta[i].AdditionalDataSize / 8; j++) for (int j = 0; j < ColumnMeta[i].AdditionalDataSize / 8; j++)
@@ -177,7 +177,7 @@ namespace Game.DataStorage
bool isIndexEmpty = Header.HasIndexTable() && indexData.Count(i => i == 0) == sections[sectionIndex].NumRecords; bool isIndexEmpty = Header.HasIndexTable() && indexData.Count(i => i == 0) == sections[sectionIndex].NumRecords;
// duplicate rows data // duplicate rows data
Dictionary<int, int> copyData = new Dictionary<int, int>(); Dictionary<int, int> copyData = new();
for (int i = 0; i < sections[sectionIndex].NumCopyRecords; i++) for (int i = 0; i < sections[sectionIndex].NumCopyRecords; i++)
copyData[reader.ReadInt32()] = reader.ReadInt32(); copyData[reader.ReadInt32()] = reader.ReadInt32();
@@ -222,7 +222,7 @@ namespace Game.DataStorage
//indexData = sparseIndexData; //indexData = sparseIndexData;
} }
BitReader bitReader = new BitReader(recordsData); BitReader bitReader = new(recordsData);
for (int i = 0; i < sections[sectionIndex].NumRecords; ++i) for (int i = 0; i < sections[sectionIndex].NumRecords; ++i)
{ {
@@ -262,7 +262,7 @@ namespace Game.DataStorage
internal Value32[][] PalletData; internal Value32[][] PalletData;
internal Dictionary<int, Value32>[] CommonData; internal Dictionary<int, Value32>[] CommonData;
Dictionary<int, WDC3Row> _records = new Dictionary<int, WDC3Row>(); Dictionary<int, WDC3Row> _records = new();
} }
class WDC3Row class WDC3Row
@@ -393,7 +393,7 @@ namespace Game.DataStorage
_data.Offset = _dataOffset; _data.Offset = _dataOffset;
int fieldIndex = 0; int fieldIndex = 0;
T obj = new T(); T obj = new();
foreach (var f in typeof(T).GetFields()) foreach (var f in typeof(T).GetFields())
{ {
@@ -533,7 +533,7 @@ namespace Game.DataStorage
case TypeCode.Object: case TypeCode.Object:
if (type == typeof(LocalizedString)) if (type == typeof(LocalizedString))
{ {
LocalizedString localized = new LocalizedString(); LocalizedString localized = new();
if (_stringsTable == null) if (_stringsTable == null)
{ {
localized[Locale.enUS] = _data.ReadCString(); localized[Locale.enUS] = _data.ReadCString();
@@ -749,6 +749,6 @@ namespace Game.DataStorage
} }
} }
StringArray stringStorage = new StringArray((int)Locale.Total); StringArray stringStorage = new((int)Locale.Total);
} }
} }
@@ -26,7 +26,7 @@ namespace Game.DataStorage
{ {
internal static GameTable<T> Read<T>(string path, string fileName, ref uint loadedFileCount) where T : new() internal static GameTable<T> Read<T>(string path, string fileName, ref uint loadedFileCount) where T : new()
{ {
GameTable<T> storage = new GameTable<T>(); GameTable<T> storage = new();
if (!File.Exists(path + fileName)) if (!File.Exists(path + fileName))
{ {
@@ -42,7 +42,7 @@ namespace Game.DataStorage
return storage; return storage;
} }
List<T> data = new List<T>(); List<T> data = new();
data.Add(new T()); // row id 0, unused data.Add(new T()); // row id 0, unused
string line; string line;
@@ -92,6 +92,6 @@ namespace Game.DataStorage
public void SetData(List<T> data) { _data = data; } public void SetData(List<T> data) { _data = data; }
List<T> _data = new List<T>(); List<T> _data = new();
} }
} }
@@ -33,8 +33,8 @@ namespace Game.DataStorage
_conversationLineTemplateStorage.Clear(); _conversationLineTemplateStorage.Clear();
_conversationTemplateStorage.Clear(); _conversationTemplateStorage.Clear();
Dictionary<uint, ConversationActorTemplate[]> actorsByConversation = new Dictionary<uint, ConversationActorTemplate[]>(); Dictionary<uint, ConversationActorTemplate[]> actorsByConversation = new();
Dictionary<uint, ulong[]> actorGuidsByConversation = new Dictionary<uint, ulong[]>(); Dictionary<uint, ulong[]> actorGuidsByConversation = new();
SQLResult actorTemplates = DB.World.Query("SELECT Id, CreatureId, CreatureModelId FROM conversation_actor_template"); SQLResult actorTemplates = DB.World.Query("SELECT Id, CreatureId, CreatureModelId FROM conversation_actor_template");
if (!actorTemplates.IsEmpty()) if (!actorTemplates.IsEmpty())
@@ -44,7 +44,7 @@ namespace Game.DataStorage
do do
{ {
uint id = actorTemplates.Read<uint>(0); uint id = actorTemplates.Read<uint>(0);
ConversationActorTemplate conversationActor = new ConversationActorTemplate(); ConversationActorTemplate conversationActor = new();
conversationActor.Id = id; conversationActor.Id = id;
conversationActor.CreatureId = actorTemplates.Read<uint>(1); conversationActor.CreatureId = actorTemplates.Read<uint>(1);
conversationActor.CreatureModelId = actorTemplates.Read<uint>(2); conversationActor.CreatureModelId = actorTemplates.Read<uint>(2);
@@ -75,7 +75,7 @@ namespace Game.DataStorage
continue; continue;
} }
ConversationLineTemplate conversationLine = new ConversationLineTemplate(); ConversationLineTemplate conversationLine = new();
conversationLine.Id = id; conversationLine.Id = id;
conversationLine.StartTime = lineTemplates.Read<uint>(1); conversationLine.StartTime = lineTemplates.Read<uint>(1);
conversationLine.UiCameraID = lineTemplates.Read<uint>(2); conversationLine.UiCameraID = lineTemplates.Read<uint>(2);
@@ -165,7 +165,7 @@ namespace Game.DataStorage
do do
{ {
ConversationTemplate conversationTemplate = new ConversationTemplate(); ConversationTemplate conversationTemplate = new();
conversationTemplate.Id = templateResult.Read<uint>(0); conversationTemplate.Id = templateResult.Read<uint>(0);
conversationTemplate.FirstLineId = templateResult.Read<uint>(1); conversationTemplate.FirstLineId = templateResult.Read<uint>(1);
conversationTemplate.LastLineEndTime = templateResult.Read<uint>(2); conversationTemplate.LastLineEndTime = templateResult.Read<uint>(2);
@@ -210,9 +210,9 @@ namespace Game.DataStorage
return _conversationTemplateStorage.LookupByKey(conversationId); return _conversationTemplateStorage.LookupByKey(conversationId);
} }
Dictionary<uint, ConversationTemplate> _conversationTemplateStorage = new Dictionary<uint, ConversationTemplate>(); Dictionary<uint, ConversationTemplate> _conversationTemplateStorage = new();
Dictionary<uint, ConversationActorTemplate> _conversationActorTemplateStorage = new Dictionary<uint, ConversationActorTemplate>(); Dictionary<uint, ConversationActorTemplate> _conversationActorTemplateStorage = new();
Dictionary<uint, ConversationLineTemplate> _conversationLineTemplateStorage = new Dictionary<uint, ConversationLineTemplate>(); Dictionary<uint, ConversationLineTemplate> _conversationLineTemplateStorage = new();
} }
public class ConversationActorTemplate public class ConversationActorTemplate
@@ -240,9 +240,9 @@ namespace Game.DataStorage
public uint TextureKitId; // Background texture public uint TextureKitId; // Background texture
public uint ScriptId; public uint ScriptId;
public List<ConversationActorTemplate> Actors = new List<ConversationActorTemplate>(); public List<ConversationActorTemplate> Actors = new();
public List<ulong> ActorGuids = new List<ulong>(); public List<ulong> ActorGuids = new();
public List<ConversationLineTemplate> Lines = new List<ConversationLineTemplate>(); public List<ConversationLineTemplate> Lines = new();
} }
+83 -83
View File
@@ -115,7 +115,7 @@ namespace Game.DataStorage
_azeriteTierUnlockLevels[key][azeriteTierUnlock.Tier] = azeriteTierUnlock.AzeriteLevel; _azeriteTierUnlockLevels[key][azeriteTierUnlock.Tier] = azeriteTierUnlock.AzeriteLevel;
} }
MultiMap<uint, AzeriteUnlockMappingRecord> azeriteUnlockMappings = new MultiMap<uint, AzeriteUnlockMappingRecord>(); MultiMap<uint, AzeriteUnlockMappingRecord> azeriteUnlockMappings = new();
foreach (AzeriteUnlockMappingRecord azeriteUnlockMapping in CliDB.AzeriteUnlockMappingStorage.Values) foreach (AzeriteUnlockMappingRecord azeriteUnlockMapping in CliDB.AzeriteUnlockMappingStorage.Values)
azeriteUnlockMappings.Add(azeriteUnlockMapping.AzeriteUnlockMappingSetID, azeriteUnlockMapping); azeriteUnlockMappings.Add(azeriteUnlockMapping.AzeriteUnlockMappingSetID, azeriteUnlockMapping);
@@ -159,8 +159,8 @@ namespace Game.DataStorage
foreach (var customizationChoice in CliDB.ChrCustomizationChoiceStorage.Values) foreach (var customizationChoice in CliDB.ChrCustomizationChoiceStorage.Values)
_chrCustomizationChoicesByOption.Add(customizationChoice.ChrCustomizationOptionID, customizationChoice); _chrCustomizationChoicesByOption.Add(customizationChoice.ChrCustomizationOptionID, customizationChoice);
MultiMap<uint, Tuple<uint, byte>> shapeshiftFormByModel = new MultiMap<uint, Tuple<uint, byte>>(); MultiMap<uint, Tuple<uint, byte>> shapeshiftFormByModel = new();
Dictionary<uint, ChrCustomizationDisplayInfoRecord> displayInfoByCustomizationChoice = new Dictionary<uint, ChrCustomizationDisplayInfoRecord>(); Dictionary<uint, ChrCustomizationDisplayInfoRecord> displayInfoByCustomizationChoice = new();
// build shapeshift form model lookup // build shapeshift form model lookup
foreach (ChrCustomizationElementRecord customizationElement in CliDB.ChrCustomizationElementStorage.Values) foreach (ChrCustomizationElementRecord customizationElement in CliDB.ChrCustomizationElementStorage.Values)
@@ -179,7 +179,7 @@ namespace Game.DataStorage
} }
} }
MultiMap<uint, ChrCustomizationOptionRecord> customizationOptionsByModel = new MultiMap<uint, ChrCustomizationOptionRecord>(); MultiMap<uint, ChrCustomizationOptionRecord> customizationOptionsByModel = new();
foreach (ChrCustomizationOptionRecord customizationOption in CliDB.ChrCustomizationOptionStorage.Values) foreach (ChrCustomizationOptionRecord customizationOption in CliDB.ChrCustomizationOptionStorage.Values)
customizationOptionsByModel.Add(customizationOption.ChrModelID, customizationOption); customizationOptionsByModel.Add(customizationOption.ChrModelID, customizationOption);
@@ -195,7 +195,7 @@ namespace Game.DataStorage
} }
} }
Dictionary<uint, uint> parentRaces = new Dictionary<uint, uint>(); Dictionary<uint, uint> parentRaces = new();
foreach (ChrRacesRecord chrRace in CliDB.ChrRacesStorage.Values) foreach (ChrRacesRecord chrRace in CliDB.ChrRacesStorage.Values)
if (chrRace.UnalteredVisualRaceID != 0) if (chrRace.UnalteredVisualRaceID != 0)
parentRaces[(uint)chrRace.UnalteredVisualRaceID] = chrRace.Id; parentRaces[(uint)chrRace.UnalteredVisualRaceID] = chrRace.Id;
@@ -220,7 +220,7 @@ namespace Game.DataStorage
// link shapeshift displays to race/gender/form // link shapeshift displays to race/gender/form
foreach (var shapeshiftOptionsForModel in shapeshiftFormByModel.LookupByKey(model.Id)) foreach (var shapeshiftOptionsForModel in shapeshiftFormByModel.LookupByKey(model.Id))
{ {
ShapeshiftFormModelData data = new ShapeshiftFormModelData(); ShapeshiftFormModelData data = new();
data.OptionID = shapeshiftOptionsForModel.Item1; data.OptionID = shapeshiftOptionsForModel.Item1;
data.Choices = _chrCustomizationChoicesByOption.LookupByKey(shapeshiftOptionsForModel.Item1); data.Choices = _chrCustomizationChoicesByOption.LookupByKey(shapeshiftOptionsForModel.Item1);
if (!data.Choices.Empty()) if (!data.Choices.Empty())
@@ -388,7 +388,7 @@ namespace Game.DataStorage
CliDB.MapDifficultyStorage.Clear(); CliDB.MapDifficultyStorage.Clear();
List<MapDifficultyXConditionRecord> mapDifficultyConditions = new List<MapDifficultyXConditionRecord>(); List<MapDifficultyXConditionRecord> mapDifficultyConditions = new();
foreach (var mapDifficultyCondition in CliDB.MapDifficultyXConditionStorage.Values) foreach (var mapDifficultyCondition in CliDB.MapDifficultyXConditionStorage.Values)
mapDifficultyConditions.Add(mapDifficultyCondition); mapDifficultyConditions.Add(mapDifficultyCondition);
@@ -597,7 +597,7 @@ namespace Game.DataStorage
_uiMapAssignmentByWmoGroup[i] = new MultiMap<int, UiMapAssignmentRecord>(); _uiMapAssignmentByWmoGroup[i] = new MultiMap<int, UiMapAssignmentRecord>();
} }
MultiMap<int, UiMapAssignmentRecord> uiMapAssignmentByUiMap = new MultiMap<int, UiMapAssignmentRecord>(); MultiMap<int, UiMapAssignmentRecord> uiMapAssignmentByUiMap = new();
foreach (UiMapAssignmentRecord uiMapAssignment in CliDB.UiMapAssignmentStorage.Values) foreach (UiMapAssignmentRecord uiMapAssignment in CliDB.UiMapAssignmentStorage.Values)
{ {
uiMapAssignmentByUiMap.Add(uiMapAssignment.UiMapID, uiMapAssignment); uiMapAssignmentByUiMap.Add(uiMapAssignment.UiMapID, uiMapAssignment);
@@ -616,13 +616,13 @@ namespace Game.DataStorage
} }
} }
Dictionary<Tuple<int, uint>, UiMapLinkRecord> uiMapLinks = new Dictionary<Tuple<int, uint>, UiMapLinkRecord>(); Dictionary<Tuple<int, uint>, UiMapLinkRecord> uiMapLinks = new();
foreach (UiMapLinkRecord uiMapLink in CliDB.UiMapLinkStorage.Values) foreach (UiMapLinkRecord uiMapLink in CliDB.UiMapLinkStorage.Values)
uiMapLinks[Tuple.Create(uiMapLink.ParentUiMapID, (uint)uiMapLink.ChildUiMapID)] = uiMapLink; uiMapLinks[Tuple.Create(uiMapLink.ParentUiMapID, (uint)uiMapLink.ChildUiMapID)] = uiMapLink;
foreach (UiMapRecord uiMap in CliDB.UiMapStorage.Values) foreach (UiMapRecord uiMap in CliDB.UiMapStorage.Values)
{ {
UiMapBounds bounds = new UiMapBounds(); UiMapBounds bounds = new();
UiMapRecord parentUiMap = CliDB.UiMapStorage.LookupByKey(uiMap.ParentUiMapID); UiMapRecord parentUiMap = CliDB.UiMapStorage.LookupByKey(uiMap.ParentUiMapID);
if (parentUiMap != null) if (parentUiMap != null)
{ {
@@ -716,7 +716,7 @@ namespace Game.DataStorage
return; return;
} }
Dictionary<(uint tableHash, int recordId), bool> deletedRecords = new Dictionary<(uint tableHash, int recordId), bool>(); Dictionary<(uint tableHash, int recordId), bool> deletedRecords = new();
uint count = 0; uint count = 0;
do do
@@ -734,7 +734,7 @@ namespace Game.DataStorage
} }
} }
HotfixRecord hotfixRecord = new HotfixRecord(); HotfixRecord hotfixRecord = new();
hotfixRecord.TableHash = tableHash; hotfixRecord.TableHash = tableHash;
hotfixRecord.RecordID = recordId; hotfixRecord.RecordID = recordId;
hotfixRecord.HotfixID = id; hotfixRecord.HotfixID = id;
@@ -845,7 +845,7 @@ namespace Game.DataStorage
if (!availableDb2Locales[(int)locale]) if (!availableDb2Locales[(int)locale])
continue; continue;
HotfixOptionalData optionalData = new HotfixOptionalData(); HotfixOptionalData optionalData = new();
optionalData.Key = result.Read<uint>(3); optionalData.Key = result.Read<uint>(3);
var allowedHotfixItr = allowedHotfixes.Find(v => var allowedHotfixItr = allowedHotfixes.Find(v =>
{ {
@@ -1086,7 +1086,7 @@ namespace Game.DataStorage
_ => 0 _ => 0
}; };
ContentTuningLevels levels = new ContentTuningLevels(); ContentTuningLevels levels = new();
levels.MinLevel = (short)(contentTuning.MinLevel + getLevelAdjustment((ContentTuningCalcType)contentTuning.MinLevelType)); levels.MinLevel = (short)(contentTuning.MinLevel + getLevelAdjustment((ContentTuningCalcType)contentTuning.MinLevelType));
levels.MaxLevel = (short)(contentTuning.MaxLevel + getLevelAdjustment((ContentTuningCalcType)contentTuning.MaxLevelType)); levels.MaxLevel = (short)(contentTuning.MaxLevel + getLevelAdjustment((ContentTuningCalcType)contentTuning.MaxLevelType));
levels.MinLevelWithDelta = (short)Math.Clamp(levels.MinLevel + contentTuning.TargetLevelDelta, 1, SharedConst.MaxLevel); levels.MinLevelWithDelta = (short)Math.Clamp(levels.MinLevel + contentTuning.TargetLevelDelta, 1, SharedConst.MaxLevel);
@@ -1432,7 +1432,7 @@ namespace Game.DataStorage
public List<uint> GetDefaultItemBonusTree(uint itemId, ItemContext itemContext) public List<uint> GetDefaultItemBonusTree(uint itemId, ItemContext itemContext)
{ {
List<uint> bonusListIDs = new List<uint>(); List<uint> bonusListIDs = new();
ItemSparseRecord proto = CliDB.ItemSparseStorage.LookupByKey(itemId); ItemSparseRecord proto = CliDB.ItemSparseStorage.LookupByKey(itemId);
if (proto == null) if (proto == null)
@@ -2134,7 +2134,7 @@ namespace Game.DataStorage
UiMapAssignmentRecord FindNearestMapAssignment(float x, float y, float z, int mapId, int areaId, int wmoDoodadPlacementId, int wmoGroupId, UiMapSystem system) UiMapAssignmentRecord FindNearestMapAssignment(float x, float y, float z, int mapId, int areaId, int wmoDoodadPlacementId, int wmoGroupId, UiMapSystem system)
{ {
UiMapAssignmentStatus nearestMapAssignment = new UiMapAssignmentStatus(); UiMapAssignmentStatus nearestMapAssignment = new();
var iterateUiMapAssignments = new Action<MultiMap<int, UiMapAssignmentRecord>, int>((assignments, id) => var iterateUiMapAssignments = new Action<MultiMap<int, UiMapAssignmentRecord>, int>((assignments, id) =>
{ {
foreach (var assignment in assignments.LookupByKey(id)) foreach (var assignment in assignments.LookupByKey(id))
@@ -2216,15 +2216,15 @@ namespace Game.DataStorage
uiMapId = uiMapAssignment.UiMapID; uiMapId = uiMapAssignment.UiMapID;
Vector2 relativePosition = new Vector2(0.5f, 0.5f); Vector2 relativePosition = new(0.5f, 0.5f);
Vector2 regionSize = new Vector2(uiMapAssignment.Region[1].X - uiMapAssignment.Region[0].X, uiMapAssignment.Region[1].Y - uiMapAssignment.Region[0].Y); Vector2 regionSize = new(uiMapAssignment.Region[1].X - uiMapAssignment.Region[0].X, uiMapAssignment.Region[1].Y - uiMapAssignment.Region[0].Y);
if (regionSize.X > 0.0f) if (regionSize.X > 0.0f)
relativePosition.X = (x - uiMapAssignment.Region[0].X) / regionSize.X; relativePosition.X = (x - uiMapAssignment.Region[0].X) / regionSize.X;
if (regionSize.Y > 0.0f) if (regionSize.Y > 0.0f)
relativePosition.Y = (y - uiMapAssignment.Region[0].Y) / regionSize.Y; relativePosition.Y = (y - uiMapAssignment.Region[0].Y) / regionSize.Y;
// x any y are swapped // x any y are swapped
Vector2 uiPosition = new Vector2(((1.0f - (1.0f - relativePosition.Y)) * uiMapAssignment.UiMin.X) + ((1.0f - relativePosition.Y) * uiMapAssignment.UiMax.X), ((1.0f - (1.0f - relativePosition.X)) * uiMapAssignment.UiMin.Y) + ((1.0f - relativePosition.X) * uiMapAssignment.UiMax.Y)); Vector2 uiPosition = new(((1.0f - (1.0f - relativePosition.Y)) * uiMapAssignment.UiMin.X) + ((1.0f - relativePosition.Y) * uiMapAssignment.UiMax.X), ((1.0f - (1.0f - relativePosition.X)) * uiMapAssignment.UiMin.Y) + ((1.0f - relativePosition.X) * uiMapAssignment.UiMax.Y));
if (!local) if (!local)
uiPosition = CalculateGlobalUiMapPosition(uiMapAssignment.UiMapID, uiPosition); uiPosition = CalculateGlobalUiMapPosition(uiMapAssignment.UiMapID, uiPosition);
@@ -2287,83 +2287,83 @@ namespace Game.DataStorage
delegate bool AllowedHotfixOptionalData(byte[] data); delegate bool AllowedHotfixOptionalData(byte[] data);
Dictionary<uint, IDB2Storage> _storage = new Dictionary<uint, IDB2Storage>(); Dictionary<uint, IDB2Storage> _storage = new();
List<HotfixRecord> _hotfixData = new List<HotfixRecord>(); List<HotfixRecord> _hotfixData = new();
Dictionary<(uint tableHash, int recordId), byte[]>[] _hotfixBlob = new Dictionary<(uint tableHash, int recordId), byte[]>[(int)Locale.Total]; Dictionary<(uint tableHash, int recordId), byte[]>[] _hotfixBlob = new Dictionary<(uint tableHash, int recordId), byte[]>[(int)Locale.Total];
MultiMap<uint, Tuple<uint, AllowedHotfixOptionalData>> _allowedHotfixOptionalData = new MultiMap<uint, Tuple<uint, AllowedHotfixOptionalData>>(); MultiMap<uint, Tuple<uint, AllowedHotfixOptionalData>> _allowedHotfixOptionalData = new();
MultiMap<(uint tableHash, int recordId), HotfixOptionalData>[]_hotfixOptionalData = new MultiMap<(uint tableHash, int recordId), HotfixOptionalData>[(int)Locale.Total]; MultiMap<(uint tableHash, int recordId), HotfixOptionalData>[]_hotfixOptionalData = new MultiMap<(uint tableHash, int recordId), HotfixOptionalData>[(int)Locale.Total];
MultiMap<uint, uint> _areaGroupMembers = new MultiMap<uint, uint>(); MultiMap<uint, uint> _areaGroupMembers = new();
MultiMap<uint, ArtifactPowerRecord> _artifactPowers = new MultiMap<uint, ArtifactPowerRecord>(); MultiMap<uint, ArtifactPowerRecord> _artifactPowers = new();
MultiMap<uint, uint> _artifactPowerLinks = new MultiMap<uint, uint>(); MultiMap<uint, uint> _artifactPowerLinks = new();
Dictionary<Tuple<uint, byte>, ArtifactPowerRankRecord> _artifactPowerRanks = new Dictionary<Tuple<uint, byte>, ArtifactPowerRankRecord>(); Dictionary<Tuple<uint, byte>, ArtifactPowerRankRecord> _artifactPowerRanks = new();
Dictionary<uint, AzeriteEmpoweredItemRecord> _azeriteEmpoweredItems = new Dictionary<uint, AzeriteEmpoweredItemRecord>(); Dictionary<uint, AzeriteEmpoweredItemRecord> _azeriteEmpoweredItems = new();
Dictionary<(uint azeriteEssenceId, uint rank), AzeriteEssencePowerRecord> _azeriteEssencePowersByIdAndRank = new Dictionary<(uint azeriteEssenceId, uint rank), AzeriteEssencePowerRecord>(); Dictionary<(uint azeriteEssenceId, uint rank), AzeriteEssencePowerRecord> _azeriteEssencePowersByIdAndRank = new();
List<AzeriteItemMilestonePowerRecord> _azeriteItemMilestonePowers = new List<AzeriteItemMilestonePowerRecord>(); List<AzeriteItemMilestonePowerRecord> _azeriteItemMilestonePowers = new();
AzeriteItemMilestonePowerRecord[] _azeriteItemMilestonePowerByEssenceSlot = new AzeriteItemMilestonePowerRecord[SharedConst.MaxAzeriteEssenceSlot]; AzeriteItemMilestonePowerRecord[] _azeriteItemMilestonePowerByEssenceSlot = new AzeriteItemMilestonePowerRecord[SharedConst.MaxAzeriteEssenceSlot];
MultiMap<uint, AzeritePowerSetMemberRecord> _azeritePowers = new MultiMap<uint, AzeritePowerSetMemberRecord>(); MultiMap<uint, AzeritePowerSetMemberRecord> _azeritePowers = new();
Dictionary<(uint azeriteUnlockSetId, ItemContext itemContext), byte[]> _azeriteTierUnlockLevels = new Dictionary<(uint azeriteUnlockSetId, ItemContext itemContext), byte[]>(); Dictionary<(uint azeriteUnlockSetId, ItemContext itemContext), byte[]> _azeriteTierUnlockLevels = new();
Dictionary<(uint itemId, ItemContext itemContext), AzeriteUnlockMappingRecord> _azeriteUnlockMappings = new Dictionary<(uint itemId, ItemContext itemContext), AzeriteUnlockMappingRecord>(); Dictionary<(uint itemId, ItemContext itemContext), AzeriteUnlockMappingRecord> _azeriteUnlockMappings = new();
ChrClassUIDisplayRecord[] _uiDisplayByClass = new ChrClassUIDisplayRecord[(int)Class.Max]; ChrClassUIDisplayRecord[] _uiDisplayByClass = new ChrClassUIDisplayRecord[(int)Class.Max];
uint[][] _powersByClass = new uint[(int)Class.Max][]; uint[][] _powersByClass = new uint[(int)Class.Max][];
MultiMap<uint, ChrCustomizationChoiceRecord> _chrCustomizationChoicesByOption = new MultiMap<uint, ChrCustomizationChoiceRecord>(); MultiMap<uint, ChrCustomizationChoiceRecord> _chrCustomizationChoicesByOption = new();
Dictionary<Tuple<byte, byte>, ChrModelRecord> _chrModelsByRaceAndGender = new Dictionary<Tuple<byte, byte>, ChrModelRecord>(); Dictionary<Tuple<byte, byte>, ChrModelRecord> _chrModelsByRaceAndGender = new();
Dictionary<Tuple<byte, byte, byte>, ShapeshiftFormModelData> _chrCustomizationChoicesForShapeshifts = new Dictionary<Tuple<byte, byte, byte>, ShapeshiftFormModelData>(); Dictionary<Tuple<byte, byte, byte>, ShapeshiftFormModelData> _chrCustomizationChoicesForShapeshifts = new();
MultiMap<Tuple<byte, byte>, ChrCustomizationOptionRecord> _chrCustomizationOptionsByRaceAndGender = new MultiMap<Tuple<byte, byte>, ChrCustomizationOptionRecord>(); MultiMap<Tuple<byte, byte>, ChrCustomizationOptionRecord> _chrCustomizationOptionsByRaceAndGender = new();
Dictionary<uint, MultiMap<uint, uint>> _chrCustomizationRequiredChoices = new Dictionary<uint, MultiMap<uint, uint>>(); Dictionary<uint, MultiMap<uint, uint>> _chrCustomizationRequiredChoices = new();
ChrSpecializationRecord[][] _chrSpecializationsByIndex = new ChrSpecializationRecord[(int)Class.Max + 1][]; ChrSpecializationRecord[][] _chrSpecializationsByIndex = new ChrSpecializationRecord[(int)Class.Max + 1][];
MultiMap<uint, CurvePointRecord> _curvePoints = new MultiMap<uint, CurvePointRecord>(); MultiMap<uint, CurvePointRecord> _curvePoints = new();
Dictionary<Tuple<uint, byte, byte, byte>, EmotesTextSoundRecord> _emoteTextSounds = new Dictionary<Tuple<uint, byte, byte, byte>, EmotesTextSoundRecord>(); Dictionary<Tuple<uint, byte, byte, byte>, EmotesTextSoundRecord> _emoteTextSounds = new();
Dictionary<Tuple<uint, int>, ExpectedStatRecord> _expectedStatsByLevel = new Dictionary<Tuple<uint, int>, ExpectedStatRecord>(); Dictionary<Tuple<uint, int>, ExpectedStatRecord> _expectedStatsByLevel = new();
MultiMap<uint, ExpectedStatModRecord> _expectedStatModsByContentTuning = new MultiMap<uint, ExpectedStatModRecord>(); MultiMap<uint, ExpectedStatModRecord> _expectedStatModsByContentTuning = new();
MultiMap<uint, uint> _factionTeams = new MultiMap<uint, uint>(); MultiMap<uint, uint> _factionTeams = new();
Dictionary<uint, HeirloomRecord> _heirlooms = new Dictionary<uint, HeirloomRecord>(); Dictionary<uint, HeirloomRecord> _heirlooms = new();
MultiMap<uint, uint> _glyphBindableSpells = new MultiMap<uint, uint>(); MultiMap<uint, uint> _glyphBindableSpells = new();
MultiMap<uint, uint> _glyphRequiredSpecs = new MultiMap<uint, uint>(); MultiMap<uint, uint> _glyphRequiredSpecs = new();
MultiMap<uint, ItemBonusRecord> _itemBonusLists = new MultiMap<uint, ItemBonusRecord>(); MultiMap<uint, ItemBonusRecord> _itemBonusLists = new();
Dictionary<short, uint> _itemLevelDeltaToBonusListContainer = new Dictionary<short, uint>(); Dictionary<short, uint> _itemLevelDeltaToBonusListContainer = new();
MultiMap<uint, ItemBonusTreeNodeRecord> _itemBonusTrees = new MultiMap<uint, ItemBonusTreeNodeRecord>(); MultiMap<uint, ItemBonusTreeNodeRecord> _itemBonusTrees = new();
Dictionary<uint, ItemChildEquipmentRecord> _itemChildEquipment = new Dictionary<uint, ItemChildEquipmentRecord>(); Dictionary<uint, ItemChildEquipmentRecord> _itemChildEquipment = new();
ItemClassRecord[] _itemClassByOldEnum = new ItemClassRecord[19]; ItemClassRecord[] _itemClassByOldEnum = new ItemClassRecord[19];
List<uint> _itemsWithCurrencyCost = new List<uint>(); List<uint> _itemsWithCurrencyCost = new();
MultiMap<uint, ItemLimitCategoryConditionRecord> _itemCategoryConditions = new MultiMap<uint, ItemLimitCategoryConditionRecord>(); MultiMap<uint, ItemLimitCategoryConditionRecord> _itemCategoryConditions = new();
MultiMap<uint, ItemLevelSelectorQualityRecord> _itemLevelQualitySelectorQualities = new MultiMap<uint, ItemLevelSelectorQualityRecord>(); MultiMap<uint, ItemLevelSelectorQualityRecord> _itemLevelQualitySelectorQualities = new();
Dictionary<uint, ItemModifiedAppearanceRecord> _itemModifiedAppearancesByItem = new Dictionary<uint, ItemModifiedAppearanceRecord>(); Dictionary<uint, ItemModifiedAppearanceRecord> _itemModifiedAppearancesByItem = new();
MultiMap<uint, uint> _itemToBonusTree = new MultiMap<uint, uint>(); MultiMap<uint, uint> _itemToBonusTree = new();
MultiMap<uint, ItemSetSpellRecord> _itemSetSpells = new MultiMap<uint, ItemSetSpellRecord>(); MultiMap<uint, ItemSetSpellRecord> _itemSetSpells = new();
MultiMap<uint, ItemSpecOverrideRecord> _itemSpecOverrides = new MultiMap<uint, ItemSpecOverrideRecord>(); MultiMap<uint, ItemSpecOverrideRecord> _itemSpecOverrides = new();
Dictionary<uint, Dictionary<uint, MapDifficultyRecord>> _mapDifficulties = new Dictionary<uint, Dictionary<uint, MapDifficultyRecord>>(); Dictionary<uint, Dictionary<uint, MapDifficultyRecord>> _mapDifficulties = new();
MultiMap<uint, Tuple<uint, PlayerConditionRecord>> _mapDifficultyConditions = new MultiMap<uint, Tuple<uint, PlayerConditionRecord>>(); MultiMap<uint, Tuple<uint, PlayerConditionRecord>> _mapDifficultyConditions = new();
Dictionary<uint, MountRecord> _mountsBySpellId = new Dictionary<uint, MountRecord>(); Dictionary<uint, MountRecord> _mountsBySpellId = new();
MultiMap<uint, MountTypeXCapabilityRecord> _mountCapabilitiesByType = new MultiMap<uint, MountTypeXCapabilityRecord>(); MultiMap<uint, MountTypeXCapabilityRecord> _mountCapabilitiesByType = new();
MultiMap<uint, MountXDisplayRecord> _mountDisplays = new MultiMap<uint, MountXDisplayRecord>(); MultiMap<uint, MountXDisplayRecord> _mountDisplays = new();
Dictionary<uint, List<NameGenRecord>[]> _nameGenData = new Dictionary<uint, List<NameGenRecord>[]>(); Dictionary<uint, List<NameGenRecord>[]> _nameGenData = new();
List<string>[] _nameValidators = new List<string>[(int)Locale.Total + 1]; List<string>[] _nameValidators = new List<string>[(int)Locale.Total + 1];
MultiMap<uint, uint> _phasesByGroup = new MultiMap<uint, uint>(); MultiMap<uint, uint> _phasesByGroup = new();
Dictionary<PowerType, PowerTypeRecord> _powerTypes = new Dictionary<PowerType, PowerTypeRecord>(); Dictionary<PowerType, PowerTypeRecord> _powerTypes = new();
Dictionary<uint, byte> _pvpItemBonus = new Dictionary<uint, byte>(); Dictionary<uint, byte> _pvpItemBonus = new();
PvpTalentSlotUnlockRecord[] _pvpTalentSlotUnlock = new PvpTalentSlotUnlockRecord[PlayerConst.MaxPvpTalentSlots]; PvpTalentSlotUnlockRecord[] _pvpTalentSlotUnlock = new PvpTalentSlotUnlockRecord[PlayerConst.MaxPvpTalentSlots];
Dictionary<uint, Tuple<List<QuestPackageItemRecord>, List<QuestPackageItemRecord>>> _questPackages = new Dictionary<uint, Tuple<List<QuestPackageItemRecord>, List<QuestPackageItemRecord>>>(); Dictionary<uint, Tuple<List<QuestPackageItemRecord>, List<QuestPackageItemRecord>>> _questPackages = new();
MultiMap<uint, RewardPackXCurrencyTypeRecord> _rewardPackCurrencyTypes = new MultiMap<uint, RewardPackXCurrencyTypeRecord>(); MultiMap<uint, RewardPackXCurrencyTypeRecord> _rewardPackCurrencyTypes = new();
MultiMap<uint, RewardPackXItemRecord> _rewardPackItems = new MultiMap<uint, RewardPackXItemRecord>(); MultiMap<uint, RewardPackXItemRecord> _rewardPackItems = new();
MultiMap<uint, SkillLineRecord> _skillLinesByParentSkillLine = new MultiMap<uint, SkillLineRecord>(); MultiMap<uint, SkillLineRecord> _skillLinesByParentSkillLine = new();
MultiMap<uint, SkillLineAbilityRecord> _skillLineAbilitiesBySkillupSkill = new MultiMap<uint, SkillLineAbilityRecord>(); MultiMap<uint, SkillLineAbilityRecord> _skillLineAbilitiesBySkillupSkill = new();
MultiMap<uint, SkillRaceClassInfoRecord> _skillRaceClassInfoBySkill = new MultiMap<uint, SkillRaceClassInfoRecord>(); MultiMap<uint, SkillRaceClassInfoRecord> _skillRaceClassInfoBySkill = new();
MultiMap<uint, SpecializationSpellsRecord> _specializationSpellsBySpec = new MultiMap<uint, SpecializationSpellsRecord>(); MultiMap<uint, SpecializationSpellsRecord> _specializationSpellsBySpec = new();
List<Tuple<int, uint>> _specsBySpecSet = new List<Tuple<int, uint>>(); List<Tuple<int, uint>> _specsBySpecSet = new();
List<byte> _spellFamilyNames = new List<byte>(); List<byte> _spellFamilyNames = new();
MultiMap<uint, SpellProcsPerMinuteModRecord> _spellProcsPerMinuteMods = new MultiMap<uint, SpellProcsPerMinuteModRecord>(); MultiMap<uint, SpellProcsPerMinuteModRecord> _spellProcsPerMinuteMods = new();
List<TalentRecord>[][][] _talentsByPosition = new List<TalentRecord>[(int)Class.Max][][]; List<TalentRecord>[][][] _talentsByPosition = new List<TalentRecord>[(int)Class.Max][][];
List<uint> _toys = new List<uint>(); List<uint> _toys = new();
MultiMap<uint, TransmogSetRecord> _transmogSetsByItemModifiedAppearance = new MultiMap<uint, TransmogSetRecord>(); MultiMap<uint, TransmogSetRecord> _transmogSetsByItemModifiedAppearance = new();
MultiMap<uint, TransmogSetItemRecord> _transmogSetItemsByTransmogSet = new MultiMap<uint, TransmogSetItemRecord>(); MultiMap<uint, TransmogSetItemRecord> _transmogSetItemsByTransmogSet = new();
Dictionary<int, UiMapBounds> _uiMapBounds = new Dictionary<int, UiMapBounds>(); Dictionary<int, UiMapBounds> _uiMapBounds = new();
MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByMap = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max]; MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByMap = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max];
MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByArea = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max]; MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByArea = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max];
MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByWmoDoodadPlacement = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max]; MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByWmoDoodadPlacement = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max];
MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByWmoGroup = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max]; MultiMap<int, UiMapAssignmentRecord>[] _uiMapAssignmentByWmoGroup = new MultiMap<int, UiMapAssignmentRecord>[(int)UiMapSystem.Max];
List<int> _uiMapPhases = new List<int>(); List<int> _uiMapPhases = new();
Dictionary<Tuple<short, sbyte, int>, WMOAreaTableRecord> _wmoAreaTableLookup = new Dictionary<Tuple<short, sbyte, int>, WMOAreaTableRecord>(); Dictionary<Tuple<short, sbyte, int>, WMOAreaTableRecord> _wmoAreaTableLookup = new();
} }
class UiMapBounds class UiMapBounds
@@ -2606,8 +2606,8 @@ namespace Game.DataStorage
public class ShapeshiftFormModelData public class ShapeshiftFormModelData
{ {
public uint OptionID; public uint OptionID;
public List<ChrCustomizationChoiceRecord> Choices = new List<ChrCustomizationChoiceRecord>(); public List<ChrCustomizationChoiceRecord> Choices = new();
public List<ChrCustomizationDisplayInfoRecord> Displays = new List<ChrCustomizationDisplayInfoRecord>(); public List<ChrCustomizationDisplayInfoRecord> Displays = new();
} }
enum CurveInterpolationMode enum CurveInterpolationMode
+8 -8
View File
@@ -27,7 +27,7 @@ namespace Game.DataStorage
// Convert the geomoetry from a spline value, to an actual WoW XYZ // Convert the geomoetry from a spline value, to an actual WoW XYZ
static Vector3 TranslateLocation(Vector4 dbcLocation, Vector3 basePosition, Vector3 splineVector) static Vector3 TranslateLocation(Vector4 dbcLocation, Vector3 basePosition, Vector3 splineVector)
{ {
Vector3 work = new Vector3(); Vector3 work = new();
float x = basePosition.X + splineVector.X; float x = basePosition.X + splineVector.X;
float y = basePosition.Y + splineVector.Y; float y = basePosition.Y + splineVector.Y;
float z = basePosition.Z + splineVector.Z; float z = basePosition.Z + splineVector.Z;
@@ -46,10 +46,10 @@ namespace Game.DataStorage
// Number of cameras not used. Multiple cameras never used in 7.1.5 // Number of cameras not used. Multiple cameras never used in 7.1.5
static void ReadCamera(M2Camera cam, BinaryReader reader, CinematicCameraRecord dbcentry) static void ReadCamera(M2Camera cam, BinaryReader reader, CinematicCameraRecord dbcentry)
{ {
List<FlyByCamera> cameras = new List<FlyByCamera>(); List<FlyByCamera> cameras = new();
List<FlyByCamera> targetcam = new List<FlyByCamera>(); List<FlyByCamera> targetcam = new();
Vector4 dbcData = new Vector4(dbcentry.Origin.X, dbcentry.Origin.Y, dbcentry.Origin.Z, dbcentry.OriginFacing); Vector4 dbcData = new(dbcentry.Origin.X, dbcentry.Origin.Y, dbcentry.Origin.Z, dbcentry.OriginFacing);
// Read target locations, only so that we can calculate orientation // Read target locations, only so that we can calculate orientation
for (uint k = 0; k < cam.target_positions.timestamps.number; ++k) for (uint k = 0; k < cam.target_positions.timestamps.number; ++k)
@@ -76,7 +76,7 @@ namespace Game.DataStorage
Vector3 newPos = TranslateLocation(dbcData, cam.target_position_base, targPositions[i].p0); Vector3 newPos = TranslateLocation(dbcData, cam.target_position_base, targPositions[i].p0);
// Add to vector // Add to vector
FlyByCamera thisCam = new FlyByCamera(); FlyByCamera thisCam = new();
thisCam.timeStamp = targTimestamps[i]; thisCam.timeStamp = targTimestamps[i];
thisCam.locations = new Vector4(newPos.X, newPos.Y, newPos.Z, 0.0f); thisCam.locations = new Vector4(newPos.X, newPos.Y, newPos.Z, 0.0f);
targetcam.Add(thisCam); targetcam.Add(thisCam);
@@ -108,7 +108,7 @@ namespace Game.DataStorage
Vector3 newPos = TranslateLocation(dbcData, cam.position_base, positions[i].p0); Vector3 newPos = TranslateLocation(dbcData, cam.position_base, positions[i].p0);
// Add to vector // Add to vector
FlyByCamera thisCam = new FlyByCamera(); FlyByCamera thisCam = new();
thisCam.timeStamp = posTimestamps[i]; thisCam.timeStamp = posTimestamps[i];
thisCam.locations = new Vector4(newPos.X, newPos.Y, newPos.Z, 0); thisCam.locations = new Vector4(newPos.X, newPos.Y, newPos.Z, 0);
@@ -170,7 +170,7 @@ namespace Game.DataStorage
try try
{ {
using (BinaryReader m2file = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read))) using (BinaryReader m2file = new(new FileStream(filename, FileMode.Open, FileAccess.Read)))
{ {
// Check file has correct magic (MD21) // Check file has correct magic (MD21)
if (m2file.ReadUInt32() != 0x3132444D) //"MD21" if (m2file.ReadUInt32() != 0x3132444D) //"MD21"
@@ -209,7 +209,7 @@ namespace Game.DataStorage
return FlyByCameraStorage.LookupByKey(cameraId); return FlyByCameraStorage.LookupByKey(cameraId);
} }
static MultiMap<uint, FlyByCamera> FlyByCameraStorage = new MultiMap<uint, FlyByCamera>(); static MultiMap<uint, FlyByCamera> FlyByCameraStorage = new();
} }
public class FlyByCamera public class FlyByCamera
+1 -1
View File
@@ -141,7 +141,7 @@ namespace Game.DungeonFinding
LfgState m_State; LfgState m_State;
LfgState m_OldState; LfgState m_OldState;
ObjectGuid m_Leader; ObjectGuid m_Leader;
List<ObjectGuid> m_Players = new List<ObjectGuid>(); List<ObjectGuid> m_Players = new();
// Dungeon // Dungeon
uint m_Dungeon; uint m_Dungeon;
// Vote Kick // Vote Kick
+42 -42
View File
@@ -43,7 +43,7 @@ namespace Game.DungeonFinding
public string ConcatenateDungeons(List<uint> dungeons) public string ConcatenateDungeons(List<uint> dungeons)
{ {
StringBuilder dungeonstr = new StringBuilder(); StringBuilder dungeonstr = new();
if (!dungeons.Empty()) if (!dungeons.Empty())
{ {
foreach (var id in dungeons) foreach (var id in dungeons)
@@ -91,7 +91,7 @@ namespace Game.DungeonFinding
if (!guid.IsParty()) if (!guid.IsParty())
return; return;
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_LFG_DATA); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_LFG_DATA);
stmt.AddValue(0, db_guid); stmt.AddValue(0, db_guid);
@@ -360,8 +360,8 @@ namespace Game.DungeonFinding
Group grp = player.GetGroup(); Group grp = player.GetGroup();
ObjectGuid guid = player.GetGUID(); ObjectGuid guid = player.GetGUID();
ObjectGuid gguid = grp ? grp.GetGUID() : guid; ObjectGuid gguid = grp ? grp.GetGUID() : guid;
LfgJoinResultData joinData = new LfgJoinResultData(); LfgJoinResultData joinData = new();
List<ObjectGuid> players = new List<ObjectGuid>(); List<ObjectGuid> players = new();
uint rDungeonId = 0; uint rDungeonId = 0;
bool isContinue = grp && grp.IsLFGGroup() && GetState(gguid) != LfgState.FinishedDungeon; bool isContinue = grp && grp.IsLFGGroup() && GetState(gguid) != LfgState.FinishedDungeon;
@@ -496,7 +496,7 @@ namespace Game.DungeonFinding
return; return;
} }
RideTicket ticket = new RideTicket(); RideTicket ticket = new();
ticket.RequesterGuid = guid; ticket.RequesterGuid = guid;
ticket.Id = GetQueueId(gguid); ticket.Id = GetQueueId(gguid);
ticket.Type = RideType.Lfg; ticket.Type = RideType.Lfg;
@@ -506,7 +506,7 @@ namespace Game.DungeonFinding
if (grp) // Begin rolecheck if (grp) // Begin rolecheck
{ {
// Create new rolecheck // Create new rolecheck
LfgRoleCheck roleCheck = new LfgRoleCheck(); LfgRoleCheck roleCheck = new();
roleCheck.cancelTime = Time.UnixTime + SharedConst.LFGTimeRolecheck; roleCheck.cancelTime = Time.UnixTime + SharedConst.LFGTimeRolecheck;
roleCheck.state = LfgRoleCheckState.Initialiting; roleCheck.state = LfgRoleCheckState.Initialiting;
roleCheck.leader = guid; roleCheck.leader = guid;
@@ -523,7 +523,7 @@ namespace Game.DungeonFinding
SetState(gguid, LfgState.Rolecheck); SetState(gguid, LfgState.Rolecheck);
// Send update to player // Send update to player
LfgUpdateData updateData = new LfgUpdateData(LfgUpdateType.JoinQueue, dungeons); LfgUpdateData updateData = new(LfgUpdateType.JoinQueue, dungeons);
for (GroupReference refe = grp.GetFirstMember(); refe != null; refe = refe.Next()) for (GroupReference refe = grp.GetFirstMember(); refe != null; refe = refe.Next())
{ {
Player plrg = refe.GetSource(); Player plrg = refe.GetSource();
@@ -546,7 +546,7 @@ namespace Game.DungeonFinding
} }
else // Add player to queue else // Add player to queue
{ {
Dictionary<ObjectGuid, LfgRoles> rolesMap = new Dictionary<ObjectGuid, LfgRoles>(); Dictionary<ObjectGuid, LfgRoles> rolesMap = new();
rolesMap[guid] = roles; rolesMap[guid] = roles;
LFGQueue queue = GetQueue(guid); LFGQueue queue = GetQueue(guid);
queue.AddQueueData(guid, Time.UnixTime, dungeons, rolesMap); queue.AddQueueData(guid, Time.UnixTime, dungeons, rolesMap);
@@ -569,7 +569,7 @@ namespace Game.DungeonFinding
player.GetSession().SendLfgJoinResult(joinData); player.GetSession().SendLfgJoinResult(joinData);
debugNames += player.GetName(); debugNames += player.GetName();
} }
StringBuilder o = new StringBuilder(); StringBuilder o = new();
o.AppendFormat("Join: [{0}] joined ({1}{2}) Members: {3}. Dungeons ({4}): ", guid, (grp ? "group" : "player"), debugNames, dungeons.Count, ConcatenateDungeons(dungeons)); o.AppendFormat("Join: [{0}] joined ({1}{2}) Members: {3}. Dungeons ({4}): ", guid, (grp ? "group" : "player"), debugNames, dungeons.Count, ConcatenateDungeons(dungeons));
Log.outDebug(LogFilter.Lfg, o.ToString()); Log.outDebug(LogFilter.Lfg, o.ToString());
} }
@@ -610,7 +610,7 @@ namespace Game.DungeonFinding
case LfgState.Proposal: case LfgState.Proposal:
{ {
// Remove from Proposals // Remove from Proposals
KeyValuePair<uint, LfgProposal> it = new KeyValuePair<uint, LfgProposal>(); KeyValuePair<uint, LfgProposal> it = new();
ObjectGuid pguid = gguid == guid ? GetLeader(gguid) : guid; ObjectGuid pguid = gguid == guid ? GetLeader(gguid) : guid;
foreach (var test in ProposalsStore) foreach (var test in ProposalsStore)
{ {
@@ -686,13 +686,13 @@ namespace Game.DungeonFinding
} }
} }
List<uint> dungeons = new List<uint>(); List<uint> dungeons = new();
if (roleCheck.rDungeonId != 0) if (roleCheck.rDungeonId != 0)
dungeons.Add(roleCheck.rDungeonId); dungeons.Add(roleCheck.rDungeonId);
else else
dungeons = roleCheck.dungeons; dungeons = roleCheck.dungeons;
LfgJoinResultData joinData = new LfgJoinResultData(LfgJoinResult.RoleCheckFailed, roleCheck.state); LfgJoinResultData joinData = new(LfgJoinResult.RoleCheckFailed, roleCheck.state);
foreach (var it in roleCheck.roles) foreach (var it in roleCheck.roles)
{ {
ObjectGuid pguid = it.Key; ObjectGuid pguid = it.Key;
@@ -736,8 +736,8 @@ namespace Game.DungeonFinding
void GetCompatibleDungeons(List<uint> dungeons, List<ObjectGuid> players, Dictionary<ObjectGuid, Dictionary<uint, LfgLockInfoData>> lockMap, List<string> playersMissingRequirement, bool isContinue) void GetCompatibleDungeons(List<uint> dungeons, List<ObjectGuid> players, Dictionary<ObjectGuid, Dictionary<uint, LfgLockInfoData>> lockMap, List<string> playersMissingRequirement, bool isContinue)
{ {
lockMap.Clear(); lockMap.Clear();
Dictionary<uint, uint> lockedDungeons = new Dictionary<uint, uint>(); Dictionary<uint, uint> lockedDungeons = new();
List<uint> dungeonsToRemove = new List<uint>(); List<uint> dungeonsToRemove = new();
foreach (var guid in players) foreach (var guid in players)
{ {
@@ -806,7 +806,7 @@ namespace Game.DungeonFinding
byte tank = 0; byte tank = 0;
byte healer = 0; byte healer = 0;
List<ObjectGuid> keys = new List<ObjectGuid>(groles.Keys); List<ObjectGuid> keys = new(groles.Keys);
for (int i = 0; i < keys.Count; i++) for (int i = 0; i < keys.Count; i++)
{ {
LfgRoles role = groles[keys[i]] & ~LfgRoles.Leader; LfgRoles role = groles[keys[i]] & ~LfgRoles.Leader;
@@ -866,8 +866,8 @@ namespace Game.DungeonFinding
void MakeNewGroup(LfgProposal proposal) void MakeNewGroup(LfgProposal proposal)
{ {
List<ObjectGuid> players = new List<ObjectGuid>(); List<ObjectGuid> players = new();
List<ObjectGuid> playersToTeleport = new List<ObjectGuid>(); List<ObjectGuid> playersToTeleport = new();
foreach (var it in proposal.players) foreach (var it in proposal.players)
{ {
@@ -981,7 +981,7 @@ namespace Game.DungeonFinding
long joinTime = Time.UnixTime; long joinTime = Time.UnixTime;
LFGQueue queue = GetQueue(guid); LFGQueue queue = GetQueue(guid);
LfgUpdateData updateData = new LfgUpdateData(LfgUpdateType.GroupFound); LfgUpdateData updateData = new(LfgUpdateType.GroupFound);
foreach (var it in proposal.players) foreach (var it in proposal.players)
{ {
ObjectGuid pguid = it.Key; ObjectGuid pguid = it.Key;
@@ -1048,7 +1048,7 @@ namespace Game.DungeonFinding
it.Value.accept = LfgAnswer.Deny; it.Value.accept = LfgAnswer.Deny;
// Mark players/groups to be removed // Mark players/groups to be removed
List<ObjectGuid> toRemove = new List<ObjectGuid>(); List<ObjectGuid> toRemove = new();
foreach (var it in proposal.players) foreach (var it in proposal.players)
{ {
if (it.Value.accept == LfgAnswer.Agree) if (it.Value.accept == LfgAnswer.Agree)
@@ -1073,7 +1073,7 @@ namespace Game.DungeonFinding
if (toRemove.Contains(gguid)) // Didn't accept or in same group that someone that didn't accept if (toRemove.Contains(gguid)) // Didn't accept or in same group that someone that didn't accept
{ {
LfgUpdateData updateData = new LfgUpdateData(); LfgUpdateData updateData = new();
if (it.Value.accept == LfgAnswer.Deny) if (it.Value.accept == LfgAnswer.Deny)
{ {
updateData.updateType = type; updateData.updateType = type;
@@ -1369,7 +1369,7 @@ namespace Game.DungeonFinding
// Give rewards // Give rewards
string doneString = done ? "" : "not"; string doneString = done ? "" : "not";
Log.outDebug(LogFilter.Lfg, $"Group: {gguid}, Player: {guid} done dungeon {GetDungeon(gguid)}, {doneString} previously done."); Log.outDebug(LogFilter.Lfg, $"Group: {gguid}, Player: {guid} done dungeon {GetDungeon(gguid)}, {doneString} previously done.");
LfgPlayerRewardData data = new LfgPlayerRewardData(dungeon.Entry(), GetDungeon(gguid, false), done, quest); LfgPlayerRewardData data = new(dungeon.Entry(), GetDungeon(gguid, false), done, quest);
player.GetSession().SendLfgPlayerReward(data); player.GetSession().SendLfgPlayerReward(data);
} }
} }
@@ -1509,7 +1509,7 @@ namespace Game.DungeonFinding
public Dictionary<uint, LfgLockInfoData> GetLockedDungeons(ObjectGuid guid) public Dictionary<uint, LfgLockInfoData> GetLockedDungeons(ObjectGuid guid)
{ {
Dictionary<uint, LfgLockInfoData> lockDic = new Dictionary<uint, LfgLockInfoData>(); Dictionary<uint, LfgLockInfoData> lockDic = new();
Player player = Global.ObjAccessor.FindConnectedPlayer(guid); Player player = Global.ObjAccessor.FindConnectedPlayer(guid);
if (!player) if (!player)
{ {
@@ -1940,7 +1940,7 @@ namespace Game.DungeonFinding
public void SetupGroupMember(ObjectGuid guid, ObjectGuid gguid) public void SetupGroupMember(ObjectGuid guid, ObjectGuid gguid)
{ {
List<uint> dungeons = new List<uint>(); List<uint> dungeons = new();
dungeons.Add(GetDungeon(gguid)); dungeons.Add(GetDungeon(gguid));
SetSelectedDungeons(guid, dungeons); SetSelectedDungeons(guid, dungeons);
SetState(guid, GetState(gguid)); SetState(guid, GetState(gguid));
@@ -1995,7 +1995,7 @@ namespace Game.DungeonFinding
public List<uint> GetRandomAndSeasonalDungeons(uint level, uint expansion, uint contentTuningReplacementConditionMask) public List<uint> GetRandomAndSeasonalDungeons(uint level, uint expansion, uint contentTuningReplacementConditionMask)
{ {
List<uint> randomDungeons = new List<uint>(); List<uint> randomDungeons = new();
foreach (var dungeon in LfgDungeonStore.Values) foreach (var dungeon in LfgDungeonStore.Values)
{ {
if (!(dungeon.type == LfgType.RandomDungeon || (dungeon.seasonal && Global.LFGMgr.IsSeasonActive(dungeon.id)))) if (!(dungeon.type == LfgType.RandomDungeon || (dungeon.seasonal && Global.LFGMgr.IsSeasonActive(dungeon.id))))
@@ -2019,17 +2019,17 @@ namespace Game.DungeonFinding
uint m_lfgProposalId; //< used as internal counter for proposals uint m_lfgProposalId; //< used as internal counter for proposals
LfgOptions m_options; //< Stores config options LfgOptions m_options; //< Stores config options
Dictionary<byte, LFGQueue> QueuesStore = new Dictionary<byte, LFGQueue>(); //< Queues Dictionary<byte, LFGQueue> QueuesStore = new(); //< Queues
MultiMap<byte, uint> CachedDungeonMapStore = new MultiMap<byte, uint>(); //< Stores all dungeons by groupType MultiMap<byte, uint> CachedDungeonMapStore = new(); //< Stores all dungeons by groupType
// Reward System // Reward System
MultiMap<uint, LfgReward> RewardMapStore = new MultiMap<uint, LfgReward>(); //< Stores rewards for random dungeons MultiMap<uint, LfgReward> RewardMapStore = new(); //< Stores rewards for random dungeons
Dictionary<uint, LFGDungeonData> LfgDungeonStore = new Dictionary<uint, LFGDungeonData>(); Dictionary<uint, LFGDungeonData> LfgDungeonStore = new();
// Rolecheck - Proposal - Vote Kicks // Rolecheck - Proposal - Vote Kicks
Dictionary<ObjectGuid, LfgRoleCheck> RoleChecksStore = new Dictionary<ObjectGuid, LfgRoleCheck>(); //< Current Role checks Dictionary<ObjectGuid, LfgRoleCheck> RoleChecksStore = new(); //< Current Role checks
Dictionary<uint, LfgProposal> ProposalsStore = new Dictionary<uint, LfgProposal>(); //< Current Proposals Dictionary<uint, LfgProposal> ProposalsStore = new(); //< Current Proposals
Dictionary<ObjectGuid, LfgPlayerBoot> BootsStore = new Dictionary<ObjectGuid, LfgPlayerBoot>(); //< Current player kicks Dictionary<ObjectGuid, LfgPlayerBoot> BootsStore = new(); //< Current player kicks
Dictionary<ObjectGuid, LFGPlayerData> PlayersStore = new Dictionary<ObjectGuid, LFGPlayerData>(); //< Player data Dictionary<ObjectGuid, LFGPlayerData> PlayersStore = new(); //< Player data
Dictionary<ObjectGuid, LFGGroupData> GroupsStore = new Dictionary<ObjectGuid, LFGGroupData>(); //< Group data Dictionary<ObjectGuid, LFGGroupData> GroupsStore = new(); //< Group data
} }
public class LfgJoinResultData public class LfgJoinResultData
@@ -2042,8 +2042,8 @@ namespace Game.DungeonFinding
public LfgJoinResult result; public LfgJoinResult result;
public LfgRoleCheckState state; public LfgRoleCheckState state;
public Dictionary<ObjectGuid, Dictionary<uint, LfgLockInfoData>> lockmap = new Dictionary<ObjectGuid, Dictionary<uint, LfgLockInfoData>>(); public Dictionary<ObjectGuid, Dictionary<uint, LfgLockInfoData>> lockmap = new();
public List<string> playersMissingRequirement = new List<string>(); public List<string> playersMissingRequirement = new();
} }
public class LfgUpdateData public class LfgUpdateData
@@ -2068,7 +2068,7 @@ namespace Game.DungeonFinding
public LfgUpdateType updateType; public LfgUpdateType updateType;
public LfgState state; public LfgState state;
public List<uint> dungeons = new List<uint>(); public List<uint> dungeons = new();
} }
public class LfgQueueStatusData public class LfgQueueStatusData
@@ -2168,17 +2168,17 @@ namespace Game.DungeonFinding
public long cancelTime; public long cancelTime;
public uint encounters; public uint encounters;
public bool isNew; public bool isNew;
public List<ObjectGuid> queues = new List<ObjectGuid>(); public List<ObjectGuid> queues = new();
public List<ulong> showorder = new List<ulong>(); public List<ulong> showorder = new();
public Dictionary<ObjectGuid, LfgProposalPlayer> players = new Dictionary<ObjectGuid, LfgProposalPlayer>(); // Players data public Dictionary<ObjectGuid, LfgProposalPlayer> players = new(); // Players data
} }
public class LfgRoleCheck public class LfgRoleCheck
{ {
public long cancelTime; public long cancelTime;
public Dictionary<ObjectGuid, LfgRoles> roles = new Dictionary<ObjectGuid, LfgRoles>(); public Dictionary<ObjectGuid, LfgRoles> roles = new();
public LfgRoleCheckState state; public LfgRoleCheckState state;
public List<uint> dungeons = new List<uint>(); public List<uint> dungeons = new();
public uint rDungeonId; public uint rDungeonId;
public ObjectGuid leader; public ObjectGuid leader;
} }
@@ -2187,7 +2187,7 @@ namespace Game.DungeonFinding
{ {
public long cancelTime; public long cancelTime;
public bool inProgress; public bool inProgress;
public Dictionary<ObjectGuid, LfgAnswer> votes = new Dictionary<ObjectGuid, LfgAnswer>(); public Dictionary<ObjectGuid, LfgAnswer> votes = new();
public ObjectGuid victim; public ObjectGuid victim;
public string reason; public string reason;
} }
+1 -1
View File
@@ -126,6 +126,6 @@ namespace Game.DungeonFinding
// Queue // Queue
LfgRoles m_Roles; LfgRoles m_Roles;
List<uint> m_SelectedDungeons = new List<uint>(); List<uint> m_SelectedDungeons = new();
} }
} }
+20 -20
View File
@@ -32,7 +32,7 @@ namespace Game.DungeonFinding
return ""; return "";
// need the guids in order to avoid duplicates // need the guids in order to avoid duplicates
StringBuilder val = new StringBuilder(); StringBuilder val = new();
guids.Sort(); guids.Sort();
var it = guids.First(); var it = guids.First();
val.Append(it); val.Append(it);
@@ -48,7 +48,7 @@ namespace Game.DungeonFinding
public static string GetRolesString(LfgRoles roles) public static string GetRolesString(LfgRoles roles)
{ {
StringBuilder rolesstr = new StringBuilder(); StringBuilder rolesstr = new();
if (roles.HasAnyFlag(LfgRoles.Tank)) if (roles.HasAnyFlag(LfgRoles.Tank))
rolesstr.Append("Tank"); rolesstr.Append("Tank");
@@ -276,7 +276,7 @@ namespace Game.DungeonFinding
public byte FindGroups() public byte FindGroups()
{ {
byte proposals = 0; byte proposals = 0;
List<ObjectGuid> firstNew = new List<ObjectGuid>(); List<ObjectGuid> firstNew = new();
while (!newToQueueStore.Empty()) while (!newToQueueStore.Empty())
{ {
ObjectGuid frontguid = newToQueueStore.First(); ObjectGuid frontguid = newToQueueStore.First();
@@ -285,7 +285,7 @@ namespace Game.DungeonFinding
firstNew.Add(frontguid); firstNew.Add(frontguid);
RemoveFromNewQueue(frontguid); RemoveFromNewQueue(frontguid);
List<ObjectGuid> temporalList = new List<ObjectGuid>(currentQueueStore); List<ObjectGuid> temporalList = new(currentQueueStore);
LfgCompatibility compatibles = FindNewGroups(firstNew, temporalList); LfgCompatibility compatibles = FindNewGroups(firstNew, temporalList);
if (compatibles == LfgCompatibility.Match) if (compatibles == LfgCompatibility.Match)
@@ -331,10 +331,10 @@ namespace Game.DungeonFinding
LfgCompatibility CheckCompatibility(List<ObjectGuid> check) LfgCompatibility CheckCompatibility(List<ObjectGuid> check)
{ {
string strGuids = ConcatenateGuids(check); string strGuids = ConcatenateGuids(check);
LfgProposal proposal = new LfgProposal(); LfgProposal proposal = new();
List<uint> proposalDungeons; List<uint> proposalDungeons;
Dictionary<ObjectGuid, ObjectGuid> proposalGroups = new Dictionary<ObjectGuid, ObjectGuid>(); Dictionary<ObjectGuid, ObjectGuid> proposalGroups = new();
Dictionary<ObjectGuid, LfgRoles> proposalRoles = new Dictionary<ObjectGuid, LfgRoles>(); Dictionary<ObjectGuid, LfgRoles> proposalRoles = new();
// Check for correct size // Check for correct size
if (check.Count > MapConst.MaxGroupSize || check.Empty()) if (check.Count > MapConst.MaxGroupSize || check.Empty())
@@ -397,7 +397,7 @@ namespace Game.DungeonFinding
var guid = check.First(); var guid = check.First();
var itQueue = QueueDataStore.LookupByKey(guid); var itQueue = QueueDataStore.LookupByKey(guid);
LfgCompatibilityData data = new LfgCompatibilityData(LfgCompatibility.WithLessPlayers); LfgCompatibilityData data = new(LfgCompatibility.WithLessPlayers);
data.roles = itQueue.roles; data.roles = itQueue.roles;
Global.LFGMgr.CheckGroupRoles(data.roles); Global.LFGMgr.CheckGroupRoles(data.roles);
@@ -428,7 +428,7 @@ namespace Game.DungeonFinding
Dictionary<ObjectGuid, LfgRoles> roles = QueueDataStore[it].roles; Dictionary<ObjectGuid, LfgRoles> roles = QueueDataStore[it].roles;
foreach (var rolePair in roles) foreach (var rolePair in roles)
{ {
KeyValuePair<ObjectGuid, LfgRoles> itPlayer = new KeyValuePair<ObjectGuid, LfgRoles>(); KeyValuePair<ObjectGuid, LfgRoles> itPlayer = new();
foreach (var _player in proposalRoles) foreach (var _player in proposalRoles)
{ {
itPlayer = _player; itPlayer = _player;
@@ -497,7 +497,7 @@ namespace Game.DungeonFinding
if (numPlayers != MapConst.MaxGroupSize) if (numPlayers != MapConst.MaxGroupSize)
{ {
Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) Compatibles but not enough players({1})", strGuids, numPlayers); Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) Compatibles but not enough players({1})", strGuids, numPlayers);
LfgCompatibilityData data = new LfgCompatibilityData(LfgCompatibility.WithLessPlayers); LfgCompatibilityData data = new(LfgCompatibility.WithLessPlayers);
data.roles = proposalRoles; data.roles = proposalRoles;
foreach (var guid in check) foreach (var guid in check)
@@ -541,7 +541,7 @@ namespace Game.DungeonFinding
proposal.leader = rolePair.Key; proposal.leader = rolePair.Key;
// Assing player data and roles // Assing player data and roles
LfgProposalPlayer data = new LfgProposalPlayer(); LfgProposalPlayer data = new();
data.role = rolePair.Value; data.role = rolePair.Value;
data.group = proposalGroups.LookupByKey(rolePair.Key); data.group = proposalGroups.LookupByKey(rolePair.Key);
if (!proposal.isNew && !data.group.IsEmpty() && data.group == proposal.group) // Player from existing group, autoaccept if (!proposal.isNew && !data.group.IsEmpty() && data.group == proposal.group) // Player from existing group, autoaccept
@@ -615,7 +615,7 @@ namespace Game.DungeonFinding
if (string.IsNullOrEmpty(queueinfo.bestCompatible)) if (string.IsNullOrEmpty(queueinfo.bestCompatible))
FindBestCompatibleInQueue(itQueue.Key, itQueue.Value); FindBestCompatibleInQueue(itQueue.Key, itQueue.Value);
LfgQueueStatusData queueData = new LfgQueueStatusData(queueId, dungeonId, waitTime, wtAvg, wtTank, wtHealer, wtDps, queuedTime, queueinfo.tanks, queueinfo.healers, queueinfo.dps); LfgQueueStatusData queueData = new(queueId, dungeonId, waitTime, wtAvg, wtTank, wtHealer, wtDps, queuedTime, queueinfo.tanks, queueinfo.healers, queueinfo.dps);
foreach (var itPlayer in queueinfo.roles) foreach (var itPlayer in queueinfo.roles)
{ {
ObjectGuid pguid = itPlayer.Key; ObjectGuid pguid = itPlayer.Key;
@@ -708,15 +708,15 @@ namespace Game.DungeonFinding
} }
// Queue // Queue
Dictionary<ObjectGuid, LfgQueueData> QueueDataStore = new Dictionary<ObjectGuid, LfgQueueData>(); Dictionary<ObjectGuid, LfgQueueData> QueueDataStore = new();
Dictionary<string, LfgCompatibilityData> CompatibleMapStore = new Dictionary<string, LfgCompatibilityData>(); Dictionary<string, LfgCompatibilityData> CompatibleMapStore = new();
Dictionary<uint, LfgWaitTime> waitTimesAvgStore = new Dictionary<uint, LfgWaitTime>(); Dictionary<uint, LfgWaitTime> waitTimesAvgStore = new();
Dictionary<uint, LfgWaitTime> waitTimesTankStore = new Dictionary<uint, LfgWaitTime>(); Dictionary<uint, LfgWaitTime> waitTimesTankStore = new();
Dictionary<uint, LfgWaitTime> waitTimesHealerStore = new Dictionary<uint, LfgWaitTime>(); Dictionary<uint, LfgWaitTime> waitTimesHealerStore = new();
Dictionary<uint, LfgWaitTime> waitTimesDpsStore = new Dictionary<uint, LfgWaitTime>(); Dictionary<uint, LfgWaitTime> waitTimesDpsStore = new();
List<ObjectGuid> currentQueueStore = new List<ObjectGuid>(); List<ObjectGuid> currentQueueStore = new();
List<ObjectGuid> newToQueueStore = new List<ObjectGuid>(); List<ObjectGuid> newToQueueStore = new();
} }
public class LfgCompatibilityData public class LfgCompatibilityData
+16 -16
View File
@@ -127,12 +127,12 @@ namespace Game.Entities
SetUpdateFieldValue(extraScaleCurve.ModifyValue(extraScaleCurve.StartTimeOffset), GetMiscTemplate().ExtraScale.Structured.StartTimeOffset); SetUpdateFieldValue(extraScaleCurve.ModifyValue(extraScaleCurve.StartTimeOffset), GetMiscTemplate().ExtraScale.Structured.StartTimeOffset);
if (GetMiscTemplate().ExtraScale.Structured.X != 0 || GetMiscTemplate().ExtraScale.Structured.Y != 0) if (GetMiscTemplate().ExtraScale.Structured.X != 0 || GetMiscTemplate().ExtraScale.Structured.Y != 0)
{ {
Vector2 point = new Vector2(GetMiscTemplate().ExtraScale.Structured.X, GetMiscTemplate().ExtraScale.Structured.Y); Vector2 point = new(GetMiscTemplate().ExtraScale.Structured.X, GetMiscTemplate().ExtraScale.Structured.Y);
SetUpdateFieldValue(ref extraScaleCurve.ModifyValue(extraScaleCurve.Points, 0), point); SetUpdateFieldValue(ref extraScaleCurve.ModifyValue(extraScaleCurve.Points, 0), point);
} }
if (GetMiscTemplate().ExtraScale.Structured.Z != 0 || GetMiscTemplate().ExtraScale.Structured.W != 0) if (GetMiscTemplate().ExtraScale.Structured.Z != 0 || GetMiscTemplate().ExtraScale.Structured.W != 0)
{ {
Vector2 point = new Vector2(GetMiscTemplate().ExtraScale.Structured.Z, GetMiscTemplate().ExtraScale.Structured.W); Vector2 point = new(GetMiscTemplate().ExtraScale.Structured.Z, GetMiscTemplate().ExtraScale.Structured.W);
SetUpdateFieldValue(ref extraScaleCurve.ModifyValue(extraScaleCurve.Points, 1), point); SetUpdateFieldValue(ref extraScaleCurve.ModifyValue(extraScaleCurve.Points, 1), point);
} }
unsafe unsafe
@@ -205,7 +205,7 @@ namespace Game.Entities
public static AreaTrigger CreateAreaTrigger(uint spellMiscId, Unit caster, Unit target, SpellInfo spell, Position pos, int duration, SpellCastVisualField spellVisual, ObjectGuid castId = default, AuraEffect aurEff = null) public static AreaTrigger CreateAreaTrigger(uint spellMiscId, Unit caster, Unit target, SpellInfo spell, Position pos, int duration, SpellCastVisualField spellVisual, ObjectGuid castId = default, AuraEffect aurEff = null)
{ {
AreaTrigger at = new AreaTrigger(); AreaTrigger at = new();
if (!at.Create(spellMiscId, caster, target, spell, pos, duration, spellVisual, castId, aurEff)) if (!at.Create(spellMiscId, caster, target, spell, pos, duration, spellVisual, castId, aurEff))
return null; return null;
@@ -327,7 +327,7 @@ namespace Game.Entities
void UpdateTargetList() void UpdateTargetList()
{ {
List<Unit> targetList = new List<Unit>(); List<Unit> targetList = new();
switch (GetTemplate().TriggerType) switch (GetTemplate().TriggerType)
{ {
@@ -405,7 +405,7 @@ namespace Game.Entities
float minZ = GetPositionZ() - halfExtentsZ; float minZ = GetPositionZ() - halfExtentsZ;
float maxZ = GetPositionZ() + halfExtentsZ; float maxZ = GetPositionZ() + halfExtentsZ;
AxisAlignedBox box = new AxisAlignedBox(new Vector3(minX, minY, minZ), new Vector3(maxX, maxY, maxZ)); AxisAlignedBox box = new(new Vector3(minX, minY, minZ), new Vector3(maxX, maxY, maxZ));
targetList.RemoveAll(unit => !box.contains(new Vector3(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ()))); targetList.RemoveAll(unit => !box.contains(new Vector3(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ())));
} }
@@ -437,7 +437,7 @@ namespace Game.Entities
List<ObjectGuid> exitUnits = _insideUnits; List<ObjectGuid> exitUnits = _insideUnits;
_insideUnits.Clear(); _insideUnits.Clear();
List<Unit> enteringUnits = new List<Unit>(); List<Unit> enteringUnits = new();
foreach (Unit unit in newTargetList) foreach (Unit unit in newTargetList)
{ {
@@ -668,7 +668,7 @@ namespace Game.Entities
float angleCos = (float)Math.Cos(GetOrientation()); float angleCos = (float)Math.Cos(GetOrientation());
// This is needed to rotate the spline, following caster orientation // This is needed to rotate the spline, following caster orientation
List<Vector3> rotatedPoints = new List<Vector3>(); List<Vector3> rotatedPoints = new();
for (var i = 0; i < offsets.Count; ++i) for (var i = 0; i < offsets.Count; ++i)
{ {
Vector3 offset = offsets[i]; Vector3 offset = offsets[i];
@@ -715,12 +715,12 @@ namespace Game.Entities
{ {
if (_reachedDestination) if (_reachedDestination)
{ {
AreaTriggerRePath reshapeDest = new AreaTriggerRePath(); AreaTriggerRePath reshapeDest = new();
reshapeDest.TriggerGUID = GetGUID(); reshapeDest.TriggerGUID = GetGUID();
SendMessageToSet(reshapeDest, true); SendMessageToSet(reshapeDest, true);
} }
AreaTriggerRePath reshape = new AreaTriggerRePath(); AreaTriggerRePath reshape = new();
reshape.TriggerGUID = GetGUID(); reshape.TriggerGUID = GetGUID();
reshape.AreaTriggerSpline.HasValue = true; reshape.AreaTriggerSpline.HasValue = true;
reshape.AreaTriggerSpline.Value.ElapsedTimeForMovement = GetElapsedTimeForMovement(); reshape.AreaTriggerSpline.Value.ElapsedTimeForMovement = GetElapsedTimeForMovement();
@@ -751,7 +751,7 @@ namespace Game.Entities
if (IsInWorld) if (IsInWorld)
{ {
AreaTriggerRePath reshape = new AreaTriggerRePath(); AreaTriggerRePath reshape = new();
reshape.TriggerGUID = GetGUID(); reshape.TriggerGUID = GetGUID();
reshape.AreaTriggerOrbit = _orbitInfo; reshape.AreaTriggerOrbit = _orbitInfo;
@@ -919,7 +919,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt8((byte)flags); buffer.WriteUInt8((byte)flags);
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
@@ -932,7 +932,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(m_values.GetChangedObjectTypeMask()); buffer.WriteUInt32(m_values.GetChangedObjectTypeMask());
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
@@ -947,14 +947,14 @@ namespace Game.Entities
void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedAreaTriggerMask, Player target) void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedAreaTriggerMask, Player target)
{ {
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
if (requestedAreaTriggerMask.IsAnySet()) if (requestedAreaTriggerMask.IsAnySet())
valuesMask.Set((int)TypeId.AreaTrigger); valuesMask.Set((int)TypeId.AreaTrigger);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -963,7 +963,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.AreaTrigger]) if (valuesMask[(int)TypeId.AreaTrigger])
m_areaTriggerData.WriteUpdate(buffer, requestedAreaTriggerMask, true, this, target); m_areaTriggerData.WriteUpdate(buffer, requestedAreaTriggerMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
@@ -1054,7 +1054,7 @@ namespace Game.Entities
AreaTriggerMiscTemplate _areaTriggerMiscTemplate; AreaTriggerMiscTemplate _areaTriggerMiscTemplate;
AreaTriggerTemplate _areaTriggerTemplate; AreaTriggerTemplate _areaTriggerTemplate;
List<ObjectGuid> _insideUnits = new List<ObjectGuid>(); List<ObjectGuid> _insideUnits = new();
AreaTriggerAI _ai; AreaTriggerAI _ai;
} }
@@ -272,9 +272,9 @@ namespace Game.Entities
public uint ScriptId; public uint ScriptId;
public float MaxSearchRadius; public float MaxSearchRadius;
public List<Vector2> PolygonVertices = new List<Vector2>(); public List<Vector2> PolygonVertices = new();
public List<Vector2> PolygonVerticesTarget = new List<Vector2>(); public List<Vector2> PolygonVerticesTarget = new();
public List<AreaTriggerAction> Actions = new List<AreaTriggerAction>(); public List<AreaTriggerAction> Actions = new();
} }
public unsafe class AreaTriggerMiscTemplate public unsafe class AreaTriggerMiscTemplate
@@ -305,12 +305,12 @@ namespace Game.Entities
public uint TimeToTarget; public uint TimeToTarget;
public uint TimeToTargetScale; public uint TimeToTargetScale;
public AreaTriggerScaleInfo OverrideScale = new AreaTriggerScaleInfo(); public AreaTriggerScaleInfo OverrideScale = new();
public AreaTriggerScaleInfo ExtraScale = new AreaTriggerScaleInfo(); public AreaTriggerScaleInfo ExtraScale = new();
public AreaTriggerOrbitInfo OrbitInfo; public AreaTriggerOrbitInfo OrbitInfo;
public AreaTriggerTemplate Template; public AreaTriggerTemplate Template;
public List<Vector3> SplinePoints = new List<Vector3>(); public List<Vector3> SplinePoints = new();
} }
public class AreaTriggerSpawn public class AreaTriggerSpawn
+12 -12
View File
@@ -104,7 +104,7 @@ namespace Game.Entities
ulong lowGuid = creator.GetMap().GenerateLowGuid(HighGuid.Conversation); ulong lowGuid = creator.GetMap().GenerateLowGuid(HighGuid.Conversation);
Conversation conversation = new Conversation(); Conversation conversation = new();
if (!conversation.Create(lowGuid, conversationEntry, creator.GetMap(), creator, pos, participants, spellInfo)) if (!conversation.Create(lowGuid, conversationEntry, creator.GetMap(), creator, pos, participants, spellInfo))
return null; return null;
@@ -139,7 +139,7 @@ namespace Game.Entities
{ {
if (actor != null) if (actor != null)
{ {
ConversationActor actorField = new ConversationActor(); ConversationActor actorField = new();
actorField.CreatureID = actor.CreatureId; actorField.CreatureID = actor.CreatureId;
actorField.CreatureDisplayInfoID = actor.CreatureModelId; actorField.CreatureDisplayInfoID = actor.CreatureModelId;
actorField.Id = (int)actor.Id; actorField.Id = (int)actor.Id;
@@ -168,13 +168,13 @@ namespace Game.Entities
Global.ScriptMgr.OnConversationCreate(this, creator); Global.ScriptMgr.OnConversationCreate(this, creator);
List<ushort> actorIndices = new List<ushort>(); List<ushort> actorIndices = new();
List<ConversationLine> lines = new List<ConversationLine>(); List<ConversationLine> lines = new();
foreach (ConversationLineTemplate line in conversationTemplate.Lines) foreach (ConversationLineTemplate line in conversationTemplate.Lines)
{ {
actorIndices.Add(line.ActorIdx); actorIndices.Add(line.ActorIdx);
ConversationLine lineField = new ConversationLine(); ConversationLine lineField = new();
lineField.ConversationLineID = line.Id; lineField.ConversationLineID = line.Id;
lineField.StartTime = line.StartTime; lineField.StartTime = line.StartTime;
lineField.UiCameraID = line.UiCameraID; lineField.UiCameraID = line.UiCameraID;
@@ -225,7 +225,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
m_conversationData.WriteCreate(buffer, flags, this, target); m_conversationData.WriteCreate(buffer, flags, this, target);
@@ -238,7 +238,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(m_values.GetChangedObjectTypeMask()); buffer.WriteUInt32(m_values.GetChangedObjectTypeMask());
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
@@ -253,14 +253,14 @@ namespace Game.Entities
void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedConversationMask, Player target) void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedConversationMask, Player target)
{ {
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
if (requestedConversationMask.IsAnySet()) if (requestedConversationMask.IsAnySet())
valuesMask.Set((int)TypeId.Conversation); valuesMask.Set((int)TypeId.Conversation);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -269,7 +269,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.Conversation]) if (valuesMask[(int)TypeId.Conversation])
m_conversationData.WriteUpdate(buffer, requestedConversationMask, true, this, target); m_conversationData.WriteUpdate(buffer, requestedConversationMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
@@ -297,10 +297,10 @@ namespace Game.Entities
ConversationData m_conversationData; ConversationData m_conversationData;
Position _stationaryPosition = new Position(); Position _stationaryPosition = new();
ObjectGuid _creatorGuid; ObjectGuid _creatorGuid;
uint _duration; uint _duration;
uint _textureKitId; uint _textureKitId;
List<ObjectGuid> _participants = new List<ObjectGuid>(); List<ObjectGuid> _participants = new();
} }
} }
+9 -9
View File
@@ -94,10 +94,10 @@ namespace Game.Entities
public void SaveToDB() public void SaveToDB()
{ {
// prevent DB data inconsistence problems and duplicates // prevent DB data inconsistence problems and duplicates
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
DeleteFromDB(trans); DeleteFromDB(trans);
StringBuilder items = new StringBuilder(); StringBuilder items = new();
for (var i = 0; i < EquipmentSlot.End; ++i) for (var i = 0; i < EquipmentSlot.End; ++i)
items.Append($"{m_corpseData.Items[i]} "); items.Append($"{m_corpseData.Items[i]} ");
@@ -178,7 +178,7 @@ namespace Game.Entities
SetObjectScale(1.0f); SetObjectScale(1.0f);
SetDisplayId(field.Read<uint>(5)); SetDisplayId(field.Read<uint>(5));
StringArray items = new StringArray(field.Read<string>(6), ' '); StringArray items = new(field.Read<string>(6), ' ');
for (uint index = 0; index < EquipmentSlot.End; ++index) for (uint index = 0; index < EquipmentSlot.End; ++index)
SetItem(index, uint.Parse(items[(int)index])); SetItem(index, uint.Parse(items[(int)index]));
@@ -225,7 +225,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
m_corpseData.WriteCreate(buffer, flags, this, target); m_corpseData.WriteCreate(buffer, flags, this, target);
@@ -238,7 +238,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(m_values.GetChangedObjectTypeMask()); buffer.WriteUInt32(m_values.GetChangedObjectTypeMask());
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
@@ -253,14 +253,14 @@ namespace Game.Entities
void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedCorpseMask, Player target) void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedCorpseMask, Player target)
{ {
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
if (requestedCorpseMask.IsAnySet()) if (requestedCorpseMask.IsAnySet())
valuesMask.Set((int)TypeId.Corpse); valuesMask.Set((int)TypeId.Corpse);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -269,7 +269,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.Corpse]) if (valuesMask[(int)TypeId.Corpse])
m_corpseData.WriteUpdate(buffer, requestedCorpseMask, true, this, target); m_corpseData.WriteUpdate(buffer, requestedCorpseMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
@@ -320,7 +320,7 @@ namespace Game.Entities
public CorpseData m_corpseData; public CorpseData m_corpseData;
public Loot loot = new Loot(); public Loot loot = new();
public Player lootRecipient; public Player lootRecipient;
CorpseType m_type; CorpseType m_type;
@@ -34,7 +34,7 @@ namespace Game.Entities
float m_suppressedOrientation; // Stores the creature's "real" orientation while casting float m_suppressedOrientation; // Stores the creature's "real" orientation while casting
long _lastDamagedTime; // Part of Evade mechanics long _lastDamagedTime; // Part of Evade mechanics
MultiMap<byte, byte> m_textRepeat = new MultiMap<byte, byte>(); MultiMap<byte, byte> m_textRepeat = new();
// Regenerate health // Regenerate health
bool _regenerateHealth; // Set on creation bool _regenerateHealth; // Set on creation
@@ -61,7 +61,7 @@ namespace Game.Entities
public uint m_originalEntry; public uint m_originalEntry;
Position m_homePosition; Position m_homePosition;
Position m_transportHomePosition = new Position(); Position m_transportHomePosition = new();
bool DisableReputationGain; bool DisableReputationGain;
@@ -90,9 +90,9 @@ namespace Game.Entities
uint m_combatPulseDelay; // (secs) how often the creature puts the entire zone in combat (only works in dungeons) uint m_combatPulseDelay; // (secs) how often the creature puts the entire zone in combat (only works in dungeons)
// vendor items // vendor items
List<VendorItemCount> m_vendorItemCounts = new List<VendorItemCount>(); List<VendorItemCount> m_vendorItemCounts = new();
public Loot loot = new Loot(); public Loot loot = new();
public uint m_groupLootTimer; // (msecs)timer used for group loot public uint m_groupLootTimer; // (msecs)timer used for group loot
public ObjectGuid lootingGroupLowGUID; // used to find group which is looting corpse public ObjectGuid lootingGroupLowGUID; // used to find group which is looting corpse
ObjectGuid m_lootRecipient; ObjectGuid m_lootRecipient;
+11 -11
View File
@@ -798,7 +798,7 @@ namespace Game.Entities
else else
lowGuid = map.GenerateLowGuid(HighGuid.Creature); lowGuid = map.GenerateLowGuid(HighGuid.Creature);
Creature creature = new Creature(); Creature creature = new();
if (!creature.Create(lowGuid, map, entry, pos, null, vehId)) if (!creature.Create(lowGuid, map, entry, pos, null, vehId))
return null; return null;
@@ -807,7 +807,7 @@ namespace Game.Entities
public static Creature CreateCreatureFromDB(ulong spawnId, Map map, bool addToMap = true, bool allowDuplicate = false) public static Creature CreateCreatureFromDB(ulong spawnId, Map map, bool addToMap = true, bool allowDuplicate = false)
{ {
Creature creature = new Creature(); Creature creature = new();
if (!creature.LoadFromDB(spawnId, map, addToMap, allowDuplicate)) if (!creature.LoadFromDB(spawnId, map, addToMap, allowDuplicate))
return null; return null;
@@ -1181,7 +1181,7 @@ namespace Game.Entities
data.phaseGroup = GetDBPhase() < 0 ? (uint)-GetDBPhase() : data.phaseGroup; data.phaseGroup = GetDBPhase() < 0 ? (uint)-GetDBPhase() : data.phaseGroup;
// update in DB // update in DB
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_CREATURE); PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_CREATURE);
stmt.AddValue(0, m_spawnId); stmt.AddValue(0, m_spawnId);
@@ -1500,7 +1500,7 @@ namespace Game.Entities
GetMap().RemoveRespawnTime(SpawnObjectType.Creature, m_spawnId); GetMap().RemoveRespawnTime(SpawnObjectType.Creature, m_spawnId);
Global.ObjectMgr.DeleteCreatureData(m_spawnId); Global.ObjectMgr.DeleteCreatureData(m_spawnId);
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_CREATURE); PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_CREATURE);
stmt.AddValue(0, m_spawnId); stmt.AddValue(0, m_spawnId);
@@ -1772,7 +1772,7 @@ namespace Game.Entities
SetDeathState(DeathState.JustRespawned); SetDeathState(DeathState.JustRespawned);
CreatureModel display = new CreatureModel(GetNativeDisplayId(), GetNativeDisplayScale(), 1.0f); CreatureModel display = new(GetNativeDisplayId(), GetNativeDisplayScale(), 1.0f);
if (Global.ObjectMgr.GetCreatureModelRandomGender(ref display, GetCreatureTemplate()) != null) if (Global.ObjectMgr.GetCreatureModelRandomGender(ref display, GetCreatureTemplate()) != null)
{ {
SetDisplayId(display.CreatureDisplayID, display.DisplayScale); SetDisplayId(display.CreatureDisplayID, display.DisplayScale);
@@ -1977,7 +1977,7 @@ namespace Game.Entities
public void SendAIReaction(AiReaction reactionType) public void SendAIReaction(AiReaction reactionType)
{ {
AIReaction packet = new AIReaction(); AIReaction packet = new();
packet.UnitGUID = GetGUID(); packet.UnitGUID = GetGUID();
packet.Reaction = reactionType; packet.Reaction = reactionType;
@@ -1995,7 +1995,7 @@ namespace Game.Entities
if (radius > 0) if (radius > 0)
{ {
List<Creature> assistList = new List<Creature>(); List<Creature> assistList = new();
var u_check = new AnyAssistCreatureInRangeCheck(this, GetVictim(), radius); var u_check = new AnyAssistCreatureInRangeCheck(this, GetVictim(), radius);
var searcher = new CreatureListSearcher(this, assistList, u_check); var searcher = new CreatureListSearcher(this, assistList, u_check);
@@ -2003,7 +2003,7 @@ namespace Game.Entities
if (!assistList.Empty()) if (!assistList.Empty())
{ {
AssistDelayEvent e = new AssistDelayEvent(GetVictim().GetGUID(), this); AssistDelayEvent e = new(GetVictim().GetGUID(), this);
while (!assistList.Empty()) while (!assistList.Empty())
{ {
// Pushing guids because in delay can happen some creature gets despawned // Pushing guids because in delay can happen some creature gets despawned
@@ -2271,7 +2271,7 @@ namespace Game.Entities
{ {
Team enemy_team = attacker.GetTeam(); Team enemy_team = attacker.GetTeam();
ZoneUnderAttack packet = new ZoneUnderAttack(); ZoneUnderAttack packet = new();
packet.AreaID = (int)GetAreaId(); packet.AreaID = (int)GetAreaId();
Global.WorldMgr.SendGlobalMessage(packet, null, (enemy_team == Team.Alliance ? Team.Horde : Team.Alliance)); Global.WorldMgr.SendGlobalMessage(packet, null, (enemy_team == Team.Alliance ? Team.Horde : Team.Alliance));
} }
@@ -2969,7 +2969,7 @@ namespace Game.Entities
// If an alive instance of this spawnId is already found, skip creation // If an alive instance of this spawnId is already found, skip creation
// If only dead instance(s) exist, despawn them and spawn a new (maybe also dead) version // If only dead instance(s) exist, despawn them and spawn a new (maybe also dead) version
var creatureBounds = map.GetCreatureBySpawnIdStore().LookupByKey(spawnId); var creatureBounds = map.GetCreatureBySpawnIdStore().LookupByKey(spawnId);
List<Creature> despawnList = new List<Creature>(); List<Creature> despawnList = new();
foreach (var creature in creatureBounds) foreach (var creature in creatureBounds)
{ {
@@ -3305,7 +3305,7 @@ namespace Game.Entities
ObjectGuid m_victim; ObjectGuid m_victim;
List<ObjectGuid> m_assistants = new List<ObjectGuid>(); List<ObjectGuid> m_assistants = new();
Unit m_owner; Unit m_owner;
} }
+11 -11
View File
@@ -30,7 +30,7 @@ namespace Game.Entities
public uint Entry; public uint Entry;
public uint[] DifficultyEntry = new uint[SharedConst.MaxCreatureDifficulties]; public uint[] DifficultyEntry = new uint[SharedConst.MaxCreatureDifficulties];
public uint[] KillCredit = new uint[SharedConst.MaxCreatureKillCredit]; public uint[] KillCredit = new uint[SharedConst.MaxCreatureKillCredit];
public List<CreatureModel> Models = new List<CreatureModel>(); public List<CreatureModel> Models = new();
public string Name; public string Name;
public string FemaleName; public string FemaleName;
public string SubName; public string SubName;
@@ -38,7 +38,7 @@ namespace Game.Entities
public string IconName; public string IconName;
public uint GossipMenuId; public uint GossipMenuId;
public short Minlevel; public short Minlevel;
public Dictionary<Difficulty, CreatureLevelScaling> scalingStorage = new Dictionary<Difficulty, CreatureLevelScaling>(); public Dictionary<Difficulty, CreatureLevelScaling> scalingStorage = new();
public short Maxlevel; public short Maxlevel;
public int HealthScalingExpansion; public int HealthScalingExpansion;
public uint RequiredExpansion; public uint RequiredExpansion;
@@ -235,7 +235,7 @@ namespace Game.Entities
QueryData.CreatureID = Entry; QueryData.CreatureID = Entry;
QueryData.Allow = true; QueryData.Allow = true;
CreatureStats stats = new CreatureStats(); CreatureStats stats = new();
stats.Leader = RacialLeader; stats.Leader = RacialLeader;
stats.Name[0] = Name; stats.Name[0] = Name;
@@ -308,10 +308,10 @@ namespace Game.Entities
public class CreatureLocale public class CreatureLocale
{ {
public StringArray Name = new StringArray((int)Locale.Total); public StringArray Name = new((int)Locale.Total);
public StringArray NameAlt = new StringArray((int)Locale.Total); public StringArray NameAlt = new((int)Locale.Total);
public StringArray Title = new StringArray((int)Locale.Total); public StringArray Title = new((int)Locale.Total);
public StringArray TitleAlt = new StringArray((int)Locale.Total); public StringArray TitleAlt = new((int)Locale.Total);
} }
public struct EquipmentItem public struct EquipmentItem
@@ -355,8 +355,8 @@ namespace Game.Entities
public class CreatureModel public class CreatureModel
{ {
public static CreatureModel DefaultInvisibleModel = new CreatureModel(11686, 1.0f, 1.0f); public static CreatureModel DefaultInvisibleModel = new(11686, 1.0f, 1.0f);
public static CreatureModel DefaultVisibleModel = new CreatureModel(17519, 1.0f, 1.0f); public static CreatureModel DefaultVisibleModel = new(17519, 1.0f, 1.0f);
public uint CreatureDisplayID; public uint CreatureDisplayID;
public float DisplayScale; public float DisplayScale;
@@ -402,7 +402,7 @@ namespace Game.Entities
public uint incrtime; // time for restore items amount if maxcount != 0 public uint incrtime; // time for restore items amount if maxcount != 0
public uint ExtendedCost; public uint ExtendedCost;
public ItemVendorType Type; public ItemVendorType Type;
public List<uint> BonusListIDs = new List<uint>(); public List<uint> BonusListIDs = new();
public uint PlayerConditionId; public uint PlayerConditionId;
public bool IgnoreFiltering; public bool IgnoreFiltering;
@@ -412,7 +412,7 @@ namespace Game.Entities
public class VendorItemData public class VendorItemData
{ {
List<VendorItem> m_items = new List<VendorItem>(); List<VendorItem> m_items = new();
public VendorItem GetItem(uint slot) public VendorItem GetItem(uint slot)
{ {
@@ -43,7 +43,7 @@ namespace Game.Entities
else else
{ {
Log.outDebug(LogFilter.Unit, "Group not found: {0}. Creating new group.", leaderGuid); Log.outDebug(LogFilter.Unit, "Group not found: {0}. Creating new group.", leaderGuid);
CreatureGroup group = new CreatureGroup(leaderGuid); CreatureGroup group = new(leaderGuid);
map.CreatureGroupHolder[leaderGuid] = group; map.CreatureGroupHolder[leaderGuid] = group;
group.AddMember(member); group.AddMember(member);
} }
@@ -126,7 +126,7 @@ namespace Game.Entities
Log.outInfo(LogFilter.ServerLoading, "Loaded {0} creatures in formations in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime)); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} creatures in formations in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
} }
public static Dictionary<ulong, FormationInfo> CreatureGroupMap = new Dictionary<ulong, FormationInfo>(); public static Dictionary<ulong, FormationInfo> CreatureGroupMap = new();
} }
public class FormationInfo public class FormationInfo
@@ -251,7 +251,7 @@ namespace Game.Entities
if (!member.IsFlying()) if (!member.IsFlying())
member.UpdateGroundPositionZ(dx, dy, ref dz); member.UpdateGroundPositionZ(dx, dy, ref dz);
Position point = new Position(dx, dy, dz, destination.GetOrientation()); Position point = new(dx, dy, dz, destination.GetOrientation());
member.GetMotionMaster().MoveFormation(id, point, moveType, !member.IsWithinDist(m_leader, dist + 5.0f), orientation); member.GetMotionMaster().MoveFormation(id, point, moveType, !member.IsWithinDist(m_leader, dist + 5.0f), orientation);
member.SetHomePosition(dx, dy, dz, pathangle); member.SetHomePosition(dx, dy, dz, pathangle);
@@ -279,7 +279,7 @@ namespace Game.Entities
public bool IsLeader(Creature creature) { return m_leader == creature; } public bool IsLeader(Creature creature) { return m_leader == creature; }
Creature m_leader; Creature m_leader;
Dictionary<Creature, FormationInfo> m_members = new Dictionary<Creature, FormationInfo>(); Dictionary<Creature, FormationInfo> m_members = new();
ulong m_groupID; ulong m_groupID;
bool m_Formed; bool m_Formed;
+23 -23
View File
@@ -49,7 +49,7 @@ namespace Game.Misc
} }
} }
GossipMenuItem menuItem = new GossipMenuItem(); GossipMenuItem menuItem = new();
menuItem.MenuItemIcon = (byte)icon; menuItem.MenuItemIcon = (byte)icon;
menuItem.Message = message; menuItem.Message = message;
@@ -131,7 +131,7 @@ namespace Game.Misc
public void AddGossipMenuItemData(uint optionIndex, uint gossipActionMenuId, uint gossipActionPoi) public void AddGossipMenuItemData(uint optionIndex, uint gossipActionMenuId, uint gossipActionPoi)
{ {
GossipMenuItemData itemData = new GossipMenuItemData(); GossipMenuItemData itemData = new();
itemData.GossipActionMenuId = gossipActionMenuId; itemData.GossipActionMenuId = gossipActionMenuId;
itemData.GossipActionPoi = gossipActionPoi; itemData.GossipActionPoi = gossipActionPoi;
@@ -208,8 +208,8 @@ namespace Game.Misc
return _menuItems; return _menuItems;
} }
Dictionary<uint, GossipMenuItem> _menuItems = new Dictionary<uint, GossipMenuItem>(); Dictionary<uint, GossipMenuItem> _menuItems = new();
Dictionary<uint, GossipMenuItemData> _menuItemData = new Dictionary<uint, GossipMenuItemData>(); Dictionary<uint, GossipMenuItemData> _menuItemData = new();
uint _menuId; uint _menuId;
Locale _locale; Locale _locale;
} }
@@ -247,14 +247,14 @@ namespace Game.Misc
_interactionData.Reset(); _interactionData.Reset();
_interactionData.SourceGuid = objectGUID; _interactionData.SourceGuid = objectGUID;
GossipMessagePkt packet = new GossipMessagePkt(); GossipMessagePkt packet = new();
packet.GossipGUID = objectGUID; packet.GossipGUID = objectGUID;
packet.GossipID = (int)_gossipMenu.GetMenuId(); packet.GossipID = (int)_gossipMenu.GetMenuId();
packet.TextID = (int)titleTextId; packet.TextID = (int)titleTextId;
foreach (var pair in _gossipMenu.GetMenuItems()) foreach (var pair in _gossipMenu.GetMenuItems())
{ {
ClientGossipOptions opt = new ClientGossipOptions(); ClientGossipOptions opt = new();
GossipMenuItem item = pair.Value; GossipMenuItem item = pair.Value;
opt.ClientOption = (int)pair.Key; opt.ClientOption = (int)pair.Key;
opt.OptionNPC = item.MenuItemIcon; opt.OptionNPC = item.MenuItemIcon;
@@ -274,7 +274,7 @@ namespace Game.Misc
Quest quest = Global.ObjectMgr.GetQuestTemplate(questID); Quest quest = Global.ObjectMgr.GetQuestTemplate(questID);
if (quest != null) if (quest != null)
{ {
ClientGossipText text = new ClientGossipText(); ClientGossipText text = new();
text.QuestID = questID; text.QuestID = questID;
text.ContentTuningID = quest.ContentTuningId; text.ContentTuningID = quest.ContentTuningId;
text.QuestType = item.QuestIcon; text.QuestType = item.QuestIcon;
@@ -314,7 +314,7 @@ namespace Game.Misc
return; return;
} }
GossipPOI packet = new GossipPOI(); GossipPOI packet = new();
packet.Id = pointOfInterest.Id; packet.Id = pointOfInterest.Id;
packet.Name = pointOfInterest.Name; packet.Name = pointOfInterest.Name;
@@ -339,7 +339,7 @@ namespace Game.Misc
ObjectGuid guid = questgiver.GetGUID(); ObjectGuid guid = questgiver.GetGUID();
Locale localeConstant = _session.GetSessionDbLocaleIndex(); Locale localeConstant = _session.GetSessionDbLocaleIndex();
QuestGiverQuestListMessage questList = new QuestGiverQuestListMessage(); QuestGiverQuestListMessage questList = new();
questList.QuestGiverGUID = guid; questList.QuestGiverGUID = guid;
QuestGreeting questGreeting = Global.ObjectMgr.GetQuestGreeting(questgiver.GetTypeId(), questgiver.GetEntry()); QuestGreeting questGreeting = Global.ObjectMgr.GetQuestGreeting(questgiver.GetTypeId(), questgiver.GetEntry());
@@ -365,7 +365,7 @@ namespace Game.Misc
Quest quest = Global.ObjectMgr.GetQuestTemplate(questID); Quest quest = Global.ObjectMgr.GetQuestTemplate(questID);
if (quest != null) if (quest != null)
{ {
ClientGossipText text = new ClientGossipText(); ClientGossipText text = new();
text.QuestID = questID; text.QuestID = questID;
text.ContentTuningID = quest.ContentTuningId; text.ContentTuningID = quest.ContentTuningId;
text.QuestType = questMenuItem.QuestIcon; text.QuestType = questMenuItem.QuestIcon;
@@ -399,7 +399,7 @@ namespace Game.Misc
public void SendQuestGiverQuestDetails(Quest quest, ObjectGuid npcGUID, bool autoLaunched, bool displayPopup) public void SendQuestGiverQuestDetails(Quest quest, ObjectGuid npcGUID, bool autoLaunched, bool displayPopup)
{ {
QuestGiverQuestDetails packet = new QuestGiverQuestDetails(); QuestGiverQuestDetails packet = new();
packet.QuestTitle = quest.LogTitle; packet.QuestTitle = quest.LogTitle;
packet.LogDescription = quest.LogDescription; packet.LogDescription = quest.LogDescription;
@@ -507,7 +507,7 @@ namespace Game.Misc
public void SendQuestGiverOfferReward(Quest quest, ObjectGuid npcGUID, bool autoLaunched) public void SendQuestGiverOfferReward(Quest quest, ObjectGuid npcGUID, bool autoLaunched)
{ {
QuestGiverOfferRewardMessage packet = new QuestGiverOfferRewardMessage(); QuestGiverOfferRewardMessage packet = new();
packet.QuestTitle = quest.LogTitle; packet.QuestTitle = quest.LogTitle;
packet.RewardText = quest.OfferRewardText; packet.RewardText = quest.OfferRewardText;
@@ -534,7 +534,7 @@ namespace Game.Misc
ObjectManager.GetLocaleString(questOfferRewardLocale.RewardText, locale, ref packet.RewardText); ObjectManager.GetLocaleString(questOfferRewardLocale.RewardText, locale, ref packet.RewardText);
} }
QuestGiverOfferReward offer = new QuestGiverOfferReward(); QuestGiverOfferReward offer = new();
quest.BuildQuestRewards(offer.Rewards, _session.GetPlayer()); quest.BuildQuestRewards(offer.Rewards, _session.GetPlayer());
offer.QuestGiverGUID = npcGUID; offer.QuestGiverGUID = npcGUID;
@@ -575,7 +575,7 @@ namespace Game.Misc
return; return;
} }
QuestGiverRequestItems packet = new QuestGiverRequestItems(); QuestGiverRequestItems packet = new();
packet.QuestTitle = quest.LogTitle; packet.QuestTitle = quest.LogTitle;
packet.CompletionText = quest.RequestItemsText; packet.CompletionText = quest.RequestItemsText;
@@ -654,10 +654,10 @@ namespace Game.Misc
public uint GetGossipOptionAction(uint selection) { return _gossipMenu.GetMenuItemAction(selection); } public uint GetGossipOptionAction(uint selection) { return _gossipMenu.GetMenuItemAction(selection); }
public bool IsGossipOptionCoded(uint selection) { return _gossipMenu.IsMenuItemCoded(selection); } public bool IsGossipOptionCoded(uint selection) { return _gossipMenu.IsMenuItemCoded(selection); }
GossipMenu _gossipMenu = new GossipMenu(); GossipMenu _gossipMenu = new();
QuestMenu _questMenu = new QuestMenu(); QuestMenu _questMenu = new();
WorldSession _session; WorldSession _session;
InteractionData _interactionData = new InteractionData(); InteractionData _interactionData = new();
} }
public class QuestMenu public class QuestMenu
@@ -667,7 +667,7 @@ namespace Game.Misc
if (Global.ObjectMgr.GetQuestTemplate(QuestId) == null) if (Global.ObjectMgr.GetQuestTemplate(QuestId) == null)
return; return;
QuestMenuItem questMenuItem = new QuestMenuItem(); QuestMenuItem questMenuItem = new();
questMenuItem.QuestId = QuestId; questMenuItem.QuestId = QuestId;
questMenuItem.QuestIcon = Icon; questMenuItem.QuestIcon = Icon;
@@ -704,7 +704,7 @@ namespace Game.Misc
return _questMenuItems.LookupByIndex(index); return _questMenuItems.LookupByIndex(index);
} }
List<QuestMenuItem> _questMenuItems = new List<QuestMenuItem>(); List<QuestMenuItem> _questMenuItems = new();
} }
public struct QuestMenuItem public struct QuestMenuItem
@@ -743,7 +743,7 @@ namespace Game.Misc
public class PageTextLocale public class PageTextLocale
{ {
public StringArray Text = new StringArray((int)Locale.Total); public StringArray Text = new((int)Locale.Total);
} }
public class GossipMenuItems public class GossipMenuItems
@@ -761,7 +761,7 @@ namespace Game.Misc
public uint BoxMoney; public uint BoxMoney;
public string BoxText; public string BoxText;
public uint BoxBroadcastTextId; public uint BoxBroadcastTextId;
public List<Condition> Conditions = new List<Condition>(); public List<Condition> Conditions = new();
} }
public class PointOfInterest public class PointOfInterest
@@ -776,13 +776,13 @@ namespace Game.Misc
public class PointOfInterestLocale public class PointOfInterestLocale
{ {
public StringArray Name = new StringArray((int)Locale.Total); public StringArray Name = new((int)Locale.Total);
} }
public class GossipMenus public class GossipMenus
{ {
public uint MenuId; public uint MenuId;
public uint TextId; public uint TextId;
public List<Condition> Conditions = new List<Condition>(); public List<Condition> Conditions = new();
} }
} }
+5 -5
View File
@@ -12,7 +12,7 @@ namespace Game.Entities
public uint MoneyCost; public uint MoneyCost;
public uint ReqSkillLine; public uint ReqSkillLine;
public uint ReqSkillRank; public uint ReqSkillRank;
public Array<uint> ReqAbility = new Array<uint>(3); public Array<uint> ReqAbility = new(3);
public byte ReqLevel; public byte ReqLevel;
public bool IsCastable() { return Global.SpellMgr.GetSpellInfo(SpellId, Difficulty.None).HasEffect(SpellEffectName.LearnSpell); } public bool IsCastable() { return Global.SpellMgr.GetSpellInfo(SpellId, Difficulty.None).HasEffect(SpellEffectName.LearnSpell); }
@@ -33,7 +33,7 @@ namespace Game.Entities
{ {
float reputationDiscount = player.GetReputationPriceDiscount(npc); float reputationDiscount = player.GetReputationPriceDiscount(npc);
TrainerList trainerList = new TrainerList(); TrainerList trainerList = new();
trainerList.TrainerGUID = npc.GetGUID(); trainerList.TrainerGUID = npc.GetGUID();
trainerList.TrainerType = (int)_type; trainerList.TrainerType = (int)_type;
trainerList.TrainerID = (int)_id; trainerList.TrainerID = (int)_id;
@@ -44,7 +44,7 @@ namespace Game.Entities
if (!player.IsSpellFitByClassAndRace(trainerSpell.SpellId)) if (!player.IsSpellFitByClassAndRace(trainerSpell.SpellId))
continue; continue;
TrainerListSpell trainerListSpell = new TrainerListSpell(); TrainerListSpell trainerListSpell = new();
trainerListSpell.SpellID = trainerSpell.SpellId; trainerListSpell.SpellID = trainerSpell.SpellId;
trainerListSpell.MoneyCost = (uint)(trainerSpell.MoneyCost * reputationDiscount); trainerListSpell.MoneyCost = (uint)(trainerSpell.MoneyCost * reputationDiscount);
trainerListSpell.ReqSkillLine = trainerSpell.ReqSkillLine; trainerListSpell.ReqSkillLine = trainerSpell.ReqSkillLine;
@@ -147,7 +147,7 @@ namespace Game.Entities
void SendTeachFailure(Creature npc, Player player, uint spellId, TrainerFailReason reason) void SendTeachFailure(Creature npc, Player player, uint spellId, TrainerFailReason reason)
{ {
TrainerBuyFailed trainerBuyFailed = new TrainerBuyFailed(); TrainerBuyFailed trainerBuyFailed = new();
trainerBuyFailed.TrainerGUID = npc.GetGUID(); trainerBuyFailed.TrainerGUID = npc.GetGUID();
trainerBuyFailed.SpellID = spellId; trainerBuyFailed.SpellID = spellId;
trainerBuyFailed.TrainerFailedReason = reason; trainerBuyFailed.TrainerFailedReason = reason;
@@ -170,6 +170,6 @@ namespace Game.Entities
uint _id; uint _id;
TrainerType _type; TrainerType _type;
List<TrainerSpell> _spells; List<TrainerSpell> _spells;
Array<string> _greeting = new Array<string>((int)Locale.Total); Array<string> _greeting = new((int)Locale.Total);
} }
} }
+5 -5
View File
@@ -250,7 +250,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt8((byte)flags); buffer.WriteUInt8((byte)flags);
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
@@ -263,7 +263,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(m_values.GetChangedObjectTypeMask()); buffer.WriteUInt32(m_values.GetChangedObjectTypeMask());
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
@@ -278,14 +278,14 @@ namespace Game.Entities
void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedDynamicObjectMask, Player target) void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedDynamicObjectMask, Player target)
{ {
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
if (requestedDynamicObjectMask.IsAnySet()) if (requestedDynamicObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.DynamicObject); valuesMask.Set((int)TypeId.DynamicObject);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -294,7 +294,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.DynamicObject]) if (valuesMask[(int)TypeId.DynamicObject])
m_dynamicObjectData.WriteUpdate(buffer, requestedDynamicObjectMask, true, this, target); m_dynamicObjectData.WriteUpdate(buffer, requestedDynamicObjectMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
+22 -22
View File
@@ -165,7 +165,7 @@ namespace Game.Entities
if (goInfo == null) if (goInfo == null)
return null; return null;
GameObject go = new GameObject(); GameObject go = new();
if (!go.Create(entry, map, pos, rotation, animProgress, goState, artKit, false, 0)) if (!go.Create(entry, map, pos, rotation, animProgress, goState, artKit, false, 0))
return null; return null;
@@ -174,7 +174,7 @@ namespace Game.Entities
public static GameObject CreateGameObjectFromDB(ulong spawnId, Map map, bool addToMap = true) public static GameObject CreateGameObjectFromDB(ulong spawnId, Map map, bool addToMap = true)
{ {
GameObject go = new GameObject(); GameObject go = new();
if (!go.LoadFromDB(spawnId, map, addToMap)) if (!go.LoadFromDB(spawnId, map, addToMap))
return null; return null;
@@ -502,7 +502,7 @@ namespace Game.Entities
SetGoState(GameObjectState.Active); SetGoState(GameObjectState.Active);
SetFlags(GameObjectFlags.NoDespawn); SetFlags(GameObjectFlags.NoDespawn);
UpdateData udata = new UpdateData(caster.GetMapId()); UpdateData udata = new(caster.GetMapId());
UpdateObject packet; UpdateObject packet;
BuildValuesUpdateBlockForPlayer(udata, caster.ToPlayer()); BuildValuesUpdateBlockForPlayer(udata, caster.ToPlayer());
udata.BuildPacket(out packet); udata.BuildPacket(out packet);
@@ -882,7 +882,7 @@ namespace Game.Entities
public void SendGameObjectDespawn() public void SendGameObjectDespawn()
{ {
GameObjectDespawn packet = new GameObjectDespawn(); GameObjectDespawn packet = new();
packet.ObjectGUID = GetGUID(); packet.ObjectGUID = GetGUID();
SendMessageToSet(packet, true); SendMessageToSet(packet, true);
} }
@@ -1065,7 +1065,7 @@ namespace Game.Entities
GetMap().RemoveRespawnTime(SpawnObjectType.GameObject, m_spawnId); GetMap().RemoveRespawnTime(SpawnObjectType.GameObject, m_spawnId);
Global.ObjectMgr.DeleteGameObjectData(m_spawnId); Global.ObjectMgr.DeleteGameObjectData(m_spawnId);
SQLTransaction trans = new SQLTransaction(); SQLTransaction trans = new();
PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_GAMEOBJECT); PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_GAMEOBJECT);
stmt.AddValue(0, m_spawnId); stmt.AddValue(0, m_spawnId);
@@ -1501,7 +1501,7 @@ namespace Game.Entities
if (info.Goober.pageID != 0) // show page... if (info.Goober.pageID != 0) // show page...
{ {
PageTextPkt data = new PageTextPkt(); PageTextPkt data = new();
data.GameObjectGUID = GetGUID(); data.GameObjectGUID = GetGUID();
player.SendPacket(data); player.SendPacket(data);
} }
@@ -1957,7 +1957,7 @@ namespace Game.Entities
return; return;
} }
OpenArtifactForge openArtifactForge = new OpenArtifactForge(); OpenArtifactForge openArtifactForge = new();
openArtifactForge.ArtifactGUID = item.GetGUID(); openArtifactForge.ArtifactGUID = item.GetGUID();
openArtifactForge.ForgeGUID = GetGUID(); openArtifactForge.ForgeGUID = GetGUID();
player.SendPacket(openArtifactForge); player.SendPacket(openArtifactForge);
@@ -1969,7 +1969,7 @@ namespace Game.Entities
if (!item) if (!item)
return; return;
OpenHeartForge openHeartForge = new OpenHeartForge(); OpenHeartForge openHeartForge = new();
openHeartForge.ForgeGUID = GetGUID(); openHeartForge.ForgeGUID = GetGUID();
player.SendPacket(openHeartForge); player.SendPacket(openHeartForge);
break; break;
@@ -1985,7 +1985,7 @@ namespace Game.Entities
if (!player) if (!player)
return; return;
GameObjectUILink gameObjectUILink = new GameObjectUILink(); GameObjectUILink gameObjectUILink = new();
gameObjectUILink.ObjectGUID = GetGUID(); gameObjectUILink.ObjectGUID = GetGUID();
gameObjectUILink.UILink = (int)GetGoInfo().UILink.UILinkType; gameObjectUILink.UILink = (int)GetGoInfo().UILink.UILinkType;
player.SendPacket(gameObjectUILink); player.SendPacket(gameObjectUILink);
@@ -2082,7 +2082,7 @@ namespace Game.Entities
public void SendCustomAnim(uint anim) public void SendCustomAnim(uint anim)
{ {
GameObjectCustomAnim customAnim = new GameObjectCustomAnim(); GameObjectCustomAnim customAnim = new();
customAnim.ObjectGUID = GetGUID(); customAnim.ObjectGUID = GetGUID();
customAnim.CustomAnim = anim; customAnim.CustomAnim = anim;
SendMessageToSet(customAnim, true); SendMessageToSet(customAnim, true);
@@ -2174,7 +2174,7 @@ namespace Game.Entities
public void SetWorldRotation(float qx, float qy, float qz, float qw) public void SetWorldRotation(float qx, float qy, float qz, float qw)
{ {
Quaternion rotation = new Quaternion(qx, qy, qz, qw); Quaternion rotation = new(qx, qy, qz, qw);
rotation.unitize(); rotation.unitize();
m_worldRotation.X = rotation.X; m_worldRotation.X = rotation.X;
m_worldRotation.Y = rotation.Y; m_worldRotation.Y = rotation.Y;
@@ -2218,7 +2218,7 @@ namespace Game.Entities
// dealing damage, send packet // dealing damage, send packet
if (player != null) if (player != null)
{ {
DestructibleBuildingDamage packet = new DestructibleBuildingDamage(); DestructibleBuildingDamage packet = new();
packet.Caster = attackerOrHealer.GetGUID(); // todo: this can be a GameObject packet.Caster = attackerOrHealer.GetGUID(); // todo: this can be a GameObject
packet.Target = GetGUID(); packet.Target = GetGUID();
packet.Damage = -change; packet.Damage = -change;
@@ -2545,7 +2545,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt8((byte)flags); buffer.WriteUInt8((byte)flags);
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
@@ -2558,7 +2558,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(m_values.GetChangedObjectTypeMask()); buffer.WriteUInt32(m_values.GetChangedObjectTypeMask());
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
@@ -2573,14 +2573,14 @@ namespace Game.Entities
public void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedGameObjectMask, Player target) public void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedGameObjectMask, Player target)
{ {
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
if (requestedGameObjectMask.IsAnySet()) if (requestedGameObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.GameObject); valuesMask.Set((int)TypeId.GameObject);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -2589,7 +2589,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.GameObject]) if (valuesMask[(int)TypeId.GameObject])
m_gameObjectData.WriteUpdate(buffer, requestedGameObjectMask, true, this, target); m_gameObjectData.WriteUpdate(buffer, requestedGameObjectMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
@@ -2655,7 +2655,7 @@ namespace Game.Entities
else else
_animKitId = 0; _animKitId = 0;
GameObjectActivateAnimKit activateAnimKit = new GameObjectActivateAnimKit(); GameObjectActivateAnimKit activateAnimKit = new();
activateAnimKit.ObjectGUID = GetGUID(); activateAnimKit.ObjectGUID = GetGUID();
activateAnimKit.AnimKitID = animKitId; activateAnimKit.AnimKitID = animKitId;
activateAnimKit.Maintain = !oneshot; activateAnimKit.Maintain = !oneshot;
@@ -2846,7 +2846,7 @@ namespace Game.Entities
// For traps this: spell casting cooldown, for doors/buttons: reset time. // For traps this: spell casting cooldown, for doors/buttons: reset time.
Player m_ritualOwner; // used for GAMEOBJECT_TYPE_SUMMONING_RITUAL where GO is not summoned (no owner) Player m_ritualOwner; // used for GAMEOBJECT_TYPE_SUMMONING_RITUAL where GO is not summoned (no owner)
List<ObjectGuid> m_unique_users = new List<ObjectGuid>(); List<ObjectGuid> m_unique_users = new();
uint m_usetimes; uint m_usetimes;
ObjectGuid m_lootRecipient; ObjectGuid m_lootRecipient;
@@ -2867,10 +2867,10 @@ namespace Game.Entities
GameObjectState m_prevGoState; // What state to set whenever resetting GameObjectState m_prevGoState; // What state to set whenever resetting
Dictionary<uint, ObjectGuid> ChairListSlots = new Dictionary<uint, ObjectGuid>(); Dictionary<uint, ObjectGuid> ChairListSlots = new();
List<ObjectGuid> m_SkillupList = new List<ObjectGuid>(); List<ObjectGuid> m_SkillupList = new();
public Loot loot = new Loot(); public Loot loot = new();
public GameObjectModel m_model; public GameObjectModel m_model;
@@ -579,7 +579,7 @@ namespace Game.Entities
QueryData.GameObjectID = entry; QueryData.GameObjectID = entry;
QueryData.Allow = true; QueryData.Allow = true;
GameObjectStats stats = new GameObjectStats(); GameObjectStats stats = new();
stats.Type = (uint)type; stats.Type = (uint)type;
stats.DisplayID = displayId; stats.DisplayID = displayId;
@@ -1369,9 +1369,9 @@ namespace Game.Entities
public class GameObjectLocale public class GameObjectLocale
{ {
public StringArray Name = new StringArray((int)Locale.Total); public StringArray Name = new((int)Locale.Total);
public StringArray CastBarCaption = new StringArray((int)Locale.Total); public StringArray CastBarCaption = new((int)Locale.Total);
public StringArray Unk1 = new StringArray((int)Locale.Total); public StringArray Unk1 = new((int)Locale.Total);
} }
public class GameObjectAddon public class GameObjectAddon
@@ -165,7 +165,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt8((byte)flags); buffer.WriteUInt8((byte)flags);
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
@@ -179,7 +179,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
m_objectData.WriteUpdate(buffer, flags, this, target); m_objectData.WriteUpdate(buffer, flags, this, target);
@@ -198,7 +198,7 @@ namespace Game.Entities
void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedItemMask, UpdateMask requestedAzeriteEmpoweredItemMask, Player target) void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedItemMask, UpdateMask requestedAzeriteEmpoweredItemMask, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
@@ -209,7 +209,7 @@ namespace Game.Entities
if (requestedAzeriteEmpoweredItemMask.IsAnySet()) if (requestedAzeriteEmpoweredItemMask.IsAnySet())
valuesMask.Set((int)TypeId.AzeriteEmpoweredItem); valuesMask.Set((int)TypeId.AzeriteEmpoweredItem);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -221,7 +221,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.AzeriteEmpoweredItem]) if (valuesMask[(int)TypeId.AzeriteEmpoweredItem])
m_azeriteEmpoweredItemData.WriteUpdate(buffer, requestedAzeriteEmpoweredItemMask, true, this, target); m_azeriteEmpoweredItemData.WriteUpdate(buffer, requestedAzeriteEmpoweredItemMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
+15 -15
View File
@@ -230,7 +230,7 @@ namespace Game.Entities
{ {
// count weeks from 14.01.2020 // count weeks from 14.01.2020
DateTime now = GameTime.GetDateAndTime(); DateTime now = GameTime.GetDateAndTime();
DateTime beginDate = new DateTime(2020, 1, 14); DateTime beginDate = new(2020, 1, 14);
uint knowledge = 0; uint knowledge = 0;
while (beginDate < now && knowledge < PlayerConst.MaxAzeriteItemKnowledgeLevel) while (beginDate < now && knowledge < PlayerConst.MaxAzeriteItemKnowledgeLevel)
{ {
@@ -293,7 +293,7 @@ namespace Game.Entities
SetState(ItemUpdateState.Changed, owner); SetState(ItemUpdateState.Changed, owner);
} }
PlayerAzeriteItemGains xpGain = new PlayerAzeriteItemGains(); PlayerAzeriteItemGains xpGain = new();
xpGain.ItemGUID = GetGUID(); xpGain.ItemGUID = GetGUID();
xpGain.XP = xp; xpGain.XP = xp;
owner.SendPacket(xpGain); owner.SendPacket(xpGain);
@@ -362,7 +362,7 @@ namespace Game.Entities
if (index < 0) if (index < 0)
{ {
UnlockedAzeriteEssence unlockedEssence = new UnlockedAzeriteEssence(); UnlockedAzeriteEssence unlockedEssence = new();
unlockedEssence.AzeriteEssenceID = azeriteEssenceId; unlockedEssence.AzeriteEssenceID = azeriteEssenceId;
unlockedEssence.Rank = rank; unlockedEssence.Rank = rank;
AddDynamicUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.UnlockedEssences), unlockedEssence); AddDynamicUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.UnlockedEssences), unlockedEssence);
@@ -385,7 +385,7 @@ namespace Game.Entities
public void CreateSelectedAzeriteEssences(uint specializationId) public void CreateSelectedAzeriteEssences(uint specializationId)
{ {
SelectedAzeriteEssences selectedEssences = new SelectedAzeriteEssences(); SelectedAzeriteEssences selectedEssences = new();
selectedEssences.ModifyValue(selectedEssences.SpecializationID).SetValue(specializationId); selectedEssences.ModifyValue(selectedEssences.SpecializationID).SetValue(specializationId);
selectedEssences.ModifyValue(selectedEssences.Enabled).SetValue(true); selectedEssences.ModifyValue(selectedEssences.Enabled).SetValue(true);
AddDynamicUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.SelectedEssences), selectedEssences); AddDynamicUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.SelectedEssences), selectedEssences);
@@ -426,7 +426,7 @@ namespace Game.Entities
public override void BuildValuesCreate(WorldPacket data, Player target) public override void BuildValuesCreate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt8((byte)flags); buffer.WriteUInt8((byte)flags);
m_objectData.WriteCreate(buffer, flags, this, target); m_objectData.WriteCreate(buffer, flags, this, target);
@@ -440,7 +440,7 @@ namespace Game.Entities
public override void BuildValuesUpdate(WorldPacket data, Player target) public override void BuildValuesUpdate(WorldPacket data, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
if (m_values.HasChanged(TypeId.Object)) if (m_values.HasChanged(TypeId.Object))
m_objectData.WriteUpdate(buffer, flags, this, target); m_objectData.WriteUpdate(buffer, flags, this, target);
@@ -458,18 +458,18 @@ namespace Game.Entities
public override void BuildValuesUpdateWithFlag(WorldPacket data, UpdateFieldFlag flags, Player target) public override void BuildValuesUpdateWithFlag(WorldPacket data, UpdateFieldFlag flags, Player target)
{ {
UpdateMask valuesMask = new UpdateMask(14); UpdateMask valuesMask = new(14);
valuesMask.Set((int)TypeId.Item); valuesMask.Set((int)TypeId.Item);
valuesMask.Set((int)TypeId.AzeriteItem); valuesMask.Set((int)TypeId.AzeriteItem);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
UpdateMask mask = new UpdateMask(40); UpdateMask mask = new(40);
m_itemData.AppendAllowedFieldsMaskForFlag(mask, flags); m_itemData.AppendAllowedFieldsMaskForFlag(mask, flags);
m_itemData.WriteUpdate(buffer, mask, true, this, target); m_itemData.WriteUpdate(buffer, mask, true, this, target);
UpdateMask mask2 = new UpdateMask(9); UpdateMask mask2 = new(9);
m_azeriteItemData.AppendAllowedFieldsMaskForFlag(mask2, flags); m_azeriteItemData.AppendAllowedFieldsMaskForFlag(mask2, flags);
m_azeriteItemData.WriteUpdate(buffer, mask2, true, this, target); m_azeriteItemData.WriteUpdate(buffer, mask2, true, this, target);
@@ -480,7 +480,7 @@ namespace Game.Entities
void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedItemMask, UpdateMask requestedAzeriteItemMask, Player target) void BuildValuesUpdateForPlayerWithMask(UpdateData data, UpdateMask requestedObjectMask, UpdateMask requestedItemMask, UpdateMask requestedAzeriteItemMask, Player target)
{ {
UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target); UpdateFieldFlag flags = GetUpdateFieldFlagsFor(target);
UpdateMask valuesMask = new UpdateMask((int)TypeId.Max); UpdateMask valuesMask = new((int)TypeId.Max);
if (requestedObjectMask.IsAnySet()) if (requestedObjectMask.IsAnySet())
valuesMask.Set((int)TypeId.Object); valuesMask.Set((int)TypeId.Object);
@@ -492,7 +492,7 @@ namespace Game.Entities
if (requestedAzeriteItemMask.IsAnySet()) if (requestedAzeriteItemMask.IsAnySet())
valuesMask.Set((int)TypeId.AzeriteItem); valuesMask.Set((int)TypeId.AzeriteItem);
WorldPacket buffer = new WorldPacket(); WorldPacket buffer = new();
buffer.WriteUInt32(valuesMask.GetBlock(0)); buffer.WriteUInt32(valuesMask.GetBlock(0));
if (valuesMask[(int)TypeId.Object]) if (valuesMask[(int)TypeId.Object])
@@ -504,7 +504,7 @@ namespace Game.Entities
if (valuesMask[(int)TypeId.AzeriteItem]) if (valuesMask[(int)TypeId.AzeriteItem])
m_azeriteItemData.WriteUpdate(buffer, requestedAzeriteItemMask, true, this, target); m_azeriteItemData.WriteUpdate(buffer, requestedAzeriteItemMask, true, this, target);
WorldPacket buffer1 = new WorldPacket(); WorldPacket buffer1 = new();
buffer1.WriteUInt8((byte)UpdateType.Values); buffer1.WriteUInt8((byte)UpdateType.Values);
buffer1.WritePackedGuid(GetGUID()); buffer1.WritePackedGuid(GetGUID());
buffer1.WriteUInt32(buffer.GetSize()); buffer1.WriteUInt32(buffer.GetSize());
@@ -555,8 +555,8 @@ namespace Game.Entities
public ulong Xp; public ulong Xp;
public uint Level; public uint Level;
public uint KnowledgeLevel; public uint KnowledgeLevel;
public List<uint> AzeriteItemMilestonePowers = new List<uint>(); public List<uint> AzeriteItemMilestonePowers = new();
public List<AzeriteEssencePowerRecord> UnlockedAzeriteEssences = new List<AzeriteEssencePowerRecord>(); public List<AzeriteEssencePowerRecord> UnlockedAzeriteEssences = new();
public AzeriteItemSelectedEssencesData[] SelectedAzeriteEssences = new AzeriteItemSelectedEssencesData[4]; public AzeriteItemSelectedEssencesData[] SelectedAzeriteEssences = new AzeriteItemSelectedEssencesData[4];
} }
} }

Some files were not shown because too many files have changed in this diff Show More