From a2b26272d28f137473c4e14841da0f042e3e8bdc Mon Sep 17 00:00:00 2001 From: Kargatum Date: Mon, 12 Oct 2020 15:08:15 +0700 Subject: [PATCH] refactor(Core/Game): restyle game lib with astyle (#3466) --- src/server/game/AI/CoreAI/CombatAI.cpp | 8 +- src/server/game/AI/CoreAI/CombatAI.h | 104 +- src/server/game/AI/CoreAI/GameObjectAI.h | 64 +- src/server/game/AI/CoreAI/GuardAI.h | 12 +- src/server/game/AI/CoreAI/PassiveAI.h | 66 +- src/server/game/AI/CoreAI/PetAI.cpp | 100 +- src/server/game/AI/CoreAI/PetAI.h | 68 +- src/server/game/AI/CoreAI/ReactorAI.h | 10 +- src/server/game/AI/CoreAI/TotemAI.cpp | 6 +- src/server/game/AI/CoreAI/TotemAI.h | 40 +- src/server/game/AI/CoreAI/UnitAI.cpp | 90 +- src/server/game/AI/CoreAI/UnitAI.h | 244 +- src/server/game/AI/CreatureAI.cpp | 4 +- src/server/game/AI/CreatureAI.h | 152 +- src/server/game/AI/CreatureAIImpl.h | 4 +- src/server/game/AI/CreatureAISelector.cpp | 2 +- .../game/AI/ScriptedAI/ScriptedCreature.cpp | 10 +- .../game/AI/ScriptedAI/ScriptedCreature.h | 150 +- .../game/AI/ScriptedAI/ScriptedEscortAI.cpp | 14 +- .../game/AI/ScriptedAI/ScriptedEscortAI.h | 120 +- .../game/AI/ScriptedAI/ScriptedFollowerAI.h | 52 +- src/server/game/AI/SmartScripts/SmartAI.cpp | 40 +- src/server/game/AI/SmartScripts/SmartAI.h | 342 +- .../game/AI/SmartScripts/SmartScript.cpp | 8088 ++++++++-------- src/server/game/AI/SmartScripts/SmartScript.h | 586 +- .../game/AI/SmartScripts/SmartScriptMgr.cpp | 416 +- .../game/AI/SmartScripts/SmartScriptMgr.h | 283 +- .../game/Achievements/AchievementMgr.cpp | 1316 +-- src/server/game/Achievements/AchievementMgr.h | 245 +- src/server/game/Addons/AddonMgr.cpp | 155 +- .../game/ArenaSpectator/ArenaSpectator.h | 28 +- .../game/AuctionHouse/AuctionHouseMgr.cpp | 99 +- .../game/AuctionHouse/AuctionHouseMgr.h | 84 +- src/server/game/Battlefield/Battlefield.cpp | 19 +- src/server/game/Battlefield/Battlefield.h | 520 +- .../game/Battlefield/BattlefieldHandler.cpp | 16 +- .../game/Battlefield/BattlefieldMgr.cpp | 22 +- src/server/game/Battlefield/BattlefieldMgr.h | 24 +- .../game/Battlefield/Zones/BattlefieldWG.cpp | 180 +- .../game/Battlefield/Zones/BattlefieldWG.h | 421 +- src/server/game/Battlegrounds/ArenaTeam.cpp | 30 +- src/server/game/Battlegrounds/ArenaTeam.h | 130 +- .../game/Battlegrounds/ArenaTeamMgr.cpp | 19 +- .../game/Battlegrounds/Battleground.cpp | 217 +- src/server/game/Battlegrounds/Battleground.h | 882 +- .../game/Battlegrounds/BattlegroundMgr.cpp | 148 +- .../game/Battlegrounds/BattlegroundMgr.h | 192 +- .../game/Battlegrounds/BattlegroundQueue.cpp | 124 +- .../game/Battlegrounds/BattlegroundQueue.h | 180 +- .../Battlegrounds/Zones/BattlegroundAB.cpp | 148 +- .../game/Battlegrounds/Zones/BattlegroundAB.h | 90 +- .../Battlegrounds/Zones/BattlegroundAV.cpp | 429 +- .../game/Battlegrounds/Zones/BattlegroundAV.h | 418 +- .../Battlegrounds/Zones/BattlegroundBE.cpp | 20 +- .../game/Battlegrounds/Zones/BattlegroundBE.h | 32 +- .../Battlegrounds/Zones/BattlegroundDS.cpp | 30 +- .../game/Battlegrounds/Zones/BattlegroundDS.h | 67 +- .../Battlegrounds/Zones/BattlegroundEY.cpp | 22 +- .../game/Battlegrounds/Zones/BattlegroundEY.h | 146 +- .../Battlegrounds/Zones/BattlegroundIC.cpp | 201 +- .../game/Battlegrounds/Zones/BattlegroundIC.h | 184 +- .../Battlegrounds/Zones/BattlegroundNA.cpp | 20 +- .../game/Battlegrounds/Zones/BattlegroundNA.h | 28 +- .../Battlegrounds/Zones/BattlegroundRL.cpp | 16 +- .../game/Battlegrounds/Zones/BattlegroundRL.h | 28 +- .../Battlegrounds/Zones/BattlegroundRV.cpp | 60 +- .../game/Battlegrounds/Zones/BattlegroundRV.h | 60 +- .../Battlegrounds/Zones/BattlegroundSA.cpp | 240 +- .../game/Battlegrounds/Zones/BattlegroundSA.h | 341 +- .../Battlegrounds/Zones/BattlegroundWS.cpp | 22 +- .../game/Battlegrounds/Zones/BattlegroundWS.h | 102 +- src/server/game/Calendar/CalendarMgr.cpp | 13 +- src/server/game/Calendar/CalendarMgr.h | 308 +- src/server/game/Chat/Channels/Channel.cpp | 34 +- src/server/game/Chat/Channels/Channel.h | 294 +- src/server/game/Chat/Channels/ChannelMgr.cpp | 10 +- src/server/game/Chat/Channels/ChannelMgr.h | 36 +- src/server/game/Chat/Chat.cpp | 166 +- src/server/game/Chat/Chat.h | 184 +- src/server/game/Chat/ChatLink.cpp | 2 +- src/server/game/Chat/ChatLink.h | 4 +- src/server/game/Combat/HostileRefManager.cpp | 6 +- src/server/game/Combat/HostileRefManager.h | 54 +- src/server/game/Combat/ThreatManager.cpp | 20 +- src/server/game/Combat/ThreatManager.h | 298 +- src/server/game/Combat/UnitEvents.h | 84 +- src/server/game/Conditions/ConditionMgr.cpp | 2036 ++-- src/server/game/Conditions/ConditionMgr.h | 71 +- src/server/game/Conditions/DisableMgr.cpp | 627 +- src/server/game/DataStores/DBCStores.cpp | 53 +- src/server/game/DataStores/DBCStores.h | 6 +- src/server/game/DungeonFinding/LFG.cpp | 48 +- src/server/game/DungeonFinding/LFG.h | 750 +- .../game/DungeonFinding/LFGGroupData.cpp | 174 +- src/server/game/DungeonFinding/LFGGroupData.h | 20 +- src/server/game/DungeonFinding/LFGMgr.cpp | 5020 +++++----- src/server/game/DungeonFinding/LFGMgr.h | 668 +- .../game/DungeonFinding/LFGPlayerData.cpp | 198 +- .../game/DungeonFinding/LFGPlayerData.h | 12 +- src/server/game/DungeonFinding/LFGQueue.cpp | 1050 +-- src/server/game/DungeonFinding/LFGQueue.h | 88 +- src/server/game/DungeonFinding/LFGScripts.cpp | 496 +- src/server/game/DungeonFinding/LFGScripts.h | 12 +- src/server/game/Entities/Corpse/Corpse.cpp | 20 +- src/server/game/Entities/Corpse/Corpse.h | 46 +- .../game/Entities/Creature/Creature.cpp | 339 +- src/server/game/Entities/Creature/Creature.h | 694 +- .../game/Entities/Creature/CreatureGroups.cpp | 5 +- .../game/Entities/Creature/CreatureGroups.h | 62 +- .../game/Entities/Creature/GossipDef.cpp | 60 +- src/server/game/Entities/Creature/GossipDef.h | 184 +- .../Entities/Creature/TemporarySummon.cpp | 182 +- .../game/Entities/Creature/TemporarySummon.h | 110 +- .../Entities/DynamicObject/DynamicObject.cpp | 30 +- .../Entities/DynamicObject/DynamicObject.h | 60 +- .../game/Entities/GameObject/GameObject.cpp | 1822 ++-- .../game/Entities/GameObject/GameObject.h | 635 +- .../game/Entities/Item/Container/Bag.cpp | 14 +- src/server/game/Entities/Item/Container/Bag.h | 54 +- src/server/game/Entities/Item/Item.cpp | 229 +- src/server/game/Entities/Item/Item.h | 246 +- .../game/Entities/Item/ItemEnchantmentMgr.cpp | 2 +- src/server/game/Entities/Item/ItemTemplate.h | 29 +- src/server/game/Entities/Object/Object.cpp | 425 +- src/server/game/Entities/Object/Object.h | 1204 +-- .../game/Entities/Object/ObjectDefines.h | 41 +- .../Entities/Object/ObjectPosSelector.cpp | 24 +- .../game/Entities/Object/ObjectPosSelector.h | 14 +- .../Entities/Object/Updates/UpdateData.cpp | 6 +- .../game/Entities/Object/Updates/UpdateData.h | 26 +- .../game/Entities/Object/Updates/UpdateMask.h | 154 +- src/server/game/Entities/Pet/Pet.cpp | 894 +- src/server/game/Entities/Pet/Pet.h | 246 +- src/server/game/Entities/Player/Player.cpp | 2810 +++--- src/server/game/Entities/Player/Player.h | 3756 ++++---- src/server/game/Entities/Player/SocialMgr.cpp | 9 +- src/server/game/Entities/Player/SocialMgr.h | 68 +- src/server/game/Entities/Totem/Totem.cpp | 20 +- src/server/game/Entities/Totem/Totem.h | 46 +- .../game/Entities/Transport/Transport.cpp | 56 +- .../game/Entities/Transport/Transport.h | 2 +- src/server/game/Entities/Unit/StatSystem.cpp | 339 +- src/server/game/Entities/Unit/Unit.cpp | 8280 +++++++++-------- src/server/game/Entities/Unit/Unit.h | 2613 +++--- src/server/game/Entities/Vehicle/Vehicle.cpp | 22 +- src/server/game/Entities/Vehicle/Vehicle.h | 110 +- src/server/game/Events/GameEventMgr.cpp | 156 +- src/server/game/Events/GameEventMgr.h | 158 +- src/server/game/Globals/ObjectAccessor.cpp | 25 +- src/server/game/Globals/ObjectAccessor.h | 380 +- src/server/game/Globals/ObjectMgr.cpp | 2108 ++--- src/server/game/Globals/ObjectMgr.h | 1472 +-- src/server/game/Grids/Cells/Cell.h | 20 +- src/server/game/Grids/Grid.h | 148 +- src/server/game/Grids/GridDefines.h | 22 +- src/server/game/Grids/GridRefManager.h | 16 +- src/server/game/Grids/GridReference.h | 42 +- src/server/game/Grids/NGrid.h | 138 +- .../game/Grids/Notifiers/GridNotifiers.cpp | 32 +- .../game/Grids/Notifiers/GridNotifiers.h | 1458 +-- .../game/Grids/Notifiers/GridNotifiersImpl.h | 136 +- src/server/game/Grids/ObjectGridLoader.cpp | 72 +- src/server/game/Grids/ObjectGridLoader.h | 42 +- src/server/game/Groups/Group.cpp | 82 +- src/server/game/Groups/Group.h | 366 +- src/server/game/Groups/GroupMgr.cpp | 14 +- src/server/game/Groups/GroupMgr.h | 2 +- src/server/game/Groups/GroupRefManager.h | 6 +- src/server/game/Groups/GroupReference.h | 24 +- src/server/game/Guilds/Guild.cpp | 131 +- src/server/game/Guilds/Guild.h | 6 +- src/server/game/Guilds/GuildMgr.cpp | 58 +- src/server/game/Handlers/AddonHandler.cpp | 6 +- src/server/game/Handlers/AddonHandler.h | 2 +- src/server/game/Handlers/ArenaTeamHandler.cpp | 26 +- .../game/Handlers/AuctionHouseHandler.cpp | 38 +- .../game/Handlers/BattleGroundHandler.cpp | 30 +- src/server/game/Handlers/CalendarHandler.cpp | 48 +- src/server/game/Handlers/ChannelHandler.cpp | 42 +- src/server/game/Handlers/CharacterHandler.cpp | 551 +- src/server/game/Handlers/ChatHandler.cpp | 616 +- src/server/game/Handlers/CombatHandler.cpp | 4 +- src/server/game/Handlers/GroupHandler.cpp | 40 +- src/server/game/Handlers/GuildHandler.cpp | 33 +- src/server/game/Handlers/ItemHandler.cpp | 350 +- src/server/game/Handlers/LFGHandler.cpp | 14 +- src/server/game/Handlers/LootHandler.cpp | 83 +- src/server/game/Handlers/MailHandler.cpp | 47 +- src/server/game/Handlers/MiscHandler.cpp | 208 +- src/server/game/Handlers/MovementHandler.cpp | 79 +- src/server/game/Handlers/NPCHandler.cpp | 54 +- src/server/game/Handlers/PetHandler.cpp | 704 +- src/server/game/Handlers/PetitionsHandler.cpp | 39 +- src/server/game/Handlers/QueryHandler.cpp | 42 +- src/server/game/Handlers/QuestHandler.cpp | 112 +- .../game/Handlers/ReferAFriendHandler.cpp | 3 +- src/server/game/Handlers/SkillHandler.cpp | 6 +- src/server/game/Handlers/SpellHandler.cpp | 18 +- src/server/game/Handlers/TaxiHandler.cpp | 8 +- src/server/game/Handlers/TicketHandler.cpp | 8 +- src/server/game/Handlers/TradeHandler.cpp | 36 +- src/server/game/Handlers/VehicleHandler.cpp | 100 +- src/server/game/Instances/InstanceSaveMgr.cpp | 38 +- src/server/game/Instances/InstanceSaveMgr.h | 218 +- src/server/game/Instances/InstanceScript.cpp | 20 +- src/server/game/Instances/InstanceScript.h | 152 +- src/server/game/Loot/LootItemStorage.cpp | 16 +- src/server/game/Loot/LootItemStorage.h | 30 +- src/server/game/Loot/LootMgr.cpp | 277 +- src/server/game/Loot/LootMgr.h | 172 +- src/server/game/Mails/Mail.cpp | 5 +- src/server/game/Mails/Mail.h | 114 +- src/server/game/Maps/Map.cpp | 601 +- src/server/game/Maps/Map.h | 848 +- src/server/game/Maps/MapInstanced.cpp | 22 +- src/server/game/Maps/MapInstanced.h | 46 +- src/server/game/Maps/MapManager.cpp | 27 +- src/server/game/Maps/MapManager.h | 206 +- src/server/game/Maps/MapRefManager.h | 26 +- src/server/game/Maps/MapReference.h | 48 +- src/server/game/Maps/MapUpdater.cpp | 94 +- src/server/game/Maps/MapUpdater.h | 34 +- src/server/game/Maps/TransportMgr.cpp | 4 +- src/server/game/Maps/TransportMgr.h | 6 +- src/server/game/Maps/ZoneScript.h | 34 +- src/server/game/Misc/AsyncAuctionListing.cpp | 8 +- src/server/game/Misc/AsyncAuctionListing.h | 24 +- src/server/game/Misc/AvgDiffTracker.h | 14 +- src/server/game/Misc/BanManager.cpp | 6 +- src/server/game/Misc/BanManager.h | 2 +- src/server/game/Misc/DynamicVisibility.cpp | 4 +- src/server/game/Misc/GameGraveyard.cpp | 18 +- src/server/game/Misc/GameGraveyard.h | 4 +- src/server/game/Misc/SavingSystem.cpp | 8 +- src/server/game/Misc/WhoListCache.cpp | 2 +- src/server/game/Misc/WhoListCache.h | 4 +- src/server/game/Miscellaneous/Formulas.h | 2 +- src/server/game/Miscellaneous/Language.h | 32 +- src/server/game/Miscellaneous/SharedDefines.h | 134 +- src/server/game/Motd/ServerMotd.cpp | 10 +- src/server/game/Movement/FollowerReference.h | 8 +- src/server/game/Movement/MotionMaster.cpp | 98 +- src/server/game/Movement/MotionMaster.h | 252 +- src/server/game/Movement/MovementGenerator.h | 66 +- .../game/Movement/MovementGeneratorImpl.h | 2 +- .../ConfusedMovementGenerator.cpp | 30 +- .../ConfusedMovementGenerator.h | 24 +- .../EscortMovementGenerator.cpp | 6 +- .../EscortMovementGenerator.h | 34 +- .../FleeingMovementGenerator.cpp | 96 +- .../FleeingMovementGenerator.h | 64 +- .../HomeMovementGenerator.h | 26 +- .../IdleMovementGenerator.cpp | 2 +- .../IdleMovementGenerator.h | 60 +- .../MovementGenerators/PathGenerator.cpp | 622 +- .../MovementGenerators/PathGenerator.h | 166 +- .../PointMovementGenerator.cpp | 12 +- .../PointMovementGenerator.h | 76 +- .../RandomMovementGenerator.cpp | 30 +- .../RandomMovementGenerator.h | 64 +- .../TargetedMovementGenerator.cpp | 48 +- .../TargetedMovementGenerator.h | 128 +- .../WaypointMovementGenerator.cpp | 26 +- .../WaypointMovementGenerator.h | 140 +- .../game/Movement/Spline/MoveSpline.cpp | 515 +- .../game/Movement/Spline/MoveSplineFlag.h | 12 +- .../game/Movement/Spline/MoveSplineInit.cpp | 4 +- .../game/Movement/Spline/MoveSplineInitArgs.h | 3 +- .../Movement/Spline/MovementPacketBuilder.cpp | 4 +- .../Movement/Spline/MovementPacketBuilder.h | 2 +- .../game/Movement/Spline/MovementUtil.cpp | 12 +- src/server/game/Movement/Spline/Spline.cpp | 511 +- src/server/game/Movement/Spline/Spline.h | 356 +- src/server/game/Movement/Spline/SplineImpl.h | 144 +- .../Movement/Waypoints/WaypointManager.cpp | 10 +- .../game/Movement/Waypoints/WaypointManager.h | 36 +- src/server/game/OutdoorPvP/OutdoorPvP.cpp | 40 +- src/server/game/OutdoorPvP/OutdoorPvP.h | 246 +- src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp | 3 +- src/server/game/OutdoorPvP/OutdoorPvPMgr.h | 86 +- src/server/game/Petitions/PetitionMgr.h | 48 +- src/server/game/Pools/PoolMgr.cpp | 40 +- src/server/game/Pools/PoolMgr.h | 164 +- src/server/game/Quests/QuestDef.cpp | 28 +- src/server/game/Quests/QuestDef.h | 358 +- src/server/game/Reputation/ReputationMgr.cpp | 37 +- src/server/game/Reputation/ReputationMgr.h | 162 +- src/server/game/Scripting/MapScripts.cpp | 455 +- src/server/game/Scripting/ScriptMgr.cpp | 243 +- src/server/game/Scripting/ScriptMgr.h | 1914 ++-- src/server/game/Scripting/ScriptSystem.cpp | 3 +- src/server/game/Scripting/ScriptSystem.h | 36 +- src/server/game/Server/Protocol/Opcodes.h | 10 +- src/server/game/Server/Protocol/PacketLog.cpp | 4 +- src/server/game/Server/Protocol/PacketLog.h | 20 +- src/server/game/Server/WorldSession.cpp | 193 +- src/server/game/Server/WorldSession.h | 1676 ++-- src/server/game/Server/WorldSocket.cpp | 162 +- src/server/game/Server/WorldSocket.h | 166 +- src/server/game/Server/WorldSocketMgr.cpp | 292 +- src/server/game/Server/WorldSocketMgr.h | 2 +- src/server/game/Skills/SkillDiscovery.cpp | 21 +- src/server/game/Skills/SkillExtraItems.cpp | 7 +- src/server/game/Skills/SkillExtraItems.h | 4 +- .../game/Spells/Auras/SpellAuraDefines.h | 2 +- .../game/Spells/Auras/SpellAuraEffects.cpp | 1955 ++-- .../game/Spells/Auras/SpellAuraEffects.h | 636 +- src/server/game/Spells/Auras/SpellAuras.cpp | 306 +- src/server/game/Spells/Auras/SpellAuras.h | 416 +- src/server/game/Spells/Spell.cpp | 3021 +++--- src/server/game/Spells/Spell.h | 1168 +-- src/server/game/Spells/SpellEffects.cpp | 2564 ++--- src/server/game/Spells/SpellInfo.cpp | 677 +- src/server/game/Spells/SpellInfo.h | 8 +- src/server/game/Spells/SpellMgr.cpp | 6779 +++++++------- src/server/game/Spells/SpellMgr.h | 364 +- src/server/game/Spells/SpellScript.cpp | 16 +- src/server/game/Spells/SpellScript.h | 1230 +-- src/server/game/Texts/CreatureTextMgr.cpp | 151 +- src/server/game/Texts/CreatureTextMgr.h | 214 +- src/server/game/Tickets/TicketMgr.cpp | 12 +- src/server/game/Tickets/TicketMgr.h | 2 +- .../game/Tools/CharacterDatabaseCleaner.cpp | 3 +- src/server/game/Tools/PlayerDump.cpp | 352 +- src/server/game/Tools/PlayerDump.h | 46 +- src/server/game/Warden/Warden.cpp | 156 +- src/server/game/Warden/Warden.h | 64 +- src/server/game/Warden/WardenCheckMgr.cpp | 10 +- src/server/game/Warden/WardenCheckMgr.h | 30 +- src/server/game/Warden/WardenMac.cpp | 11 +- src/server/game/Warden/WardenMac.h | 20 +- src/server/game/Warden/WardenWin.cpp | 267 +- src/server/game/Warden/WardenWin.h | 30 +- src/server/game/Weather/Weather.cpp | 24 +- src/server/game/Weather/Weather.h | 36 +- src/server/game/Weather/WeatherMgr.cpp | 249 +- src/server/game/World/World.cpp | 233 +- src/server/game/World/World.h | 548 +- 338 files changed, 52196 insertions(+), 50944 deletions(-) diff --git a/src/server/game/AI/CoreAI/CombatAI.cpp b/src/server/game/AI/CoreAI/CombatAI.cpp index b234224fd..bdb96c3fd 100644 --- a/src/server/game/AI/CoreAI/CombatAI.cpp +++ b/src/server/game/AI/CoreAI/CombatAI.cpp @@ -64,7 +64,7 @@ void CombatAI::EnterCombat(Unit* who) if (AISpellInfo[*i].condition == AICOND_AGGRO) me->CastSpell(who, *i, false); else if (AISpellInfo[*i].condition == AICOND_COMBAT) - events.ScheduleEvent(*i, AISpellInfo[*i].cooldown + rand()%AISpellInfo[*i].cooldown); + events.ScheduleEvent(*i, AISpellInfo[*i].cooldown + rand() % AISpellInfo[*i].cooldown); } } @@ -81,7 +81,7 @@ void CombatAI::UpdateAI(uint32 diff) if (uint32 spellId = events.ExecuteEvent()) { DoCast(spellId); - events.ScheduleEvent(spellId, AISpellInfo[spellId].cooldown + rand()%AISpellInfo[spellId].cooldown); + events.ScheduleEvent(spellId, AISpellInfo[spellId].cooldown + rand() % AISpellInfo[spellId].cooldown); } else DoMeleeAttackIfReady(); @@ -108,7 +108,7 @@ void CasterAI::EnterCombat(Unit* who) if (spells.empty()) return; - uint32 spell = rand()%spells.size(); + uint32 spell = rand() % spells.size(); uint32 count = 0; for (SpellVct::iterator itr = spells.begin(); itr != spells.end(); ++itr, ++count) { @@ -219,7 +219,7 @@ bool TurretAI::CanAIAttack(const Unit* /*who*/) const { // TODO: use one function to replace it if (!me->IsWithinCombatRange(me->GetVictim(), me->m_CombatDistance) - || (m_minRange && me->IsWithinCombatRange(me->GetVictim(), m_minRange))) + || (m_minRange && me->IsWithinCombatRange(me->GetVictim(), m_minRange))) return false; return true; } diff --git a/src/server/game/AI/CoreAI/CombatAI.h b/src/server/game/AI/CoreAI/CombatAI.h index f563b93e0..19c64bea6 100644 --- a/src/server/game/AI/CoreAI/CombatAI.h +++ b/src/server/game/AI/CoreAI/CombatAI.h @@ -15,94 +15,94 @@ class Creature; class AggressorAI : public CreatureAI { - public: - explicit AggressorAI(Creature* c) : CreatureAI(c) {} +public: + explicit AggressorAI(Creature* c) : CreatureAI(c) {} - void UpdateAI(uint32); - static int Permissible(const Creature*); + void UpdateAI(uint32); + static int Permissible(const Creature*); }; typedef std::vector SpellVct; class CombatAI : public CreatureAI { - public: - explicit CombatAI(Creature* c) : CreatureAI(c) {} +public: + explicit CombatAI(Creature* c) : CreatureAI(c) {} - void InitializeAI(); - void Reset(); - void EnterCombat(Unit* who); - void JustDied(Unit* killer); - void UpdateAI(uint32 diff); + void InitializeAI(); + void Reset(); + void EnterCombat(Unit* who); + void JustDied(Unit* killer); + void UpdateAI(uint32 diff); - static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } + static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } - protected: - EventMap events; - SpellVct spells; +protected: + EventMap events; + SpellVct spells; }; class CasterAI : public CombatAI { - public: - explicit CasterAI(Creature* c) : CombatAI(c) { m_attackDist = MELEE_RANGE; } - void InitializeAI(); - void AttackStart(Unit* victim) { AttackStartCaster(victim, m_attackDist); } - void UpdateAI(uint32 diff); - void EnterCombat(Unit* /*who*/); - private: - float m_attackDist; +public: + explicit CasterAI(Creature* c) : CombatAI(c) { m_attackDist = MELEE_RANGE; } + void InitializeAI(); + void AttackStart(Unit* victim) { AttackStartCaster(victim, m_attackDist); } + void UpdateAI(uint32 diff); + void EnterCombat(Unit* /*who*/); +private: + float m_attackDist; }; struct ArcherAI : public CreatureAI { - public: - explicit ArcherAI(Creature* c); - void AttackStart(Unit* who); - void UpdateAI(uint32 diff); +public: + explicit ArcherAI(Creature* c); + void AttackStart(Unit* who); + void UpdateAI(uint32 diff); - static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } + static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } - protected: - float m_minRange; +protected: + float m_minRange; }; struct TurretAI : public CreatureAI { - public: - explicit TurretAI(Creature* c); - bool CanAIAttack(const Unit* who) const; - void AttackStart(Unit* who); - void UpdateAI(uint32 diff); +public: + explicit TurretAI(Creature* c); + bool CanAIAttack(const Unit* who) const; + void AttackStart(Unit* who); + void UpdateAI(uint32 diff); - static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } + static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } - protected: - float m_minRange; +protected: + float m_minRange; }; #define VEHICLE_CONDITION_CHECK_TIME 1000 #define VEHICLE_DISMISS_TIME 5000 struct VehicleAI : public CreatureAI { - public: - explicit VehicleAI(Creature* creature); +public: + explicit VehicleAI(Creature* creature); - void UpdateAI(uint32 diff); - void MoveInLineOfSight(Unit*) {} - void AttackStart(Unit*) {} - void OnCharmed(bool apply); + void UpdateAI(uint32 diff); + void MoveInLineOfSight(Unit*) {} + void AttackStart(Unit*) {} + void OnCharmed(bool apply); - static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } + static int Permissible(Creature const* /*creature*/) { return PERMIT_BASE_NO; } - private: - void LoadConditions(); - void CheckConditions(uint32 diff); - ConditionList conditions; - uint32 m_ConditionsTimer; - bool m_DoDismiss; - uint32 m_DismissTimer; +private: + void LoadConditions(); + void CheckConditions(uint32 diff); + ConditionList conditions; + uint32 m_ConditionsTimer; + bool m_DoDismiss; + uint32 m_DismissTimer; }; #endif diff --git a/src/server/game/AI/CoreAI/GameObjectAI.h b/src/server/game/AI/CoreAI/GameObjectAI.h index 625c9160a..644a1b772 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.h +++ b/src/server/game/AI/CoreAI/GameObjectAI.h @@ -16,49 +16,49 @@ class GameObjectAI { - protected: - GameObject* const go; - public: - explicit GameObjectAI(GameObject* g) : go(g) {} - virtual ~GameObjectAI() {} +protected: + GameObject* const go; +public: + explicit GameObjectAI(GameObject* g) : go(g) {} + virtual ~GameObjectAI() {} - virtual void UpdateAI(uint32 /*diff*/) {} + virtual void UpdateAI(uint32 /*diff*/) {} - virtual void InitializeAI() { Reset(); } + virtual void InitializeAI() { Reset(); } - virtual void Reset() { } + virtual void Reset() { } - // Pass parameters between AI - virtual void DoAction(int32 /*param = 0 */) {} - virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) {} - virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; } + // Pass parameters between AI + virtual void DoAction(int32 /*param = 0 */) {} + virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) {} + virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; } - static int Permissible(GameObject const* go); + static int Permissible(GameObject const* go); - virtual bool GossipHello(Player* /*player*/, bool /*reportUse*/) { return false; } - virtual bool GossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) { return false; } - virtual bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) { return false; } - virtual bool QuestAccept(Player* /*player*/, Quest const* /*quest*/) { return false; } - virtual bool QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } - virtual uint32 GetDialogStatus(Player* /*player*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } - virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) {} - virtual uint32 GetData(uint32 /*id*/) const { return 0; } - virtual void SetData64(uint32 /*id*/, uint64 /*value*/) {} - virtual uint64 GetData64(uint32 /*id*/) const { return 0; } - virtual void SetData(uint32 /*id*/, uint32 /*value*/) {} - virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) {} - virtual void OnStateChanged(uint32 /*state*/, Unit* /*unit*/) {} - virtual void EventInform(uint32 /*eventId*/) {} - virtual void SpellHit(Unit* /*unit*/, const SpellInfo* /*spellInfo*/) {} + virtual bool GossipHello(Player* /*player*/, bool /*reportUse*/) { return false; } + virtual bool GossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) { return false; } + virtual bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) { return false; } + virtual bool QuestAccept(Player* /*player*/, Quest const* /*quest*/) { return false; } + virtual bool QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } + virtual uint32 GetDialogStatus(Player* /*player*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } + virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) {} + virtual uint32 GetData(uint32 /*id*/) const { return 0; } + virtual void SetData64(uint32 /*id*/, uint64 /*value*/) {} + virtual uint64 GetData64(uint32 /*id*/) const { return 0; } + virtual void SetData(uint32 /*id*/, uint32 /*value*/) {} + virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) {} + virtual void OnStateChanged(uint32 /*state*/, Unit* /*unit*/) {} + virtual void EventInform(uint32 /*eventId*/) {} + virtual void SpellHit(Unit* /*unit*/, const SpellInfo* /*spellInfo*/) {} }; class NullGameObjectAI : public GameObjectAI { - public: - explicit NullGameObjectAI(GameObject* g); +public: + explicit NullGameObjectAI(GameObject* g); - void UpdateAI(uint32 /*diff*/) {} + void UpdateAI(uint32 /*diff*/) {} - static int Permissible(GameObject const* /*go*/) { return PERMIT_BASE_IDLE; } + static int Permissible(GameObject const* /*go*/) { return PERMIT_BASE_IDLE; } }; #endif diff --git a/src/server/game/AI/CoreAI/GuardAI.h b/src/server/game/AI/CoreAI/GuardAI.h index efd6e13ec..beff5c7f8 100644 --- a/src/server/game/AI/CoreAI/GuardAI.h +++ b/src/server/game/AI/CoreAI/GuardAI.h @@ -13,13 +13,13 @@ class Creature; class GuardAI : public ScriptedAI { - public: - explicit GuardAI(Creature* creature); +public: + explicit GuardAI(Creature* creature); - static int Permissible(Creature const* creature); + static int Permissible(Creature const* creature); - void Reset(); - void EnterEvadeMode(); - void JustDied(Unit* killer); + void Reset(); + void EnterEvadeMode(); + void JustDied(Unit* killer); }; #endif diff --git a/src/server/game/AI/CoreAI/PassiveAI.h b/src/server/game/AI/CoreAI/PassiveAI.h index 634c1725a..ec928187a 100644 --- a/src/server/game/AI/CoreAI/PassiveAI.h +++ b/src/server/game/AI/CoreAI/PassiveAI.h @@ -12,65 +12,65 @@ class PassiveAI : public CreatureAI { - public: - explicit PassiveAI(Creature* c); +public: + explicit PassiveAI(Creature* c); - void MoveInLineOfSight(Unit*) {} - void AttackStart(Unit*) {} - void UpdateAI(uint32); + void MoveInLineOfSight(Unit*) {} + void AttackStart(Unit*) {} + void UpdateAI(uint32); - static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } + static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } }; class PossessedAI : public CreatureAI { - public: - explicit PossessedAI(Creature* c); +public: + explicit PossessedAI(Creature* c); - void MoveInLineOfSight(Unit*) {} - void AttackStart(Unit* target); - void UpdateAI(uint32); - void EnterEvadeMode() {} + void MoveInLineOfSight(Unit*) {} + void AttackStart(Unit* target); + void UpdateAI(uint32); + void EnterEvadeMode() {} - void JustDied(Unit*); - void KilledUnit(Unit* victim); + void JustDied(Unit*); + void KilledUnit(Unit* victim); - static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } + static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } }; class NullCreatureAI : public CreatureAI { - public: - explicit NullCreatureAI(Creature* c); +public: + explicit NullCreatureAI(Creature* c); - void MoveInLineOfSight(Unit*) {} - void AttackStart(Unit*) {} - void UpdateAI(uint32) {} - void EnterEvadeMode() {} - void OnCharmed(bool /*apply*/) {} + void MoveInLineOfSight(Unit*) {} + void AttackStart(Unit*) {} + void UpdateAI(uint32) {} + void EnterEvadeMode() {} + void OnCharmed(bool /*apply*/) {} - static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } + static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } }; class CritterAI : public PassiveAI { - public: - explicit CritterAI(Creature* c) : PassiveAI(c) { _combatTimer = 0; } +public: + explicit CritterAI(Creature* c) : PassiveAI(c) { _combatTimer = 0; } - void DamageTaken(Unit* /*done_by*/, uint32& /*damage*/, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask); - void EnterEvadeMode(); - void UpdateAI(uint32); + void DamageTaken(Unit* /*done_by*/, uint32& /*damage*/, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask); + void EnterEvadeMode(); + void UpdateAI(uint32); // Xinef: Added - private: - uint32 _combatTimer; +private: + uint32 _combatTimer; }; class TriggerAI : public NullCreatureAI { - public: - explicit TriggerAI(Creature* c) : NullCreatureAI(c) {} - void IsSummonedBy(Unit* summoner); +public: + explicit TriggerAI(Creature* c) : NullCreatureAI(c) {} + void IsSummonedBy(Unit* summoner); }; #endif diff --git a/src/server/game/AI/CoreAI/PetAI.cpp b/src/server/game/AI/CoreAI/PetAI.cpp index ec19cb95f..58526d1c9 100644 --- a/src/server/game/AI/CoreAI/PetAI.cpp +++ b/src/server/game/AI/CoreAI/PetAI.cpp @@ -40,12 +40,12 @@ bool PetAI::_needToStop() return true; // xinef: dont allow to follow targets out of visibility range - if (me->GetExactDist(me->GetVictim()) > me->GetVisibilityRange()-5.0f) + if (me->GetExactDist(me->GetVictim()) > me->GetVisibilityRange() - 5.0f) return true; // dont allow pets to follow targets far away from owner if (Unit* owner = me->GetCharmerOrOwner()) - if (owner->GetExactDist(me) >= (owner->GetVisibilityRange()-10.0f)) + if (owner->GetExactDist(me) >= (owner->GetVisibilityRange() - 10.0f)) return true; if (!me->_CanDetectFeignDeathOf(me->GetVictim())) @@ -95,39 +95,39 @@ bool PetAI::_canMeleeAttack() case ENTRY_IMP: case ENTRY_WATER_ELEMENTAL: case ENTRY_WATER_ELEMENTAL_PERM: - { - for (uint8 i = 0; i < me->GetPetAutoSpellSize(); ++i) { - uint32 spellID = me->GetPetAutoSpellOnPos(i); - switch (spellID) + for (uint8 i = 0; i < me->GetPetAutoSpellSize(); ++i) { - case IMP_FIREBOLT_RANK_1: - case IMP_FIREBOLT_RANK_2: - case IMP_FIREBOLT_RANK_3: - case IMP_FIREBOLT_RANK_4: - case IMP_FIREBOLT_RANK_5: - case IMP_FIREBOLT_RANK_6: - case IMP_FIREBOLT_RANK_7: - case IMP_FIREBOLT_RANK_8: - case IMP_FIREBOLT_RANK_9: - case WATER_ELEMENTAL_WATERBOLT_1: - case WATER_ELEMENTAL_WATERBOLT_2: + uint32 spellID = me->GetPetAutoSpellOnPos(i); + switch (spellID) { - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID); - int32 mana = me->GetPower(POWER_MANA); + case IMP_FIREBOLT_RANK_1: + case IMP_FIREBOLT_RANK_2: + case IMP_FIREBOLT_RANK_3: + case IMP_FIREBOLT_RANK_4: + case IMP_FIREBOLT_RANK_5: + case IMP_FIREBOLT_RANK_6: + case IMP_FIREBOLT_RANK_7: + case IMP_FIREBOLT_RANK_8: + case IMP_FIREBOLT_RANK_9: + case WATER_ELEMENTAL_WATERBOLT_1: + case WATER_ELEMENTAL_WATERBOLT_2: + { + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID); + int32 mana = me->GetPower(POWER_MANA); - if (mana >= spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask())) - { - combatRange = spellInfo->GetMaxRange(); - return true; - } + if (mana >= spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask())) + { + combatRange = spellInfo->GetMaxRange(); + return true; + } + } + default: + break; } - default: - break; } + return false; } - return false; - } default: break; } @@ -349,7 +349,7 @@ void PetAI::UpdateAllies() Unit* owner = me->GetCharmerOrOwner(); Group* group = nullptr; - m_updateAlliesTimer = 10*IN_MILLISECONDS; //update friendly targets every 10 seconds, lesser checks increase performance + m_updateAlliesTimer = 10 * IN_MILLISECONDS; //update friendly targets every 10 seconds, lesser checks increase performance if (!owner) return; @@ -622,29 +622,29 @@ void PetAI::MovementInform(uint32 moveType, uint32 data) switch (moveType) { case POINT_MOTION_TYPE: - { - // Pet is returning to where stay was clicked. data should be - // pet's GUIDLow since we set that as the waypoint ID - if (data == me->GetGUIDLow() && me->GetCharmInfo()->IsReturning()) { - ClearCharmInfoFlags(); - me->GetCharmInfo()->SetIsAtStay(true); - me->GetMotionMaster()->Clear(); - me->GetMotionMaster()->MoveIdle(); + // Pet is returning to where stay was clicked. data should be + // pet's GUIDLow since we set that as the waypoint ID + if (data == me->GetGUIDLow() && me->GetCharmInfo()->IsReturning()) + { + ClearCharmInfoFlags(); + me->GetCharmInfo()->SetIsAtStay(true); + me->GetMotionMaster()->Clear(); + me->GetMotionMaster()->MoveIdle(); + } + break; } - break; - } case FOLLOW_MOTION_TYPE: - { - // If data is owner's GUIDLow then we've reached follow point, - // otherwise we're probably chasing a creature - if (me->GetCharmerOrOwner() && me->GetCharmInfo() && data == me->GetCharmerOrOwner()->GetGUIDLow() && me->GetCharmInfo()->IsReturning()) { - ClearCharmInfoFlags(); - me->GetCharmInfo()->SetIsFollowing(true); + // If data is owner's GUIDLow then we've reached follow point, + // otherwise we're probably chasing a creature + if (me->GetCharmerOrOwner() && me->GetCharmInfo() && data == me->GetCharmerOrOwner()->GetGUIDLow() && me->GetCharmInfo()->IsReturning()) + { + ClearCharmInfoFlags(); + me->GetCharmInfo()->SetIsFollowing(true); + } + break; } - break; - } default: break; } @@ -698,7 +698,7 @@ bool PetAI::CanAttack(Unit* target, const SpellInfo* spellInfo) // Stay - can attack if target is within range or commanded to if (me->GetCharmInfo()->HasCommandState(COMMAND_STAY)) return (me->IsWithinMeleeRange(target) || me->GetCharmInfo()->IsCommandAttack()); - + // Pets attacking something (or chasing) should only switch targets if owner tells them to if (me->GetVictim() && me->GetVictim() != target) { @@ -708,14 +708,14 @@ bool PetAI::CanAttack(Unit* target, const SpellInfo* spellInfo) ownerTarget = owner->GetSelectedUnit(); else ownerTarget = me->GetCharmerOrOwner()->GetVictim(); - + if (ownerTarget && me->GetCharmInfo()->IsCommandAttack()) return (target->GetGUID() == ownerTarget->GetGUID()); } // Follow if (me->GetCharmInfo()->HasCommandState(COMMAND_FOLLOW)) - return !me->GetCharmInfo()->IsReturning(); + return !me->GetCharmInfo()->IsReturning(); // default, though we shouldn't ever get here return false; diff --git a/src/server/game/AI/CoreAI/PetAI.h b/src/server/game/AI/CoreAI/PetAI.h index 61ea0a824..a0e7e141b 100644 --- a/src/server/game/AI/CoreAI/PetAI.h +++ b/src/server/game/AI/CoreAI/PetAI.h @@ -34,47 +34,47 @@ enum SpecialPets class PetAI : public CreatureAI { - public: +public: - explicit PetAI(Creature* c); + explicit PetAI(Creature* c); - void UpdateAI(uint32); - static int Permissible(const Creature*); + void UpdateAI(uint32); + static int Permissible(const Creature*); - void KilledUnit(Unit* /*victim*/); - void AttackStart(Unit* target); - void MovementInform(uint32 moveType, uint32 data); - void OwnerAttackedBy(Unit* attacker); - void OwnerAttacked(Unit* target); - void AttackedBy(Unit* attacker); - void ReceiveEmote(Player* player, uint32 textEmote); + void KilledUnit(Unit* /*victim*/); + void AttackStart(Unit* target); + void MovementInform(uint32 moveType, uint32 data); + void OwnerAttackedBy(Unit* attacker); + void OwnerAttacked(Unit* target); + void AttackedBy(Unit* attacker); + void ReceiveEmote(Player* player, uint32 textEmote); - // The following aren't used by the PetAI but need to be defined to override - // default CreatureAI functions which interfere with the PetAI - // - void MoveInLineOfSight(Unit* /*who*/) {} // CreatureAI interferes with returning pets - void MoveInLineOfSight_Safe(Unit* /*who*/) {} // CreatureAI interferes with returning pets - void EnterEvadeMode() {} // For fleeing, pets don't use this type of Evade mechanic - void SpellHit(Unit* caster, const SpellInfo* spellInfo); + // The following aren't used by the PetAI but need to be defined to override + // default CreatureAI functions which interfere with the PetAI + // + void MoveInLineOfSight(Unit* /*who*/) {} // CreatureAI interferes with returning pets + void MoveInLineOfSight_Safe(Unit* /*who*/) {} // CreatureAI interferes with returning pets + void EnterEvadeMode() {} // For fleeing, pets don't use this type of Evade mechanic + void SpellHit(Unit* caster, const SpellInfo* spellInfo); - private: - bool _isVisible(Unit*) const; - bool _needToStop(void); - void _stopAttack(void); - void _doMeleeAttack(); - bool _canMeleeAttack(); +private: + bool _isVisible(Unit*) const; + bool _needToStop(void); + void _stopAttack(void); + void _doMeleeAttack(); + bool _canMeleeAttack(); - void UpdateAllies(); + void UpdateAllies(); - TimeTracker i_tracker; - std::set m_AllySet; - uint32 m_updateAlliesTimer; - float combatRange; + TimeTracker i_tracker; + std::set m_AllySet; + uint32 m_updateAlliesTimer; + float combatRange; - Unit* SelectNextTarget(bool allowAutoSelect) const; - void HandleReturnMovement(); - void DoAttack(Unit* target, bool chase); - bool CanAttack(Unit* target, const SpellInfo* spellInfo = nullptr); - void ClearCharmInfoFlags(); + Unit* SelectNextTarget(bool allowAutoSelect) const; + void HandleReturnMovement(); + void DoAttack(Unit* target, bool chase); + bool CanAttack(Unit* target, const SpellInfo* spellInfo = nullptr); + void ClearCharmInfoFlags(); }; #endif diff --git a/src/server/game/AI/CoreAI/ReactorAI.h b/src/server/game/AI/CoreAI/ReactorAI.h index d2ffc54de..e646ba5bd 100644 --- a/src/server/game/AI/CoreAI/ReactorAI.h +++ b/src/server/game/AI/CoreAI/ReactorAI.h @@ -13,13 +13,13 @@ class Unit; class ReactorAI : public CreatureAI { - public: +public: - explicit ReactorAI(Creature* c) : CreatureAI(c) {} + explicit ReactorAI(Creature* c) : CreatureAI(c) {} - void MoveInLineOfSight(Unit*) {} - void UpdateAI(uint32 diff); + void MoveInLineOfSight(Unit*) {} + void UpdateAI(uint32 diff); - static int Permissible(const Creature*); + static int Permissible(const Creature*); }; #endif diff --git a/src/server/game/AI/CoreAI/TotemAI.cpp b/src/server/game/AI/CoreAI/TotemAI.cpp index 2b673a32f..5133e208d 100644 --- a/src/server/game/AI/CoreAI/TotemAI.cpp +++ b/src/server/game/AI/CoreAI/TotemAI.cpp @@ -68,8 +68,8 @@ void TotemAI::UpdateAI(uint32 /*diff*/) // Search victim if no, not attackable, or out of range, or friendly (possible in case duel end) if (!victim || - !victim->isTargetableForAttack(true, me) || !me->IsWithinDistInMap(victim, max_range) || - me->IsFriendlyTo(victim) || !me->CanSeeOrDetect(victim)) + !victim->isTargetableForAttack(true, me) || !me->IsWithinDistInMap(victim, max_range) || + me->IsFriendlyTo(victim) || !me->CanSeeOrDetect(victim)) { victim = nullptr; acore::NearestAttackableUnitInObjectRangeCheck u_check(me, me, max_range); @@ -96,7 +96,7 @@ void TotemAI::AttackStart(Unit* /*victim*/) // Sentry totem sends ping on attack if (me->GetEntry() == SENTRY_TOTEM_ENTRY && me->GetOwner()->GetTypeId() == TYPEID_PLAYER) { - WorldPacket data(MSG_MINIMAP_PING, (8+4+4)); + WorldPacket data(MSG_MINIMAP_PING, (8 + 4 + 4)); data << me->GetGUID(); data << me->GetPositionX(); data << me->GetPositionY(); diff --git a/src/server/game/AI/CoreAI/TotemAI.h b/src/server/game/AI/CoreAI/TotemAI.h index 578b2fda4..2112bd523 100644 --- a/src/server/game/AI/CoreAI/TotemAI.h +++ b/src/server/game/AI/CoreAI/TotemAI.h @@ -15,35 +15,35 @@ class Totem; class TotemAI : public CreatureAI { - public: +public: - explicit TotemAI(Creature* c); + explicit TotemAI(Creature* c); - void MoveInLineOfSight(Unit* who); - void AttackStart(Unit* victim); - void EnterEvadeMode(); - void SpellHit(Unit* /*caster*/, const SpellInfo* /*spellInfo*/); - void DoAction(int32 param); + void MoveInLineOfSight(Unit* who); + void AttackStart(Unit* victim); + void EnterEvadeMode(); + void SpellHit(Unit* /*caster*/, const SpellInfo* /*spellInfo*/); + void DoAction(int32 param); - void UpdateAI(uint32 diff); - static int Permissible(Creature const* creature); + void UpdateAI(uint32 diff); + static int Permissible(Creature const* creature); - private: - uint64 i_victimGuid; +private: + uint64 i_victimGuid; }; class KillMagnetEvent : public BasicEvent { - public: - KillMagnetEvent(Unit& self) : _self(self) { } - bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) - { - _self.setDeathState(JUST_DIED); - return true; - } +public: + KillMagnetEvent(Unit& self) : _self(self) { } + bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) + { + _self.setDeathState(JUST_DIED); + return true; + } - protected: - Unit& _self; +protected: + Unit& _self; }; #endif diff --git a/src/server/game/AI/CoreAI/UnitAI.cpp b/src/server/game/AI/CoreAI/UnitAI.cpp index 8380023f5..56a119b4c 100644 --- a/src/server/game/AI/CoreAI/UnitAI.cpp +++ b/src/server/game/AI/CoreAI/UnitAI.cpp @@ -31,7 +31,7 @@ void UnitAI::DoMeleeAttackIfReady() if (me->HasUnitState(UNIT_STATE_CASTING)) return; - Unit *victim = me->GetVictim(); + Unit* victim = me->GetVictim(); if (!victim || !victim->IsInWorld()) return; @@ -130,32 +130,40 @@ void UnitAI::DoCast(uint32 spellId) switch (AISpellInfo[spellId].target) { default: - case AITARGET_SELF: target = me; break; - case AITARGET_VICTIM: target = me->GetVictim(); break; + case AITARGET_SELF: + target = me; + break; + case AITARGET_VICTIM: + target = me->GetVictim(); + break; case AITARGET_ENEMY: - { - const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); - bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); - //float range = GetSpellMaxRange(spellInfo, false); - target = SelectTarget(SELECT_TARGET_RANDOM, 0, spellInfo->GetMaxRange(false), playerOnly); + { + const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); + bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); + //float range = GetSpellMaxRange(spellInfo, false); + target = SelectTarget(SELECT_TARGET_RANDOM, 0, spellInfo->GetMaxRange(false), playerOnly); + break; + } + case AITARGET_ALLY: + target = me; + break; + case AITARGET_BUFF: + target = me; break; - } - case AITARGET_ALLY: target = me; break; - case AITARGET_BUFF: target = me; break; case AITARGET_DEBUFF: - { - const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); - bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); - float range = spellInfo->GetMaxRange(false); + { + const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); + bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); + float range = spellInfo->GetMaxRange(false); - DefaultTargetSelector targetSelector(me, range, playerOnly, -(int32)spellId); - if (!(spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_VICTIM) - && targetSelector(me->GetVictim())) - target = me->GetVictim(); - else - target = SelectTarget(SELECT_TARGET_RANDOM, 0, targetSelector); - break; - } + DefaultTargetSelector targetSelector(me, range, playerOnly, -(int32)spellId); + if (!(spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_VICTIM) + && targetSelector(me->GetVictim())) + target = me->GetVictim(); + else + target = SelectTarget(SELECT_TARGET_RANDOM, 0, targetSelector); + break; + } } if (target) @@ -213,27 +221,27 @@ void UnitAI::FillAISpellInfo() if (!spellInfo->GetMaxRange(false)) UPDATE_TARGET(AITARGET_SELF) - else - { - for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) + else { - uint32 targetType = spellInfo->Effects[j].TargetA.GetTarget(); - - if (targetType == TARGET_UNIT_TARGET_ENEMY - || targetType == TARGET_DEST_TARGET_ENEMY) - UPDATE_TARGET(AITARGET_VICTIM) - else if (targetType == TARGET_UNIT_DEST_AREA_ENEMY) - UPDATE_TARGET(AITARGET_ENEMY) - - if (spellInfo->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA) + for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { - if (targetType == TARGET_UNIT_TARGET_ENEMY) - UPDATE_TARGET(AITARGET_DEBUFF) - else if (spellInfo->IsPositive()) - UPDATE_TARGET(AITARGET_BUFF) + uint32 targetType = spellInfo->Effects[j].TargetA.GetTarget(); + + if (targetType == TARGET_UNIT_TARGET_ENEMY + || targetType == TARGET_DEST_TARGET_ENEMY) + UPDATE_TARGET(AITARGET_VICTIM) + else if (targetType == TARGET_UNIT_DEST_AREA_ENEMY) + UPDATE_TARGET(AITARGET_ENEMY) + + if (spellInfo->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA) + { + if (targetType == TARGET_UNIT_TARGET_ENEMY) + UPDATE_TARGET(AITARGET_DEBUFF) + else if (spellInfo->IsPositive()) + UPDATE_TARGET(AITARGET_BUFF) + } } } - } AIInfo->realCooldown = spellInfo->RecoveryTime + spellInfo->StartRecoveryTime; AIInfo->maxRange = spellInfo->GetMaxRange(false) * 3 / 4; } @@ -247,7 +255,7 @@ void PlayerAI::OnCharmed(bool apply) void SimpleCharmedAI::UpdateAI(uint32 /*diff*/) { - Creature* charmer = me->GetCharmer()->ToCreature(); + Creature* charmer = me->GetCharmer()->ToCreature(); //kill self if charm aura has infinite duration if (charmer->IsInEvadeMode()) diff --git a/src/server/game/AI/CoreAI/UnitAI.h b/src/server/game/AI/CoreAI/UnitAI.h index 281a33178..1ffeddf7c 100644 --- a/src/server/game/AI/CoreAI/UnitAI.h +++ b/src/server/game/AI/CoreAI/UnitAI.h @@ -80,13 +80,13 @@ struct DefaultTargetSelector : public acore::unary_function // TODO: Add more checks from Spell::CheckCast struct SpellTargetSelector : public acore::unary_function { - public: - SpellTargetSelector(Unit* caster, uint32 spellId); - bool operator()(Unit const* target) const; +public: + SpellTargetSelector(Unit* caster, uint32 spellId); + bool operator()(Unit const* target) const; - private: - Unit const* _caster; - SpellInfo const* _spellInfo; +private: + Unit const* _caster; + SpellInfo const* _spellInfo; }; // Very simple target selector, will just skip main target @@ -94,13 +94,13 @@ struct SpellTargetSelector : public acore::unary_function // because tank will not be in the temporary list struct NonTankTargetSelector : public acore::unary_function { - public: - NonTankTargetSelector(Creature* source, bool playerOnly = true) : _source(source), _playerOnly(playerOnly) { } - bool operator()(Unit const* target) const; +public: + NonTankTargetSelector(Creature* source, bool playerOnly = true) : _source(source), _playerOnly(playerOnly) { } + bool operator()(Unit const* target) const; - private: - Creature const* _source; - bool _playerOnly; +private: + Creature const* _source; + bool _playerOnly; }; // Simple selector for units using mana @@ -165,165 +165,165 @@ private: class UnitAI { - protected: - Unit* const me; - public: - explicit UnitAI(Unit* unit) : me(unit) {} - virtual ~UnitAI() {} +protected: + Unit* const me; +public: + explicit UnitAI(Unit* unit) : me(unit) {} + virtual ~UnitAI() {} - virtual bool CanAIAttack(Unit const* /*target*/) const { return true; } - virtual void AttackStart(Unit* /*target*/); - virtual void UpdateAI(uint32 diff) = 0; + virtual bool CanAIAttack(Unit const* /*target*/) const { return true; } + virtual void AttackStart(Unit* /*target*/); + virtual void UpdateAI(uint32 diff) = 0; - virtual void InitializeAI() { if (!me->isDead()) Reset(); } + virtual void InitializeAI() { if (!me->isDead()) Reset(); } - virtual void Reset() {}; + virtual void Reset() {}; - // Called when unit is charmed - virtual void OnCharmed(bool apply) = 0; + // Called when unit is charmed + virtual void OnCharmed(bool apply) = 0; - // Pass parameters between AI - virtual void DoAction(int32 /*param*/) {} - virtual uint32 GetData(uint32 /*id = 0*/) const { return 0; } - virtual void SetData(uint32 /*id*/, uint32 /*value*/) {} - virtual void SetGUID(uint64 /*guid*/, int32 /*id*/ = 0) {} - virtual uint64 GetGUID(int32 /*id*/ = 0) const { return 0; } + // Pass parameters between AI + virtual void DoAction(int32 /*param*/) {} + virtual uint32 GetData(uint32 /*id = 0*/) const { return 0; } + virtual void SetData(uint32 /*id*/, uint32 /*value*/) {} + virtual void SetGUID(uint64 /*guid*/, int32 /*id*/ = 0) {} + virtual uint64 GetGUID(int32 /*id*/ = 0) const { return 0; } - Unit* SelectTarget(SelectAggroTarget targetType, uint32 position = 0, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); - // Select the targets satifying the predicate. - // predicate shall extend acore::unary_function - template Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) + Unit* SelectTarget(SelectAggroTarget targetType, uint32 position = 0, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); + // Select the targets satifying the predicate. + // predicate shall extend acore::unary_function + template Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) + { + ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); + if (position >= threatlist.size()) + return nullptr; + + std::list targetList; + for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) + if (predicate((*itr)->getTarget())) + targetList.push_back((*itr)->getTarget()); + + if (position >= targetList.size()) + return nullptr; + + if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) + targetList.sort(acore::ObjectDistanceOrderPred(me)); + + switch (targetType) { - ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); - if (position >= threatlist.size()) - return nullptr; - - std::list targetList; - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - if (predicate((*itr)->getTarget())) - targetList.push_back((*itr)->getTarget()); - - if (position >= targetList.size()) - return nullptr; - - if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - targetList.sort(acore::ObjectDistanceOrderPred(me)); - - switch (targetType) - { - case SELECT_TARGET_NEAREST: - case SELECT_TARGET_TOPAGGRO: + case SELECT_TARGET_NEAREST: + case SELECT_TARGET_TOPAGGRO: { std::list::iterator itr = targetList.begin(); std::advance(itr, position); return *itr; } - case SELECT_TARGET_FARTHEST: - case SELECT_TARGET_BOTTOMAGGRO: + case SELECT_TARGET_FARTHEST: + case SELECT_TARGET_BOTTOMAGGRO: { std::list::reverse_iterator ritr = targetList.rbegin(); std::advance(ritr, position); return *ritr; } - case SELECT_TARGET_RANDOM: + case SELECT_TARGET_RANDOM: { std::list::iterator itr = targetList.begin(); std::advance(itr, urand(position, targetList.size() - 1)); return *itr; } - default: - break; - } - - return nullptr; + default: + break; } - void SelectTargetList(std::list& targetList, uint32 num, SelectAggroTarget targetType, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); + return nullptr; + } - // Select the targets satifying the predicate. - // predicate shall extend acore::unary_function - template void SelectTargetList(std::list& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) - { - ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); - if (threatlist.empty()) - return; + void SelectTargetList(std::list& targetList, uint32 num, SelectAggroTarget targetType, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - if (predicate((*itr)->getTarget())) - targetList.push_back((*itr)->getTarget()); + // Select the targets satifying the predicate. + // predicate shall extend acore::unary_function + template void SelectTargetList(std::list& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) + { + ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); + if (threatlist.empty()) + return; - if (targetList.size() < maxTargets) - return; + for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) + if (predicate((*itr)->getTarget())) + targetList.push_back((*itr)->getTarget()); - if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - targetList.sort(acore::ObjectDistanceOrderPred(me)); + if (targetList.size() < maxTargets) + return; - if (targetType == SELECT_TARGET_FARTHEST || targetType == SELECT_TARGET_BOTTOMAGGRO) - targetList.reverse(); + if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) + targetList.sort(acore::ObjectDistanceOrderPred(me)); - if (targetType == SELECT_TARGET_RANDOM) - acore::Containers::RandomResizeList(targetList, maxTargets); - else - targetList.resize(maxTargets); - } + if (targetType == SELECT_TARGET_FARTHEST || targetType == SELECT_TARGET_BOTTOMAGGRO) + targetList.reverse(); - // Called at any Damage to any victim (before damage apply) - virtual void DamageDealt(Unit* /*victim*/, uint32& /*damage*/, DamageEffectType /*damageType*/) { } + if (targetType == SELECT_TARGET_RANDOM) + acore::Containers::RandomResizeList(targetList, maxTargets); + else + targetList.resize(maxTargets); + } - // Called at any Damage from any attacker (before damage apply) - // Note: it for recalculation damage or special reaction at damage - // for attack reaction use AttackedBy called for not DOT damage in Unit::DealDamage also - virtual void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/, DamageEffectType /*damagetype*/, SpellSchoolMask /*damageSchoolMask*/ ) {} + // Called at any Damage to any victim (before damage apply) + virtual void DamageDealt(Unit* /*victim*/, uint32& /*damage*/, DamageEffectType /*damageType*/) { } - // Called when the creature receives heal - virtual void HealReceived(Unit* /*done_by*/, uint32& /*addhealth*/) {} + // Called at any Damage from any attacker (before damage apply) + // Note: it for recalculation damage or special reaction at damage + // for attack reaction use AttackedBy called for not DOT damage in Unit::DealDamage also + virtual void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/, DamageEffectType /*damagetype*/, SpellSchoolMask /*damageSchoolMask*/ ) {} - // Called when the unit heals - virtual void HealDone(Unit* /*done_to*/, uint32& /*addhealth*/) {} + // Called when the creature receives heal + virtual void HealReceived(Unit* /*done_by*/, uint32& /*addhealth*/) {} - void AttackStartCaster(Unit* victim, float dist); + // Called when the unit heals + virtual void HealDone(Unit* /*done_to*/, uint32& /*addhealth*/) {} - void DoAddAuraToAllHostilePlayers(uint32 spellid); - void DoCast(uint32 spellId); - void DoCast(Unit* victim, uint32 spellId, bool triggered = false); - inline void DoCastSelf(uint32 spellId, bool triggered = false) { DoCast(me, spellId, triggered); } - void DoCastToAllHostilePlayers(uint32 spellid, bool triggered = false); - void DoCastVictim(uint32 spellId, bool triggered = false); - void DoCastAOE(uint32 spellId, bool triggered = false); + void AttackStartCaster(Unit* victim, float dist); - float DoGetSpellMaxRange(uint32 spellId, bool positive = false); + void DoAddAuraToAllHostilePlayers(uint32 spellid); + void DoCast(uint32 spellId); + void DoCast(Unit* victim, uint32 spellId, bool triggered = false); + inline void DoCastSelf(uint32 spellId, bool triggered = false) { DoCast(me, spellId, triggered); } + void DoCastToAllHostilePlayers(uint32 spellid, bool triggered = false); + void DoCastVictim(uint32 spellId, bool triggered = false); + void DoCastAOE(uint32 spellId, bool triggered = false); - void DoMeleeAttackIfReady(); - bool DoSpellAttackIfReady(uint32 spell); + float DoGetSpellMaxRange(uint32 spellId, bool positive = false); - static AISpellInfoType* AISpellInfo; - static void FillAISpellInfo(); + void DoMeleeAttackIfReady(); + bool DoSpellAttackIfReady(uint32 spell); - virtual void sGossipHello(Player* /*player*/) {} - virtual void sGossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) {} - virtual void sGossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) {} - virtual void sQuestAccept(Player* /*player*/, Quest const* /*quest*/) {} - virtual void sQuestSelect(Player* /*player*/, Quest const* /*quest*/) {} - virtual void sQuestComplete(Player* /*player*/, Quest const* /*quest*/) {} - virtual void sQuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) {} - virtual void sOnGameEvent(bool /*start*/, uint16 /*eventId*/) {} + static AISpellInfoType* AISpellInfo; + static void FillAISpellInfo(); + + virtual void sGossipHello(Player* /*player*/) {} + virtual void sGossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) {} + virtual void sGossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) {} + virtual void sQuestAccept(Player* /*player*/, Quest const* /*quest*/) {} + virtual void sQuestSelect(Player* /*player*/, Quest const* /*quest*/) {} + virtual void sQuestComplete(Player* /*player*/, Quest const* /*quest*/) {} + virtual void sQuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) {} + virtual void sOnGameEvent(bool /*start*/, uint16 /*eventId*/) {} }; class PlayerAI : public UnitAI { - protected: - Player* const me; - public: - explicit PlayerAI(Player* player) : UnitAI((Unit*)player), me(player) {} +protected: + Player* const me; +public: + explicit PlayerAI(Player* player) : UnitAI((Unit*)player), me(player) {} - void OnCharmed(bool apply); + void OnCharmed(bool apply); }; class SimpleCharmedAI : public PlayerAI { - public: - void UpdateAI(uint32 diff); - SimpleCharmedAI(Player* player): PlayerAI(player) {} +public: + void UpdateAI(uint32 diff); + SimpleCharmedAI(Player* player): PlayerAI(player) {} }; #endif diff --git a/src/server/game/AI/CreatureAI.cpp b/src/server/game/AI/CreatureAI.cpp index 7d7719042..0f7fc51ac 100644 --- a/src/server/game/AI/CreatureAI.cpp +++ b/src/server/game/AI/CreatureAI.cpp @@ -118,8 +118,8 @@ void CreatureAI::MoveInLineOfSight(Unit* who) // pussywizard: civilian, non-combat pet or any other NOT HOSTILE TO ANYONE (!) if (me->IsMoveInLineOfSightDisabled()) if (me->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET || // nothing more to do, return - !who->IsInCombat() || // if not in combat, nothing more to do - !me->IsWithinDist(who, ATTACK_DISTANCE)) // if in combat and in dist - neutral to all can actually assist other creatures + !who->IsInCombat() || // if not in combat, nothing more to do + !me->IsWithinDist(who, ATTACK_DISTANCE)) // if in combat and in dist - neutral to all can actually assist other creatures return; if (me->CanStartAttack(who)) diff --git a/src/server/game/AI/CreatureAI.h b/src/server/game/AI/CreatureAI.h index ed5768669..50a757681 100644 --- a/src/server/game/AI/CreatureAI.h +++ b/src/server/game/AI/CreatureAI.h @@ -53,122 +53,122 @@ enum SCEquip class CreatureAI : public UnitAI { - protected: - Creature* const me; +protected: + Creature* const me; - bool UpdateVictim(); - bool UpdateVictimWithGaze(); + bool UpdateVictim(); + bool UpdateVictimWithGaze(); - void SetGazeOn(Unit* target); + void SetGazeOn(Unit* target); - Creature* DoSummon(uint32 entry, Position const& pos, uint32 despawnTime = 30000, TempSummonType summonType = TEMPSUMMON_CORPSE_TIMED_DESPAWN); - Creature* DoSummon(uint32 entry, WorldObject* obj, float radius = 5.0f, uint32 despawnTime = 30000, TempSummonType summonType = TEMPSUMMON_CORPSE_TIMED_DESPAWN); - Creature* DoSummonFlyer(uint32 entry, WorldObject* obj, float flightZ, float radius = 5.0f, uint32 despawnTime = 30000, TempSummonType summonType = TEMPSUMMON_CORPSE_TIMED_DESPAWN); + Creature* DoSummon(uint32 entry, Position const& pos, uint32 despawnTime = 30000, TempSummonType summonType = TEMPSUMMON_CORPSE_TIMED_DESPAWN); + Creature* DoSummon(uint32 entry, WorldObject* obj, float radius = 5.0f, uint32 despawnTime = 30000, TempSummonType summonType = TEMPSUMMON_CORPSE_TIMED_DESPAWN); + Creature* DoSummonFlyer(uint32 entry, WorldObject* obj, float flightZ, float radius = 5.0f, uint32 despawnTime = 30000, TempSummonType summonType = TEMPSUMMON_CORPSE_TIMED_DESPAWN); - public: - void Talk(uint8 id, WorldObject const* whisperTarget = nullptr); - explicit CreatureAI(Creature* creature) : UnitAI(creature), me(creature), m_MoveInLineOfSight_locked(false) {} +public: + void Talk(uint8 id, WorldObject const* whisperTarget = nullptr); + explicit CreatureAI(Creature* creature) : UnitAI(creature), me(creature), m_MoveInLineOfSight_locked(false) {} - virtual ~CreatureAI() {} + virtual ~CreatureAI() {} - /// == Reactions At ================================= + /// == Reactions At ================================= - // Called if IsVisible(Unit* who) is true at each who move, reaction at visibility zone enter - void MoveInLineOfSight_Safe(Unit* who); + // Called if IsVisible(Unit* who) is true at each who move, reaction at visibility zone enter + void MoveInLineOfSight_Safe(Unit* who); - // Trigger Creature "Alert" state (creature can see stealthed unit) - void TriggerAlert(Unit const* who) const; + // Trigger Creature "Alert" state (creature can see stealthed unit) + void TriggerAlert(Unit const* who) const; - // Called in Creature::Update when deathstate = DEAD. Inherited classes may maniuplate the ability to respawn based on scripted events. - virtual bool CanRespawn() { return true; } + // Called in Creature::Update when deathstate = DEAD. Inherited classes may maniuplate the ability to respawn based on scripted events. + virtual bool CanRespawn() { return true; } - // Called for reaction at stopping attack at no attackers or targets - virtual void EnterEvadeMode(); + // Called for reaction at stopping attack at no attackers or targets + virtual void EnterEvadeMode(); - // Called for reaction at enter to combat if not in combat yet (enemy can be nullptr) - virtual void EnterCombat(Unit* /*victim*/) {} + // Called for reaction at enter to combat if not in combat yet (enemy can be nullptr) + virtual void EnterCombat(Unit* /*victim*/) {} - // Called when the creature is killed - virtual void JustDied(Unit* /*killer*/) {} + // Called when the creature is killed + virtual void JustDied(Unit* /*killer*/) {} - // Called when the creature kills a unit - virtual void KilledUnit(Unit* /*victim*/) {} + // Called when the creature kills a unit + virtual void KilledUnit(Unit* /*victim*/) {} - // Called when the creature summon successfully other creature - virtual void JustSummoned(Creature* /*summon*/) {} - virtual void IsSummonedBy(Unit* /*summoner*/) {} + // Called when the creature summon successfully other creature + virtual void JustSummoned(Creature* /*summon*/) {} + virtual void IsSummonedBy(Unit* /*summoner*/) {} - virtual void SummonedCreatureDespawn(Creature* /*summon*/) {} - virtual void SummonedCreatureDies(Creature* /*summon*/, Unit* /*killer*/) {} + virtual void SummonedCreatureDespawn(Creature* /*summon*/) {} + virtual void SummonedCreatureDies(Creature* /*summon*/, Unit* /*killer*/) {} - // Called when hit by a spell - virtual void SpellHit(Unit* /*caster*/, SpellInfo const* /*spell*/) {} + // Called when hit by a spell + virtual void SpellHit(Unit* /*caster*/, SpellInfo const* /*spell*/) {} - // Called when spell hits a target - virtual void SpellHitTarget(Unit* /*target*/, SpellInfo const* /*spell*/) {} + // Called when spell hits a target + virtual void SpellHitTarget(Unit* /*target*/, SpellInfo const* /*spell*/) {} - // Called when the creature is target of hostile action: swing, hostile spell landed, fear/etc) - virtual void AttackedBy(Unit* /*attacker*/) {} - virtual bool IsEscorted() { return false; } + // Called when the creature is target of hostile action: swing, hostile spell landed, fear/etc) + virtual void AttackedBy(Unit* /*attacker*/) {} + virtual bool IsEscorted() { return false; } - // Called when creature is spawned or respawned (for reseting variables) - virtual void JustRespawned() { Reset(); } + // Called when creature is spawned or respawned (for reseting variables) + virtual void JustRespawned() { Reset(); } - // Called at waypoint reached or point movement finished - virtual void MovementInform(uint32 /*type*/, uint32 /*id*/) {} + // Called at waypoint reached or point movement finished + virtual void MovementInform(uint32 /*type*/, uint32 /*id*/) {} - void OnCharmed(bool apply); + void OnCharmed(bool apply); - // Called at reaching home after evade - virtual void JustReachedHome() {} + // Called at reaching home after evade + virtual void JustReachedHome() {} - void DoZoneInCombat(Creature* creature = NULL, float maxRangeToNearestTarget = 50.0f); + void DoZoneInCombat(Creature* creature = NULL, float maxRangeToNearestTarget = 50.0f); - // Called at text emote receive from player - virtual void ReceiveEmote(Player* /*player*/, uint32 /*emoteId*/) {} + // Called at text emote receive from player + virtual void ReceiveEmote(Player* /*player*/, uint32 /*emoteId*/) {} - // Called when owner takes damage - virtual void OwnerAttackedBy(Unit* /*attacker*/) {} + // Called when owner takes damage + virtual void OwnerAttackedBy(Unit* /*attacker*/) {} - // Called when owner attacks something - virtual void OwnerAttacked(Unit* /*target*/) {} + // Called when owner attacks something + virtual void OwnerAttacked(Unit* /*target*/) {} - /// == Triggered Actions Requested ================== + /// == Triggered Actions Requested ================== - // Called when creature attack expected (if creature can and no have current victim) - // Note: for reaction at hostile action must be called AttackedBy function. - //virtual void AttackStart(Unit*) {} + // Called when creature attack expected (if creature can and no have current victim) + // Note: for reaction at hostile action must be called AttackedBy function. + //virtual void AttackStart(Unit*) {} - // Called at World update tick - //virtual void UpdateAI(uint32 /*diff*/) {} + // Called at World update tick + //virtual void UpdateAI(uint32 /*diff*/) {} - /// == State checks ================================= + /// == State checks ================================= - // Is unit visible for MoveInLineOfSight - //virtual bool IsVisible(Unit*) const { return false; } + // Is unit visible for MoveInLineOfSight + //virtual bool IsVisible(Unit*) const { return false; } - // called when the corpse of this creature gets removed - virtual void CorpseRemoved(uint32& /*respawnDelay*/) {} + // called when the corpse of this creature gets removed + virtual void CorpseRemoved(uint32& /*respawnDelay*/) {} - // Called when victim entered water and creature can not enter water - //virtual bool CanReachByRangeAttack(Unit*) { return false; } + // Called when victim entered water and creature can not enter water + //virtual bool CanReachByRangeAttack(Unit*) { return false; } - /// == Fields ======================================= - virtual void PassengerBoarded(Unit* /*passenger*/, int8 /*seatId*/, bool /*apply*/) {} + /// == Fields ======================================= + virtual void PassengerBoarded(Unit* /*passenger*/, int8 /*seatId*/, bool /*apply*/) {} - virtual void OnSpellClick(Unit* /*clicker*/, bool& /*result*/) { } + virtual void OnSpellClick(Unit* /*clicker*/, bool& /*result*/) { } - virtual bool CanSeeAlways(WorldObject const* /*obj*/) { return false; } + virtual bool CanSeeAlways(WorldObject const* /*obj*/) { return false; } - virtual bool CanBeSeen(Player const* /*seer*/) { return true; } + virtual bool CanBeSeen(Player const* /*seer*/) { return true; } - protected: - virtual void MoveInLineOfSight(Unit* /*who*/); +protected: + virtual void MoveInLineOfSight(Unit* /*who*/); - bool _EnterEvadeMode(); + bool _EnterEvadeMode(); - private: - bool m_MoveInLineOfSight_locked; +private: + bool m_MoveInLineOfSight_locked; }; enum Permitions diff --git a/src/server/game/AI/CreatureAIImpl.h b/src/server/game/AI/CreatureAIImpl.h index 763e79fe3..aa0ea152a 100644 --- a/src/server/game/AI/CreatureAIImpl.h +++ b/src/server/game/AI/CreatureAIImpl.h @@ -16,7 +16,7 @@ #include template -static inline First const& RAND(First const& first, Second const& second, Rest const&... rest) +static inline First const& RAND(First const& first, Second const& second, Rest const& ... rest) { std::reference_wrapper::type> const pack[] = { first, second, rest... }; return pack[urand(0, sizeof...(rest) + 1)].get(); @@ -44,7 +44,7 @@ enum AICondition struct AISpellInfoType { AISpellInfoType() : target(AITARGET_SELF), condition(AICOND_COMBAT) - , cooldown(AI_DEFAULT_COOLDOWN), realCooldown(0), maxRange(0.0f){} + , cooldown(AI_DEFAULT_COOLDOWN), realCooldown(0), maxRange(0.0f) {} AITarget target; AICondition condition; uint32 cooldown; diff --git a/src/server/game/AI/CreatureAISelector.cpp b/src/server/game/AI/CreatureAISelector.cpp index c5dfefabf..4785222c0 100644 --- a/src/server/game/AI/CreatureAISelector.cpp +++ b/src/server/game/AI/CreatureAISelector.cpp @@ -32,7 +32,7 @@ namespace FactorySelector return scriptedAI; // AIname in db - std::string ainame=creature->GetAIName(); + std::string ainame = creature->GetAIName(); if (!ai_factory && !ainame.empty()) ai_factory = ai_registry.GetRegistryItem(ainame); diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp index 4fcabf4e0..0bcc10dad 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2016+ AzerothCore , released under GNU GPL v2 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-GPL2 - * + * * * This program is free software licensed under GPL version 2 * Please see the included DOCS/LICENSE.TXT for more information */ @@ -211,7 +211,7 @@ void ScriptedAI::DoPlayMusic(uint32 soundId, bool zone) if (me && me->FindMap()) { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); targets = new ObjectList(); if (!players.isEmpty()) @@ -278,11 +278,11 @@ SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mec // Targets and Effects checked first as most used restrictions //Check the spell targets if specified - if (targets && !(SpellSummary[me->m_spells[i]].Targets & (1 << (targets-1)))) + if (targets && !(SpellSummary[me->m_spells[i]].Targets & (1 << (targets - 1)))) continue; //Check the type of spell if we are looking for a specific spell type - if (effects && !(SpellSummary[me->m_spells[i]].Effects & (1 << (effects-1)))) + if (effects && !(SpellSummary[me->m_spells[i]].Effects & (1 << (effects - 1)))) continue; //Check for school if specified @@ -482,7 +482,7 @@ Player* ScriptedAI::SelectTargetFromPlayerList(float maxdist, uint32 excludeAura tList.push_back(itr->GetSource()); } if (!tList.empty()) - return tList[urand(0,tList.size()-1)]; + return tList[urand(0, tList.size() - 1)]; else return nullptr; } diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index a8856b169..06a82fae8 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -80,7 +80,7 @@ public: void DespawnAll(); template - void DespawnIf(T const &predicate) + void DespawnIf(T const& predicate) { storage_.remove_if(predicate); } @@ -135,25 +135,25 @@ private: class EntryCheckPredicate { - public: - EntryCheckPredicate(uint32 entry) : _entry(entry) {} - bool operator()(uint64 guid) { return GUID_ENPART(guid) == _entry; } +public: + EntryCheckPredicate(uint32 entry) : _entry(entry) {} + bool operator()(uint64 guid) { return GUID_ENPART(guid) == _entry; } - private: - uint32 _entry; +private: + uint32 _entry; }; class PlayerOrPetCheck { - public: - bool operator() (WorldObject* unit) const - { - if (unit->GetTypeId() != TYPEID_PLAYER) - if (!IS_PLAYER_GUID(unit->ToUnit()->GetOwnerGUID())) - return true; +public: + bool operator() (WorldObject* unit) const + { + if (unit->GetTypeId() != TYPEID_PLAYER) + if (!IS_PLAYER_GUID(unit->ToUnit()->GetOwnerGUID())) + return true; - return false; - } + return false; + } }; struct ScriptedAI : public CreatureAI @@ -353,92 +353,92 @@ struct ScriptedAI : public CreatureAI Player* SelectTargetFromPlayerList(float maxdist, uint32 excludeAura = 0, bool mustBeInLOS = false) const; - private: - Difficulty _difficulty; - uint32 _evadeCheckCooldown; - bool _isCombatMovementAllowed; - bool _isHeroic; +private: + Difficulty _difficulty; + uint32 _evadeCheckCooldown; + bool _isCombatMovementAllowed; + bool _isHeroic; }; class BossAI : public ScriptedAI { - public: - BossAI(Creature* creature, uint32 bossId); - virtual ~BossAI() {} +public: + BossAI(Creature* creature, uint32 bossId); + virtual ~BossAI() {} - InstanceScript* const instance; - BossBoundaryMap const* GetBoundary() const { return _boundary; } + InstanceScript* const instance; + BossBoundaryMap const* GetBoundary() const { return _boundary; } - void JustSummoned(Creature* summon); - void SummonedCreatureDespawn(Creature* summon); + void JustSummoned(Creature* summon); + void SummonedCreatureDespawn(Creature* summon); - virtual void UpdateAI(uint32 diff); + virtual void UpdateAI(uint32 diff); - // Hook used to execute events scheduled into EventMap without the need - // to override UpdateAI - // note: You must re-schedule the event within this method if the event - // is supposed to run more than once - virtual void ExecuteEvent(uint32 /*eventId*/) { } + // Hook used to execute events scheduled into EventMap without the need + // to override UpdateAI + // note: You must re-schedule the event within this method if the event + // is supposed to run more than once + virtual void ExecuteEvent(uint32 /*eventId*/) { } - void Reset() { _Reset(); } - void EnterCombat(Unit* /*who*/) { _EnterCombat(); } - void JustDied(Unit* /*killer*/) { _JustDied(); } - void JustReachedHome() { _JustReachedHome(); } + void Reset() { _Reset(); } + void EnterCombat(Unit* /*who*/) { _EnterCombat(); } + void JustDied(Unit* /*killer*/) { _JustDied(); } + void JustReachedHome() { _JustReachedHome(); } - protected: - void _Reset(); - void _EnterCombat(); - void _JustDied(); - void _JustReachedHome() { me->setActive(false); } +protected: + void _Reset(); + void _EnterCombat(); + void _JustDied(); + void _JustReachedHome() { me->setActive(false); } - bool CheckInRoom() - { - if (CheckBoundary(me)) - return true; + bool CheckInRoom() + { + if (CheckBoundary(me)) + return true; - EnterEvadeMode(); - return false; - } + EnterEvadeMode(); + return false; + } - bool CheckBoundary(Unit* who); - void TeleportCheaters(); + bool CheckBoundary(Unit* who); + void TeleportCheaters(); - EventMap events; - SummonList summons; + EventMap events; + SummonList summons; - private: - BossBoundaryMap const* const _boundary; - uint32 const _bossId; +private: + BossBoundaryMap const* const _boundary; + uint32 const _bossId; }; class WorldBossAI : public ScriptedAI { - public: - WorldBossAI(Creature* creature); - virtual ~WorldBossAI() {} +public: + WorldBossAI(Creature* creature); + virtual ~WorldBossAI() {} - void JustSummoned(Creature* summon); - void SummonedCreatureDespawn(Creature* summon); + void JustSummoned(Creature* summon); + void SummonedCreatureDespawn(Creature* summon); - virtual void UpdateAI(uint32 diff); + virtual void UpdateAI(uint32 diff); - // Hook used to execute events scheduled into EventMap without the need - // to override UpdateAI - // note: You must re-schedule the event within this method if the event - // is supposed to run more than once - virtual void ExecuteEvent(uint32 /*eventId*/) { } + // Hook used to execute events scheduled into EventMap without the need + // to override UpdateAI + // note: You must re-schedule the event within this method if the event + // is supposed to run more than once + virtual void ExecuteEvent(uint32 /*eventId*/) { } - void Reset() { _Reset(); } - void EnterCombat(Unit* /*who*/) { _EnterCombat(); } - void JustDied(Unit* /*killer*/) { _JustDied(); } + void Reset() { _Reset(); } + void EnterCombat(Unit* /*who*/) { _EnterCombat(); } + void JustDied(Unit* /*killer*/) { _JustDied(); } - protected: - void _Reset(); - void _EnterCombat(); - void _JustDied(); +protected: + void _Reset(); + void _EnterCombat(); + void _JustDied(); - EventMap events; - SummonList summons; + EventMap events; + SummonList summons; }; // SD2 grid searchers. diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp index 552bec907..3459a7368 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp @@ -131,7 +131,7 @@ void npc_escortAI::JustDied(Unit* /*killer*/) void npc_escortAI::JustRespawned() { - RemoveEscortState(STATE_ESCORT_ESCORTING|STATE_ESCORT_RETURNING|STATE_ESCORT_PAUSED); + RemoveEscortState(STATE_ESCORT_ESCORTING | STATE_ESCORT_RETURNING | STATE_ESCORT_PAUSED); if (!IsCombatMovementAllowed()) SetCombatMovement(true); @@ -432,7 +432,7 @@ void npc_escortAI::Start(bool isActiveAttacker /* = true*/, bool run /* = false if (WaypointList.empty()) { sLog->outErrorDb("TSCR: EscortAI (script: %s, creature entry: %u) starts with 0 waypoints (possible missing entry in script_waypoint. Quest: %u).", - me->GetScriptName().c_str(), me->GetEntry(), quest ? quest->GetQuestId() : 0); + me->GetScriptName().c_str(), me->GetEntry(), quest ? quest->GetQuestId() : 0); return; } @@ -556,7 +556,7 @@ void npc_escortAI::GenerateWaypointArray(Movement::PointsArray* points) uint32 startingWaypointId = CurrentWP->id; // Flying unit, just fill array - if (me->m_movementInfo.HasMovementFlag((MovementFlags)(MOVEMENTFLAG_CAN_FLY|MOVEMENTFLAG_DISABLE_GRAVITY))) + if (me->m_movementInfo.HasMovementFlag((MovementFlags)(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_DISABLE_GRAVITY))) { // xinef: first point in vector is unit real position points->clear(); @@ -571,7 +571,7 @@ void npc_escortAI::GenerateWaypointArray(Movement::PointsArray* points) std::vector pVector; // xinef: first point in vector is unit real position pVector.push_back(G3D::Vector3(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ())); - uint32 length = (WaypointList.size() - startingWaypointId)*size; + uint32 length = (WaypointList.size() - startingWaypointId) * size; uint32 cnt = 0; for (std::list::const_iterator itr = CurrentWP; itr != WaypointList.end() && cnt <= length; ++itr, ++cnt) @@ -579,11 +579,11 @@ void npc_escortAI::GenerateWaypointArray(Movement::PointsArray* points) if (pVector.size() > 2) // more than source + dest { - G3D::Vector3 middle = (pVector[0] + pVector[pVector.size()-1]) / 2.f; + G3D::Vector3 middle = (pVector[0] + pVector[pVector.size() - 1]) / 2.f; G3D::Vector3 offset; bool continueLoop = false; - for (uint32 i = 1; i < pVector.size()-1; ++i) + for (uint32 i = 1; i < pVector.size() - 1; ++i) { offset = middle - pVector[i]; if (fabs(offset.x) >= 0xFF || fabs(offset.y) >= 0xFF || fabs(offset.z) >= 0x7F) @@ -599,6 +599,6 @@ void npc_escortAI::GenerateWaypointArray(Movement::PointsArray* points) // everything ok *points = pVector; break; - } + } } } diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h index d2e0c5987..ba30f3203 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h @@ -38,92 +38,92 @@ enum eEscortState struct npc_escortAI : public ScriptedAI { - public: - explicit npc_escortAI(Creature* creature); - ~npc_escortAI() {} +public: + explicit npc_escortAI(Creature* creature); + ~npc_escortAI() {} - // CreatureAI functions - void AttackStart(Unit* who); + // CreatureAI functions + void AttackStart(Unit* who); - void MoveInLineOfSight(Unit* who); + void MoveInLineOfSight(Unit* who); - void JustDied(Unit*); + void JustDied(Unit*); - void JustRespawned(); + void JustRespawned(); - void ReturnToLastPoint(); + void ReturnToLastPoint(); - void EnterEvadeMode(); + void EnterEvadeMode(); - void UpdateAI(uint32 diff); //the "internal" update, calls UpdateEscortAI() - virtual void UpdateEscortAI(uint32 diff); //used when it's needed to add code in update (abilities, scripted events, etc) + void UpdateAI(uint32 diff); //the "internal" update, calls UpdateEscortAI() + virtual void UpdateEscortAI(uint32 diff); //used when it's needed to add code in update (abilities, scripted events, etc) - void MovementInform(uint32, uint32); + void MovementInform(uint32, uint32); - // EscortAI functions - void AddWaypoint(uint32 id, float x, float y, float z, uint32 waitTime = 0); // waitTime is in ms + // EscortAI functions + void AddWaypoint(uint32 id, float x, float y, float z, uint32 waitTime = 0); // waitTime is in ms - //this will set the current position to x/y/z/o, and the current WP to pointId. - bool SetNextWaypoint(uint32 pointId, float x, float y, float z, float orientation); + //this will set the current position to x/y/z/o, and the current WP to pointId. + bool SetNextWaypoint(uint32 pointId, float x, float y, float z, float orientation); - //this will set the current position to WP start position (if setPosition == true), - //and the current WP to pointId - bool SetNextWaypoint(uint32 pointId, bool setPosition = true); + //this will set the current position to WP start position (if setPosition == true), + //and the current WP to pointId + bool SetNextWaypoint(uint32 pointId, bool setPosition = true); - bool GetWaypointPosition(uint32 pointId, float& x, float& y, float& z); + bool GetWaypointPosition(uint32 pointId, float& x, float& y, float& z); - void GenerateWaypointArray(Movement::PointsArray* points); + void GenerateWaypointArray(Movement::PointsArray* points); - virtual void WaypointReached(uint32 pointId) = 0; - virtual void WaypointStart(uint32 /*pointId*/) {} + virtual void WaypointReached(uint32 pointId) = 0; + virtual void WaypointStart(uint32 /*pointId*/) {} - void Start(bool isActiveAttacker = true, bool run = false, uint64 playerGUID = 0, Quest const* quest = NULL, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); + void Start(bool isActiveAttacker = true, bool run = false, uint64 playerGUID = 0, Quest const* quest = NULL, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); - void SetRun(bool on = true); - void SetEscortPaused(bool on); + void SetRun(bool on = true); + void SetEscortPaused(bool on); - bool HasEscortState(uint32 escortState) { return (m_uiEscortState & escortState); } - virtual bool IsEscorted() { return (m_uiEscortState & STATE_ESCORT_ESCORTING); } + bool HasEscortState(uint32 escortState) { return (m_uiEscortState & escortState); } + virtual bool IsEscorted() { return (m_uiEscortState & STATE_ESCORT_ESCORTING); } - void SetMaxPlayerDistance(float newMax) { MaxPlayerDistance = newMax; } - float GetMaxPlayerDistance() { return MaxPlayerDistance; } + void SetMaxPlayerDistance(float newMax) { MaxPlayerDistance = newMax; } + float GetMaxPlayerDistance() { return MaxPlayerDistance; } - void SetDespawnAtEnd(bool despawn) { DespawnAtEnd = despawn; } - void SetDespawnAtFar(bool despawn) { DespawnAtFar = despawn; } - bool GetAttack() { return m_bIsActiveAttacker; }//used in EnterEvadeMode override - void SetCanAttack(bool attack) { m_bIsActiveAttacker = attack; } - uint64 GetEventStarterGUID() { return m_uiPlayerGUID; } + void SetDespawnAtEnd(bool despawn) { DespawnAtEnd = despawn; } + void SetDespawnAtFar(bool despawn) { DespawnAtFar = despawn; } + bool GetAttack() { return m_bIsActiveAttacker; }//used in EnterEvadeMode override + void SetCanAttack(bool attack) { m_bIsActiveAttacker = attack; } + uint64 GetEventStarterGUID() { return m_uiPlayerGUID; } - void AddEscortState(uint32 escortState) { m_uiEscortState |= escortState; } - void RemoveEscortState(uint32 escortState) { m_uiEscortState &= ~escortState; } + void AddEscortState(uint32 escortState) { m_uiEscortState |= escortState; } + void RemoveEscortState(uint32 escortState) { m_uiEscortState &= ~escortState; } - protected: - Player* GetPlayerForEscort() { return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); } +protected: + Player* GetPlayerForEscort() { return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); } - private: - bool AssistPlayerInCombat(Unit* who); - bool IsPlayerOrGroupInRange(); - void FillPointMovementListForCreature(); +private: + bool AssistPlayerInCombat(Unit* who); + bool IsPlayerOrGroupInRange(); + void FillPointMovementListForCreature(); - uint64 m_uiPlayerGUID; - uint32 m_uiWPWaitTimer; - uint32 m_uiPlayerCheckTimer; - uint32 m_uiEscortState; - float MaxPlayerDistance; + uint64 m_uiPlayerGUID; + uint32 m_uiWPWaitTimer; + uint32 m_uiPlayerCheckTimer; + uint32 m_uiEscortState; + float MaxPlayerDistance; - Quest const* m_pQuestForEscort; //generally passed in Start() when regular escort script. + Quest const* m_pQuestForEscort; //generally passed in Start() when regular escort script. - std::list WaypointList; - std::list::iterator CurrentWP; + std::list WaypointList; + std::list::iterator CurrentWP; - bool m_bIsActiveAttacker; //obsolete, determined by faction. - bool m_bIsRunning; //all creatures are walking by default (has flag MOVEMENTFLAG_WALK) - bool m_bCanInstantRespawn; //if creature should respawn instantly after escort over (if not, database respawntime are used) - bool m_bCanReturnToStart; //if creature can walk same path (loop) without despawn. Not for regular escort quests. - bool DespawnAtEnd; - bool DespawnAtFar; - bool ScriptWP; - bool HasImmuneToNPCFlags; + bool m_bIsActiveAttacker; //obsolete, determined by faction. + bool m_bIsRunning; //all creatures are walking by default (has flag MOVEMENTFLAG_WALK) + bool m_bCanInstantRespawn; //if creature should respawn instantly after escort over (if not, database respawntime are used) + bool m_bCanReturnToStart; //if creature can walk same path (loop) without despawn. Not for regular escort quests. + bool DespawnAtEnd; + bool DespawnAtFar; + bool ScriptWP; + bool HasImmuneToNPCFlags; }; #endif diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h index 99987fc6d..d79bb1189 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h @@ -21,48 +21,48 @@ enum eFollowState class FollowerAI : public ScriptedAI { - public: - explicit FollowerAI(Creature* creature); - ~FollowerAI() {} +public: + explicit FollowerAI(Creature* creature); + ~FollowerAI() {} - //virtual void WaypointReached(uint32 uiPointId) = 0; + //virtual void WaypointReached(uint32 uiPointId) = 0; - void MovementInform(uint32 motionType, uint32 pointId); + void MovementInform(uint32 motionType, uint32 pointId); - void AttackStart(Unit*); + void AttackStart(Unit*); - void MoveInLineOfSight(Unit*); + void MoveInLineOfSight(Unit*); - void EnterEvadeMode(); + void EnterEvadeMode(); - void JustDied(Unit*); + void JustDied(Unit*); - void JustRespawned(); + void JustRespawned(); - void UpdateAI(uint32); //the "internal" update, calls UpdateFollowerAI() - virtual void UpdateFollowerAI(uint32); //used when it's needed to add code in update (abilities, scripted events, etc) + void UpdateAI(uint32); //the "internal" update, calls UpdateFollowerAI() + virtual void UpdateFollowerAI(uint32); //used when it's needed to add code in update (abilities, scripted events, etc) - void StartFollow(Player* player, uint32 factionForFollower = 0, const Quest* quest = nullptr); + void StartFollow(Player* player, uint32 factionForFollower = 0, const Quest* quest = nullptr); - void SetFollowPaused(bool bPaused); //if special event require follow mode to hold/resume during the follow - void SetFollowComplete(bool bWithEndEvent = false); + void SetFollowPaused(bool bPaused); //if special event require follow mode to hold/resume during the follow + void SetFollowComplete(bool bWithEndEvent = false); - bool HasFollowState(uint32 uiFollowState) { return (m_uiFollowState & uiFollowState); } + bool HasFollowState(uint32 uiFollowState) { return (m_uiFollowState & uiFollowState); } - protected: - Player* GetLeaderForFollower(); +protected: + Player* GetLeaderForFollower(); - private: - void AddFollowState(uint32 uiFollowState) { m_uiFollowState |= uiFollowState; } - void RemoveFollowState(uint32 uiFollowState) { m_uiFollowState &= ~uiFollowState; } +private: + void AddFollowState(uint32 uiFollowState) { m_uiFollowState |= uiFollowState; } + void RemoveFollowState(uint32 uiFollowState) { m_uiFollowState &= ~uiFollowState; } - bool AssistPlayerInCombat(Unit* who); + bool AssistPlayerInCombat(Unit* who); - uint64 m_uiLeaderGUID; - uint32 m_uiUpdateFollowTimer; - uint32 m_uiFollowState; + uint64 m_uiLeaderGUID; + uint32 m_uiUpdateFollowTimer; + uint32 m_uiFollowState; - const Quest* m_pQuestForFollow; //normally we have a quest + const Quest* m_pQuestForFollow; //normally we have a quest }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index 8e9c12d4f..d5f00cb95 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -112,7 +112,7 @@ void SmartAI::GenerateWayPointArray(Movement::PointsArray* points) return; // Flying unit, just fill array - if (me->m_movementInfo.HasMovementFlag((MovementFlags)(MOVEMENTFLAG_CAN_FLY|MOVEMENTFLAG_DISABLE_GRAVITY))) + if (me->m_movementInfo.HasMovementFlag((MovementFlags)(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_DISABLE_GRAVITY))) { // xinef: first point in vector is unit real position points->clear(); @@ -132,7 +132,7 @@ void SmartAI::GenerateWayPointArray(Movement::PointsArray* points) std::vector pVector; // xinef: first point in vector is unit real position pVector.push_back(G3D::Vector3(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ())); - uint32 length = (mWayPoints->size() - mCurrentWPID)*size; + uint32 length = (mWayPoints->size() - mCurrentWPID) * size; uint32 cnt = 0; uint32 wpCounter = mCurrentWPID; @@ -145,11 +145,11 @@ void SmartAI::GenerateWayPointArray(Movement::PointsArray* points) if (pVector.size() > 2) // more than source + dest { - G3D::Vector3 middle = (pVector[0] + pVector[pVector.size()-1]) / 2.f; + G3D::Vector3 middle = (pVector[0] + pVector[pVector.size() - 1]) / 2.f; G3D::Vector3 offset; bool continueLoop = false; - for (uint32 i = 1; i < pVector.size()-1; ++i) + for (uint32 i = 1; i < pVector.size() - 1; ++i) { offset = middle - pVector[i]; if (fabs(offset.x) >= 0xFF || fabs(offset.y) >= 0xFF || fabs(offset.z) >= 0x7F) @@ -516,7 +516,7 @@ bool SmartAI::IsEscortInvokerInRange() ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); if (targets) { - float checkDist = me->GetInstanceScript() ? SMART_ESCORT_MAX_PLAYER_DIST*2 : SMART_ESCORT_MAX_PLAYER_DIST; + float checkDist = me->GetInstanceScript() ? SMART_ESCORT_MAX_PLAYER_DIST * 2 : SMART_ESCORT_MAX_PLAYER_DIST; if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) { Player* player = (*targets->begin())->ToPlayer(); @@ -616,7 +616,7 @@ void SmartAI::EnterEvadeMode() // xinef: fixes strange jumps when charming SmartAI npc if (!me->IsAlive() || me->IsInEvadeMode()) return; - + if (IS_PLAYER_GUID(me->GetCharmerGUID()) || me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED)) { me->AttackStop(); @@ -653,7 +653,7 @@ void SmartAI::EnterEvadeMode() else { me->GetMotionMaster()->MoveTargetedHome(); - + // xinef: do not forget to reset scripts as we wont call reached home if (!me->HasUnitState(UNIT_STATE_EVADE)) GetScript()->OnReset(); @@ -1027,7 +1027,7 @@ void SmartAI::StopFollow(bool complete) mFollowArrivedTimer = 1000; mFollowArrivedEntry = 0; mFollowCreditType = 0; - + me->GetMotionMaster()->Clear(false); me->StopMoving(); me->GetMotionMaster()->MoveIdle(); @@ -1177,23 +1177,23 @@ void SmartGameObjectAI::SpellHit(Unit* unit, const SpellInfo* spellInfo) class SmartTrigger : public AreaTriggerScript { - public: +public: - SmartTrigger() : AreaTriggerScript("SmartTrigger") {} + SmartTrigger() : AreaTriggerScript("SmartTrigger") {} - bool OnTrigger(Player* player, AreaTrigger const* trigger) - { - if (!player->IsAlive()) - return false; + bool OnTrigger(Player* player, AreaTrigger const* trigger) + { + if (!player->IsAlive()) + return false; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "AreaTrigger %u is using SmartTrigger script", trigger->entry); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "AreaTrigger %u is using SmartTrigger script", trigger->entry); #endif - SmartScript script; - script.OnInitialize(nullptr, trigger); - script.ProcessEventsFor(SMART_EVENT_AREATRIGGER_ONTRIGGER, player, trigger->entry); - return true; - } + SmartScript script; + script.OnInitialize(nullptr, trigger); + script.ProcessEventsFor(SMART_EVENT_AREATRIGGER_ONTRIGGER, player, trigger->entry); + return true; + } }; void AddSC_SmartScripts() diff --git a/src/server/game/AI/SmartScripts/SmartAI.h b/src/server/game/AI/SmartScripts/SmartAI.h index 8eeb2fa24..9163b65b1 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.h +++ b/src/server/game/AI/SmartScripts/SmartAI.h @@ -33,231 +33,231 @@ enum SmartEscortVars class SmartAI : public CreatureAI { - public: - ~SmartAI(){}; - explicit SmartAI(Creature* c); +public: + ~SmartAI() {}; + explicit SmartAI(Creature* c); - // Start moving to the desired MovePoint - void StartPath(bool run = false, uint32 path = 0, bool repeat = false, Unit* invoker = nullptr); - bool LoadPath(uint32 entry); - void PausePath(uint32 delay, bool forced = false); - void StopPath(uint32 DespawnTime = 0, uint32 quest = 0, bool fail = false); - void EndPath(bool fail = false); - void ResumePath(); - WayPoint* GetNextWayPoint(); - void GenerateWayPointArray(Movement::PointsArray* points); - bool HasEscortState(uint32 uiEscortState) { return (mEscortState & uiEscortState); } - void AddEscortState(uint32 uiEscortState) { mEscortState |= uiEscortState; } - virtual bool IsEscorted() { return (mEscortState & SMART_ESCORT_ESCORTING); } - void RemoveEscortState(uint32 uiEscortState) { mEscortState &= ~uiEscortState; } - void SetAutoAttack(bool on) { mCanAutoAttack = on; } - void SetCombatMove(bool on); - bool CanCombatMove() { return mCanCombatMove; } - void SetFollow(Unit* target, float dist = 0.0f, float angle = 0.0f, uint32 credit = 0, uint32 end = 0, uint32 creditType = 0, bool aliveState = true); - void StopFollow(bool complete); + // Start moving to the desired MovePoint + void StartPath(bool run = false, uint32 path = 0, bool repeat = false, Unit* invoker = nullptr); + bool LoadPath(uint32 entry); + void PausePath(uint32 delay, bool forced = false); + void StopPath(uint32 DespawnTime = 0, uint32 quest = 0, bool fail = false); + void EndPath(bool fail = false); + void ResumePath(); + WayPoint* GetNextWayPoint(); + void GenerateWayPointArray(Movement::PointsArray* points); + bool HasEscortState(uint32 uiEscortState) { return (mEscortState & uiEscortState); } + void AddEscortState(uint32 uiEscortState) { mEscortState |= uiEscortState; } + virtual bool IsEscorted() { return (mEscortState & SMART_ESCORT_ESCORTING); } + void RemoveEscortState(uint32 uiEscortState) { mEscortState &= ~uiEscortState; } + void SetAutoAttack(bool on) { mCanAutoAttack = on; } + void SetCombatMove(bool on); + bool CanCombatMove() { return mCanCombatMove; } + void SetFollow(Unit* target, float dist = 0.0f, float angle = 0.0f, uint32 credit = 0, uint32 end = 0, uint32 creditType = 0, bool aliveState = true); + void StopFollow(bool complete); - void SetScript9(SmartScriptHolder& e, uint32 entry, Unit* invoker); - SmartScript* GetScript() { return &mScript; } - bool IsEscortInvokerInRange(); + void SetScript9(SmartScriptHolder& e, uint32 entry, Unit* invoker); + SmartScript* GetScript() { return &mScript; } + bool IsEscortInvokerInRange(); - // Called when creature is spawned or respawned - void JustRespawned(); + // Called when creature is spawned or respawned + void JustRespawned(); - // Called at reaching home after evade, InitializeAI(), EnterEvadeMode() for resetting variables - void JustReachedHome(); + // Called at reaching home after evade, InitializeAI(), EnterEvadeMode() for resetting variables + void JustReachedHome(); - // Called for reaction at enter to combat if not in combat yet (enemy can be nullptr) - void EnterCombat(Unit* enemy); + // Called for reaction at enter to combat if not in combat yet (enemy can be nullptr) + void EnterCombat(Unit* enemy); - // Called for reaction at stopping attack at no attackers or targets - void EnterEvadeMode(); + // Called for reaction at stopping attack at no attackers or targets + void EnterEvadeMode(); - // Called when the creature is killed - void JustDied(Unit* killer); + // Called when the creature is killed + void JustDied(Unit* killer); - // Called when the creature kills a unit - void KilledUnit(Unit* victim); + // Called when the creature kills a unit + void KilledUnit(Unit* victim); - // Called when the creature summon successfully other creature - void JustSummoned(Creature* creature); + // Called when the creature summon successfully other creature + void JustSummoned(Creature* creature); - // Tell creature to attack and follow the victim - void AttackStart(Unit* who); + // Tell creature to attack and follow the victim + void AttackStart(Unit* who); - // Called if IsVisible(Unit* who) is true at each *who move, reaction at visibility zone enter - void MoveInLineOfSight(Unit* who); + // Called if IsVisible(Unit* who) is true at each *who move, reaction at visibility zone enter + void MoveInLineOfSight(Unit* who); - // Called when hit by a spell - void SpellHit(Unit* unit, const SpellInfo* spellInfo); + // Called when hit by a spell + void SpellHit(Unit* unit, const SpellInfo* spellInfo); - // Called when spell hits a target - void SpellHitTarget(Unit* target, const SpellInfo* spellInfo); + // Called when spell hits a target + void SpellHitTarget(Unit* target, const SpellInfo* spellInfo); - // Called at any Damage from any attacker (before damage apply) - void DamageTaken(Unit* done_by, uint32 &damage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask); + // Called at any Damage from any attacker (before damage apply) + void DamageTaken(Unit* done_by, uint32& damage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask); - // Called when the creature receives heal - void HealReceived(Unit* doneBy, uint32& addhealth); + // Called when the creature receives heal + void HealReceived(Unit* doneBy, uint32& addhealth); - // Called at World update tick - void UpdateAI(uint32 diff); + // Called at World update tick + void UpdateAI(uint32 diff); - // Called at text emote receive from player - void ReceiveEmote(Player* player, uint32 textEmote); + // Called at text emote receive from player + void ReceiveEmote(Player* player, uint32 textEmote); - // Called at waypoint reached or point movement finished - void MovementInform(uint32 MovementType, uint32 Data); + // Called at waypoint reached or point movement finished + void MovementInform(uint32 MovementType, uint32 Data); - // Called when creature is summoned by another unit - void IsSummonedBy(Unit* summoner); + // Called when creature is summoned by another unit + void IsSummonedBy(Unit* summoner); - // Called at any Damage to any victim (before damage apply) - void DamageDealt(Unit* doneTo, uint32& damage, DamageEffectType damagetyp); + // Called at any Damage to any victim (before damage apply) + void DamageDealt(Unit* doneTo, uint32& damage, DamageEffectType damagetyp); - // Called when a summoned creature dissapears (UnSommoned) - void SummonedCreatureDespawn(Creature* unit); + // Called when a summoned creature dissapears (UnSommoned) + void SummonedCreatureDespawn(Creature* unit); - // called when the corpse of this creature gets removed - void CorpseRemoved(uint32& respawnDelay); + // called when the corpse of this creature gets removed + void CorpseRemoved(uint32& respawnDelay); - // Called at World update tick if creature is charmed - void UpdateAIWhileCharmed(const uint32 diff); + // Called at World update tick if creature is charmed + void UpdateAIWhileCharmed(const uint32 diff); - // Called when a Player/Creature enters the creature (vehicle) - void PassengerBoarded(Unit* who, int8 seatId, bool apply); + // Called when a Player/Creature enters the creature (vehicle) + void PassengerBoarded(Unit* who, int8 seatId, bool apply); - // Called when gets initialized, when creature is added to world - void InitializeAI(); + // Called when gets initialized, when creature is added to world + void InitializeAI(); - // Called when creature gets charmed by another unit - void OnCharmed(bool apply); + // Called when creature gets charmed by another unit + void OnCharmed(bool apply); - // Called when victim is in line of sight - bool CanAIAttack(const Unit* who) const; + // Called when victim is in line of sight + bool CanAIAttack(const Unit* who) const; - // Used in scripts to share variables - void DoAction(int32 param = 0); + // Used in scripts to share variables + void DoAction(int32 param = 0); - // Used in scripts to share variables - uint32 GetData(uint32 id = 0) const; + // Used in scripts to share variables + uint32 GetData(uint32 id = 0) const; - // Used in scripts to share variables - void SetData(uint32 id, uint32 value); + // Used in scripts to share variables + void SetData(uint32 id, uint32 value); - // Used in scripts to share variables - void SetGUID(uint64 guid, int32 id = 0); + // Used in scripts to share variables + void SetGUID(uint64 guid, int32 id = 0); - // Used in scripts to share variables - uint64 GetGUID(int32 id = 0) const; + // Used in scripts to share variables + uint64 GetGUID(int32 id = 0) const; - //core related - static int32 Permissible(const Creature*); + //core related + static int32 Permissible(const Creature*); - // Called at movepoint reached - void MovepointReached(uint32 id); + // Called at movepoint reached + void MovepointReached(uint32 id); - // Makes the creature run/walk - void SetRun(bool run = true); + // Makes the creature run/walk + void SetRun(bool run = true); - void SetFly(bool fly = true); + void SetFly(bool fly = true); - void SetSwim(bool swim = true); + void SetSwim(bool swim = true); - void SetInvincibilityHpLevel(uint32 level) { mInvincibilityHpLevel = level; } + void SetInvincibilityHpLevel(uint32 level) { mInvincibilityHpLevel = level; } - void sGossipHello(Player* player); - void sGossipSelect(Player* player, uint32 sender, uint32 action); - void sGossipSelectCode(Player* player, uint32 sender, uint32 action, const char* code); - void sQuestAccept(Player* player, Quest const* quest); - //void sQuestSelect(Player* player, Quest const* quest); - //void sQuestComplete(Player* player, Quest const* quest); - void sQuestReward(Player* player, Quest const* quest, uint32 opt); - void sOnGameEvent(bool start, uint16 eventId); + void sGossipHello(Player* player); + void sGossipSelect(Player* player, uint32 sender, uint32 action); + void sGossipSelectCode(Player* player, uint32 sender, uint32 action, const char* code); + void sQuestAccept(Player* player, Quest const* quest); + //void sQuestSelect(Player* player, Quest const* quest); + //void sQuestComplete(Player* player, Quest const* quest); + void sQuestReward(Player* player, Quest const* quest, uint32 opt); + void sOnGameEvent(bool start, uint16 eventId); - uint32 mEscortQuestID; + uint32 mEscortQuestID; - void SetDespawnTime (uint32 t) - { - mDespawnTime = t; - mDespawnState = t ? 1 : 0; - } - void StartDespawn() { mDespawnState = 2; } + void SetDespawnTime (uint32 t) + { + mDespawnTime = t; + mDespawnState = t ? 1 : 0; + } + void StartDespawn() { mDespawnState = 2; } - void OnSpellClick(Unit* clicker, bool& result); + void OnSpellClick(Unit* clicker, bool& result); - // Xinef - void SetWPPauseTimer(uint32 time) { mWPPauseTimer = time; } - void SetForcedCombatMove(float dist); + // Xinef + void SetWPPauseTimer(uint32 time) { mWPPauseTimer = time; } + void SetForcedCombatMove(float dist); - private: - uint32 mFollowCreditType; - uint32 mFollowArrivedTimer; - uint32 mFollowCredit; - uint32 mFollowArrivedEntry; - bool mFollowArrivedAlive; - uint64 mFollowGuid; - float mFollowDist; - float mFollowAngle; +private: + uint32 mFollowCreditType; + uint32 mFollowArrivedTimer; + uint32 mFollowCredit; + uint32 mFollowArrivedEntry; + bool mFollowArrivedAlive; + uint64 mFollowGuid; + float mFollowDist; + float mFollowAngle; - void ReturnToLastOOCPos(); - void UpdatePath(const uint32 diff); - SmartScript mScript; - WPPath* mWayPoints; - uint32 mEscortState; - uint32 mCurrentWPID; - bool mWPReached; - bool mOOCReached; - uint32 mWPPauseTimer; - WayPoint* mLastWP; - uint32 mEscortNPCFlags; - uint32 GetWPCount() { return mWayPoints ? mWayPoints->size() : 0; } - bool mCanRepeatPath; - bool mRun; - bool mCanAutoAttack; - bool mCanCombatMove; - bool mForcedPaused; - uint32 mInvincibilityHpLevel; + void ReturnToLastOOCPos(); + void UpdatePath(const uint32 diff); + SmartScript mScript; + WPPath* mWayPoints; + uint32 mEscortState; + uint32 mCurrentWPID; + bool mWPReached; + bool mOOCReached; + uint32 mWPPauseTimer; + WayPoint* mLastWP; + uint32 mEscortNPCFlags; + uint32 GetWPCount() { return mWayPoints ? mWayPoints->size() : 0; } + bool mCanRepeatPath; + bool mRun; + bool mCanAutoAttack; + bool mCanCombatMove; + bool mForcedPaused; + uint32 mInvincibilityHpLevel; - bool AssistPlayerInCombat(Unit* who); + bool AssistPlayerInCombat(Unit* who); - uint32 mDespawnTime; - uint32 mDespawnState; - void UpdateDespawn(const uint32 diff); - uint32 mEscortInvokerCheckTimer; - bool mJustReset; + uint32 mDespawnTime; + uint32 mDespawnState; + void UpdateDespawn(const uint32 diff); + uint32 mEscortInvokerCheckTimer; + bool mJustReset; - // Xinef: Vehicle conditions - void CheckConditions(const uint32 diff); - ConditionList conditions; - uint32 m_ConditionsTimer; + // Xinef: Vehicle conditions + void CheckConditions(const uint32 diff); + ConditionList conditions; + uint32 m_ConditionsTimer; }; class SmartGameObjectAI : public GameObjectAI { - public: - SmartGameObjectAI(GameObject* g) : GameObjectAI(g) {} - ~SmartGameObjectAI() {} +public: + SmartGameObjectAI(GameObject* g) : GameObjectAI(g) {} + ~SmartGameObjectAI() {} - void UpdateAI(uint32 diff); - void InitializeAI(); - void Reset(); - SmartScript* GetScript() { return &mScript; } - static int32 Permissible(const GameObject* g); + void UpdateAI(uint32 diff); + void InitializeAI(); + void Reset(); + SmartScript* GetScript() { return &mScript; } + static int32 Permissible(const GameObject* g); - bool GossipHello(Player* player, bool reportUse); - bool GossipSelect(Player* player, uint32 sender, uint32 action); - bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/); - bool QuestAccept(Player* player, Quest const* quest); - bool QuestReward(Player* player, Quest const* quest, uint32 opt); - void Destroyed(Player* player, uint32 eventId); - void SetData(uint32 id, uint32 value); - void SetScript9(SmartScriptHolder& e, uint32 entry, Unit* invoker); - void OnGameEvent(bool start, uint16 eventId); - void OnStateChanged(uint32 state, Unit* unit); - void EventInform(uint32 eventId); - void SpellHit(Unit* unit, const SpellInfo* spellInfo); + bool GossipHello(Player* player, bool reportUse); + bool GossipSelect(Player* player, uint32 sender, uint32 action); + bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/); + bool QuestAccept(Player* player, Quest const* quest); + bool QuestReward(Player* player, Quest const* quest, uint32 opt); + void Destroyed(Player* player, uint32 eventId); + void SetData(uint32 id, uint32 value); + void SetScript9(SmartScriptHolder& e, uint32 entry, Unit* invoker); + void OnGameEvent(bool start, uint16 eventId); + void OnStateChanged(uint32 state, Unit* unit); + void EventInform(uint32 eventId); + void SpellHit(Unit* unit, const SpellInfo* spellInfo); - protected: - SmartScript mScript; +protected: + SmartScript mScript; }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index 5d92b2d0a..753e34f9f 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -153,3143 +153,3143 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u switch (e.GetActionType()) { - case SMART_ACTION_TALK: - { - ObjectList* targets = GetTargets(e, unit); - Creature* talker = e.target.type == 0 ? me : nullptr; // xinef: tc retardness fix - Unit* talkTarget = nullptr; - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_TALK: { - if (IsCreature((*itr)) && !(*itr)->ToCreature()->IsPet()) // Prevented sending text to pets. + ObjectList* targets = GetTargets(e, unit); + Creature* talker = e.target.type == 0 ? me : nullptr; // xinef: tc retardness fix + Unit* talkTarget = nullptr; + if (targets) { - if (e.action.talk.useTalkTarget) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { - talker = me; - talkTarget = (*itr)->ToCreature(); + if (IsCreature((*itr)) && !(*itr)->ToCreature()->IsPet()) // Prevented sending text to pets. + { + if (e.action.talk.useTalkTarget) + { + talker = me; + talkTarget = (*itr)->ToCreature(); + } + else + talker = (*itr)->ToCreature(); + break; + } + else if (IsPlayer((*itr))) + { + talker = me; // xinef: added + talkTarget = (*itr)->ToPlayer(); + break; + } } - else - talker = (*itr)->ToCreature(); + + delete targets; + } + + if (!talkTarget) + talkTarget = GetLastInvoker(); + + if (!talker) + break; + + if (!sCreatureTextMgr->TextExist(talker->GetEntry(), uint8(e.action.talk.textGroupID))) + { + sLog->outErrorDb("SmartScript::ProcessAction: SMART_ACTION_TALK: EntryOrGuid %d SourceType %u EventType %u TargetType %u using non-existent Text id %u for talker %u, ignored.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetTargetType(), e.action.talk.textGroupID, talker->GetEntry()); break; } - else if (IsPlayer((*itr))) - { - talker = me; // xinef: added - talkTarget = (*itr)->ToPlayer(); - break; - } - } - delete targets; - } - - if (!talkTarget) - talkTarget = GetLastInvoker(); - - if (!talker) - break; - - if (!sCreatureTextMgr->TextExist(talker->GetEntry(), uint8(e.action.talk.textGroupID))) - { - sLog->outErrorDb("SmartScript::ProcessAction: SMART_ACTION_TALK: EntryOrGuid %d SourceType %u EventType %u TargetType %u using non-existent Text id %u for talker %u, ignored.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetTargetType(), e.action.talk.textGroupID,talker->GetEntry()); - break; - } - - mTalkerEntry = talker->GetEntry(); - mLastTextID = e.action.talk.textGroupID; - mTextTimer = e.action.talk.duration; - mUseTextTimer = true; - sCreatureTextMgr->SendChat(talker, uint8(e.action.talk.textGroupID), talkTarget); + mTalkerEntry = talker->GetEntry(); + mLastTextID = e.action.talk.textGroupID; + mTextTimer = e.action.talk.duration; + mUseTextTimer = true; + sCreatureTextMgr->SendChat(talker, uint8(e.action.talk.textGroupID), talkTarget); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_TALK: talker: %s (GuidLow: %u), textId: %u", talker->GetName().c_str(), talker->GetGUIDLow(), mLastTextID); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_TALK: talker: %s (GuidLow: %u), textId: %u", talker->GetName().c_str(), talker->GetGUIDLow(), mLastTextID); #endif - break; - } - case SMART_ACTION_SIMPLE_TALK: - { - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + break; + } + case SMART_ACTION_SIMPLE_TALK: { - if (IsCreature(*itr)) - sCreatureTextMgr->SendChat((*itr)->ToCreature(), uint8(e.action.talk.textGroupID), IsPlayer(GetLastInvoker()) ? GetLastInvoker() : 0); - else if (IsPlayer(*itr) && me) + ObjectList* targets = GetTargets(e, unit); + if (targets) { - Unit* templastInvoker = GetLastInvoker(); - sCreatureTextMgr->SendChat(me, uint8(e.action.talk.textGroupID), IsPlayer(templastInvoker) ? templastInvoker : 0, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_NEUTRAL, false, (*itr)->ToPlayer()); - } -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SIMPLE_TALK: talker: %s (GuidLow: %u), textGroupId: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), uint8(e.action.talk.textGroupID)); -#endif - } - - delete targets; - } - break; - } - case SMART_ACTION_PLAY_EMOTE: - { - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - (*itr)->ToUnit()->HandleEmoteCommand(e.action.emote.emote); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_PLAY_EMOTE: target: %s (GuidLow: %u), emote: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), e.action.emote.emote); -#endif - } - } - - delete targets; - } - break; - } - case SMART_ACTION_SOUND: - { - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - (*itr)->SendPlaySound(e.action.sound.sound, e.action.sound.onlySelf > 0); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SOUND: target: %s (GuidLow: %u), sound: %u, onlyself: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), e.action.sound.sound, e.action.sound.onlySelf); -#endif - } - } - - delete targets; - } - break; - } - case SMART_ACTION_RANDOM_SOUND: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - uint32 sounds[4]; - sounds[0] = e.action.randomSound.sound1; - sounds[1] = e.action.randomSound.sound2; - sounds[2] = e.action.randomSound.sound3; - sounds[3] = e.action.randomSound.sound4; - uint32 temp[4]; - uint32 count = 0; - for (uint8 i = 0; i < 4; i++) - { - if (sounds[i]) - { - temp[count] = sounds[i]; - ++count; - } - } - - if (count == 0) - { - delete targets; - break; - } - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - uint32 sound = temp[urand(0, count - 1)]; - (*itr)->SendPlaySound(sound, e.action.randomSound.onlySelf > 0); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_SOUND: target: %s (GuidLow: %u), sound: %u, onlyself: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), sound, e.action.randomSound.onlySelf); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_MUSIC: - { - ObjectList* targets = nullptr; - - if (e.action.music.type > 0) - { - if (me && me->FindMap()) - { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); - targets = new ObjectList(); - - if (!players.isEmpty()) - { - for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) - if (Player* player = i->GetSource()) - { - if (player->GetZoneId() == me->GetZoneId()) - { - if (e.action.music.type > 1) - { - if (player->GetAreaId() == me->GetAreaId()) - targets->push_back(player); - } - else - targets->push_back(player); - } - } - } - } - } - else - targets = GetTargets(e, unit); - - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - (*itr)->SendPlayMusic(e.action.music.sound, e.action.music.onlySelf > 0); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MUSIC: target: %s (GuidLow: %u), sound: %u, onlySelf: %u, type: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), e.action.music.sound, e.action.music.onlySelf, e.action.music.type); -#endif - } - } - - delete targets; - } - break; - } - case SMART_ACTION_RANDOM_MUSIC: - { - ObjectList* targets = nullptr; - - if (e.action.randomMusic.type > 0) - { - if (me && me->FindMap()) - { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); - targets = new ObjectList(); - - if (!players.isEmpty()) - { - for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) - if (Player* player = i->GetSource()) - { - if (player->GetZoneId() == me->GetZoneId()) - { - if (e.action.randomMusic.type > 1) - { - if (player->GetAreaId() == me->GetAreaId()) - targets->push_back(player); - } - else - targets->push_back(player); - } - } - } - } - } - else - targets = GetTargets(e, unit); - - if (!targets) - break; - - uint32 sounds[4]; - sounds[0] = e.action.randomMusic.sound1; - sounds[1] = e.action.randomMusic.sound2; - sounds[2] = e.action.randomMusic.sound3; - sounds[3] = e.action.randomMusic.sound4; - uint32 temp[4]; - uint32 count = 0; - for (uint8 i = 0; i < 4; i++) - { - if (sounds[i]) - { - temp[count] = sounds[i]; - ++count; - } - } - - if (count == 0) - { - delete targets; - break; - } - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - uint32 sound = temp[urand(0, count - 1)]; - (*itr)->SendPlayMusic(sound, e.action.randomMusic.onlySelf > 0); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_MUSIC: target: %s (GuidLow: %u), sound: %u, onlyself: %u, type: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), sound, e.action.randomMusic.onlySelf, e.action.randomMusic.type); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_SET_FACTION: - { - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - { - if (e.action.faction.factionID) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { - (*itr)->ToCreature()->setFaction(e.action.faction.factionID); + if (IsCreature(*itr)) + sCreatureTextMgr->SendChat((*itr)->ToCreature(), uint8(e.action.talk.textGroupID), IsPlayer(GetLastInvoker()) ? GetLastInvoker() : 0); + else if (IsPlayer(*itr) && me) + { + Unit* templastInvoker = GetLastInvoker(); + sCreatureTextMgr->SendChat(me, uint8(e.action.talk.textGroupID), IsPlayer(templastInvoker) ? templastInvoker : 0, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_NEUTRAL, false, (*itr)->ToPlayer()); + } #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", - (*itr)->GetEntry(), (*itr)->GetGUIDLow(), e.action.faction.factionID); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SIMPLE_TALK: talker: %s (GuidLow: %u), textGroupId: %u", + (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), uint8(e.action.talk.textGroupID)); #endif } - else + + delete targets; + } + break; + } + case SMART_ACTION_PLAY_EMOTE: + { + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { - if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate((*itr)->ToCreature()->GetEntry())) + if (IsUnit(*itr)) { - if ((*itr)->ToCreature()->getFaction() != ci->faction) + (*itr)->ToUnit()->HandleEmoteCommand(e.action.emote.emote); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_PLAY_EMOTE: target: %s (GuidLow: %u), emote: %u", + (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), e.action.emote.emote); +#endif + } + } + + delete targets; + } + break; + } + case SMART_ACTION_SOUND: + { + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + (*itr)->SendPlaySound(e.action.sound.sound, e.action.sound.onlySelf > 0); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SOUND: target: %s (GuidLow: %u), sound: %u, onlyself: %u", + (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), e.action.sound.sound, e.action.sound.onlySelf); +#endif + } + } + + delete targets; + } + break; + } + case SMART_ACTION_RANDOM_SOUND: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + uint32 sounds[4]; + sounds[0] = e.action.randomSound.sound1; + sounds[1] = e.action.randomSound.sound2; + sounds[2] = e.action.randomSound.sound3; + sounds[3] = e.action.randomSound.sound4; + uint32 temp[4]; + uint32 count = 0; + for (uint8 i = 0; i < 4; i++) + { + if (sounds[i]) + { + temp[count] = sounds[i]; + ++count; + } + } + + if (count == 0) + { + delete targets; + break; + } + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + uint32 sound = temp[urand(0, count - 1)]; + (*itr)->SendPlaySound(sound, e.action.randomSound.onlySelf > 0); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_SOUND: target: %s (GuidLow: %u), sound: %u, onlyself: %u", + (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), sound, e.action.randomSound.onlySelf); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_MUSIC: + { + ObjectList* targets = nullptr; + + if (e.action.music.type > 0) + { + if (me && me->FindMap()) + { + Map::PlayerList const& players = me->GetMap()->GetPlayers(); + targets = new ObjectList(); + + if (!players.isEmpty()) + { + for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) + if (Player* player = i->GetSource()) + { + if (player->GetZoneId() == me->GetZoneId()) + { + if (e.action.music.type > 1) + { + if (player->GetAreaId() == me->GetAreaId()) + targets->push_back(player); + } + else + targets->push_back(player); + } + } + } + } + } + else + targets = GetTargets(e, unit); + + if (targets) + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + (*itr)->SendPlayMusic(e.action.music.sound, e.action.music.onlySelf > 0); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MUSIC: target: %s (GuidLow: %u), sound: %u, onlySelf: %u, type: %u", + (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), e.action.music.sound, e.action.music.onlySelf, e.action.music.type); +#endif + } + } + + delete targets; + } + break; + } + case SMART_ACTION_RANDOM_MUSIC: + { + ObjectList* targets = nullptr; + + if (e.action.randomMusic.type > 0) + { + if (me && me->FindMap()) + { + Map::PlayerList const& players = me->GetMap()->GetPlayers(); + targets = new ObjectList(); + + if (!players.isEmpty()) + { + for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) + if (Player* player = i->GetSource()) + { + if (player->GetZoneId() == me->GetZoneId()) + { + if (e.action.randomMusic.type > 1) + { + if (player->GetAreaId() == me->GetAreaId()) + targets->push_back(player); + } + else + targets->push_back(player); + } + } + } + } + } + else + targets = GetTargets(e, unit); + + if (!targets) + break; + + uint32 sounds[4]; + sounds[0] = e.action.randomMusic.sound1; + sounds[1] = e.action.randomMusic.sound2; + sounds[2] = e.action.randomMusic.sound3; + sounds[3] = e.action.randomMusic.sound4; + uint32 temp[4]; + uint32 count = 0; + for (uint8 i = 0; i < 4; i++) + { + if (sounds[i]) + { + temp[count] = sounds[i]; + ++count; + } + } + + if (count == 0) + { + delete targets; + break; + } + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + uint32 sound = temp[urand(0, count - 1)]; + (*itr)->SendPlayMusic(sound, e.action.randomMusic.onlySelf > 0); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_MUSIC: target: %s (GuidLow: %u), sound: %u, onlyself: %u, type: %u", + (*itr)->GetName().c_str(), (*itr)->GetGUIDLow(), sound, e.action.randomMusic.onlySelf, e.action.randomMusic.type); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_SET_FACTION: + { + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + if (e.action.faction.factionID) { - (*itr)->ToCreature()->setFaction(ci->faction); + (*itr)->ToCreature()->setFaction(e.action.faction.factionID); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", - (*itr)->GetEntry(), (*itr)->GetGUIDLow(), ci->faction); + (*itr)->GetEntry(), (*itr)->GetGUIDLow(), e.action.faction.factionID); +#endif + } + else + { + if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate((*itr)->ToCreature()->GetEntry())) + { + if ((*itr)->ToCreature()->getFaction() != ci->faction) + { + (*itr)->ToCreature()->setFaction(ci->faction); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", + (*itr)->GetEntry(), (*itr)->GetGUIDLow(), ci->faction); +#endif + } + } + } + } + } + + delete targets; + } + break; + } + case SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsCreature(*itr)) + continue; + + if (e.action.morphOrMount.creature || e.action.morphOrMount.model) + { + //set model based on entry from creature_template + if (e.action.morphOrMount.creature) + { + if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) + { + uint32 displayId = ObjectMgr::ChooseDisplayId(ci); + (*itr)->ToCreature()->SetDisplayId(displayId); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u set displayid to %u", + (*itr)->GetEntry(), (*itr)->GetGUIDLow(), displayId); +#endif + } + } + //if no param1, then use value from param2 (modelId) + else + { + (*itr)->ToCreature()->SetDisplayId(e.action.morphOrMount.model); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u set displayid to %u", + (*itr)->GetEntry(), (*itr)->GetGUIDLow(), e.action.morphOrMount.model); +#endif + } + } + else + { + (*itr)->ToCreature()->DeMorph(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u demorphs.", + (*itr)->GetEntry(), (*itr)->GetGUIDLow()); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_FAIL_QUEST: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsPlayer(*itr)) + { + (*itr)->ToPlayer()->FailQuest(e.action.quest.quest); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_FAIL_QUEST: Player guidLow %u fails quest %u", + (*itr)->GetGUIDLow(), e.action.quest.quest); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_OFFER_QUEST: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Player* pTarget = (*itr)->ToPlayer()) + { + if (Quest const* q = sObjectMgr->GetQuestTemplate(e.action.questOffer.questID)) + { + if (me && e.action.questOffer.directAdd == 0) + { + if (pTarget->CanTakeQuest(q, true)) + if (WorldSession* session = pTarget->GetSession()) + { + PlayerMenu menu(session); + menu.SendQuestGiverQuestDetails(q, me->GetGUID(), true); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug( + LOG_FILTER_DATABASE_AI, + "SmartScript::ProcessAction:: SMART_ACTION_OFFER_QUEST: Player guidLow %u - offering quest %u", + (*itr)->GetGUIDLow(), + e.action.questOffer.questID); +#endif + } + } + else + { + (*itr)->ToPlayer()->AddQuestAndCheckCompletion(q, nullptr); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug( + LOG_FILTER_DATABASE_AI, + "SmartScript::ProcessAction:: SMART_ACTION_OFFER_QUEST: Player guidLow %u - quest %u added", + (*itr)->GetGUIDLow(), + e.action.questOffer.questID); #endif } } } } + + delete targets; + break; } - - delete targets; - } - break; - } - case SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsCreature(*itr)) - continue; - - if (e.action.morphOrMount.creature || e.action.morphOrMount.model) + case SMART_ACTION_SET_REACT_STATE: { - //set model based on entry from creature_template - if (e.action.morphOrMount.creature) + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { - if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) + if (!IsCreature(*itr)) + continue; + + (*itr)->ToCreature()->SetReactState(ReactStates(e.action.react.state)); + } + + delete targets; + break; + } + case SMART_ACTION_RANDOM_EMOTE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + uint32 emotes[SMART_ACTION_PARAM_COUNT]; + emotes[0] = e.action.randomEmote.emote1; + emotes[1] = e.action.randomEmote.emote2; + emotes[2] = e.action.randomEmote.emote3; + emotes[3] = e.action.randomEmote.emote4; + emotes[4] = e.action.randomEmote.emote5; + emotes[5] = e.action.randomEmote.emote6; + uint32 temp[SMART_ACTION_PARAM_COUNT]; + uint32 count = 0; + for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) + { + if (emotes[i]) { - uint32 displayId = ObjectMgr::ChooseDisplayId(ci); - (*itr)->ToCreature()->SetDisplayId(displayId); + temp[count] = emotes[i]; + ++count; + } + } + + if (count == 0) + { + delete targets; + break; + } + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + uint32 emote = temp[urand(0, count - 1)]; + (*itr)->ToUnit()->HandleEmoteCommand(emote); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u set displayid to %u", - (*itr)->GetEntry(), (*itr)->GetGUIDLow(), displayId); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_EMOTE: Creature guidLow %u handle random emote %u", + (*itr)->GetGUIDLow(), emote); #endif } } - //if no param1, then use value from param2 (modelId) - else + + delete targets; + break; + } + case SMART_ACTION_THREAT_ALL_PCT: + { + if (!me) + break; + + ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); + for (ThreatContainer::StorageType::const_iterator i = threatList.begin(); i != threatList.end(); ++i) { - (*itr)->ToCreature()->SetDisplayId(e.action.morphOrMount.model); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u set displayid to %u", - (*itr)->GetEntry(), (*itr)->GetGUIDLow(), e.action.morphOrMount.model); -#endif - } - } - else - { - (*itr)->ToCreature()->DeMorph(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u demorphs.", - (*itr)->GetEntry(), (*itr)->GetGUIDLow()); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_FAIL_QUEST: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsPlayer(*itr)) - { - (*itr)->ToPlayer()->FailQuest(e.action.quest.quest); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_FAIL_QUEST: Player guidLow %u fails quest %u", - (*itr)->GetGUIDLow(), e.action.quest.quest); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_OFFER_QUEST: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (Player* pTarget = (*itr)->ToPlayer()) - { - if (Quest const* q = sObjectMgr->GetQuestTemplate(e.action.questOffer.questID)) - { - if (me && e.action.questOffer.directAdd == 0) + if (Unit* target = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) { - if (pTarget->CanTakeQuest(q, true)) - if (WorldSession* session = pTarget->GetSession()) - { - PlayerMenu menu(session); - menu.SendQuestGiverQuestDetails(q, me->GetGUID(), true); + me->getThreatManager().modifyThreatPercent(target, e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug( - LOG_FILTER_DATABASE_AI, - "SmartScript::ProcessAction:: SMART_ACTION_OFFER_QUEST: Player guidLow %u - offering quest %u", - (*itr)->GetGUIDLow(), - e.action.questOffer.questID); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_THREAT_ALL_PCT: Creature guidLow %u modify threat for unit %u, value %i", + me->GetGUIDLow(), target->GetGUIDLow(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); #endif + } + } + break; + } + case SMART_ACTION_THREAT_SINGLE_PCT: + { + if (!me) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + me->getThreatManager().modifyThreatPercent((*itr)->ToUnit(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_THREAT_SINGLE_PCT: Creature guidLow %u modify threat for unit %u, value %i", + me->GetGUIDLow(), (*itr)->GetGUIDLow(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + // Special handling for vehicles + if (IsUnit(*itr)) + { + if (Vehicle* vehicle = (*itr)->ToUnit()->GetVehicleKit()) + for (SeatMap::iterator it = vehicle->Seats.begin(); it != vehicle->Seats.end(); ++it) + if (Player* player = ObjectAccessor::GetPlayer(*(*itr), it->second.Passenger.Guid)) + player->AreaExploredOrEventHappens(e.action.quest.quest); + + if (Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself()) + { + player->GroupEventHappens(e.action.quest.quest, me); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: Player guidLow %u credited quest %u", + (*itr)->GetGUIDLow(), e.action.quest.quest); +#endif + } + } + } + + delete targets; + break; + } + case SMART_ACTION_CAST: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + Unit* caster = me; + // Areatrigger Cast! + if (e.GetScriptType() == SMART_SCRIPT_TYPE_AREATRIGGER) + caster = unit->SummonTrigger(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetOrientation(), 5000); + + if (e.action.cast.targetsLimit > 0 && targets->size() > e.action.cast.targetsLimit) + acore::Containers::RandomResizeList(*targets, e.action.cast.targetsLimit); + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (go) + { + // Xinef: may be NULL! + go->CastSpell((*itr)->ToUnit(), e.action.cast.spell); + } + + if (!IsUnit(*itr)) + continue; + + if (caster && caster != me) // Areatrigger cast + { + caster->CastSpell((*itr)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); + } + else if (me && (!(e.action.cast.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.cast.spell))) + { + if (e.action.cast.flags & SMARTCAST_INTERRUPT_PREVIOUS) + me->InterruptNonMeleeSpells(false); + + // Xinef: flag usable only if caster has max dist set + if ((e.action.cast.flags & SMARTCAST_COMBAT_MOVE) && GetCasterMaxDist() > 0.0f && me->GetMaxPower(GetCasterPowerType()) > 0) + { + // Xinef: check mana case only and operate movement accordingly, LoS and range is checked in targetet movement generator + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(e.action.cast.spell); + int32 currentPower = me->GetPower(GetCasterPowerType()); + + if ((spellInfo && (currentPower < spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask()))) || me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED)) + { + SetCasterActualDist(0); + CAST_AI(SmartAI, me->AI())->SetForcedCombatMove(0); } + else if (GetCasterActualDist() == 0.0f && me->GetPowerPct(GetCasterPowerType()) > 30.0f) + { + RestoreCasterMaxDist(); + CAST_AI(SmartAI, me->AI())->SetForcedCombatMove(GetCasterActualDist()); + } + } + + me->CastSpell((*itr)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); + } + } + + delete targets; + break; + } + case SMART_ACTION_INVOKER_CAST: + { + Unit* tempLastInvoker = GetLastInvoker(unit); // xinef: can be used for area triggers cast + if (!tempLastInvoker) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + if (e.action.cast.targetsLimit > 0 && targets->size() > e.action.cast.targetsLimit) + acore::Containers::RandomResizeList(*targets, e.action.cast.targetsLimit); + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsUnit(*itr)) + continue; + + if (!(e.action.cast.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.cast.spell)) + { + if (e.action.cast.flags & SMARTCAST_INTERRUPT_PREVIOUS) + tempLastInvoker->InterruptNonMeleeSpells(false); + + tempLastInvoker->CastSpell((*itr)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); + } + } + + delete targets; + break; + } + case SMART_ACTION_ADD_AURA: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + (*itr)->ToUnit()->AddAura(e.action.cast.spell, (*itr)->ToUnit()); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_ADD_AURA: Adding aura %u to unit %u", + e.action.cast.spell, (*itr)->GetGUIDLow()); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_ACTIVATE_GOBJECT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsGameObject(*itr)) + { + // Activate + // xinef: wtf is this shit? + (*itr)->ToGameObject()->SetLootState(GO_READY); + (*itr)->ToGameObject()->UseDoorOrButton(0, !!e.action.activateObject.alternative, unit); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_ACTIVATE_GOBJECT. Gameobject %u (entry: %u) activated", + (*itr)->GetGUIDLow(), (*itr)->GetEntry()); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_RESET_GOBJECT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsGameObject(*itr)) + { + (*itr)->ToGameObject()->ResetDoorOrButton(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RESET_GOBJECT. Gameobject %u (entry: %u) reset", + (*itr)->GetGUIDLow(), (*itr)->GetEntry()); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_SET_EMOTE_STATE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + (*itr)->ToUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, e.action.emote.emote); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_EMOTE_STATE. Unit %u set emotestate to %u", + (*itr)->GetGUIDLow(), e.action.emote.emote); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_SET_UNIT_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + if (!e.action.unitFlag.type) + { + (*itr)->ToUnit()->SetFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); + //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_UNIT_FLAG. Unit %u added flag %u to UNIT_FIELD_FLAGS", + //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); + } + else + { + (*itr)->ToUnit()->SetFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); + //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_UNIT_FLAG. Unit %u added flag %u to UNIT_FIELD_FLAGS_2", + //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); + } + } + } + + delete targets; + break; + } + case SMART_ACTION_REMOVE_UNIT_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + if (!e.action.unitFlag.type) + { + (*itr)->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); + //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_REMOVE_UNIT_FLAG. Unit %u removed flag %u to UNIT_FIELD_FLAGS", + //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); + } + else + { + (*itr)->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); + //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_REMOVE_UNIT_FLAG. Unit %u removed flag %u to UNIT_FIELD_FLAGS_2", + //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); + } + } + } + + delete targets; + break; + } + case SMART_ACTION_AUTO_ATTACK: + { + if (!IsSmart()) + break; + + CAST_AI(SmartAI, me->AI())->SetAutoAttack(e.action.autoAttack.attack); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_AUTO_ATTACK: Creature: %u bool on = %u", + me->GetGUIDLow(), e.action.autoAttack.attack); +#endif + break; + } + case SMART_ACTION_ALLOW_COMBAT_MOVEMENT: + { + if (!IsSmart()) + break; + + // Xinef: Fix Combat Movement + bool move = e.action.combatMove.move; + if (move && GetMaxCombatDist() && e.GetEventType() == SMART_EVENT_MANA_PCT) + { + SetActualCombatDist(0); + CAST_AI(SmartAI, me->AI())->SetForcedCombatMove(0); + } + else + CAST_AI(SmartAI, me->AI())->SetCombatMove(move); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_ALLOW_COMBAT_MOVEMENT: Creature %u bool on = %u", + me->GetGUIDLow(), e.action.combatMove.move); +#endif + break; + } + case SMART_ACTION_SET_EVENT_PHASE: + { + if (!GetBaseObject()) + break; + + SetPhase(e.action.setEventPhase.phase); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_EVENT_PHASE: Creature %u set event phase %u", + GetBaseObject()->GetGUIDLow(), e.action.setEventPhase.phase); +#endif + break; + } + case SMART_ACTION_INC_EVENT_PHASE: + { + if (!GetBaseObject()) + break; + + IncPhase(e.action.incEventPhase.inc); + DecPhase(e.action.incEventPhase.dec); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_INC_EVENT_PHASE: Creature %u inc event phase by %u, " + "decrease by %u", GetBaseObject()->GetGUIDLow(), e.action.incEventPhase.inc, e.action.incEventPhase.dec); +#endif + break; + } + case SMART_ACTION_EVADE: + { + if (!GetBaseObject()) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature((*itr))) + if ((*itr)->ToCreature()->IsAIEnabled) + (*itr)->ToCreature()->AI()->EnterEvadeMode(); + + delete targets; + break; + } + case SMART_ACTION_FLEE_FOR_ASSIST: + { + // Xinef: do not allow to flee without control (stun, fear etc) + if (!me || me->HasUnitState(UNIT_STATE_LOST_CONTROL) || me->GetSpeed(MOVE_RUN) < 0.1f) + break; + + me->DoFleeToGetAssistance(); + if (e.action.flee.withEmote) + { + AcoreStringTextBuilder builder(me, CHAT_MSG_MONSTER_EMOTE, LANG_FLEE, LANG_UNIVERSAL, nullptr); + sCreatureTextMgr->SendChatPacket(me, builder, CHAT_MSG_MONSTER_EMOTE); + } +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_FLEE_FOR_ASSIST: Creature %u DoFleeToGetAssistance", me->GetGUIDLow()); +#endif + break; + } + case SMART_ACTION_COMBAT_STOP: + { + if (!me) + break; + + me->CombatStop(true); + break; + } + case SMART_ACTION_CALL_GROUPEVENTHAPPENS: + { + if (!GetBaseObject()) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit((*itr))) + { + if (Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself()) + player->GroupEventHappens(e.action.quest.quest, GetBaseObject()); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_GROUPEVENTHAPPENS: Player %u, group credit for quest %u", + (*itr)->GetGUIDLow(), e.action.quest.quest); +#endif + } + } + + delete targets; + break; + } + case SMART_ACTION_REMOVEAURASFROMSPELL: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsUnit((*itr))) + continue; + + if (e.action.removeAura.spell) + { + if (e.action.removeAura.charges) + { + if (Aura* aur = (*itr)->ToUnit()->GetAura(e.action.removeAura.spell)) + aur->ModCharges(-static_cast(e.action.removeAura.charges), AURA_REMOVE_BY_EXPIRE); + } + else + (*itr)->ToUnit()->RemoveAurasDueToSpell(e.action.removeAura.spell); } else - { - (*itr)->ToPlayer()->AddQuestAndCheckCompletion(q, nullptr); + (*itr)->ToUnit()->RemoveAllAuras(); + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug( - LOG_FILTER_DATABASE_AI, - "SmartScript::ProcessAction:: SMART_ACTION_OFFER_QUEST: Player guidLow %u - quest %u added", - (*itr)->GetGUIDLow(), - e.action.questOffer.questID); -#endif - } - } - } - } - - delete targets; - break; - } - case SMART_ACTION_SET_REACT_STATE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsCreature(*itr)) - continue; - - (*itr)->ToCreature()->SetReactState(ReactStates(e.action.react.state)); - } - - delete targets; - break; - } - case SMART_ACTION_RANDOM_EMOTE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - uint32 emotes[SMART_ACTION_PARAM_COUNT]; - emotes[0] = e.action.randomEmote.emote1; - emotes[1] = e.action.randomEmote.emote2; - emotes[2] = e.action.randomEmote.emote3; - emotes[3] = e.action.randomEmote.emote4; - emotes[4] = e.action.randomEmote.emote5; - emotes[5] = e.action.randomEmote.emote6; - uint32 temp[SMART_ACTION_PARAM_COUNT]; - uint32 count = 0; - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) - { - if (emotes[i]) - { - temp[count] = emotes[i]; - ++count; - } - } - - if (count == 0) - { - delete targets; - break; - } - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - uint32 emote = temp[urand(0, count - 1)]; - (*itr)->ToUnit()->HandleEmoteCommand(emote); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_EMOTE: Creature guidLow %u handle random emote %u", - (*itr)->GetGUIDLow(), emote); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_THREAT_ALL_PCT: - { - if (!me) - break; - - ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator i = threatList.begin(); i != threatList.end(); ++i) - { - if (Unit* target = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) - { - me->getThreatManager().modifyThreatPercent(target, e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_THREAT_ALL_PCT: Creature guidLow %u modify threat for unit %u, value %i", - me->GetGUIDLow(), target->GetGUIDLow(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); -#endif - } - } - break; - } - case SMART_ACTION_THREAT_SINGLE_PCT: - { - if (!me) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - me->getThreatManager().modifyThreatPercent((*itr)->ToUnit(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_THREAT_SINGLE_PCT: Creature guidLow %u modify threat for unit %u, value %i", - me->GetGUIDLow(), (*itr)->GetGUIDLow(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - // Special handling for vehicles - if (IsUnit(*itr)) - { - if (Vehicle* vehicle = (*itr)->ToUnit()->GetVehicleKit()) - for (SeatMap::iterator it = vehicle->Seats.begin(); it != vehicle->Seats.end(); ++it) - if (Player* player = ObjectAccessor::GetPlayer(*(*itr), it->second.Passenger.Guid)) - player->AreaExploredOrEventHappens(e.action.quest.quest); - - if (Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself()) - { - player->GroupEventHappens(e.action.quest.quest, me); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: Player guidLow %u credited quest %u", - (*itr)->GetGUIDLow(), e.action.quest.quest); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_REMOVEAURASFROMSPELL: Unit %u, spell %u", + (*itr)->GetGUIDLow(), e.action.removeAura.spell); #endif } + + delete targets; + break; } - } - - delete targets; - break; - } - case SMART_ACTION_CAST: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - Unit* caster = me; - // Areatrigger Cast! - if (e.GetScriptType() == SMART_SCRIPT_TYPE_AREATRIGGER) - caster = unit->SummonTrigger(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetOrientation(), 5000); - - if (e.action.cast.targetsLimit > 0 && targets->size() > e.action.cast.targetsLimit) - acore::Containers::RandomResizeList(*targets, e.action.cast.targetsLimit); - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (go) + case SMART_ACTION_FOLLOW: { - // Xinef: may be NULL! - go->CastSpell((*itr)->ToUnit(), e.action.cast.spell); - } + if (!IsSmart()) + break; - if (!IsUnit(*itr)) - continue; - - if (caster && caster != me) // Areatrigger cast - { - caster->CastSpell((*itr)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); - } - else if (me && (!(e.action.cast.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.cast.spell))) - { - if (e.action.cast.flags & SMARTCAST_INTERRUPT_PREVIOUS) - me->InterruptNonMeleeSpells(false); - - // Xinef: flag usable only if caster has max dist set - if ((e.action.cast.flags & SMARTCAST_COMBAT_MOVE) && GetCasterMaxDist() > 0.0f && me->GetMaxPower(GetCasterPowerType()) > 0) + ObjectList* targets = GetTargets(e, unit); + if (!targets) { - // Xinef: check mana case only and operate movement accordingly, LoS and range is checked in targetet movement generator - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(e.action.cast.spell); - int32 currentPower = me->GetPower(GetCasterPowerType()); + CAST_AI(SmartAI, me->AI())->StopFollow(false); + break; + } - if ((spellInfo && (currentPower < spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask()))) || me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED)) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit((*itr))) { - SetCasterActualDist(0); - CAST_AI(SmartAI, me->AI())->SetForcedCombatMove(0); - } - else if (GetCasterActualDist() == 0.0f && me->GetPowerPct(GetCasterPowerType()) > 30.0f) - { - RestoreCasterMaxDist(); - CAST_AI(SmartAI, me->AI())->SetForcedCombatMove(GetCasterActualDist()); + float angle = e.action.follow.angle > 6 ? (e.action.follow.angle * M_PI / 180.0f) : e.action.follow.angle; + CAST_AI(SmartAI, me->AI())->SetFollow((*itr)->ToUnit(), float(int32(e.action.follow.dist)) + 0.1f, angle, e.action.follow.credit, e.action.follow.entry, e.action.follow.creditType, e.action.follow.aliveState); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_FOLLOW: Creature %u following target %u", + me->GetGUIDLow(), (*itr)->GetGUIDLow()); +#endif + break; } } - me->CastSpell((*itr)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); + delete targets; + break; } - } - - delete targets; - break; - } - case SMART_ACTION_INVOKER_CAST: - { - Unit* tempLastInvoker = GetLastInvoker(unit); // xinef: can be used for area triggers cast - if (!tempLastInvoker) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - if (e.action.cast.targetsLimit > 0 && targets->size() > e.action.cast.targetsLimit) - acore::Containers::RandomResizeList(*targets, e.action.cast.targetsLimit); - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsUnit(*itr)) - continue; - - if (!(e.action.cast.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.cast.spell)) + case SMART_ACTION_RANDOM_PHASE: { - if (e.action.cast.flags & SMARTCAST_INTERRUPT_PREVIOUS) - tempLastInvoker->InterruptNonMeleeSpells(false); + if (!GetBaseObject()) + break; - tempLastInvoker->CastSpell((*itr)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); - } - } - - delete targets; - break; - } - case SMART_ACTION_ADD_AURA: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - (*itr)->ToUnit()->AddAura(e.action.cast.spell, (*itr)->ToUnit()); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_ADD_AURA: Adding aura %u to unit %u", - e.action.cast.spell, (*itr)->GetGUIDLow()); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_ACTIVATE_GOBJECT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsGameObject(*itr)) - { - // Activate - // xinef: wtf is this shit? - (*itr)->ToGameObject()->SetLootState(GO_READY); - (*itr)->ToGameObject()->UseDoorOrButton(0, !!e.action.activateObject.alternative, unit); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_ACTIVATE_GOBJECT. Gameobject %u (entry: %u) activated", - (*itr)->GetGUIDLow(), (*itr)->GetEntry()); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_RESET_GOBJECT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsGameObject(*itr)) - { - (*itr)->ToGameObject()->ResetDoorOrButton(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_RESET_GOBJECT. Gameobject %u (entry: %u) reset", - (*itr)->GetGUIDLow(), (*itr)->GetEntry()); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_SET_EMOTE_STATE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - (*itr)->ToUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, e.action.emote.emote); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_EMOTE_STATE. Unit %u set emotestate to %u", - (*itr)->GetGUIDLow(), e.action.emote.emote); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_SET_UNIT_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - if (!e.action.unitFlag.type) + uint32 phases[SMART_ACTION_PARAM_COUNT]; + phases[0] = e.action.randomPhase.phase1; + phases[1] = e.action.randomPhase.phase2; + phases[2] = e.action.randomPhase.phase3; + phases[3] = e.action.randomPhase.phase4; + phases[4] = e.action.randomPhase.phase5; + phases[5] = e.action.randomPhase.phase6; + uint32 temp[SMART_ACTION_PARAM_COUNT]; + uint32 count = 0; + for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) { - (*itr)->ToUnit()->SetFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); - //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_UNIT_FLAG. Unit %u added flag %u to UNIT_FIELD_FLAGS", - //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); + if (phases[i] > 0) + { + temp[count] = phases[i]; + ++count; + } } - else - { - (*itr)->ToUnit()->SetFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); - //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_UNIT_FLAG. Unit %u added flag %u to UNIT_FIELD_FLAGS_2", - //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); - } - } - } - delete targets; - break; - } - case SMART_ACTION_REMOVE_UNIT_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + if (count == 0) + break; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - if (!e.action.unitFlag.type) - { - (*itr)->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); - //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_REMOVE_UNIT_FLAG. Unit %u removed flag %u to UNIT_FIELD_FLAGS", - //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); - } - else - { - (*itr)->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); - //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_REMOVE_UNIT_FLAG. Unit %u removed flag %u to UNIT_FIELD_FLAGS_2", - //(*itr)->GetGUIDLow(), e.action.unitFlag.flag); - } - } - } - - delete targets; - break; - } - case SMART_ACTION_AUTO_ATTACK: - { - if (!IsSmart()) - break; - - CAST_AI(SmartAI, me->AI())->SetAutoAttack(e.action.autoAttack.attack); + uint32 phase = temp[urand(0, count - 1)]; + SetPhase(phase); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_AUTO_ATTACK: Creature: %u bool on = %u", - me->GetGUIDLow(), e.action.autoAttack.attack); -#endif - break; - } - case SMART_ACTION_ALLOW_COMBAT_MOVEMENT: - { - if (!IsSmart()) - break; - - // Xinef: Fix Combat Movement - bool move = e.action.combatMove.move; - if (move && GetMaxCombatDist() && e.GetEventType() == SMART_EVENT_MANA_PCT) - { - SetActualCombatDist(0); - CAST_AI(SmartAI, me->AI())->SetForcedCombatMove(0); - } - else - CAST_AI(SmartAI, me->AI())->SetCombatMove(move); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_ALLOW_COMBAT_MOVEMENT: Creature %u bool on = %u", - me->GetGUIDLow(), e.action.combatMove.move); -#endif - break; - } - case SMART_ACTION_SET_EVENT_PHASE: - { - if (!GetBaseObject()) - break; - - SetPhase(e.action.setEventPhase.phase); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SET_EVENT_PHASE: Creature %u set event phase %u", - GetBaseObject()->GetGUIDLow(), e.action.setEventPhase.phase); -#endif - break; - } - case SMART_ACTION_INC_EVENT_PHASE: - { - if (!GetBaseObject()) - break; - - IncPhase(e.action.incEventPhase.inc); - DecPhase(e.action.incEventPhase.dec); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_INC_EVENT_PHASE: Creature %u inc event phase by %u, " - "decrease by %u", GetBaseObject()->GetGUIDLow(), e.action.incEventPhase.inc, e.action.incEventPhase.dec); -#endif - break; - } - case SMART_ACTION_EVADE: - { - if (!GetBaseObject()) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature((*itr))) - if ((*itr)->ToCreature()->IsAIEnabled) - (*itr)->ToCreature()->AI()->EnterEvadeMode(); - - delete targets; - break; - } - case SMART_ACTION_FLEE_FOR_ASSIST: - { - // Xinef: do not allow to flee without control (stun, fear etc) - if (!me || me->HasUnitState(UNIT_STATE_LOST_CONTROL) || me->GetSpeed(MOVE_RUN) < 0.1f) - break; - - me->DoFleeToGetAssistance(); - if (e.action.flee.withEmote) - { - AcoreStringTextBuilder builder(me, CHAT_MSG_MONSTER_EMOTE, LANG_FLEE, LANG_UNIVERSAL, nullptr); - sCreatureTextMgr->SendChatPacket(me, builder, CHAT_MSG_MONSTER_EMOTE); - } -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_FLEE_FOR_ASSIST: Creature %u DoFleeToGetAssistance", me->GetGUIDLow()); -#endif - break; - } - case SMART_ACTION_COMBAT_STOP: - { - if (!me) - break; - - me->CombatStop(true); - break; - } - case SMART_ACTION_CALL_GROUPEVENTHAPPENS: - { - if (!GetBaseObject()) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit((*itr))) - { - if (Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself()) - player->GroupEventHappens(e.action.quest.quest, GetBaseObject()); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_GROUPEVENTHAPPENS: Player %u, group credit for quest %u", - (*itr)->GetGUIDLow(), e.action.quest.quest); -#endif - } - } - - delete targets; - break; - } - case SMART_ACTION_REMOVEAURASFROMSPELL: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsUnit((*itr))) - continue; - - if (e.action.removeAura.spell) - { - if (e.action.removeAura.charges) - { - if (Aura* aur = (*itr)->ToUnit()->GetAura(e.action.removeAura.spell)) - aur->ModCharges(-static_cast(e.action.removeAura.charges), AURA_REMOVE_BY_EXPIRE); - } - else - (*itr)->ToUnit()->RemoveAurasDueToSpell(e.action.removeAura.spell); - } - else - (*itr)->ToUnit()->RemoveAllAuras(); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_REMOVEAURASFROMSPELL: Unit %u, spell %u", - (*itr)->GetGUIDLow(), e.action.removeAura.spell); -#endif - } - - delete targets; - break; - } - case SMART_ACTION_FOLLOW: - { - if (!IsSmart()) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - { - CAST_AI(SmartAI, me->AI())->StopFollow(false); - break; - } - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit((*itr))) - { - float angle = e.action.follow.angle > 6 ? (e.action.follow.angle * M_PI / 180.0f) : e.action.follow.angle; - CAST_AI(SmartAI, me->AI())->SetFollow((*itr)->ToUnit(), float(int32(e.action.follow.dist)) + 0.1f, angle, e.action.follow.credit, e.action.follow.entry, e.action.follow.creditType, e.action.follow.aliveState); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_FOLLOW: Creature %u following target %u", - me->GetGUIDLow(), (*itr)->GetGUIDLow()); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE: Creature %u sets event phase to %u", + GetBaseObject()->GetGUIDLow(), phase); #endif break; } - } - - delete targets; - break; - } - case SMART_ACTION_RANDOM_PHASE: - { - if (!GetBaseObject()) - break; - - uint32 phases[SMART_ACTION_PARAM_COUNT]; - phases[0] = e.action.randomPhase.phase1; - phases[1] = e.action.randomPhase.phase2; - phases[2] = e.action.randomPhase.phase3; - phases[3] = e.action.randomPhase.phase4; - phases[4] = e.action.randomPhase.phase5; - phases[5] = e.action.randomPhase.phase6; - uint32 temp[SMART_ACTION_PARAM_COUNT]; - uint32 count = 0; - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) - { - if (phases[i] > 0) + case SMART_ACTION_RANDOM_PHASE_RANGE: { - temp[count] = phases[i]; - ++count; - } - } + if (!GetBaseObject()) + break; - if (count == 0) - break; - - uint32 phase = temp[urand(0, count - 1)]; - SetPhase(phase); + uint32 phase = urand(e.action.randomPhaseRange.phaseMin, e.action.randomPhaseRange.phaseMax); + SetPhase(phase); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE: Creature %u sets event phase to %u", - GetBaseObject()->GetGUIDLow(), phase); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE_RANGE: Creature %u sets event phase to %u", + GetBaseObject()->GetGUIDLow(), phase); #endif - break; - } - case SMART_ACTION_RANDOM_PHASE_RANGE: - { - if (!GetBaseObject()) - break; - - uint32 phase = urand(e.action.randomPhaseRange.phaseMin, e.action.randomPhaseRange.phaseMax); - SetPhase(phase); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE_RANGE: Creature %u sets event phase to %u", - GetBaseObject()->GetGUIDLow(), phase); -#endif - break; - } - case SMART_ACTION_CALL_KILLEDMONSTER: - { - if (trigger && IsPlayer(unit)) - { - unit->ToPlayer()->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, unit); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: (trigger == true) Player %u, Killcredit: %u", - unit->GetGUIDLow(), e.action.killedMonster.creature); -#endif - } - else if (e.target.type == SMART_TARGET_NONE || e.target.type == SMART_TARGET_SELF) // Loot recipient and his group members - { - if (!me) break; - - if (Player* player = me->GetLootRecipient()) - { - player->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, player); - //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player %u, Killcredit: %u", - // player->GetGUIDLow(), e.action.killedMonster.creature); } - } - else // Specific target type - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_CALL_KILLEDMONSTER: { - if (!IsUnit(*itr)) - continue; - - Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself(); - if (!player) - continue; - - player->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, player); + if (trigger && IsPlayer(unit)) + { + unit->ToPlayer()->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, unit); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player %u, Killcredit: %u", - (*itr)->GetGUIDLow(), e.action.killedMonster.creature); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: (trigger == true) Player %u, Killcredit: %u", + unit->GetGUIDLow(), e.action.killedMonster.creature); #endif - } + } + else if (e.target.type == SMART_TARGET_NONE || e.target.type == SMART_TARGET_SELF) // Loot recipient and his group members + { + if (!me) + break; - delete targets; - } - break; - } - case SMART_ACTION_SET_INST_DATA: - { - WorldObject* obj = GetBaseObject(); - if (!obj) - obj = unit; - - if (!obj) - break; - - InstanceScript* instance = obj->GetInstanceScript(); - if (!instance) - { - sLog->outErrorDb("SmartScript: Event %u attempt to set instance data without instance script. EntryOrGuid %d", e.GetEventType(), e.entryOrGuid); - break; - } - - instance->SetData(e.action.setInstanceData.field, e.action.setInstanceData.data); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA: Field: %u, data: %u", - e.action.setInstanceData.field, e.action.setInstanceData.data); -#endif - break; - } - case SMART_ACTION_SET_INST_DATA64: - { - WorldObject* obj = GetBaseObject(); - if (!obj) - obj = unit; - - if (!obj) - break; - - InstanceScript* instance = obj->GetInstanceScript(); - if (!instance) - { - sLog->outErrorDb("SmartScript: Event %u attempt to set instance data without instance script. EntryOrGuid %d", e.GetEventType(), e.entryOrGuid); - break; - } - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - instance->SetData64(e.action.setInstanceData64.field, targets->front()->GetGUID()); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA64: Field: %u, data: %lu", - e.action.setInstanceData64.field, targets->front()->GetGUID()); -#endif - delete targets; - break; - } - case SMART_ACTION_UPDATE_TEMPLATE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->UpdateEntry(e.action.updateTemplate.creature, NULL, e.action.updateTemplate.updateLevel != 0); - - delete targets; - break; - } - case SMART_ACTION_DIE: - { - if (me && !me->isDead()) - { - Unit::Kill(me, me); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_DIE: Creature %u", me->GetGUIDLow()); -#endif - } - break; - } - case SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - if (!me->GetMap()->IsDungeon()) - { - ObjectList* units = GetWorldObjectsInDist((float)e.action.combatZone.range); - if (!units->empty() && GetBaseObject()) - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr) && !(*itr)->ToPlayer()->isDead()) + if (Player* player = me->GetLootRecipient()) { - me->SetInCombatWith((*itr)->ToPlayer()); - (*itr)->ToPlayer()->SetInCombatWith(me); - me->AddThreat((*itr)->ToPlayer(), 0.0f); + player->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, player); + //TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player %u, Killcredit: %u", + // player->GetGUIDLow(), e.action.killedMonster.creature); } - } - else - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetInCombatWithZone(); - } - - delete targets; - break; - } - case SMART_ACTION_CALL_FOR_HELP: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - { - (*itr)->ToCreature()->CallForHelp((float)e.action.callHelp.range); - if (e.action.callHelp.withEmote) - { - AcoreStringTextBuilder builder(*itr, CHAT_MSG_MONSTER_EMOTE, LANG_CALL_FOR_HELP, LANG_UNIVERSAL, nullptr); - sCreatureTextMgr->SendChatPacket(*itr, builder, CHAT_MSG_MONSTER_EMOTE); } - } + else // Specific target type + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - delete targets; - break; - } - case SMART_ACTION_SET_SHEATH: - { - if (me) - { - me->SetSheath(SheathState(e.action.setSheath.sheath)); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsUnit(*itr)) + continue; + + Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself(); + if (!player) + continue; + + player->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, player); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_SET_SHEATH: Creature %u, State: %u", - me->GetGUIDLow(), e.action.setSheath.sheath); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player %u, Killcredit: %u", + (*itr)->GetGUIDLow(), e.action.killedMonster.creature); #endif - } - break; - } - case SMART_ACTION_FORCE_DESPAWN: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + } - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - (*itr)->ToCreature()->DespawnOrUnsummon(e.action.forceDespawn.delay + 1); - else if (IsGameObject(*itr)) - (*itr)->ToGameObject()->Delete(); - } - - delete targets; - break; - } - case SMART_ACTION_SET_INGAME_PHASE_MASK: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPhaseMask(e.action.ingamePhaseMask.mask, true); - else if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetPhaseMask(e.action.ingamePhaseMask.mask, true); - } - - delete targets; - break; - } - case SMART_ACTION_MOUNT_TO_ENTRY_OR_MODEL: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsUnit(*itr)) - continue; - - if (e.action.morphOrMount.creature || e.action.morphOrMount.model) + delete targets; + } + break; + } + case SMART_ACTION_SET_INST_DATA: { - if (e.action.morphOrMount.creature > 0) + WorldObject* obj = GetBaseObject(); + if (!obj) + obj = unit; + + if (!obj) + break; + + InstanceScript* instance = obj->GetInstanceScript(); + if (!instance) { - if (CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) - (*itr)->ToUnit()->Mount(ObjectMgr::ChooseDisplayId(cInfo)); + sLog->outErrorDb("SmartScript: Event %u attempt to set instance data without instance script. EntryOrGuid %d", e.GetEventType(), e.entryOrGuid); + break; + } + + instance->SetData(e.action.setInstanceData.field, e.action.setInstanceData.data); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA: Field: %u, data: %u", + e.action.setInstanceData.field, e.action.setInstanceData.data); +#endif + break; + } + case SMART_ACTION_SET_INST_DATA64: + { + WorldObject* obj = GetBaseObject(); + if (!obj) + obj = unit; + + if (!obj) + break; + + InstanceScript* instance = obj->GetInstanceScript(); + if (!instance) + { + sLog->outErrorDb("SmartScript: Event %u attempt to set instance data without instance script. EntryOrGuid %d", e.GetEventType(), e.entryOrGuid); + break; + } + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + instance->SetData64(e.action.setInstanceData64.field, targets->front()->GetGUID()); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA64: Field: %u, data: %lu", + e.action.setInstanceData64.field, targets->front()->GetGUID()); +#endif + delete targets; + break; + } + case SMART_ACTION_UPDATE_TEMPLATE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->UpdateEntry(e.action.updateTemplate.creature, NULL, e.action.updateTemplate.updateLevel != 0); + + delete targets; + break; + } + case SMART_ACTION_DIE: + { + if (me && !me->isDead()) + { + Unit::Kill(me, me); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_DIE: Creature %u", me->GetGUIDLow()); +#endif + } + break; + } + case SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + if (!me->GetMap()->IsDungeon()) + { + ObjectList* units = GetWorldObjectsInDist((float)e.action.combatZone.range); + if (!units->empty() && GetBaseObject()) + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + if (IsPlayer(*itr) && !(*itr)->ToPlayer()->isDead()) + { + me->SetInCombatWith((*itr)->ToPlayer()); + (*itr)->ToPlayer()->SetInCombatWith(me); + me->AddThreat((*itr)->ToPlayer(), 0.0f); + } } else - (*itr)->ToUnit()->Mount(e.action.morphOrMount.model); + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->SetInCombatWithZone(); + } + + delete targets; + break; } - else - (*itr)->ToUnit()->Dismount(); - } - - delete targets; - break; - } - case SMART_ACTION_SET_INVINCIBILITY_HP_LEVEL: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) + case SMART_ACTION_CALL_FOR_HELP: { - SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI()); - if (!ai) - continue; + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - if (e.action.invincHP.percent) - ai->SetInvincibilityHpLevel((*itr)->ToCreature()->CountPctFromMaxHealth(e.action.invincHP.percent)); - else - ai->SetInvincibilityHpLevel(e.action.invincHP.minHP); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + { + (*itr)->ToCreature()->CallForHelp((float)e.action.callHelp.range); + if (e.action.callHelp.withEmote) + { + AcoreStringTextBuilder builder(*itr, CHAT_MSG_MONSTER_EMOTE, LANG_CALL_FOR_HELP, LANG_UNIVERSAL, nullptr); + sCreatureTextMgr->SendChatPacket(*itr, builder, CHAT_MSG_MONSTER_EMOTE); + } + } + + delete targets; + break; } - } - - delete targets; - break; - } - case SMART_ACTION_SET_DATA: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - (*itr)->ToCreature()->AI()->SetData(e.action.setData.field, e.action.setData.data); - else if (IsGameObject(*itr)) - (*itr)->ToGameObject()->AI()->SetData(e.action.setData.field, e.action.setData.data); - } - - delete targets; - break; - } - case SMART_ACTION_MOVE_FORWARD: - { - if (!me) - break; - - float x, y, z; - me->GetClosePoint(x, y, z, me->GetObjectSize() / 3, (float)e.action.moveRandom.distance); - me->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, x, y, z); - break; - } - case SMART_ACTION_RISE_UP: - { - if (!me) - break; - - me->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ() + (float)e.action.moveRandom.distance); - break; - } - case SMART_ACTION_SET_VISIBILITY: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetVisible(!!e.action.visibility.state); - - delete targets; - break; - } - case SMART_ACTION_SET_ACTIVE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - (*itr)->setActive(!!e.action.setActive.state); - - delete targets; - break; - } - case SMART_ACTION_ATTACK_START: - { - if (!me) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - // xinef: attack random target - if (Unit* target = acore::Containers::SelectRandomContainerElement(*targets)->ToUnit()) - me->AI()->AttackStart(target); - - delete targets; - break; - } - case SMART_ACTION_SUMMON_CREATURE: - { - ObjectList* targets = GetTargets(e, unit); - WorldObject* summoner = GetBaseObject() ? GetBaseObject() : unit; - if (!summoner) - break; - - if (e.GetTargetType() == SMART_TARGET_RANDOM_POINT) - { - float range = (float)e.target.randomPoint.range; - Position randomPoint; - Position srcPos = { e.target.x, e.target.y, e.target.z, e.target.o }; - for (uint32 i = 0; i < e.target.randomPoint.amount; i++) + case SMART_ACTION_SET_SHEATH: { - if (e.target.randomPoint.self > 0) - me->GetRandomPoint(me->GetPosition(), range, randomPoint); - else - me->GetRandomPoint(srcPos, range, randomPoint); - if (Creature* summon = summoner->SummonCreature(e.action.summonCreature.creature, randomPoint, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) + if (me) + { + me->SetSheath(SheathState(e.action.setSheath.sheath)); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction: SMART_ACTION_SET_SHEATH: Creature %u, State: %u", + me->GetGUIDLow(), e.action.setSheath.sheath); +#endif + } + break; + } + case SMART_ACTION_FORCE_DESPAWN: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + (*itr)->ToCreature()->DespawnOrUnsummon(e.action.forceDespawn.delay + 1); + else if (IsGameObject(*itr)) + (*itr)->ToGameObject()->Delete(); + } + + delete targets; + break; + } + case SMART_ACTION_SET_INGAME_PHASE_MASK: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetPhaseMask(e.action.ingamePhaseMask.mask, true); + else if (IsGameObject(*itr)) + (*itr)->ToGameObject()->SetPhaseMask(e.action.ingamePhaseMask.mask, true); + } + + delete targets; + break; + } + case SMART_ACTION_MOUNT_TO_ENTRY_OR_MODEL: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsUnit(*itr)) + continue; + + if (e.action.morphOrMount.creature || e.action.morphOrMount.model) + { + if (e.action.morphOrMount.creature > 0) + { + if (CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) + (*itr)->ToUnit()->Mount(ObjectMgr::ChooseDisplayId(cInfo)); + } + else + (*itr)->ToUnit()->Mount(e.action.morphOrMount.model); + } + else + (*itr)->ToUnit()->Dismount(); + } + + delete targets; + break; + } + case SMART_ACTION_SET_INVINCIBILITY_HP_LEVEL: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI()); + if (!ai) + continue; + + if (e.action.invincHP.percent) + ai->SetInvincibilityHpLevel((*itr)->ToCreature()->CountPctFromMaxHealth(e.action.invincHP.percent)); + else + ai->SetInvincibilityHpLevel(e.action.invincHP.minHP); + } + } + + delete targets; + break; + } + case SMART_ACTION_SET_DATA: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + (*itr)->ToCreature()->AI()->SetData(e.action.setData.field, e.action.setData.data); + else if (IsGameObject(*itr)) + (*itr)->ToGameObject()->AI()->SetData(e.action.setData.field, e.action.setData.data); + } + + delete targets; + break; + } + case SMART_ACTION_MOVE_FORWARD: + { + if (!me) + break; + + float x, y, z; + me->GetClosePoint(x, y, z, me->GetObjectSize() / 3, (float)e.action.moveRandom.distance); + me->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, x, y, z); + break; + } + case SMART_ACTION_RISE_UP: + { + if (!me) + break; + + me->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ() + (float)e.action.moveRandom.distance); + break; + } + case SMART_ACTION_SET_VISIBILITY: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetVisible(!!e.action.visibility.state); + + delete targets; + break; + } + case SMART_ACTION_SET_ACTIVE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + (*itr)->setActive(!!e.action.setActive.state); + + delete targets; + break; + } + case SMART_ACTION_ATTACK_START: + { + if (!me) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + // xinef: attack random target + if (Unit* target = acore::Containers::SelectRandomContainerElement(*targets)->ToUnit()) + me->AI()->AttackStart(target); + + delete targets; + break; + } + case SMART_ACTION_SUMMON_CREATURE: + { + ObjectList* targets = GetTargets(e, unit); + WorldObject* summoner = GetBaseObject() ? GetBaseObject() : unit; + if (!summoner) + break; + + if (e.GetTargetType() == SMART_TARGET_RANDOM_POINT) + { + float range = (float)e.target.randomPoint.range; + Position randomPoint; + Position srcPos = { e.target.x, e.target.y, e.target.z, e.target.o }; + for (uint32 i = 0; i < e.target.randomPoint.amount; i++) + { + if (e.target.randomPoint.self > 0) + me->GetRandomPoint(me->GetPosition(), range, randomPoint); + else + me->GetRandomPoint(srcPos, range, randomPoint); + if (Creature* summon = summoner->SummonCreature(e.action.summonCreature.creature, randomPoint, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) + { + if (unit && e.action.summonCreature.attackInvoker) + summon->AI()->AttackStart(unit); + else if (me && e.action.summonCreature.attackScriptOwner) + summon->AI()->AttackStart(me); + } + } + break; + } + + if (targets) + { + float x, y, z, o; + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + (*itr)->GetPosition(x, y, z, o); + x += e.target.x; + y += e.target.y; + z += e.target.z; + o += e.target.o; + if (Creature* summon = summoner->SummonCreature(e.action.summonCreature.creature, x, y, z, o, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) + { + if (e.action.summonCreature.attackInvoker == 2) // pussywizard: proper attackInvoker implementation, but not spoiling tc shitness + summon->AI()->AttackStart(unit); + else if (e.action.summonCreature.attackInvoker) + summon->AI()->AttackStart((*itr)->ToUnit()); + else if (me && e.action.summonCreature.attackScriptOwner) + summon->AI()->AttackStart(me); + } + } + + delete targets; + } + + if (e.GetTargetType() != SMART_TARGET_POSITION) + break; + + if (Creature* summon = summoner->SummonCreature(e.action.summonCreature.creature, e.target.x, e.target.y, e.target.z, e.target.o, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) { if (unit && e.action.summonCreature.attackInvoker) summon->AI()->AttackStart(unit); else if (me && e.action.summonCreature.attackScriptOwner) summon->AI()->AttackStart(me); } + break; } - break; - } - - if (targets) - { - float x, y, z, o; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_SUMMON_GO: { - (*itr)->GetPosition(x, y, z, o); - x += e.target.x; - y += e.target.y; - z += e.target.z; - o += e.target.o; - if (Creature* summon = summoner->SummonCreature(e.action.summonCreature.creature, x, y, z, o, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) + if (!GetBaseObject()) + break; + + ObjectList* targets = GetTargets(e, unit); + if (targets) { - if (e.action.summonCreature.attackInvoker == 2) // pussywizard: proper attackInvoker implementation, but not spoiling tc shitness - summon->AI()->AttackStart(unit); - else if (e.action.summonCreature.attackInvoker) - summon->AI()->AttackStart((*itr)->ToUnit()); - else if (me && e.action.summonCreature.attackScriptOwner) - summon->AI()->AttackStart(me); + float x, y, z, o; + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + // xinef: allow gameobjects to summon gameobjects! + //if(!IsUnit((*itr))) + // continue; + + (*itr)->GetPosition(x, y, z, o); + x += e.target.x; + y += e.target.y; + z += e.target.z; + o += e.target.o; + if (!e.action.summonGO.targetsummon) + GetBaseObject()->SummonGameObject(e.action.summonGO.entry, x, y, z, o, 0, 0, 0, 0, e.action.summonGO.despawnTime); + else + (*itr)->SummonGameObject(e.action.summonGO.entry, GetBaseObject()->GetPositionX(), GetBaseObject()->GetPositionY(), GetBaseObject()->GetPositionZ(), GetBaseObject()->GetOrientation(), 0, 0, 0, 0, e.action.summonGO.despawnTime); + } + + delete targets; } + + if (e.GetTargetType() != SMART_TARGET_POSITION) + break; + + GetBaseObject()->SummonGameObject(e.action.summonGO.entry, e.target.x, e.target.y, e.target.z, e.target.o, 0, 0, 0, 0, e.action.summonGO.despawnTime); + break; } - - delete targets; - } - - if (e.GetTargetType() != SMART_TARGET_POSITION) - break; - - if (Creature* summon = summoner->SummonCreature(e.action.summonCreature.creature, e.target.x, e.target.y, e.target.z, e.target.o, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) - { - if (unit && e.action.summonCreature.attackInvoker) - summon->AI()->AttackStart(unit); - else if (me && e.action.summonCreature.attackScriptOwner) - summon->AI()->AttackStart(me); - } - break; - } - case SMART_ACTION_SUMMON_GO: - { - if (!GetBaseObject()) - break; - - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - float x, y, z, o; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_KILL_UNIT: { - // xinef: allow gameobjects to summon gameobjects! - //if(!IsUnit((*itr))) - // continue; + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - (*itr)->GetPosition(x, y, z, o); - x += e.target.x; - y += e.target.y; - z += e.target.z; - o += e.target.o; - if (!e.action.summonGO.targetsummon) - GetBaseObject()->SummonGameObject(e.action.summonGO.entry, x, y, z, o, 0, 0, 0, 0, e.action.summonGO.despawnTime); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsUnit(*itr)) + continue; + + Unit::Kill((*itr)->ToUnit(), (*itr)->ToUnit()); + } + + delete targets; + break; + } + case SMART_ACTION_INSTALL_AI_TEMPLATE: + { + InstallTemplate(e); + break; + } + case SMART_ACTION_ADD_ITEM: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsPlayer(*itr)) + continue; + + (*itr)->ToPlayer()->AddItem(e.action.item.entry, e.action.item.count); + } + + delete targets; + break; + } + case SMART_ACTION_REMOVE_ITEM: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsPlayer(*itr)) + continue; + + (*itr)->ToPlayer()->DestroyItemCount(e.action.item.entry, e.action.item.count, true); + } + + delete targets; + break; + } + case SMART_ACTION_STORE_TARGET_LIST: + { + ObjectList* targets = GetTargets(e, unit); + StoreTargetList(targets, e.action.storeTargets.id); + break; + } + case SMART_ACTION_TELEPORT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsPlayer(*itr)) + (*itr)->ToPlayer()->TeleportTo(e.action.teleport.mapID, e.target.x, e.target.y, e.target.z, e.target.o); + else if (IsUnit(*itr)) + (*itr)->ToUnit()->NearTeleportTo(e.target.x, e.target.y, e.target.z, e.target.o); + } + + delete targets; + break; + } + case SMART_ACTION_SET_FLY: + { + if (!IsSmart()) + break; + + CAST_AI(SmartAI, me->AI())->SetFly(e.action.setFly.fly); + // Xinef: Set speed if any + if (e.action.setFly.speed) + me->SetSpeed(MOVE_RUN, float(e.action.setFly.speed / 100.0f), true); + + // Xinef: this wil be executed only if state is different + me->SetDisableGravity(e.action.setFly.disableGravity); + break; + } + case SMART_ACTION_SET_RUN: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + if (IsSmart((*itr)->ToCreature())) + CAST_AI(SmartAI, (*itr)->ToCreature()->AI())->SetRun(e.action.setRun.run); + else + (*itr)->ToCreature()->SetWalk(e.action.setRun.run ? false : true); // Xinef: reversed + } + } + + delete targets; + break; + } + case SMART_ACTION_SET_SWIM: + { + if (!IsSmart()) + break; + + CAST_AI(SmartAI, me->AI())->SetSwim(e.action.setSwim.swim); + break; + } + case SMART_ACTION_SET_COUNTER: + { + if (ObjectList* targets = GetTargets(e, unit)) + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + if (SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI())) + ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); + else + sLog->outError("SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartAI, skipping"); + } + else if (IsGameObject(*itr)) + { + if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, (*itr)->ToGameObject()->AI())) + ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); + else + sLog->outError("SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartGameObjectAI, skipping"); + } + } + + delete targets; + } else - (*itr)->SummonGameObject(e.action.summonGO.entry, GetBaseObject()->GetPositionX(), GetBaseObject()->GetPositionY(), GetBaseObject()->GetPositionZ(), GetBaseObject()->GetOrientation(), 0, 0, 0, 0, e.action.summonGO.despawnTime); + StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); + + break; } - - delete targets; - } - - if (e.GetTargetType() != SMART_TARGET_POSITION) - break; - - GetBaseObject()->SummonGameObject(e.action.summonGO.entry, e.target.x, e.target.y, e.target.z, e.target.o, 0, 0, 0, 0, e.action.summonGO.despawnTime); - break; - } - case SMART_ACTION_KILL_UNIT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsUnit(*itr)) - continue; - - Unit::Kill((*itr)->ToUnit(), (*itr)->ToUnit()); - } - - delete targets; - break; - } - case SMART_ACTION_INSTALL_AI_TEMPLATE: - { - InstallTemplate(e); - break; - } - case SMART_ACTION_ADD_ITEM: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsPlayer(*itr)) - continue; - - (*itr)->ToPlayer()->AddItem(e.action.item.entry, e.action.item.count); - } - - delete targets; - break; - } - case SMART_ACTION_REMOVE_ITEM: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsPlayer(*itr)) - continue; - - (*itr)->ToPlayer()->DestroyItemCount(e.action.item.entry, e.action.item.count, true); - } - - delete targets; - break; - } - case SMART_ACTION_STORE_TARGET_LIST: - { - ObjectList* targets = GetTargets(e, unit); - StoreTargetList(targets, e.action.storeTargets.id); - break; - } - case SMART_ACTION_TELEPORT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsPlayer(*itr)) - (*itr)->ToPlayer()->TeleportTo(e.action.teleport.mapID, e.target.x, e.target.y, e.target.z, e.target.o); - else if (IsUnit(*itr)) - (*itr)->ToUnit()->NearTeleportTo(e.target.x, e.target.y, e.target.z, e.target.o); - } - - delete targets; - break; - } - case SMART_ACTION_SET_FLY: - { - if (!IsSmart()) - break; - - CAST_AI(SmartAI, me->AI())->SetFly(e.action.setFly.fly); - // Xinef: Set speed if any - if (e.action.setFly.speed) - me->SetSpeed(MOVE_RUN, float(e.action.setFly.speed / 100.0f), true); - - // Xinef: this wil be executed only if state is different - me->SetDisableGravity(e.action.setFly.disableGravity); - break; - } - case SMART_ACTION_SET_RUN: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) + case SMART_ACTION_WP_START: { - if (IsSmart((*itr)->ToCreature())) - CAST_AI(SmartAI, (*itr)->ToCreature()->AI())->SetRun(e.action.setRun.run); - else - (*itr)->ToCreature()->SetWalk(e.action.setRun.run ? false : true); // Xinef: reversed - } - } + if (!IsSmart()) + break; - delete targets; - break; - } - case SMART_ACTION_SET_SWIM: - { - if (!IsSmart()) - break; + bool run = e.action.wpStart.run; + uint32 entry = e.action.wpStart.pathID; + bool repeat = e.action.wpStart.repeat; - CAST_AI(SmartAI, me->AI())->SetSwim(e.action.setSwim.swim); - break; - } - case SMART_ACTION_SET_COUNTER: - { - if (ObjectList* targets = GetTargets(e, unit)) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) + // Xinef: ensure that SMART_ESCORT_TARGETS contains at least one player reference + bool stored = false; + ObjectList* targets = GetTargets(e, unit); + if (targets) { - if (SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI())) - ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); - else - sLog->outError("SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartAI, skipping"); - } - else if (IsGameObject(*itr)) - { - if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, (*itr)->ToGameObject()->AI())) - ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); - else - sLog->outError("SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartGameObjectAI, skipping"); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsPlayer(*itr)) + { + stored = true; + StoreTargetList(targets, SMART_ESCORT_TARGETS); + break; + } + } + if (!stored) + delete targets; } + + me->SetReactState((ReactStates)e.action.wpStart.reactState); + CAST_AI(SmartAI, me->AI())->StartPath(run, entry, repeat, unit); + + uint32 quest = e.action.wpStart.quest; + uint32 DespawnTime = e.action.wpStart.despawnTime; + CAST_AI(SmartAI, me->AI())->mEscortQuestID = quest; + CAST_AI(SmartAI, me->AI())->SetDespawnTime(DespawnTime); + break; } - - delete targets; - } - else - StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); - - break; - } - case SMART_ACTION_WP_START: - { - if (!IsSmart()) - break; - - bool run = e.action.wpStart.run; - uint32 entry = e.action.wpStart.pathID; - bool repeat = e.action.wpStart.repeat; - - // Xinef: ensure that SMART_ESCORT_TARGETS contains at least one player reference - bool stored = false; - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_WP_PAUSE: { - if (IsPlayer(*itr)) + if (!IsSmart()) + break; + + uint32 delay = e.action.wpPause.delay; + CAST_AI(SmartAI, me->AI())->PausePath(delay, e.GetEventType() == SMART_EVENT_WAYPOINT_REACHED ? false : true); + break; + } + case SMART_ACTION_WP_STOP: + { + if (!IsSmart()) + break; + + uint32 DespawnTime = e.action.wpStop.despawnTime; + uint32 quest = e.action.wpStop.quest; + bool fail = e.action.wpStop.fail; + CAST_AI(SmartAI, me->AI())->StopPath(DespawnTime, quest, fail); + break; + } + case SMART_ACTION_WP_RESUME: + { + if (!IsSmart()) + break; + + CAST_AI(SmartAI, me->AI())->SetWPPauseTimer(0); + break; + } + case SMART_ACTION_SET_ORIENTATION: + { + if (!me) + break; + + if (e.action.orientation.random > 0) { - stored = true; - StoreTargetList(targets, SMART_ESCORT_TARGETS); + float randomOri = frand(0.0f, 2 * M_PI); + me->SetFacingTo(randomOri); + if (e.action.orientation.quickChange) + me->SetOrientation(randomOri); break; } - } - if (!stored) - delete targets; - } - me->SetReactState((ReactStates)e.action.wpStart.reactState); - CAST_AI(SmartAI, me->AI())->StartPath(run, entry, repeat, unit); - - uint32 quest = e.action.wpStart.quest; - uint32 DespawnTime = e.action.wpStart.despawnTime; - CAST_AI(SmartAI, me->AI())->mEscortQuestID = quest; - CAST_AI(SmartAI, me->AI())->SetDespawnTime(DespawnTime); - break; - } - case SMART_ACTION_WP_PAUSE: - { - if (!IsSmart()) - break; - - uint32 delay = e.action.wpPause.delay; - CAST_AI(SmartAI, me->AI())->PausePath(delay, e.GetEventType() == SMART_EVENT_WAYPOINT_REACHED ? false : true); - break; - } - case SMART_ACTION_WP_STOP: - { - if (!IsSmart()) - break; - - uint32 DespawnTime = e.action.wpStop.despawnTime; - uint32 quest = e.action.wpStop.quest; - bool fail = e.action.wpStop.fail; - CAST_AI(SmartAI, me->AI())->StopPath(DespawnTime, quest, fail); - break; - } - case SMART_ACTION_WP_RESUME: - { - if (!IsSmart()) - break; - - CAST_AI(SmartAI, me->AI())->SetWPPauseTimer(0); - break; - } - case SMART_ACTION_SET_ORIENTATION: - { - if (!me) - break; - - if (e.action.orientation.random > 0) - { - float randomOri = frand(0.0f, 2 * M_PI); - me->SetFacingTo(randomOri); - if (e.action.orientation.quickChange) - me->SetOrientation(randomOri); - break; - } - - if (e.GetTargetType() == SMART_TARGET_SELF) - { - me->SetFacingTo((me->HasUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT) && me->GetTransGUID() ? me->GetTransportHomePosition() : me->GetHomePosition()).GetOrientation()); - if (e.action.orientation.quickChange) - me->SetOrientation((me->HasUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT) && me->GetTransGUID() ? me->GetTransportHomePosition() : me->GetHomePosition()).GetOrientation()); - } - else if (e.GetTargetType() == SMART_TARGET_POSITION) - { - me->SetFacingTo(e.target.o); - if (e.action.orientation.quickChange) - me->SetOrientation(e.target.o); - } - else if (ObjectList* targets = GetTargets(e, unit)) - { - if (!targets->empty()) - { - me->SetFacingToObject(*targets->begin()); - if (e.action.orientation.quickChange) - me->SetInFront(*targets->begin()); - } - - delete targets; - } - - break; - } - case SMART_ACTION_PLAYMOVIE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsPlayer(*itr)) - continue; - - (*itr)->ToPlayer()->SendMovieStart(e.action.movie.entry); - } - - delete targets; - break; - } - case SMART_ACTION_MOVE_TO_POS: - { - if (!IsSmart()) - break; - - WorldObject* target = nullptr; - - if (e.GetTargetType() == SMART_TARGET_RANDOM_POINT) - { - if (me) - { - float range = (float)e.target.randomPoint.range; - Position randomPoint; - Position srcPos = { e.target.x, e.target.y, e.target.z, e.target.o }; - me->GetRandomPoint(srcPos, range, randomPoint); - me->GetMotionMaster()->MovePoint( - e.action.MoveToPos.pointId, - randomPoint.m_positionX, - randomPoint.m_positionY, - randomPoint.m_positionZ, - true, - true, - isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE - ); - } - - break; - } - - /*if (e.GetTargetType() == SMART_TARGET_CREATURE_RANGE || e.GetTargetType() == SMART_TARGET_CREATURE_GUID || - e.GetTargetType() == SMART_TARGET_CREATURE_DISTANCE || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_RANGE || - e.GetTargetType() == SMART_TARGET_GAMEOBJECT_GUID || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_DISTANCE || - e.GetTargetType() == SMART_TARGET_CLOSEST_CREATURE || e.GetTargetType() == SMART_TARGET_CLOSEST_GAMEOBJECT || - e.GetTargetType() == SMART_TARGET_OWNER_OR_SUMMONER || e.GetTargetType() == SMART_TARGET_ACTION_INVOKER || - e.GetTargetType() == SMART_TARGET_CLOSEST_ENEMY || e.GetTargetType() == SMART_TARGET_CLOSEST_FRIENDLY || - e.GetTargetType() == SMART_TARGET_SELF || e.GetTargetType() == SMART_TARGET_STORED) // Xinef: bieda i rozpierdol TC)*/ - { - if (ObjectList* targets = GetTargets(e, unit)) - { - // xinef: we want to move to random element - target = acore::Containers::SelectRandomContainerElement(*targets); - delete targets; - } - } - - if (!target) - { - G3D::Vector3 dest(e.target.x, e.target.y, e.target.z); - if (e.action.MoveToPos.transport) - if (TransportBase* trans = me->GetDirectTransport()) - trans->CalculatePassengerPosition(dest.x, dest.y, dest.z); - - me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, dest.x, dest.y, dest.z, true, true, isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE); - } - else // Xinef: we can use dest.x, dest.y, dest.z to make offset - { - float x, y, z; - target->GetPosition(x, y, z); - if (e.action.MoveToPos.ContactDistance > 0) - target->GetContactPoint(me, x, y, z, e.action.MoveToPos.ContactDistance); - me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, x + e.target.x, y + e.target.y, z + e.target.z, true, true, isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE); - } - break; - } - case SMART_ACTION_MOVE_TO_POS_TARGET: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - return; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - { - Creature* target = (*itr)->ToCreature(); - target->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, e.target.x, e.target.y, e.target.z, true, true, isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE); - } - } - - delete targets; - break; - } - case SMART_ACTION_RESPAWN_TARGET: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - (*itr)->ToCreature()->Respawn(e.action.RespawnTarget.goRespawnTime); - else if (IsGameObject(*itr)) - { - // Xinef: do not modify respawndelay of already spawned gameobjects QQ - if ((*itr)->ToGameObject()->isSpawnedByDefault()) - (*itr)->ToGameObject()->Respawn(); - else - (*itr)->ToGameObject()->SetRespawnTime(e.action.RespawnTarget.goRespawnTime); - } - } - - delete targets; - break; - } - case SMART_ACTION_CLOSE_GOSSIP: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsPlayer(*itr)) - (*itr)->ToPlayer()->PlayerTalkClass->SendCloseGossip(); - - delete targets; - break; - } - case SMART_ACTION_EQUIP: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (Creature* npc = (*itr)->ToCreature()) - { - uint32 slot[3]; - int8 equipId = (int8)e.action.equip.entry; - if (equipId) + if (e.GetTargetType() == SMART_TARGET_SELF) { - EquipmentInfo const* einfo = sObjectMgr->GetEquipmentInfo(npc->GetEntry(), equipId); - if (!einfo) + me->SetFacingTo((me->HasUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT) && me->GetTransGUID() ? me->GetTransportHomePosition() : me->GetHomePosition()).GetOrientation()); + if (e.action.orientation.quickChange) + me->SetOrientation((me->HasUnitMovementFlag(MOVEMENTFLAG_ONTRANSPORT) && me->GetTransGUID() ? me->GetTransportHomePosition() : me->GetHomePosition()).GetOrientation()); + } + else if (e.GetTargetType() == SMART_TARGET_POSITION) + { + me->SetFacingTo(e.target.o); + if (e.action.orientation.quickChange) + me->SetOrientation(e.target.o); + } + else if (ObjectList* targets = GetTargets(e, unit)) + { + if (!targets->empty()) { - sLog->outError("SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id %u for creature %u", equipId, npc->GetEntry()); + me->SetFacingToObject(*targets->begin()); + if (e.action.orientation.quickChange) + me->SetInFront(*targets->begin()); + } + + delete targets; + } + + break; + } + case SMART_ACTION_PLAYMOVIE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsPlayer(*itr)) + continue; + + (*itr)->ToPlayer()->SendMovieStart(e.action.movie.entry); + } + + delete targets; + break; + } + case SMART_ACTION_MOVE_TO_POS: + { + if (!IsSmart()) + break; + + WorldObject* target = nullptr; + + if (e.GetTargetType() == SMART_TARGET_RANDOM_POINT) + { + if (me) + { + float range = (float)e.target.randomPoint.range; + Position randomPoint; + Position srcPos = { e.target.x, e.target.y, e.target.z, e.target.o }; + me->GetRandomPoint(srcPos, range, randomPoint); + me->GetMotionMaster()->MovePoint( + e.action.MoveToPos.pointId, + randomPoint.m_positionX, + randomPoint.m_positionY, + randomPoint.m_positionZ, + true, + true, + isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE + ); + } + + break; + } + + /*if (e.GetTargetType() == SMART_TARGET_CREATURE_RANGE || e.GetTargetType() == SMART_TARGET_CREATURE_GUID || + e.GetTargetType() == SMART_TARGET_CREATURE_DISTANCE || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_RANGE || + e.GetTargetType() == SMART_TARGET_GAMEOBJECT_GUID || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_DISTANCE || + e.GetTargetType() == SMART_TARGET_CLOSEST_CREATURE || e.GetTargetType() == SMART_TARGET_CLOSEST_GAMEOBJECT || + e.GetTargetType() == SMART_TARGET_OWNER_OR_SUMMONER || e.GetTargetType() == SMART_TARGET_ACTION_INVOKER || + e.GetTargetType() == SMART_TARGET_CLOSEST_ENEMY || e.GetTargetType() == SMART_TARGET_CLOSEST_FRIENDLY || + e.GetTargetType() == SMART_TARGET_SELF || e.GetTargetType() == SMART_TARGET_STORED) // Xinef: bieda i rozpierdol TC)*/ + { + if (ObjectList* targets = GetTargets(e, unit)) + { + // xinef: we want to move to random element + target = acore::Containers::SelectRandomContainerElement(*targets); + delete targets; + } + } + + if (!target) + { + G3D::Vector3 dest(e.target.x, e.target.y, e.target.z); + if (e.action.MoveToPos.transport) + if (TransportBase* trans = me->GetDirectTransport()) + trans->CalculatePassengerPosition(dest.x, dest.y, dest.z); + + me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, dest.x, dest.y, dest.z, true, true, isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE); + } + else // Xinef: we can use dest.x, dest.y, dest.z to make offset + { + float x, y, z; + target->GetPosition(x, y, z); + if (e.action.MoveToPos.ContactDistance > 0) + target->GetContactPoint(me, x, y, z, e.action.MoveToPos.ContactDistance); + me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, x + e.target.x, y + e.target.y, z + e.target.z, true, true, isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE); + } + break; + } + case SMART_ACTION_MOVE_TO_POS_TARGET: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + return; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + Creature* target = (*itr)->ToCreature(); + target->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, e.target.x, e.target.y, e.target.z, true, true, isControlled ? MOTION_SLOT_CONTROLLED : MOTION_SLOT_ACTIVE); + } + } + + delete targets; + break; + } + case SMART_ACTION_RESPAWN_TARGET: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + (*itr)->ToCreature()->Respawn(e.action.RespawnTarget.goRespawnTime); + else if (IsGameObject(*itr)) + { + // Xinef: do not modify respawndelay of already spawned gameobjects QQ + if ((*itr)->ToGameObject()->isSpawnedByDefault()) + (*itr)->ToGameObject()->Respawn(); + else + (*itr)->ToGameObject()->SetRespawnTime(e.action.RespawnTarget.goRespawnTime); + } + } + + delete targets; + break; + } + case SMART_ACTION_CLOSE_GOSSIP: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsPlayer(*itr)) + (*itr)->ToPlayer()->PlayerTalkClass->SendCloseGossip(); + + delete targets; + break; + } + case SMART_ACTION_EQUIP: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Creature* npc = (*itr)->ToCreature()) + { + uint32 slot[3]; + int8 equipId = (int8)e.action.equip.entry; + if (equipId) + { + EquipmentInfo const* einfo = sObjectMgr->GetEquipmentInfo(npc->GetEntry(), equipId); + if (!einfo) + { + sLog->outError("SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id %u for creature %u", equipId, npc->GetEntry()); + break; + } + npc->SetCurrentEquipmentId(equipId); + slot[0] = einfo->ItemEntry[0]; + slot[1] = einfo->ItemEntry[1]; + slot[2] = einfo->ItemEntry[2]; + } + else + { + slot[0] = e.action.equip.slot1; + slot[1] = e.action.equip.slot2; + slot[2] = e.action.equip.slot3; + } + if (!e.action.equip.mask || (e.action.equip.mask & 1)) + npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 0, slot[0]); + if (!e.action.equip.mask || (e.action.equip.mask & 2)) + npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, slot[1]); + if (!e.action.equip.mask || (e.action.equip.mask & 4)) + npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, slot[2]); + } + } + + delete targets; + break; + } + case SMART_ACTION_CREATE_TIMED_EVENT: + { + SmartEvent ne = SmartEvent(); + ne.type = (SMART_EVENT)SMART_EVENT_UPDATE; + ne.event_chance = e.action.timeEvent.chance; + if (!ne.event_chance) ne.event_chance = 100; + + ne.minMaxRepeat.min = e.action.timeEvent.min; + ne.minMaxRepeat.max = e.action.timeEvent.max; + ne.minMaxRepeat.repeatMin = e.action.timeEvent.repeatMin; + ne.minMaxRepeat.repeatMax = e.action.timeEvent.repeatMax; + + ne.event_flags = 0; + if (!ne.minMaxRepeat.repeatMin && !ne.minMaxRepeat.repeatMax) + ne.event_flags |= SMART_EVENT_FLAG_NOT_REPEATABLE; + + SmartAction ac = SmartAction(); + ac.type = (SMART_ACTION)SMART_ACTION_TRIGGER_TIMED_EVENT; + ac.timeEvent.id = e.action.timeEvent.id; + + SmartScriptHolder ev = SmartScriptHolder(); + ev.event = ne; + ev.event_id = e.action.timeEvent.id; + ev.target = e.target; + ev.action = ac; + InitTimer(ev); + mStoredEvents.push_back(ev); + break; + } + case SMART_ACTION_TRIGGER_TIMED_EVENT: + ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, NULL, e.action.timeEvent.id); + + // xinef: remove this event if not repeatable + if (e.event.event_flags & SMART_EVENT_FLAG_NOT_REPEATABLE) + mRemIDs.push_back(e.action.timeEvent.id); + break; + case SMART_ACTION_REMOVE_TIMED_EVENT: + mRemIDs.push_back(e.action.timeEvent.id); + break; + case SMART_ACTION_OVERRIDE_SCRIPT_BASE_OBJECT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + if (!meOrigGUID) + meOrigGUID = me ? me->GetGUID() : 0; + if (!goOrigGUID) + goOrigGUID = go ? go->GetGUID() : 0; + go = nullptr; + me = (*itr)->ToCreature(); break; } - npc->SetCurrentEquipmentId(equipId); - slot[0] = einfo->ItemEntry[0]; - slot[1] = einfo->ItemEntry[1]; - slot[2] = einfo->ItemEntry[2]; - } - else - { - slot[0] = e.action.equip.slot1; - slot[1] = e.action.equip.slot2; - slot[2] = e.action.equip.slot3; - } - if (!e.action.equip.mask || (e.action.equip.mask & 1)) - npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 0, slot[0]); - if (!e.action.equip.mask || (e.action.equip.mask & 2)) - npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, slot[1]); - if (!e.action.equip.mask || (e.action.equip.mask & 4)) - npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, slot[2]); - } - } - - delete targets; - break; - } - case SMART_ACTION_CREATE_TIMED_EVENT: - { - SmartEvent ne = SmartEvent(); - ne.type = (SMART_EVENT)SMART_EVENT_UPDATE; - ne.event_chance = e.action.timeEvent.chance; - if (!ne.event_chance) ne.event_chance = 100; - - ne.minMaxRepeat.min = e.action.timeEvent.min; - ne.minMaxRepeat.max = e.action.timeEvent.max; - ne.minMaxRepeat.repeatMin = e.action.timeEvent.repeatMin; - ne.minMaxRepeat.repeatMax = e.action.timeEvent.repeatMax; - - ne.event_flags = 0; - if (!ne.minMaxRepeat.repeatMin && !ne.minMaxRepeat.repeatMax) - ne.event_flags |= SMART_EVENT_FLAG_NOT_REPEATABLE; - - SmartAction ac = SmartAction(); - ac.type = (SMART_ACTION)SMART_ACTION_TRIGGER_TIMED_EVENT; - ac.timeEvent.id = e.action.timeEvent.id; - - SmartScriptHolder ev = SmartScriptHolder(); - ev.event = ne; - ev.event_id = e.action.timeEvent.id; - ev.target = e.target; - ev.action = ac; - InitTimer(ev); - mStoredEvents.push_back(ev); - break; - } - case SMART_ACTION_TRIGGER_TIMED_EVENT: - ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, NULL, e.action.timeEvent.id); - - // xinef: remove this event if not repeatable - if (e.event.event_flags & SMART_EVENT_FLAG_NOT_REPEATABLE) - mRemIDs.push_back(e.action.timeEvent.id); - break; - case SMART_ACTION_REMOVE_TIMED_EVENT: - mRemIDs.push_back(e.action.timeEvent.id); - break; - case SMART_ACTION_OVERRIDE_SCRIPT_BASE_OBJECT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - { - if (!meOrigGUID) - meOrigGUID = me ? me->GetGUID() : 0; - if (!goOrigGUID) - goOrigGUID = go ? go->GetGUID() : 0; - go = nullptr; - me = (*itr)->ToCreature(); - break; - } - else if (IsGameObject(*itr)) - { - if (!meOrigGUID) - meOrigGUID = me ? me->GetGUID() : 0; - if (!goOrigGUID) - goOrigGUID = go ? go->GetGUID() : 0; - go = (*itr)->ToGameObject(); - me = nullptr; - break; - } - } - - delete targets; - break; - } - case SMART_ACTION_RESET_SCRIPT_BASE_OBJECT: - ResetBaseObject(); - break; - case SMART_ACTION_CALL_SCRIPT_RESET: - OnReset(); - break; - case SMART_ACTION_SET_RANGED_MOVEMENT: - { - if (!IsSmart()) - break; - - float attackDistance = float(e.action.setRangedMovement.distance); - float attackAngle = float(e.action.setRangedMovement.angle) / 180.0f * M_PI; - - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (Creature* target = (*itr)->ToCreature()) - if (IsSmart(target) && target->GetVictim()) - if (CAST_AI(SmartAI, target->AI())->CanCombatMove()) - target->GetMotionMaster()->MoveChase(target->GetVictim(), attackDistance, attackAngle); - - delete targets; - } - break; - } - case SMART_ACTION_CALL_TIMED_ACTIONLIST: - { - if (e.GetTargetType() == SMART_TARGET_NONE) - { - sLog->outErrorDb("SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); - break; - } - - if (ObjectList* targets = GetTargets(e, unit)) - { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (Creature* target = (*itr)->ToCreature()) - { - if (IsSmart(target)) - CAST_AI(SmartAI, target->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); - } - else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - CAST_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); - } - } - - delete targets; - } - break; - } - case SMART_ACTION_SET_NPC_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToUnit()->SetUInt32Value(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_ADD_NPC_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToUnit()->SetFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_REMOVE_NPC_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToUnit()->RemoveFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_CROSS_CAST: - { - ObjectList* casters = GetTargets(CreateSmartEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.crossCast.targetType, e.action.crossCast.targetParam1, e.action.crossCast.targetParam2, e.action.crossCast.targetParam3, 0, 0), unit); - if (!casters) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - { - delete casters; // casters already validated, delete now - break; - } - - for (ObjectList::const_iterator itr = casters->begin(); itr != casters->end(); ++itr) - { - if (!IsUnit(*itr)) - continue; - - bool interruptedSpell = false; - - for (ObjectList::const_iterator it = targets->begin(); it != targets->end(); ++it) - { - if (!IsUnit(*it)) - continue; - - if (!(e.action.cast.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*it)->ToUnit()->HasAura(e.action.cast.spell)) - { - if (!interruptedSpell && e.action.cast.flags & SMARTCAST_INTERRUPT_PREVIOUS) + else if (IsGameObject(*itr)) { - (*itr)->ToUnit()->InterruptNonMeleeSpells(false); - interruptedSpell = true; + if (!meOrigGUID) + meOrigGUID = me ? me->GetGUID() : 0; + if (!goOrigGUID) + goOrigGUID = go ? go->GetGUID() : 0; + go = (*itr)->ToGameObject(); + me = nullptr; + break; + } + } + + delete targets; + break; + } + case SMART_ACTION_RESET_SCRIPT_BASE_OBJECT: + ResetBaseObject(); + break; + case SMART_ACTION_CALL_SCRIPT_RESET: + OnReset(); + break; + case SMART_ACTION_SET_RANGED_MOVEMENT: + { + if (!IsSmart()) + break; + + float attackDistance = float(e.action.setRangedMovement.distance); + float attackAngle = float(e.action.setRangedMovement.angle) / 180.0f * M_PI; + + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (Creature* target = (*itr)->ToCreature()) + if (IsSmart(target) && target->GetVictim()) + if (CAST_AI(SmartAI, target->AI())->CanCombatMove()) + target->GetMotionMaster()->MoveChase(target->GetVictim(), attackDistance, attackAngle); + + delete targets; + } + break; + } + case SMART_ACTION_CALL_TIMED_ACTIONLIST: + { + if (e.GetTargetType() == SMART_TARGET_NONE) + { + sLog->outErrorDb("SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + break; + } + + if (ObjectList* targets = GetTargets(e, unit)) + { + for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Creature* target = (*itr)->ToCreature()) + { + if (IsSmart(target)) + CAST_AI(SmartAI, target->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); + } + else if (GameObject* goTarget = (*itr)->ToGameObject()) + { + if (IsSmartGO(goTarget)) + CAST_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); + } } - (*itr)->ToUnit()->CastSpell((*it)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); + delete targets; } - //else - // TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "Spell %u not casted because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (Guid: " UI64FMTD " Entry: %u Type: %u) already has the aura", e.action.cast.spell, (*it)->GetGUID(), (*it)->GetEntry(), uint32((*it)->GetTypeId())); + break; } - } - - delete targets; - delete casters; - break; - } - case SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST: - { - uint32 actions[SMART_ACTION_PARAM_COUNT]; - actions[0] = e.action.randTimedActionList.entry1; - actions[1] = e.action.randTimedActionList.entry2; - actions[2] = e.action.randTimedActionList.entry3; - actions[3] = e.action.randTimedActionList.entry4; - actions[4] = e.action.randTimedActionList.entry5; - actions[5] = e.action.randTimedActionList.entry6; - uint32 temp[SMART_ACTION_PARAM_COUNT]; - uint32 count = 0; - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) - { - if (actions[i] > 0) + case SMART_ACTION_SET_NPC_FLAG: { - temp[count] = actions[i]; - ++count; + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToUnit()->SetUInt32Value(UNIT_NPC_FLAGS, e.action.unitFlag.flag); + + delete targets; + break; } - } - - if (count == 0) - break; - - uint32 id = temp[urand(0, count - 1)]; - if (e.GetTargetType() == SMART_TARGET_NONE) - { - sLog->outErrorDb("SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); - break; - } - - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_ADD_NPC_FLAG: { - if (Creature* target = (*itr)->ToCreature()) - { - if (IsSmart(target)) - CAST_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); - } - else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - CAST_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); - } + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToUnit()->SetFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); + + delete targets; + break; } - - delete targets; - } - break; - } - case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: - { - uint32 id = urand(e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2); - if (e.GetTargetType() == SMART_TARGET_NONE) - { - sLog->outErrorDb("SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); - break; - } - - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + case SMART_ACTION_REMOVE_NPC_FLAG: { - if (Creature* target = (*itr)->ToCreature()) - { - if (IsSmart(target)) - CAST_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); - } - else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - CAST_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); - } + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToUnit()->RemoveFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); + + delete targets; + break; } - - delete targets; - } - break; - } - case SMART_ACTION_ACTIVATE_TAXI: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsPlayer(*itr)) - (*itr)->ToPlayer()->ActivateTaxiPathTo(e.action.taxi.id); - - delete targets; - break; - } - case SMART_ACTION_RANDOM_MOVE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - bool foundTarget = false; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature((*itr))) + case SMART_ACTION_CROSS_CAST: { - foundTarget = true; + ObjectList* casters = GetTargets(CreateSmartEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.crossCast.targetType, e.action.crossCast.targetParam1, e.action.crossCast.targetParam2, e.action.crossCast.targetParam3, 0, 0), unit); + if (!casters) + break; - if (e.action.moveRandom.distance) - (*itr)->ToCreature()->GetMotionMaster()->MoveRandom((float)e.action.moveRandom.distance); + ObjectList* targets = GetTargets(e, unit); + if (!targets) + { + delete casters; // casters already validated, delete now + break; + } + + for (ObjectList::const_iterator itr = casters->begin(); itr != casters->end(); ++itr) + { + if (!IsUnit(*itr)) + continue; + + bool interruptedSpell = false; + + for (ObjectList::const_iterator it = targets->begin(); it != targets->end(); ++it) + { + if (!IsUnit(*it)) + continue; + + if (!(e.action.cast.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*it)->ToUnit()->HasAura(e.action.cast.spell)) + { + if (!interruptedSpell && e.action.cast.flags & SMARTCAST_INTERRUPT_PREVIOUS) + { + (*itr)->ToUnit()->InterruptNonMeleeSpells(false); + interruptedSpell = true; + } + + (*itr)->ToUnit()->CastSpell((*it)->ToUnit(), e.action.cast.spell, (e.action.cast.flags & SMARTCAST_TRIGGERED)); + } + //else + // TC_LOG_DEBUG(LOG_FILTER_DATABASE_AI, "Spell %u not casted because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (Guid: " UI64FMTD " Entry: %u Type: %u) already has the aura", e.action.cast.spell, (*it)->GetGUID(), (*it)->GetEntry(), uint32((*it)->GetTypeId())); + } + } + + delete targets; + delete casters; + break; + } + case SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST: + { + uint32 actions[SMART_ACTION_PARAM_COUNT]; + actions[0] = e.action.randTimedActionList.entry1; + actions[1] = e.action.randTimedActionList.entry2; + actions[2] = e.action.randTimedActionList.entry3; + actions[3] = e.action.randTimedActionList.entry4; + actions[4] = e.action.randTimedActionList.entry5; + actions[5] = e.action.randTimedActionList.entry6; + uint32 temp[SMART_ACTION_PARAM_COUNT]; + uint32 count = 0; + for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) + { + if (actions[i] > 0) + { + temp[count] = actions[i]; + ++count; + } + } + + if (count == 0) + break; + + uint32 id = temp[urand(0, count - 1)]; + if (e.GetTargetType() == SMART_TARGET_NONE) + { + sLog->outErrorDb("SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + break; + } + + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Creature* target = (*itr)->ToCreature()) + { + if (IsSmart(target)) + CAST_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); + } + else if (GameObject* goTarget = (*itr)->ToGameObject()) + { + if (IsSmartGO(goTarget)) + CAST_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); + } + } + + delete targets; + } + break; + } + case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: + { + uint32 id = urand(e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2); + if (e.GetTargetType() == SMART_TARGET_NONE) + { + sLog->outErrorDb("SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + break; + } + + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Creature* target = (*itr)->ToCreature()) + { + if (IsSmart(target)) + CAST_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); + } + else if (GameObject* goTarget = (*itr)->ToGameObject()) + { + if (IsSmartGO(goTarget)) + CAST_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); + } + } + + delete targets; + } + break; + } + case SMART_ACTION_ACTIVATE_TAXI: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsPlayer(*itr)) + (*itr)->ToPlayer()->ActivateTaxiPathTo(e.action.taxi.id); + + delete targets; + break; + } + case SMART_ACTION_RANDOM_MOVE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + bool foundTarget = false; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature((*itr))) + { + foundTarget = true; + + if (e.action.moveRandom.distance) + (*itr)->ToCreature()->GetMotionMaster()->MoveRandom((float)e.action.moveRandom.distance); + else + (*itr)->ToCreature()->GetMotionMaster()->MoveIdle(); + } + } + + if (!foundTarget && me && IsCreature(me)) + { + if (e.action.moveRandom.distance) + me->GetMotionMaster()->MoveRandom((float)e.action.moveRandom.distance); + else + me->GetMotionMaster()->MoveIdle(); + } + + delete targets; + break; + } + case SMART_ACTION_SET_UNIT_FIELD_BYTES_1: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetByteFlag(UNIT_FIELD_BYTES_1, e.action.setunitByte.type, e.action.setunitByte.byte1); + + delete targets; + break; + } + case SMART_ACTION_REMOVE_UNIT_FIELD_BYTES_1: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->RemoveByteFlag(UNIT_FIELD_BYTES_1, e.action.delunitByte.type, e.action.delunitByte.byte1); + + delete targets; + break; + } + case SMART_ACTION_INTERRUPT_SPELL: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->InterruptNonMeleeSpells(e.action.interruptSpellCasting.withDelayed, e.action.interruptSpellCasting.spell_id, e.action.interruptSpellCasting.withInstant); + + delete targets; + break; + } + case SMART_ACTION_SEND_GO_CUSTOM_ANIM: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsGameObject(*itr)) + (*itr)->ToGameObject()->SendCustomAnim(e.action.sendGoCustomAnim.anim); + + delete targets; + break; + } + case SMART_ACTION_SET_DYNAMIC_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetUInt32Value(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); + + delete targets; + break; + } + case SMART_ACTION_ADD_DYNAMIC_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); + + delete targets; + break; + } + case SMART_ACTION_REMOVE_DYNAMIC_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->RemoveFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); + + delete targets; + break; + } + case SMART_ACTION_JUMP_TO_POS: + { + if (e.GetTargetType() == SMART_TARGET_RANDOM_POINT) + { + if (me) + { + float range = (float)e.target.randomPoint.range; + Position randomPoint; + Position srcPos = { e.target.x, e.target.y, e.target.z, e.target.o }; + me->GetRandomPoint(srcPos, range, randomPoint); + me->GetMotionMaster()->MoveJump(randomPoint, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); + } + + break; + } + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + // xinef: my implementation + if (e.action.jump.selfJump) + { + if (WorldObject* target = acore::Containers::SelectRandomContainerElement(*targets)) + if (me) + me->GetMotionMaster()->MoveJump(target->GetPositionX() + e.target.x, target->GetPositionY() + e.target.y, target->GetPositionZ() + e.target.z, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); + } else - (*itr)->ToCreature()->GetMotionMaster()->MoveIdle(); - } - } - - if (!foundTarget && me && IsCreature(me)) - { - if (e.action.moveRandom.distance) - me->GetMotionMaster()->MoveRandom((float)e.action.moveRandom.distance); - else - me->GetMotionMaster()->MoveIdle(); - } - - delete targets; - break; - } - case SMART_ACTION_SET_UNIT_FIELD_BYTES_1: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetByteFlag(UNIT_FIELD_BYTES_1, e.action.setunitByte.type, e.action.setunitByte.byte1); - - delete targets; - break; - } - case SMART_ACTION_REMOVE_UNIT_FIELD_BYTES_1: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveByteFlag(UNIT_FIELD_BYTES_1, e.action.delunitByte.type, e.action.delunitByte.byte1); - - delete targets; - break; - } - case SMART_ACTION_INTERRUPT_SPELL: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->InterruptNonMeleeSpells(e.action.interruptSpellCasting.withDelayed, e.action.interruptSpellCasting.spell_id, e.action.interruptSpellCasting.withInstant); - - delete targets; - break; - } - case SMART_ACTION_SEND_GO_CUSTOM_ANIM: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SendCustomAnim(e.action.sendGoCustomAnim.anim); - - delete targets; - break; - } - case SMART_ACTION_SET_DYNAMIC_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetUInt32Value(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_ADD_DYNAMIC_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_REMOVE_DYNAMIC_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_JUMP_TO_POS: - { - if (e.GetTargetType() == SMART_TARGET_RANDOM_POINT) - { - if (me) - { - float range = (float)e.target.randomPoint.range; - Position randomPoint; - Position srcPos = { e.target.x, e.target.y, e.target.z, e.target.o }; - me->GetRandomPoint(srcPos, range, randomPoint); - me->GetMotionMaster()->MoveJump(randomPoint, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); - } - - break; - } - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - // xinef: my implementation - if (e.action.jump.selfJump) - { - if (WorldObject* target = acore::Containers::SelectRandomContainerElement(*targets)) - if (me) - me->GetMotionMaster()->MoveJump(target->GetPositionX() + e.target.x, target->GetPositionY() + e.target.y, target->GetPositionZ() + e.target.z, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); - } - else - { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (WorldObject* obj = (*itr)) { - if (Creature* creature = obj->ToCreature()) - creature->GetMotionMaster()->MoveJump(e.target.x, e.target.y, e.target.z, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (WorldObject* obj = (*itr)) + { + if (Creature* creature = obj->ToCreature()) + creature->GetMotionMaster()->MoveJump(e.target.x, e.target.y, e.target.z, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); + } } - } - delete targets; - break; - } - case SMART_ACTION_GO_SET_LOOT_STATE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetLootState((LootState)e.action.setGoLootState.state); - - delete targets; - break; - } - case SMART_ACTION_SEND_TARGET_TO_TARGET: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - ObjectList* storedTargets = GetTargetList(e.action.sendTargetToTarget.id); - if (!storedTargets) - { - delete targets; - break; - } - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - { - if (SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI())) - ai->GetScript()->StoreTargetList(new ObjectList(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list - else - sLog->outErrorDb("SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartAI, skipping"); + delete targets; + break; } - else if (IsGameObject(*itr)) + case SMART_ACTION_GO_SET_LOOT_STATE: { - if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, (*itr)->ToGameObject()->AI())) - ai->GetScript()->StoreTargetList(new ObjectList(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list - else - sLog->outErrorDb("SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartGameObjectAI, skipping"); - } - } + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - delete targets; - break; - } - case SMART_ACTION_SEND_GOSSIP_MENU: - { - if (!GetBaseObject()) - break; + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsGameObject(*itr)) + (*itr)->ToGameObject()->SetLootState((LootState)e.action.setGoLootState.state); + + delete targets; + break; + } + case SMART_ACTION_SEND_TARGET_TO_TARGET: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + ObjectList* storedTargets = GetTargetList(e.action.sendTargetToTarget.id); + if (!storedTargets) + { + delete targets; + break; + } + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + { + if (SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI())) + ai->GetScript()->StoreTargetList(new ObjectList(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list + else + sLog->outErrorDb("SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartAI, skipping"); + } + else if (IsGameObject(*itr)) + { + if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, (*itr)->ToGameObject()->AI())) + ai->GetScript()->StoreTargetList(new ObjectList(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list + else + sLog->outErrorDb("SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartGameObjectAI, skipping"); + } + } + + delete targets; + break; + } + case SMART_ACTION_SEND_GOSSIP_MENU: + { + if (!GetBaseObject()) + break; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SEND_GOSSIP_MENU: gossipMenuId %d, gossipNpcTextId %d", - e.action.sendGossipMenu.gossipMenuId, e.action.sendGossipMenu.gossipNpcTextId); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::ProcessAction:: SMART_ACTION_SEND_GOSSIP_MENU: gossipMenuId %d, gossipNpcTextId %d", + e.action.sendGossipMenu.gossipMenuId, e.action.sendGossipMenu.gossipNpcTextId); #endif - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (Player* player = (*itr)->ToPlayer()) - { - if (e.action.sendGossipMenu.gossipMenuId) - player->PrepareGossipMenu(GetBaseObject(), e.action.sendGossipMenu.gossipMenuId, true); - else - ClearGossipMenuFor(player); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (Player* player = (*itr)->ToPlayer()) + { + if (e.action.sendGossipMenu.gossipMenuId) + player->PrepareGossipMenu(GetBaseObject(), e.action.sendGossipMenu.gossipMenuId, true); + else + ClearGossipMenuFor(player); - SendGossipMenuFor(player, e.action.sendGossipMenu.gossipNpcTextId, GetBaseObject()->GetGUID()); + SendGossipMenuFor(player, e.action.sendGossipMenu.gossipNpcTextId, GetBaseObject()->GetGUID()); + } + + delete targets; + break; } + case SMART_ACTION_SET_HOME_POS: + { + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + float x, y, z, o; + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + { + if (e.action.setHomePos.spawnPos) + { + (*itr)->ToCreature()->GetRespawnPosition(x, y, z, &o); + (*itr)->ToCreature()->SetHomePosition(x, y, z, o); + } + else + (*itr)->ToCreature()->SetHomePosition((*itr)->GetPositionX(), (*itr)->GetPositionY(), (*itr)->GetPositionZ(), (*itr)->GetOrientation()); - delete targets; - break; - } - case SMART_ACTION_SET_HOME_POS: - { - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - float x, y, z, o; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) + } + delete targets; + } + else if (me && e.GetTargetType() == SMART_TARGET_POSITION) { if (e.action.setHomePos.spawnPos) { - (*itr)->ToCreature()->GetRespawnPosition(x, y, z, &o); - (*itr)->ToCreature()->SetHomePosition(x, y, z, o); + float x, y, z, o; + me->GetRespawnPosition(x, y, z, &o); + me->SetHomePosition(x, y, z, o); } else - (*itr)->ToCreature()->SetHomePosition((*itr)->GetPositionX(), (*itr)->GetPositionY(), (*itr)->GetPositionZ(), (*itr)->GetOrientation()); - + me->SetHomePosition(e.target.x, e.target.y, e.target.z, e.target.o); } - delete targets; - } - else if (me && e.GetTargetType() == SMART_TARGET_POSITION) - { - if (e.action.setHomePos.spawnPos) - { - float x, y, z, o; - me->GetRespawnPosition(x, y, z, &o); - me->SetHomePosition(x, y, z, o); + break; } - else - me->SetHomePosition(e.target.x, e.target.y, e.target.z, e.target.o); - } + /*{ + ObjectList* movers = GetTargets(CreateSmartEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.sethome.targetType, e.action.sethome.targetParam1, e.action.sethome.targetParam2, e.action.sethome.targetParam3, 0), unit); + if (!movers) break; - } - /*{ - ObjectList* movers = GetTargets(CreateSmartEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.sethome.targetType, e.action.sethome.targetParam1, e.action.sethome.targetParam2, e.action.sethome.targetParam3, 0), unit); - if (!movers) - break; - if (e.GetTargetType() == SMART_TARGET_POSITION) - { - for (ObjectList::const_iterator itr = movers->begin(); itr != movers->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetHomePosition(e.target.x, e.target.y, e.target.z, e.target.o); - } - else if (ObjectList* targets = GetTargets(e, unit)) - { - if (WorldObject* target = targets->front()) - for (ObjectList::const_iterator itr = movers->begin(); itr != movers->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetHomePosition(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation()); - - delete targets; - } - - delete movers; - break; - }*/ - case SMART_ACTION_SET_HEALTH_REGEN: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetRegeneratingHealth(e.action.setHealthRegen.regenHealth); - - delete targets; - break; - } - case SMART_ACTION_SET_ROOT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetControlled(e.action.setRoot.root, UNIT_STATE_ROOT); - - delete targets; - break; - } - case SMART_ACTION_SET_GO_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetUInt32Value(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_ADD_GO_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_REMOVE_GO_FLAG: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->RemoveFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - - delete targets; - break; - } - case SMART_ACTION_SUMMON_CREATURE_GROUP: - { - std::list summonList; - GetBaseObject()->SummonCreatureGroup(e.action.creatureGroup.group, &summonList); - - for (std::list::const_iterator itr = summonList.begin(); itr != summonList.end(); ++itr) + if (e.GetTargetType() == SMART_TARGET_POSITION) { - if (unit && e.action.creatureGroup.attackInvoker) - (*itr)->AI()->AttackStart(unit); - else if (me && e.action.creatureGroup.attackScriptOwner) - (*itr)->AI()->AttackStart(me); + for (ObjectList::const_iterator itr = movers->begin(); itr != movers->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->SetHomePosition(e.target.x, e.target.y, e.target.z, e.target.o); + } + else if (ObjectList* targets = GetTargets(e, unit)) + { + if (WorldObject* target = targets->front()) + for (ObjectList::const_iterator itr = movers->begin(); itr != movers->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->SetHomePosition(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation()); + + delete targets; } + delete movers; break; - } - case SMART_ACTION_SET_POWER: - { - ObjectList* targets = GetTargets(e, unit); - - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), e.action.power.newPower); - - delete targets; - break; - } - case SMART_ACTION_ADD_POWER: - { - ObjectList* targets = GetTargets(e, unit); - - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), (*itr)->ToUnit()->GetPower(Powers(e.action.power.powerType)) + e.action.power.newPower); - - delete targets; - break; - } - case SMART_ACTION_REMOVE_POWER: - { - ObjectList* targets = GetTargets(e, unit); - - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), (*itr)->ToUnit()->GetPower(Powers(e.action.power.powerType)) - e.action.power.newPower); - - delete targets; - break; - } - case SMART_ACTION_GAME_EVENT_STOP: - { - uint32 eventId = e.action.gameEventStop.id; - if (!sGameEventMgr->IsActiveEvent(eventId)) - { - sLog->outError("SmartScript::ProcessAction: At case SMART_ACTION_GAME_EVENT_STOP, inactive event (id: %u)", eventId); - break; - } - sGameEventMgr->StopEvent(eventId, true); - break; - } - case SMART_ACTION_GAME_EVENT_START: - { - uint32 eventId = e.action.gameEventStart.id; - if (sGameEventMgr->IsActiveEvent(eventId)) - { - sLog->outError("SmartScript::ProcessAction: At case SMART_ACTION_GAME_EVENT_START, already activated event (id: %u)", eventId); - break; - } - sGameEventMgr->StartEvent(eventId, true); - break; - } - case SMART_ACTION_START_CLOSEST_WAYPOINT: - { - uint32 waypoints[SMART_ACTION_PARAM_COUNT]; - waypoints[0] = e.action.closestWaypointFromList.wp1; - waypoints[1] = e.action.closestWaypointFromList.wp2; - waypoints[2] = e.action.closestWaypointFromList.wp3; - waypoints[3] = e.action.closestWaypointFromList.wp4; - waypoints[4] = e.action.closestWaypointFromList.wp5; - waypoints[5] = e.action.closestWaypointFromList.wp6; - float distanceToClosest = std::numeric_limits::max(); - WayPoint* closestWp = nullptr; - - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + }*/ + case SMART_ACTION_SET_HEALTH_REGEN: { - if (Creature* target = (*itr)->ToCreature()) + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->SetRegeneratingHealth(e.action.setHealthRegen.regenHealth); + + delete targets; + break; + } + case SMART_ACTION_SET_ROOT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->SetControlled(e.action.setRoot.root, UNIT_STATE_ROOT); + + delete targets; + break; + } + case SMART_ACTION_SET_GO_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsGameObject(*itr)) + (*itr)->ToGameObject()->SetUInt32Value(GAMEOBJECT_FLAGS, e.action.goFlag.flag); + + delete targets; + break; + } + case SMART_ACTION_ADD_GO_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsGameObject(*itr)) + (*itr)->ToGameObject()->SetFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); + + delete targets; + break; + } + case SMART_ACTION_REMOVE_GO_FLAG: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsGameObject(*itr)) + (*itr)->ToGameObject()->RemoveFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); + + delete targets; + break; + } + case SMART_ACTION_SUMMON_CREATURE_GROUP: + { + std::list summonList; + GetBaseObject()->SummonCreatureGroup(e.action.creatureGroup.group, &summonList); + + for (std::list::const_iterator itr = summonList.begin(); itr != summonList.end(); ++itr) { - if (IsSmart(target)) - { - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) - { - if (!waypoints[i]) - continue; - - WPPath* path = sSmartWaypointMgr->GetPath(waypoints[i]); - - if (!path || path->empty()) - continue; - - WPPath::const_iterator itrWp = path->find(0); - - if (itrWp != path->end()) - { - if (WayPoint* wp = itrWp->second) - { - float distToThisPath = target->GetDistance(wp->x, wp->y, wp->z); - - if (distToThisPath < distanceToClosest) - { - distanceToClosest = distToThisPath; - closestWp = wp; - } - } - } - } - - if (closestWp) - CAST_AI(SmartAI, target->AI())->StartPath(false, closestWp->id, true); - } + if (unit && e.action.creatureGroup.attackInvoker) + (*itr)->AI()->AttackStart(unit); + else if (me && e.action.creatureGroup.attackScriptOwner) + (*itr)->AI()->AttackStart(me); } + + break; } - - delete targets; - } - break; - } - case SMART_ACTION_SET_GO_STATE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetGoState((GOState)e.action.goState.state); - - delete targets; - break; - } - case SMART_ACTION_EXIT_VEHICLE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->ExitVehicle(); - - delete targets; - break; - } - case SMART_ACTION_SET_UNIT_MOVEMENT_FLAGS: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) + case SMART_ACTION_SET_POWER: { - (*itr)->ToUnit()->SetUnitMovementFlags(e.action.movementFlag.flag); - (*itr)->ToUnit()->SendMovementFlagUpdate(); + ObjectList* targets = GetTargets(e, unit); + + if (targets) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), e.action.power.newPower); + + delete targets; + break; } - - delete targets; - break; - } - case SMART_ACTION_SET_COMBAT_DISTANCE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->m_CombatDistance = e.action.combatDistance.dist; - - delete targets; - break; - } - case SMART_ACTION_SET_CASTER_COMBAT_DIST: - { - if (e.action.casterDistance.reset) - RestoreCasterMaxDist(); - else - SetCasterActualDist(e.action.casterDistance.dist); - - if (me->GetVictim() && me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) - me->GetMotionMaster()->MoveChase(me->GetVictim(), GetCasterActualDist()); - break; - } - case SMART_ACTION_SET_SIGHT_DIST: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->m_SightDistance = e.action.sightDistance.dist; - - delete targets; - break; - } - case SMART_ACTION_FLEE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->GetMotionMaster()->MoveFleeing(me, e.action.flee.withEmote); - - delete targets; - break; - } - case SMART_ACTION_ADD_THREAT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - me->AddThreat((*itr)->ToUnit(), (float)e.action.threatPCT.threatINC - (float)e.action.threatPCT.threatDEC); - - delete targets; - break; - } - case SMART_ACTION_LOAD_EQUIPMENT: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->LoadEquipment(e.action.loadEquipment.id, e.action.loadEquipment.force); - - delete targets; - break; - } - case SMART_ACTION_TRIGGER_RANDOM_TIMED_EVENT: - { - uint32 eventId = urand(e.action.randomTimedEvent.minId, e.action.randomTimedEvent.maxId); - ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, NULL, eventId); - break; - } - case SMART_ACTION_SET_HOVER: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetHover(e.action.setHover.state); - - delete targets; - break; - } - case SMART_ACTION_ADD_IMMUNITY: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->ApplySpellImmune(e.action.immunity.id, e.action.immunity.type, e.action.immunity.value, true); - - delete targets; - break; - } - case SMART_ACTION_REMOVE_IMMUNITY: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->ApplySpellImmune(e.action.immunity.id, e.action.immunity.type, e.action.immunity.value, false); - - delete targets; - break; - } - case SMART_ACTION_FALL: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->GetMotionMaster()->MoveFall(); - - delete targets; - break; - } - case SMART_ACTION_SET_EVENT_FLAG_RESET: - { - SetPhaseReset(e.action.setActive.state); - break; - } - case SMART_ACTION_REMOVE_ALL_GAMEOBJECTS: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveAllGameObjects(); - - delete targets; - break; - } - case SMART_ACTION_STOP_MOTION: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) + case SMART_ACTION_ADD_POWER: { - if (e.action.stopMotion.stopMovement) - (*itr)->ToUnit()->StopMoving(); - if (e.action.stopMotion.movementExpired) - (*itr)->ToUnit()->GetMotionMaster()->MovementExpired(); + ObjectList* targets = GetTargets(e, unit); + + if (targets) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), (*itr)->ToUnit()->GetPower(Powers(e.action.power.powerType)) + e.action.power.newPower); + + delete targets; + break; } + case SMART_ACTION_REMOVE_POWER: + { + ObjectList* targets = GetTargets(e, unit); - delete targets; - break; - } - case SMART_ACTION_NO_ENVIRONMENT_UPDATE: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + if (targets) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), (*itr)->ToUnit()->GetPower(Powers(e.action.power.powerType)) - e.action.power.newPower); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->AddUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD); - - delete targets; - break; - } - case SMART_ACTION_ZONE_UNDER_ATTACK: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - if (Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself()) + delete targets; + break; + } + case SMART_ACTION_GAME_EVENT_STOP: + { + uint32 eventId = e.action.gameEventStop.id; + if (!sGameEventMgr->IsActiveEvent(eventId)) { - me->SendZoneUnderAttackMessage(player); + sLog->outError("SmartScript::ProcessAction: At case SMART_ACTION_GAME_EVENT_STOP, inactive event (id: %u)", eventId); break; } - - delete targets; - break; - } - case SMART_ACTION_LOAD_GRID: - { - if (me && me->FindMap()) - me->FindMap()->LoadGrid(e.target.x, e.target.y); - break; - } - case SMART_ACTION_PLAYER_TALK: - { - ObjectList* targets = GetTargets(e, unit); - char const* text = sObjectMgr->GetAcoreString(e.action.playerTalk.textId, DEFAULT_LOCALE); - - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsPlayer(*itr)) - !e.action.playerTalk.flag ? (*itr)->ToPlayer()->Say(text, LANG_UNIVERSAL) : (*itr)->ToPlayer()->Yell(text, LANG_UNIVERSAL); - - delete targets; - break; - } - case SMART_ACTION_CUSTOM_CAST: - { - if (!me) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsUnit(*itr)) - { - if (e.action.castCustom.flags & SMARTCAST_INTERRUPT_PREVIOUS) - me->InterruptNonMeleeSpells(false); - - if (e.action.castCustom.flags & SMARTCAST_COMBAT_MOVE) - { - // If cast flag SMARTCAST_COMBAT_MOVE is set combat movement will not be allowed - // unless target is outside spell range, out of mana, or LOS. - - bool _allowMove = false; - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(e.action.castCustom.spell); - int32 mana = me->GetPower(POWER_MANA); - - if (me->GetDistance((*itr)->ToUnit()) > spellInfo->GetMaxRange(true) || - me->GetDistance((*itr)->ToUnit()) < spellInfo->GetMinRange(true) || - !me->IsWithinLOSInMap((*itr)->ToUnit()) || - mana < spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask())) - _allowMove = true; - - CAST_AI(SmartAI, me->AI())->SetCombatMove(_allowMove); - } - - if (!(e.action.castCustom.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.castCustom.spell)) - { - CustomSpellValues values; - if (e.action.castCustom.bp1) - values.AddSpellMod(SPELLVALUE_BASE_POINT0, e.action.castCustom.bp1); - if (e.action.castCustom.bp2) - values.AddSpellMod(SPELLVALUE_BASE_POINT1, e.action.castCustom.bp2); - if (e.action.castCustom.bp3) - values.AddSpellMod(SPELLVALUE_BASE_POINT2, e.action.castCustom.bp3); - me->CastCustomSpell(e.action.castCustom.spell, values, (*itr)->ToUnit(), (e.action.castCustom.flags & SMARTCAST_TRIGGERED) ? TRIGGERED_FULL_MASK : TRIGGERED_NONE); - } + sGameEventMgr->StopEvent(eventId, true); + break; } - } - delete targets; - break; - } - case SMART_ACTION_VORTEX_SUMMON: - { - if (!me) - break; - - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - TempSummonType summon_type = (e.action.summonVortex.summonDuration > 0) ? TEMPSUMMON_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN; - - float a = static_cast(e.action.summonVortex.a); - float k = static_cast(e.action.summonVortex.k) / 1000.0f; - float r_max = static_cast(e.action.summonVortex.r_max); - float delta_phi = M_PI * static_cast(e.action.summonVortex.phi_delta) / 180.0f; - - // r(phi) = a * e ^ (k * phi) - // r(phi + delta_phi) = a * e ^ (k * (phi + delta_phi)) - // r(phi + delta_phi) = a * e ^ (k * phi) * e ^ (k * delta_phi) - // r(phi + delta_phi) = r(phi) * e ^ (k * delta_phi) - float factor = std::exp(k * delta_phi); - - // r(0) = a * e ^ (k * 0) = a * e ^ 0 = a * 1 = a - float summonRadius = a; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - // Offset by orientation, should not count into radius calculation, - // but is needed for vortex direction (polar coordinates) - float phi = (*itr)->GetOrientation(); - - do + case SMART_ACTION_GAME_EVENT_START: { - Position summonPosition(**itr); - summonPosition.RelocatePolarOffset(phi, summonRadius); - - me->SummonCreature(e.action.summonVortex.summonEntry, summonPosition, summon_type, e.action.summonVortex.summonDuration); - - phi += delta_phi; - summonRadius *= factor; - } while (summonRadius <= r_max); - } - - delete targets; - break; - } - case SMART_ACTION_CONE_SUMMON: - { - if (!me) - break; - - TempSummonType spawnType = (e.action.coneSummon.summonDuration > 0) ? TEMPSUMMON_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN; - - float distInARow = static_cast(e.action.coneSummon.distanceBetweenSummons); - float coneAngle = static_cast(e.action.coneSummon.coneAngle) * M_PI / 180.0f; - - for (uint32 radius = 0; radius <= e.action.coneSummon.coneLength; radius += e.action.coneSummon.distanceBetweenRings) - { - float deltaAngle = 0.0f; - if (radius > 0) - deltaAngle = distInARow / radius; - - uint32 count = 1; - if (deltaAngle > 0) - count += coneAngle / deltaAngle; - - float currentAngle = -static_cast(count) * deltaAngle / 2.0f; - - if (e.GetTargetType() == SMART_TARGET_SELF || e.GetTargetType() == SMART_TARGET_NONE) - currentAngle += G3D::fuzzyGt(e.target.o, 0.0f) ? (e.target.o - me->GetOrientation()) : 0.0f; - else if (ObjectList* targets = GetTargets(e, unit)) + uint32 eventId = e.action.gameEventStart.id; + if (sGameEventMgr->IsActiveEvent(eventId)) + { + sLog->outError("SmartScript::ProcessAction: At case SMART_ACTION_GAME_EVENT_START, already activated event (id: %u)", eventId); + break; + } + sGameEventMgr->StartEvent(eventId, true); + break; + } + case SMART_ACTION_START_CLOSEST_WAYPOINT: { - currentAngle += (me->GetAngle(targets->front()) - me->GetOrientation()); + uint32 waypoints[SMART_ACTION_PARAM_COUNT]; + waypoints[0] = e.action.closestWaypointFromList.wp1; + waypoints[1] = e.action.closestWaypointFromList.wp2; + waypoints[2] = e.action.closestWaypointFromList.wp3; + waypoints[3] = e.action.closestWaypointFromList.wp4; + waypoints[4] = e.action.closestWaypointFromList.wp5; + waypoints[5] = e.action.closestWaypointFromList.wp6; + float distanceToClosest = std::numeric_limits::max(); + WayPoint* closestWp = nullptr; + + ObjectList* targets = GetTargets(e, unit); + if (targets) + { + for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Creature* target = (*itr)->ToCreature()) + { + if (IsSmart(target)) + { + for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) + { + if (!waypoints[i]) + continue; + + WPPath* path = sSmartWaypointMgr->GetPath(waypoints[i]); + + if (!path || path->empty()) + continue; + + WPPath::const_iterator itrWp = path->find(0); + + if (itrWp != path->end()) + { + if (WayPoint* wp = itrWp->second) + { + float distToThisPath = target->GetDistance(wp->x, wp->y, wp->z); + + if (distToThisPath < distanceToClosest) + { + distanceToClosest = distToThisPath; + closestWp = wp; + } + } + } + } + + if (closestWp) + CAST_AI(SmartAI, target->AI())->StartPath(false, closestWp->id, true); + } + } + } + + delete targets; + } + break; + } + case SMART_ACTION_SET_GO_STATE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsGameObject(*itr)) + (*itr)->ToGameObject()->SetGoState((GOState)e.action.goState.state); + delete targets; + break; } - - for (uint32 index = 0; index < count; ++index) + case SMART_ACTION_EXIT_VEHICLE: { - Position spawnPosition(*me); - spawnPosition.RelocatePolarOffset(currentAngle, radius); - currentAngle += deltaAngle; + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - me->SummonCreature(e.action.coneSummon.summonEntry, spawnPosition, spawnType, e.action.coneSummon.summonDuration); + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->ExitVehicle(); + + delete targets; + break; } - } + case SMART_ACTION_SET_UNIT_MOVEMENT_FLAGS: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; - break; - } - case SMART_ACTION_CU_ENCOUNTER_START: - { - ObjectList* targets = GetTargets(e, unit); - if (!targets) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + { + (*itr)->ToUnit()->SetUnitMovementFlags(e.action.movementFlag.flag); + (*itr)->ToUnit()->SendMovementFlagUpdate(); + } + + delete targets; + break; + } + case SMART_ACTION_SET_COMBAT_DISTANCE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->m_CombatDistance = e.action.combatDistance.dist; + + delete targets; + break; + } + case SMART_ACTION_SET_CASTER_COMBAT_DIST: + { + if (e.action.casterDistance.reset) + RestoreCasterMaxDist(); + else + SetCasterActualDist(e.action.casterDistance.dist); + + if (me->GetVictim() && me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) + me->GetMotionMaster()->MoveChase(me->GetVictim(), GetCasterActualDist()); + break; + } + case SMART_ACTION_SET_SIGHT_DIST: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->m_SightDistance = e.action.sightDistance.dist; + + delete targets; + break; + } + case SMART_ACTION_FLEE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->GetMotionMaster()->MoveFleeing(me, e.action.flee.withEmote); + + delete targets; + break; + } + case SMART_ACTION_ADD_THREAT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + me->AddThreat((*itr)->ToUnit(), (float)e.action.threatPCT.threatINC - (float)e.action.threatPCT.threatDEC); + + delete targets; + break; + } + case SMART_ACTION_LOAD_EQUIPMENT: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(*itr)) + (*itr)->ToCreature()->LoadEquipment(e.action.loadEquipment.id, e.action.loadEquipment.force); + + delete targets; + break; + } + case SMART_ACTION_TRIGGER_RANDOM_TIMED_EVENT: + { + uint32 eventId = urand(e.action.randomTimedEvent.minId, e.action.randomTimedEvent.maxId); + ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, NULL, eventId); + break; + } + case SMART_ACTION_SET_HOVER: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->SetHover(e.action.setHover.state); + + delete targets; + break; + } + case SMART_ACTION_ADD_IMMUNITY: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->ApplySpellImmune(e.action.immunity.id, e.action.immunity.type, e.action.immunity.value, true); + + delete targets; + break; + } + case SMART_ACTION_REMOVE_IMMUNITY: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->ApplySpellImmune(e.action.immunity.id, e.action.immunity.type, e.action.immunity.value, false); + + delete targets; + break; + } + case SMART_ACTION_FALL: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->GetMotionMaster()->MoveFall(); + + delete targets; + break; + } + case SMART_ACTION_SET_EVENT_FLAG_RESET: + { + SetPhaseReset(e.action.setActive.state); + break; + } + case SMART_ACTION_REMOVE_ALL_GAMEOBJECTS: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->RemoveAllGameObjects(); + + delete targets; + break; + } + case SMART_ACTION_STOP_MOTION: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + { + if (e.action.stopMotion.stopMovement) + (*itr)->ToUnit()->StopMoving(); + if (e.action.stopMotion.movementExpired) + (*itr)->ToUnit()->GetMotionMaster()->MovementExpired(); + } + + delete targets; + break; + } + case SMART_ACTION_NO_ENVIRONMENT_UPDATE: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + (*itr)->ToUnit()->AddUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD); + + delete targets; + break; + } + case SMART_ACTION_ZONE_UNDER_ATTACK: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(*itr)) + if (Player* player = (*itr)->ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself()) + { + me->SendZoneUnderAttackMessage(player); + break; + } + + delete targets; + break; + } + case SMART_ACTION_LOAD_GRID: + { + if (me && me->FindMap()) + me->FindMap()->LoadGrid(e.target.x, e.target.y); + break; + } + case SMART_ACTION_PLAYER_TALK: + { + ObjectList* targets = GetTargets(e, unit); + char const* text = sObjectMgr->GetAcoreString(e.action.playerTalk.textId, DEFAULT_LOCALE); + + if (targets) + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsPlayer(*itr)) + !e.action.playerTalk.flag ? (*itr)->ToPlayer()->Say(text, LANG_UNIVERSAL) : (*itr)->ToPlayer()->Yell(text, LANG_UNIVERSAL); + + delete targets; + break; + } + case SMART_ACTION_CUSTOM_CAST: + { + if (!me) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsUnit(*itr)) + { + if (e.action.castCustom.flags & SMARTCAST_INTERRUPT_PREVIOUS) + me->InterruptNonMeleeSpells(false); + + if (e.action.castCustom.flags & SMARTCAST_COMBAT_MOVE) + { + // If cast flag SMARTCAST_COMBAT_MOVE is set combat movement will not be allowed + // unless target is outside spell range, out of mana, or LOS. + + bool _allowMove = false; + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(e.action.castCustom.spell); + int32 mana = me->GetPower(POWER_MANA); + + if (me->GetDistance((*itr)->ToUnit()) > spellInfo->GetMaxRange(true) || + me->GetDistance((*itr)->ToUnit()) < spellInfo->GetMinRange(true) || + !me->IsWithinLOSInMap((*itr)->ToUnit()) || + mana < spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask())) + _allowMove = true; + + CAST_AI(SmartAI, me->AI())->SetCombatMove(_allowMove); + } + + if (!(e.action.castCustom.flags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.castCustom.spell)) + { + CustomSpellValues values; + if (e.action.castCustom.bp1) + values.AddSpellMod(SPELLVALUE_BASE_POINT0, e.action.castCustom.bp1); + if (e.action.castCustom.bp2) + values.AddSpellMod(SPELLVALUE_BASE_POINT1, e.action.castCustom.bp2); + if (e.action.castCustom.bp3) + values.AddSpellMod(SPELLVALUE_BASE_POINT2, e.action.castCustom.bp3); + me->CastCustomSpell(e.action.castCustom.spell, values, (*itr)->ToUnit(), (e.action.castCustom.flags & SMARTCAST_TRIGGERED) ? TRIGGERED_FULL_MASK : TRIGGERED_NONE); + } + } + } + delete targets; + break; + } + case SMART_ACTION_VORTEX_SUMMON: + { + if (!me) + break; + + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + TempSummonType summon_type = (e.action.summonVortex.summonDuration > 0) ? TEMPSUMMON_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN; + + float a = static_cast(e.action.summonVortex.a); + float k = static_cast(e.action.summonVortex.k) / 1000.0f; + float r_max = static_cast(e.action.summonVortex.r_max); + float delta_phi = M_PI * static_cast(e.action.summonVortex.phi_delta) / 180.0f; + + // r(phi) = a * e ^ (k * phi) + // r(phi + delta_phi) = a * e ^ (k * (phi + delta_phi)) + // r(phi + delta_phi) = a * e ^ (k * phi) * e ^ (k * delta_phi) + // r(phi + delta_phi) = r(phi) * e ^ (k * delta_phi) + float factor = std::exp(k * delta_phi); + + // r(0) = a * e ^ (k * 0) = a * e ^ 0 = a * 1 = a + float summonRadius = a; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + // Offset by orientation, should not count into radius calculation, + // but is needed for vortex direction (polar coordinates) + float phi = (*itr)->GetOrientation(); + + do + { + Position summonPosition(**itr); + summonPosition.RelocatePolarOffset(phi, summonRadius); + + me->SummonCreature(e.action.summonVortex.summonEntry, summonPosition, summon_type, e.action.summonVortex.summonDuration); + + phi += delta_phi; + summonRadius *= factor; + } while (summonRadius <= r_max); + } + + delete targets; + break; + } + case SMART_ACTION_CONE_SUMMON: + { + if (!me) + break; + + TempSummonType spawnType = (e.action.coneSummon.summonDuration > 0) ? TEMPSUMMON_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN; + + float distInARow = static_cast(e.action.coneSummon.distanceBetweenSummons); + float coneAngle = static_cast(e.action.coneSummon.coneAngle) * M_PI / 180.0f; + + for (uint32 radius = 0; radius <= e.action.coneSummon.coneLength; radius += e.action.coneSummon.distanceBetweenRings) + { + float deltaAngle = 0.0f; + if (radius > 0) + deltaAngle = distInARow / radius; + + uint32 count = 1; + if (deltaAngle > 0) + count += coneAngle / deltaAngle; + + float currentAngle = -static_cast(count) * deltaAngle / 2.0f; + + if (e.GetTargetType() == SMART_TARGET_SELF || e.GetTargetType() == SMART_TARGET_NONE) + currentAngle += G3D::fuzzyGt(e.target.o, 0.0f) ? (e.target.o - me->GetOrientation()) : 0.0f; + else if (ObjectList* targets = GetTargets(e, unit)) + { + currentAngle += (me->GetAngle(targets->front()) - me->GetOrientation()); + delete targets; + } + + for (uint32 index = 0; index < count; ++index) + { + Position spawnPosition(*me); + spawnPosition.RelocatePolarOffset(currentAngle, radius); + currentAngle += deltaAngle; + + me->SummonCreature(e.action.coneSummon.summonEntry, spawnPosition, spawnType, e.action.coneSummon.summonDuration); + } + } + + break; + } + case SMART_ACTION_CU_ENCOUNTER_START: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (Player* playerTarget = (*itr)->ToPlayer()) + { + playerTarget->RemoveArenaSpellCooldowns(); + playerTarget->RemoveAurasDueToSpell(57724); // Spell Shaman Debuff - Sated (Heroism) + playerTarget->RemoveAurasDueToSpell(57723); // Spell Shaman Debuff - Exhaustion (Bloodlust) + playerTarget->RemoveAurasDueToSpell(2825); // Bloodlust + playerTarget->RemoveAurasDueToSpell(32182); // Heroism + } + } + + delete targets; + break; + } + default: + sLog->outErrorDb("SmartScript::ProcessAction: Entry %d SourceType %u, Event %u, Unhandled Action type %u", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (Player* playerTarget = (*itr)->ToPlayer()) - { - playerTarget->RemoveArenaSpellCooldowns(); - playerTarget->RemoveAurasDueToSpell(57724); // Spell Shaman Debuff - Sated (Heroism) - playerTarget->RemoveAurasDueToSpell(57723); // Spell Shaman Debuff - Exhaustion (Bloodlust) - playerTarget->RemoveAurasDueToSpell(2825); // Bloodlust - playerTarget->RemoveAurasDueToSpell(32182); // Heroism - } - } - - delete targets; - break; - } - default: - sLog->outErrorDb("SmartScript::ProcessAction: Entry %d SourceType %u, Event %u, Unhandled Action type %u", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); - break; } if (e.link && e.link != e.event_id) @@ -3329,65 +3329,65 @@ void SmartScript::InstallTemplate(SmartScriptHolder const& e) mTemplate = (SMARTAI_TEMPLATE)e.action.installTtemplate.id; switch ((SMARTAI_TEMPLATE)e.action.installTtemplate.id) { - case SMARTAI_TEMPLATE_CASTER: - { - AddEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, e.action.installTtemplate.param2, e.action.installTtemplate.param3, 0, SMART_ACTION_CAST, e.action.installTtemplate.param1, e.target.raw.param1, 0, 0, 0, 0, SMART_TARGET_VICTIM, 0, 0, 0, 0, 1); - AddEvent(SMART_EVENT_RANGE, 0, e.action.installTtemplate.param4, 300, 0, 0, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); - AddEvent(SMART_EVENT_RANGE, 0, 0, e.action.installTtemplate.param4>10?e.action.installTtemplate.param4-10:0, 0, 0, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 0, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); - AddEvent(SMART_EVENT_MANA_PCT, 0, e.action.installTtemplate.param5-15>100?100:e.action.installTtemplate.param5+15, 100, 1000, 1000, 0, SMART_ACTION_SET_EVENT_PHASE, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - AddEvent(SMART_EVENT_MANA_PCT, 0, 0, e.action.installTtemplate.param5, 1000, 1000, 0, SMART_ACTION_SET_EVENT_PHASE, 0, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - AddEvent(SMART_EVENT_MANA_PCT, 0, 0, e.action.installTtemplate.param5, 1000, 1000, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - break; - } - case SMARTAI_TEMPLATE_TURRET: - { - AddEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, e.action.installTtemplate.param2, e.action.installTtemplate.param3, 0, SMART_ACTION_CAST, e.action.installTtemplate.param1, e.target.raw.param1, 0, 0, 0, 0, SMART_TARGET_VICTIM, 0, 0, 0, 0, 0); - AddEvent(SMART_EVENT_JUST_CREATED, 0, 0, 0, 0, 0, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 0, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - break; - } - case SMARTAI_TEMPLATE_CAGED_NPC_PART: - { - if (!me) + case SMARTAI_TEMPLATE_CASTER: + { + AddEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, e.action.installTtemplate.param2, e.action.installTtemplate.param3, 0, SMART_ACTION_CAST, e.action.installTtemplate.param1, e.target.raw.param1, 0, 0, 0, 0, SMART_TARGET_VICTIM, 0, 0, 0, 0, 1); + AddEvent(SMART_EVENT_RANGE, 0, e.action.installTtemplate.param4, 300, 0, 0, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); + AddEvent(SMART_EVENT_RANGE, 0, 0, e.action.installTtemplate.param4 > 10 ? e.action.installTtemplate.param4 - 10 : 0, 0, 0, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 0, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); + AddEvent(SMART_EVENT_MANA_PCT, 0, e.action.installTtemplate.param5 - 15 > 100 ? 100 : e.action.installTtemplate.param5 + 15, 100, 1000, 1000, 0, SMART_ACTION_SET_EVENT_PHASE, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + AddEvent(SMART_EVENT_MANA_PCT, 0, 0, e.action.installTtemplate.param5, 1000, 1000, 0, SMART_ACTION_SET_EVENT_PHASE, 0, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + AddEvent(SMART_EVENT_MANA_PCT, 0, 0, e.action.installTtemplate.param5, 1000, 1000, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + break; + } + case SMARTAI_TEMPLATE_TURRET: + { + AddEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, e.action.installTtemplate.param2, e.action.installTtemplate.param3, 0, SMART_ACTION_CAST, e.action.installTtemplate.param1, e.target.raw.param1, 0, 0, 0, 0, SMART_TARGET_VICTIM, 0, 0, 0, 0, 0); + AddEvent(SMART_EVENT_JUST_CREATED, 0, 0, 0, 0, 0, 0, SMART_ACTION_ALLOW_COMBAT_MOVEMENT, 0, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + break; + } + case SMARTAI_TEMPLATE_CAGED_NPC_PART: + { + if (!me) + return; + //store cage as id1 + AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_STORE_TARGET_LIST, 1, 0, 0, 0, 0, 0, SMART_TARGET_CLOSEST_GAMEOBJECT, e.action.installTtemplate.param1, 10, 0, 0, 0); + + //reset(close) cage on hostage(me) respawn + AddEvent(SMART_EVENT_UPDATE, SMART_EVENT_FLAG_NOT_REPEATABLE, 0, 0, 0, 0, 0, SMART_ACTION_RESET_GOBJECT, 0, 0, 0, 0, 0, 0, SMART_TARGET_GAMEOBJECT_DISTANCE, e.action.installTtemplate.param1, 5, 0, 0, 0); + + AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_SET_RUN, e.action.installTtemplate.param3, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_SET_EVENT_PHASE, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + + AddEvent(SMART_EVENT_UPDATE, SMART_EVENT_FLAG_NOT_REPEATABLE, 1000, 1000, 0, 0, 0, SMART_ACTION_MOVE_FORWARD, e.action.installTtemplate.param4, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); + //phase 1: give quest credit on movepoint reached + AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, 0, SMART_ACTION_SET_DATA, 0, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 1, 0, 0, 0, 1); + //phase 1: despawn after time on movepoint reached + AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, 0, SMART_ACTION_FORCE_DESPAWN, e.action.installTtemplate.param2, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); + + if (sCreatureTextMgr->TextExist(me->GetEntry(), (uint8)e.action.installTtemplate.param5)) + AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, 0, SMART_ACTION_TALK, e.action.installTtemplate.param5, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); + break; + } + case SMARTAI_TEMPLATE_CAGED_GO_PART: + { + if (!go) + return; + //store hostage as id1 + AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_STORE_TARGET_LIST, 1, 0, 0, 0, 0, 0, SMART_TARGET_CLOSEST_CREATURE, e.action.installTtemplate.param1, 10, 0, 0, 0); + //store invoker as id2 + AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_STORE_TARGET_LIST, 2, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); + //signal hostage + AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_SET_DATA, 0, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 1, 0, 0, 0, 0); + //when hostage raeched end point, give credit to invoker + if (e.action.installTtemplate.param2) + AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_CALL_KILLEDMONSTER, e.action.installTtemplate.param1, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 2, 0, 0, 0, 0); + else + AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_CALL_KILLEDMONSTER, e.action.installTtemplate.param1, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 2, 0, 0, 0, 0); + break; + } + case SMARTAI_TEMPLATE_BASIC: + default: return; - //store cage as id1 - AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_STORE_TARGET_LIST, 1, 0, 0, 0, 0, 0, SMART_TARGET_CLOSEST_GAMEOBJECT, e.action.installTtemplate.param1, 10, 0, 0, 0); - - //reset(close) cage on hostage(me) respawn - AddEvent(SMART_EVENT_UPDATE, SMART_EVENT_FLAG_NOT_REPEATABLE, 0, 0, 0, 0, 0, SMART_ACTION_RESET_GOBJECT, 0, 0, 0, 0, 0, 0, SMART_TARGET_GAMEOBJECT_DISTANCE, e.action.installTtemplate.param1, 5, 0, 0, 0); - - AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_SET_RUN, e.action.installTtemplate.param3, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_SET_EVENT_PHASE, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - - AddEvent(SMART_EVENT_UPDATE, SMART_EVENT_FLAG_NOT_REPEATABLE, 1000, 1000, 0, 0, 0, SMART_ACTION_MOVE_FORWARD, e.action.installTtemplate.param4, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); - //phase 1: give quest credit on movepoint reached - AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, 0, SMART_ACTION_SET_DATA, 0, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 1, 0, 0, 0, 1); - //phase 1: despawn after time on movepoint reached - AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, 0, SMART_ACTION_FORCE_DESPAWN, e.action.installTtemplate.param2, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); - - if (sCreatureTextMgr->TextExist(me->GetEntry(), (uint8)e.action.installTtemplate.param5)) - AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, 0, SMART_ACTION_TALK, e.action.installTtemplate.param5, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 1); - break; - } - case SMARTAI_TEMPLATE_CAGED_GO_PART: - { - if (!go) - return; - //store hostage as id1 - AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_STORE_TARGET_LIST, 1, 0, 0, 0, 0, 0, SMART_TARGET_CLOSEST_CREATURE, e.action.installTtemplate.param1, 10, 0, 0, 0); - //store invoker as id2 - AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_STORE_TARGET_LIST, 2, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0, 0); - //signal hostage - AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_SET_DATA, 0, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 1, 0, 0, 0, 0); - //when hostage raeched end point, give credit to invoker - if (e.action.installTtemplate.param2) - AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, 0, SMART_ACTION_CALL_KILLEDMONSTER, e.action.installTtemplate.param1, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 2, 0, 0, 0, 0); - else - AddEvent(SMART_EVENT_GO_STATE_CHANGED, 0, 2, 0, 0, 0, 0, SMART_ACTION_CALL_KILLEDMONSTER, e.action.installTtemplate.param1, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 2, 0, 0, 0, 0); - break; - } - case SMARTAI_TEMPLATE_BASIC: - default: - return; } } @@ -3441,425 +3441,425 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* ObjectList* l = new ObjectList(); switch (e.GetTargetType()) { - case SMART_TARGET_SELF: - if (baseObject) - l->push_back(baseObject); - break; - case SMART_TARGET_VICTIM: - if (me && me->GetVictim()) - l->push_back(me->GetVictim()); - break; - case SMART_TARGET_HOSTILE_SECOND_AGGRO: - if (me) - { - if (e.target.hostilRandom.powerType) + case SMART_TARGET_SELF: + if (baseObject) + l->push_back(baseObject); + break; + case SMART_TARGET_VICTIM: + if (me && me->GetVictim()) + l->push_back(me->GetVictim()); + break; + case SMART_TARGET_HOSTILE_SECOND_AGGRO: + if (me) { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) - l->push_back(u); - } - else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) - l->push_back(u); - } - break; - case SMART_TARGET_HOSTILE_LAST_AGGRO: - if (me) - { - if (e.target.hostilRandom.powerType) - { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) - l->push_back(u); - } - else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) - l->push_back(u); - } - break; - case SMART_TARGET_HOSTILE_RANDOM: - if (me) - { - if (e.target.hostilRandom.powerType) - { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) - l->push_back(u); - } - else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) - l->push_back(u); - } - break; - case SMART_TARGET_HOSTILE_RANDOM_NOT_TOP: - if (me) - { - if (e.target.hostilRandom.powerType) - { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) - l->push_back(u); - } - else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) - l->push_back(u); - } - break; - case SMART_TARGET_FARTHEST: - if (me) - { - if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_FARTHEST, 0, FarthestTargetSelector(me, e.target.farthest.maxDist, e.target.farthest.playerOnly, e.target.farthest.isInLos))) - l->push_back(u); - } - break; - case SMART_TARGET_ACTION_INVOKER: - if (scriptTrigger) - l->push_back(scriptTrigger); - break; - case SMART_TARGET_ACTION_INVOKER_VEHICLE: - if (scriptTrigger && scriptTrigger->GetVehicle() && scriptTrigger->GetVehicle()->GetBase()) - l->push_back(scriptTrigger->GetVehicle()->GetBase()); - break; - case SMART_TARGET_INVOKER_PARTY: - if (scriptTrigger) - { - if (Player* player = scriptTrigger->ToPlayer()) - { - if (Group* group = player->GetGroup()) + if (e.target.hostilRandom.powerType) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) - if (Player* member = groupRef->GetSource()) - if (member->IsInMap(player)) - l->push_back(member); + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) + l->push_back(u); } - // We still add the player to the list if there is no group. If we do - // this even if there is a group (thus the else-check), it will add the - // same player to the list twice. We don't want that to happen. - else - l->push_back(scriptTrigger); + else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) + l->push_back(u); } - } - break; - case SMART_TARGET_CREATURE_RANGE: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.unitRange.maxDist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - { - if (!IsCreature(*itr)) - continue; - - if (me && me->GetGUID() == (*itr)->GetGUID()) - continue; - - // check alive state - 1 alive, 2 dead, 0 both - if (uint32 state = e.target.unitRange.livingState) - { - if ((*itr)->ToCreature()->IsAlive() && state == 2) - continue; - if (!(*itr)->ToCreature()->IsAlive() && state == 1) - continue; - } - - if (((e.target.unitRange.creature && (*itr)->ToCreature()->GetEntry() == e.target.unitRange.creature) || !e.target.unitRange.creature) && baseObject->IsInRange(*itr, (float)e.target.unitRange.minDist, (float)e.target.unitRange.maxDist)) - l->push_back(*itr); - } - - delete units; - break; - } - case SMART_TARGET_CREATURE_DISTANCE: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.unitDistance.dist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - { - if (!IsCreature(*itr)) - continue; - - if (me && me->GetGUID() == (*itr)->GetGUID()) - continue; - - // check alive state - 1 alive, 2 dead, 0 both - if (uint32 state = e.target.unitDistance.livingState) - { - if ((*itr)->ToCreature()->IsAlive() && state == 2) - continue; - if (!(*itr)->ToCreature()->IsAlive() && state == 1) - continue; - } - - if ((e.target.unitDistance.creature && (*itr)->ToCreature()->GetEntry() == e.target.unitDistance.creature) || !e.target.unitDistance.creature) - l->push_back(*itr); - } - - delete units; - break; - } - case SMART_TARGET_GAMEOBJECT_DISTANCE: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.goDistance.dist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - { - if (!IsGameObject(*itr)) - continue; - - if (go && go->GetGUID() == (*itr)->GetGUID()) - continue; - - if ((e.target.goDistance.entry && (*itr)->ToGameObject()->GetEntry() == e.target.goDistance.entry) || !e.target.goDistance.entry) - l->push_back(*itr); - } - - delete units; - break; - } - case SMART_TARGET_GAMEOBJECT_RANGE: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.goRange.maxDist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - { - if (!IsGameObject(*itr)) - continue; - - if (go && go->GetGUID() == (*itr)->GetGUID()) - continue; - - if (((e.target.goRange.entry && IsGameObject(*itr) && (*itr)->ToGameObject()->GetEntry() == e.target.goRange.entry) || !e.target.goRange.entry) && baseObject->IsInRange((*itr), (float)e.target.goRange.minDist, (float)e.target.goRange.maxDist)) - l->push_back(*itr); - } - - delete units; - break; - } - case SMART_TARGET_CREATURE_GUID: - { - Creature* target = nullptr; - if (!scriptTrigger && !baseObject) - { - sLog->outError("SMART_TARGET_CREATURE_GUID can not be used without invoker"); break; - } - - // xinef: my addition - if (e.target.unitGUID.getFromHashMap) - { - if ((target = ObjectAccessor::GetCreature(scriptTrigger ? *scriptTrigger : *GetBaseObject(), MAKE_NEW_GUID(e.target.unitGUID.dbGuid, e.target.unitGUID.entry, HIGHGUID_UNIT)))) - l->push_back(target); - } - else - { - target = FindCreatureNear(scriptTrigger ? scriptTrigger : GetBaseObject(), e.target.unitGUID.dbGuid); - if (target && (!e.target.unitGUID.entry || target->GetEntry() == e.target.unitGUID.entry)) - l->push_back(target); - } - break; - } - case SMART_TARGET_GAMEOBJECT_GUID: - { - GameObject* target = nullptr; - if (!scriptTrigger && !GetBaseObject()) - { - sLog->outError("SMART_TARGET_GAMEOBJECT_GUID can not be used without invoker"); + case SMART_TARGET_HOSTILE_LAST_AGGRO: + if (me) + { + if (e.target.hostilRandom.powerType) + { + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) + l->push_back(u); + } + else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) + l->push_back(u); + } break; - } - - // xinef: my addition - if (e.target.goGUID.getFromHashMap) - { - if ((target = ObjectAccessor::GetGameObject(scriptTrigger ? *scriptTrigger : *GetBaseObject(), MAKE_NEW_GUID(e.target.goGUID.dbGuid, e.target.goGUID.entry, HIGHGUID_GAMEOBJECT)))) - l->push_back(target); - } - else - { - target = FindGameObjectNear(scriptTrigger ? scriptTrigger : GetBaseObject(), e.target.goGUID.dbGuid); - if (target && (!e.target.goGUID.entry || target->GetEntry() == e.target.goGUID.entry)) - l->push_back(target); - } - break; - } - case SMART_TARGET_PLAYER_RANGE: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.playerRange.maxDist); - if (!units->empty() && GetBaseObject()) - { - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr) && GetBaseObject()->IsInRange(*itr, (float)e.target.playerRange.minDist, (float)e.target.playerRange.maxDist) && (*itr)->ToPlayer()->IsAlive() && !(*itr)->ToPlayer()->IsGameMaster()) - l->push_back(*itr); - - // If Orientation is also set and we didnt find targets, try it with all the range - if (l->empty() && e.target.o > 0) + case SMART_TARGET_HOSTILE_RANDOM: + if (me) + { + if (e.target.hostilRandom.powerType) + { + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) + l->push_back(u); + } + else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) + l->push_back(u); + } + break; + case SMART_TARGET_HOSTILE_RANDOM_NOT_TOP: + if (me) + { + if (e.target.hostilRandom.powerType) + { + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly))) + l->push_back(u); + } + else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly)) + l->push_back(u); + } + break; + case SMART_TARGET_FARTHEST: + if (me) + { + if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_FARTHEST, 0, FarthestTargetSelector(me, e.target.farthest.maxDist, e.target.farthest.playerOnly, e.target.farthest.isInLos))) + l->push_back(u); + } + break; + case SMART_TARGET_ACTION_INVOKER: + if (scriptTrigger) + l->push_back(scriptTrigger); + break; + case SMART_TARGET_ACTION_INVOKER_VEHICLE: + if (scriptTrigger && scriptTrigger->GetVehicle() && scriptTrigger->GetVehicle()->GetBase()) + l->push_back(scriptTrigger->GetVehicle()->GetBase()); + break; + case SMART_TARGET_INVOKER_PARTY: + if (scriptTrigger) + { + if (Player* player = scriptTrigger->ToPlayer()) + { + if (Group* group = player->GetGroup()) + { + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) + if (Player* member = groupRef->GetSource()) + if (member->IsInMap(player)) + l->push_back(member); + } + // We still add the player to the list if there is no group. If we do + // this even if there is a group (thus the else-check), it will add the + // same player to the list twice. We don't want that to happen. + else + l->push_back(scriptTrigger); + } + } + break; + case SMART_TARGET_CREATURE_RANGE: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist((float)e.target.unitRange.maxDist); for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr) && baseObject->IsInRange(*itr, 0.0f, float(e.target.playerRange.maxDist)) && (*itr)->ToPlayer()->IsAlive() && !(*itr)->ToPlayer()->IsGameMaster()) - l->push_back(*itr); - - if (e.target.playerRange.maxCount > 0) - acore::Containers::RandomResizeList(*l, e.target.playerRange.maxCount); - } - - delete units; - break; - } - case SMART_TARGET_PLAYER_DISTANCE: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.playerDistance.dist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr)) - l->push_back(*itr); - - delete units; - break; - } - case SMART_TARGET_STORED: - { - ObjectListMap::iterator itr = mTargetStorage->find(e.target.stored.id); - if (itr != mTargetStorage->end()) - { - ObjectList* objectList = itr->second->GetObjectList(); - l->assign(objectList->begin(), objectList->end()); - } - - // xinef: return l, retardness... what if list is empty? will return empty list instead of null pointer - break; - } - case SMART_TARGET_CLOSEST_CREATURE: - { - Creature* target = GetClosestCreatureWithEntry(GetBaseObject(), e.target.closest.entry, (float)(e.target.closest.dist ? e.target.closest.dist : 100), !e.target.closest.dead); - if (target) - l->push_back(target); - break; - } - case SMART_TARGET_CLOSEST_GAMEOBJECT: - { - GameObject* target = GetClosestGameObjectWithEntry(GetBaseObject(), e.target.closest.entry, (float)(e.target.closest.dist ? e.target.closest.dist : 100)); - if (target) - l->push_back(target); - break; - } - case SMART_TARGET_CLOSEST_PLAYER: - { - if (WorldObject* obj = GetBaseObject()) - { - Player* target = obj->SelectNearestPlayer((float)e.target.playerDistance.dist); - if (target) - l->push_back(target); - } - break; - } - case SMART_TARGET_OWNER_OR_SUMMONER: - { - if (me) - { - if (Unit* owner = ObjectAccessor::GetUnit(*me, me->GetCharmerOrOwnerGUID())) - l->push_back(owner); - // Xinef: dont add same unit twice - else if (me->IsSummon() && me->ToTempSummon()->GetSummoner()) - l->push_back(me->ToTempSummon()->GetSummoner()); - } - else if (go) - { - if (Unit* owner = ObjectAccessor::GetUnit(*go, go->GetOwnerGUID())) - l->push_back(owner); - } - - // xinef: Get owner of owner - if (e.target.owner.useCharmerOrOwner && !l->empty()) - { - Unit* owner = l->front()->ToUnit(); - l->clear(); - - if (Unit* base = ObjectAccessor::GetUnit(*owner, owner->GetCharmerOrOwnerGUID())) - l->push_back(base); - } - break; - } - case SMART_TARGET_THREAT_LIST: - { - if (me) - { - ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator i = threatList.begin(); i != threatList.end(); ++i) - if (Unit* temp = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) - // Xinef: added distance check - if (e.target.hostilRandom.maxDist == 0 || me->IsWithinCombatRange(temp, (float)e.target.hostilRandom.maxDist)) - l->push_back(temp); - } - break; - } - case SMART_TARGET_CLOSEST_ENEMY: - { - if (me) - if (Unit* target = me->SelectNearestTarget(e.target.closestAttackable.maxDist, e.target.closestAttackable.playerOnly)) - l->push_back(target); - - break; - } - case SMART_TARGET_CLOSEST_FRIENDLY: - { - if (me) - if (Unit* target = DoFindClosestFriendlyInRange(e.target.closestFriendly.maxDist, e.target.closestFriendly.playerOnly)) - l->push_back(target); - - break; - } - case SMART_TARGET_PLAYER_WITH_AURA: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist(e.target.z ? e.target.z : float(e.target.playerWithAura.distMax)); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr) && (*itr)->ToPlayer()->IsAlive() && !(*itr)->ToPlayer()->IsGameMaster()) - if (GetBaseObject()->IsInRange(*itr, (float)e.target.playerWithAura.distMin, (float)e.target.playerWithAura.distMax)) - if (bool(e.target.playerWithAura.negation) != (*itr)->ToPlayer()->HasAura(e.target.playerWithAura.spellId)) - l->push_back(*itr); - - if (e.target.o > 0) - acore::Containers::RandomResizeList(*l, e.target.o); - - delete units; - break; - } - case SMART_TARGET_ROLE_SELECTION: - { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist(float(e.target.roleSelection.maxDist)); - // 1 = Tanks, 2 = Healer, 4 = Damage - uint32 roleMask = e.target.roleSelection.roleMask; - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (Player* targetPlayer = (*itr)->ToPlayer()) - if (targetPlayer->IsAlive() && !targetPlayer->IsGameMaster()) { - if (roleMask & SMART_TARGET_ROLE_FLAG_TANKS) + if (!IsCreature(*itr)) + continue; + + if (me && me->GetGUID() == (*itr)->GetGUID()) + continue; + + // check alive state - 1 alive, 2 dead, 0 both + if (uint32 state = e.target.unitRange.livingState) { - if (targetPlayer->HasTankSpec()) - { - l->push_back(*itr); + if ((*itr)->ToCreature()->IsAlive() && state == 2) continue; - } - } - if (roleMask & SMART_TARGET_ROLE_FLAG_HEALERS) - { - if (targetPlayer->HasHealSpec()) - { - l->push_back(*itr); + if (!(*itr)->ToCreature()->IsAlive() && state == 1) continue; - } - } - if (roleMask & SMART_TARGET_ROLE_FLAG_DAMAGERS) - { - if (targetPlayer->HasCasterSpec() || targetPlayer->HasMeleeSpec()) - { - l->push_back(*itr); - continue; - } } + + if (((e.target.unitRange.creature && (*itr)->ToCreature()->GetEntry() == e.target.unitRange.creature) || !e.target.unitRange.creature) && baseObject->IsInRange(*itr, (float)e.target.unitRange.minDist, (float)e.target.unitRange.maxDist)) + l->push_back(*itr); } - if (e.target.roleSelection.resize > 0) - acore::Containers::RandomResizeList(*l, e.target.roleSelection.resize); + delete units; + break; + } + case SMART_TARGET_CREATURE_DISTANCE: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist((float)e.target.unitDistance.dist); + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + { + if (!IsCreature(*itr)) + continue; - delete units; - break; - } - case SMART_TARGET_NONE: - case SMART_TARGET_POSITION: - default: - break; + if (me && me->GetGUID() == (*itr)->GetGUID()) + continue; + + // check alive state - 1 alive, 2 dead, 0 both + if (uint32 state = e.target.unitDistance.livingState) + { + if ((*itr)->ToCreature()->IsAlive() && state == 2) + continue; + if (!(*itr)->ToCreature()->IsAlive() && state == 1) + continue; + } + + if ((e.target.unitDistance.creature && (*itr)->ToCreature()->GetEntry() == e.target.unitDistance.creature) || !e.target.unitDistance.creature) + l->push_back(*itr); + } + + delete units; + break; + } + case SMART_TARGET_GAMEOBJECT_DISTANCE: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist((float)e.target.goDistance.dist); + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + { + if (!IsGameObject(*itr)) + continue; + + if (go && go->GetGUID() == (*itr)->GetGUID()) + continue; + + if ((e.target.goDistance.entry && (*itr)->ToGameObject()->GetEntry() == e.target.goDistance.entry) || !e.target.goDistance.entry) + l->push_back(*itr); + } + + delete units; + break; + } + case SMART_TARGET_GAMEOBJECT_RANGE: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist((float)e.target.goRange.maxDist); + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + { + if (!IsGameObject(*itr)) + continue; + + if (go && go->GetGUID() == (*itr)->GetGUID()) + continue; + + if (((e.target.goRange.entry && IsGameObject(*itr) && (*itr)->ToGameObject()->GetEntry() == e.target.goRange.entry) || !e.target.goRange.entry) && baseObject->IsInRange((*itr), (float)e.target.goRange.minDist, (float)e.target.goRange.maxDist)) + l->push_back(*itr); + } + + delete units; + break; + } + case SMART_TARGET_CREATURE_GUID: + { + Creature* target = nullptr; + if (!scriptTrigger && !baseObject) + { + sLog->outError("SMART_TARGET_CREATURE_GUID can not be used without invoker"); + break; + } + + // xinef: my addition + if (e.target.unitGUID.getFromHashMap) + { + if ((target = ObjectAccessor::GetCreature(scriptTrigger ? *scriptTrigger : *GetBaseObject(), MAKE_NEW_GUID(e.target.unitGUID.dbGuid, e.target.unitGUID.entry, HIGHGUID_UNIT)))) + l->push_back(target); + } + else + { + target = FindCreatureNear(scriptTrigger ? scriptTrigger : GetBaseObject(), e.target.unitGUID.dbGuid); + if (target && (!e.target.unitGUID.entry || target->GetEntry() == e.target.unitGUID.entry)) + l->push_back(target); + } + break; + } + case SMART_TARGET_GAMEOBJECT_GUID: + { + GameObject* target = nullptr; + if (!scriptTrigger && !GetBaseObject()) + { + sLog->outError("SMART_TARGET_GAMEOBJECT_GUID can not be used without invoker"); + break; + } + + // xinef: my addition + if (e.target.goGUID.getFromHashMap) + { + if ((target = ObjectAccessor::GetGameObject(scriptTrigger ? *scriptTrigger : *GetBaseObject(), MAKE_NEW_GUID(e.target.goGUID.dbGuid, e.target.goGUID.entry, HIGHGUID_GAMEOBJECT)))) + l->push_back(target); + } + else + { + target = FindGameObjectNear(scriptTrigger ? scriptTrigger : GetBaseObject(), e.target.goGUID.dbGuid); + if (target && (!e.target.goGUID.entry || target->GetEntry() == e.target.goGUID.entry)) + l->push_back(target); + } + break; + } + case SMART_TARGET_PLAYER_RANGE: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist((float)e.target.playerRange.maxDist); + if (!units->empty() && GetBaseObject()) + { + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + if (IsPlayer(*itr) && GetBaseObject()->IsInRange(*itr, (float)e.target.playerRange.minDist, (float)e.target.playerRange.maxDist) && (*itr)->ToPlayer()->IsAlive() && !(*itr)->ToPlayer()->IsGameMaster()) + l->push_back(*itr); + + // If Orientation is also set and we didnt find targets, try it with all the range + if (l->empty() && e.target.o > 0) + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + if (IsPlayer(*itr) && baseObject->IsInRange(*itr, 0.0f, float(e.target.playerRange.maxDist)) && (*itr)->ToPlayer()->IsAlive() && !(*itr)->ToPlayer()->IsGameMaster()) + l->push_back(*itr); + + if (e.target.playerRange.maxCount > 0) + acore::Containers::RandomResizeList(*l, e.target.playerRange.maxCount); + } + + delete units; + break; + } + case SMART_TARGET_PLAYER_DISTANCE: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist((float)e.target.playerDistance.dist); + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + if (IsPlayer(*itr)) + l->push_back(*itr); + + delete units; + break; + } + case SMART_TARGET_STORED: + { + ObjectListMap::iterator itr = mTargetStorage->find(e.target.stored.id); + if (itr != mTargetStorage->end()) + { + ObjectList* objectList = itr->second->GetObjectList(); + l->assign(objectList->begin(), objectList->end()); + } + + // xinef: return l, retardness... what if list is empty? will return empty list instead of null pointer + break; + } + case SMART_TARGET_CLOSEST_CREATURE: + { + Creature* target = GetClosestCreatureWithEntry(GetBaseObject(), e.target.closest.entry, (float)(e.target.closest.dist ? e.target.closest.dist : 100), !e.target.closest.dead); + if (target) + l->push_back(target); + break; + } + case SMART_TARGET_CLOSEST_GAMEOBJECT: + { + GameObject* target = GetClosestGameObjectWithEntry(GetBaseObject(), e.target.closest.entry, (float)(e.target.closest.dist ? e.target.closest.dist : 100)); + if (target) + l->push_back(target); + break; + } + case SMART_TARGET_CLOSEST_PLAYER: + { + if (WorldObject* obj = GetBaseObject()) + { + Player* target = obj->SelectNearestPlayer((float)e.target.playerDistance.dist); + if (target) + l->push_back(target); + } + break; + } + case SMART_TARGET_OWNER_OR_SUMMONER: + { + if (me) + { + if (Unit* owner = ObjectAccessor::GetUnit(*me, me->GetCharmerOrOwnerGUID())) + l->push_back(owner); + // Xinef: dont add same unit twice + else if (me->IsSummon() && me->ToTempSummon()->GetSummoner()) + l->push_back(me->ToTempSummon()->GetSummoner()); + } + else if (go) + { + if (Unit* owner = ObjectAccessor::GetUnit(*go, go->GetOwnerGUID())) + l->push_back(owner); + } + + // xinef: Get owner of owner + if (e.target.owner.useCharmerOrOwner && !l->empty()) + { + Unit* owner = l->front()->ToUnit(); + l->clear(); + + if (Unit* base = ObjectAccessor::GetUnit(*owner, owner->GetCharmerOrOwnerGUID())) + l->push_back(base); + } + break; + } + case SMART_TARGET_THREAT_LIST: + { + if (me) + { + ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); + for (ThreatContainer::StorageType::const_iterator i = threatList.begin(); i != threatList.end(); ++i) + if (Unit* temp = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) + // Xinef: added distance check + if (e.target.hostilRandom.maxDist == 0 || me->IsWithinCombatRange(temp, (float)e.target.hostilRandom.maxDist)) + l->push_back(temp); + } + break; + } + case SMART_TARGET_CLOSEST_ENEMY: + { + if (me) + if (Unit* target = me->SelectNearestTarget(e.target.closestAttackable.maxDist, e.target.closestAttackable.playerOnly)) + l->push_back(target); + + break; + } + case SMART_TARGET_CLOSEST_FRIENDLY: + { + if (me) + if (Unit* target = DoFindClosestFriendlyInRange(e.target.closestFriendly.maxDist, e.target.closestFriendly.playerOnly)) + l->push_back(target); + + break; + } + case SMART_TARGET_PLAYER_WITH_AURA: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist(e.target.z ? e.target.z : float(e.target.playerWithAura.distMax)); + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + if (IsPlayer(*itr) && (*itr)->ToPlayer()->IsAlive() && !(*itr)->ToPlayer()->IsGameMaster()) + if (GetBaseObject()->IsInRange(*itr, (float)e.target.playerWithAura.distMin, (float)e.target.playerWithAura.distMax)) + if (bool(e.target.playerWithAura.negation) != (*itr)->ToPlayer()->HasAura(e.target.playerWithAura.spellId)) + l->push_back(*itr); + + if (e.target.o > 0) + acore::Containers::RandomResizeList(*l, e.target.o); + + delete units; + break; + } + case SMART_TARGET_ROLE_SELECTION: + { + // will always return a valid pointer, even if empty list + ObjectList* units = GetWorldObjectsInDist(float(e.target.roleSelection.maxDist)); + // 1 = Tanks, 2 = Healer, 4 = Damage + uint32 roleMask = e.target.roleSelection.roleMask; + for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + if (Player* targetPlayer = (*itr)->ToPlayer()) + if (targetPlayer->IsAlive() && !targetPlayer->IsGameMaster()) + { + if (roleMask & SMART_TARGET_ROLE_FLAG_TANKS) + { + if (targetPlayer->HasTankSpec()) + { + l->push_back(*itr); + continue; + } + } + if (roleMask & SMART_TARGET_ROLE_FLAG_HEALERS) + { + if (targetPlayer->HasHealSpec()) + { + l->push_back(*itr); + continue; + } + } + if (roleMask & SMART_TARGET_ROLE_FLAG_DAMAGERS) + { + if (targetPlayer->HasCasterSpec() || targetPlayer->HasMeleeSpec()) + { + l->push_back(*itr); + continue; + } + } + } + + if (e.target.roleSelection.resize > 0) + acore::Containers::RandomResizeList(*l, e.target.roleSelection.resize); + + delete units; + break; + } + case SMART_TARGET_NONE: + case SMART_TARGET_POSITION: + default: + break; } if (l->empty()) @@ -3894,582 +3894,582 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui switch (e.GetEventType()) { - case SMART_EVENT_LINK://special handling - ProcessAction(e, unit, var0, var1, bvar, spell, gob); - break; - //called from Update tick - case SMART_EVENT_UPDATE: - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); - break; - case SMART_EVENT_UPDATE_OOC: - if (me && me->IsInCombat()) - return; - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); - break; - case SMART_EVENT_UPDATE_IC: - if (!me || !me->IsInCombat()) - return; - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); - break; - case SMART_EVENT_HEALTH_PCT: - { - if (!me || !me->IsInCombat() || !me->GetMaxHealth()) - return; - uint32 perc = (uint32)me->GetHealthPct(); - if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) - return; - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); - break; - } - case SMART_EVENT_TARGET_HEALTH_PCT: - { - if (!me || !me->IsInCombat() || !me->GetVictim() || !me->GetVictim()->GetMaxHealth()) - return; - uint32 perc = (uint32)me->GetVictim()->GetHealthPct(); - if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) - return; - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax, me->GetVictim()); - break; - } - case SMART_EVENT_MANA_PCT: - { - if (!me || !me->IsInCombat() || !me->GetMaxPower(POWER_MANA)) - return; - uint32 perc = uint32(me->GetPowerPct(POWER_MANA)); - if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) - return; - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); - break; - } - case SMART_EVENT_TARGET_MANA_PCT: - { - if (!me || !me->IsInCombat() || !me->GetVictim() || !me->GetVictim()->GetMaxPower(POWER_MANA)) - return; - uint32 perc = uint32(me->GetVictim()->GetPowerPct(POWER_MANA)); - if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) - return; - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax, me->GetVictim()); - break; - } - case SMART_EVENT_RANGE: - { - if (!me || !me->IsInCombat() || !me->GetVictim()) - return; - - if (me->IsInRange(me->GetVictim(), (float)e.event.minMaxRepeat.min, (float)e.event.minMaxRepeat.max)) - ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax, me->GetVictim()); - else // xinef: make it predictable - RecalcTimer(e, 500, 500); - break; - } - case SMART_EVENT_VICTIM_CASTING: - { - if (!me || !me->IsInCombat()) - return; - - Unit* victim = me->GetVictim(); - - if (!victim || !victim->IsNonMeleeSpellCast(false, false, true)) - return; - - if (e.event.targetCasting.spellId > 0) - if (Spell* currSpell = victim->GetCurrentSpell(CURRENT_GENERIC_SPELL)) - if (currSpell->m_spellInfo->Id != e.event.targetCasting.spellId) - return; - - ProcessTimedAction(e, e.event.targetCasting.repeatMin, e.event.targetCasting.repeatMax, me->GetVictim()); - break; - } - case SMART_EVENT_FRIENDLY_HEALTH: - { - if (!me || !me->IsInCombat()) - return; - - Unit* target = DoSelectLowestHpFriendly((float)e.event.friendlyHealth.radius, e.event.friendlyHealth.hpDeficit); - if (!target || !target->IsInCombat()) - { - // Xinef: if there are at least two same npcs, they will perform the same action immediately even if this is useless... - RecalcTimer(e, 1000, 3000); - return; - } - ProcessTimedAction(e, e.event.friendlyHealth.repeatMin, e.event.friendlyHealth.repeatMax, target); - break; - } - case SMART_EVENT_FRIENDLY_IS_CC: - { - if (!me || !me->IsInCombat()) - return; - - std::list pList; - DoFindFriendlyCC(pList, (float)e.event.friendlyCC.radius); - if (pList.empty()) - { - // Xinef: if there are at least two same npcs, they will perform the same action immediately even if this is useless... - RecalcTimer(e, 1000, 3000); - return; - } - ProcessTimedAction(e, e.event.friendlyCC.repeatMin, e.event.friendlyCC.repeatMax, acore::Containers::SelectRandomContainerElement(pList)); - break; - } - case SMART_EVENT_FRIENDLY_MISSING_BUFF: - { - std::list pList; - DoFindFriendlyMissingBuff(pList, (float)e.event.missingBuff.radius, e.event.missingBuff.spell); - - if (pList.empty()) - return; - - ProcessTimedAction(e, e.event.missingBuff.repeatMin, e.event.missingBuff.repeatMax, acore::Containers::SelectRandomContainerElement(pList)); - break; - } - case SMART_EVENT_HAS_AURA: - { - if (!me) - return; - uint32 count = me->GetAuraCount(e.event.aura.spell); - if ((!e.event.aura.count && !count) || (e.event.aura.count && count >= e.event.aura.count)) - ProcessTimedAction(e, e.event.aura.repeatMin, e.event.aura.repeatMax); - break; - } - case SMART_EVENT_TARGET_BUFFED: - { - if (!me || !me->GetVictim()) - return; - uint32 count = me->GetVictim()->GetAuraCount(e.event.aura.spell); - if (count < e.event.aura.count) - return; - ProcessTimedAction(e, e.event.aura.repeatMin, e.event.aura.repeatMax); - break; - } - //no params - case SMART_EVENT_AGGRO: - case SMART_EVENT_DEATH: - case SMART_EVENT_EVADE: - case SMART_EVENT_REACHED_HOME: - case SMART_EVENT_CHARMED: - case SMART_EVENT_CHARMED_TARGET: - case SMART_EVENT_CORPSE_REMOVED: - case SMART_EVENT_AI_INIT: - case SMART_EVENT_TRANSPORT_ADDPLAYER: - case SMART_EVENT_TRANSPORT_REMOVE_PLAYER: - case SMART_EVENT_QUEST_ACCEPTED: - case SMART_EVENT_QUEST_OBJ_COPLETETION: - case SMART_EVENT_QUEST_COMPLETION: - case SMART_EVENT_QUEST_REWARDED: - case SMART_EVENT_QUEST_FAIL: - case SMART_EVENT_JUST_SUMMONED: - case SMART_EVENT_RESET: - case SMART_EVENT_JUST_CREATED: - case SMART_EVENT_FOLLOW_COMPLETED: - case SMART_EVENT_ON_SPELLCLICK: - ProcessAction(e, unit, var0, var1, bvar, spell, gob); - break; - // Xinef: added no report use distinction for gameobjects - case SMART_EVENT_GOSSIP_HELLO: - if (e.event.gossipHello.noReportUse && var0) - return; - ProcessAction(e, unit, var0, var1, bvar, spell, gob); - break; - case SMART_EVENT_IS_BEHIND_TARGET: - { - if (!me) - return; - - if (Unit* victim = me->GetVictim()) - { - if (!victim->HasInArc(static_cast(M_PI), me)) - ProcessTimedAction(e, e.event.behindTarget.cooldownMin, e.event.behindTarget.cooldownMax, victim); - } - break; - } - case SMART_EVENT_RECEIVE_EMOTE: - if (e.event.emote.emote == var0) - { - ProcessAction(e, unit); - RecalcTimer(e, e.event.emote.cooldownMin, e.event.emote.cooldownMax); - } - break; - case SMART_EVENT_KILL: - { - if (!me || !unit) - return; - if (e.event.kill.playerOnly && unit->GetTypeId() != TYPEID_PLAYER) - return; - if (e.event.kill.creature && unit->GetEntry() != e.event.kill.creature) - return; - RecalcTimer(e, e.event.kill.cooldownMin, e.event.kill.cooldownMax); - ProcessAction(e, unit); - break; - } - case SMART_EVENT_SPELLHIT_TARGET: - case SMART_EVENT_SPELLHIT: - { - if (!spell) - return; - if ((!e.event.spellHit.spell || spell->Id == e.event.spellHit.spell) && - (!e.event.spellHit.school || (spell->SchoolMask & e.event.spellHit.school))) - { - RecalcTimer(e, e.event.spellHit.cooldownMin, e.event.spellHit.cooldownMax); - ProcessAction(e, unit, 0, 0, bvar, spell); - } - break; - } - case SMART_EVENT_OOC_LOS: - { - if (!me || me->IsInCombat()) - return; - //can trigger if closer than fMaxAllowedRange - float range = (float)e.event.los.maxDist; - - //if range is ok and we are actually in LOS - if (me->IsWithinDistInMap(unit, range) && me->IsWithinLOSInMap(unit)) - { - //if friendly event&&who is not hostile OR hostile event&&who is hostile - if ((e.event.los.noHostile && !me->IsHostileTo(unit)) || - (!e.event.los.noHostile && me->IsHostileTo(unit))) - { - if (e.event.los.playerOnly && unit->GetTypeId() != TYPEID_PLAYER) - return; - RecalcTimer(e, e.event.los.cooldownMin, e.event.los.cooldownMax); - ProcessAction(e, unit); - } - } - break; - } - case SMART_EVENT_IC_LOS: - { - if (!me || !me->IsInCombat()) - return; - //can trigger if closer than fMaxAllowedRange - float range = (float)e.event.los.maxDist; - - //if range is ok and we are actually in LOS - if (me->IsWithinDistInMap(unit, range) && me->IsWithinLOSInMap(unit)) - { - //if friendly event&&who is not hostile OR hostile event&&who is hostile - if ((e.event.los.noHostile && !me->IsHostileTo(unit)) || - (!e.event.los.noHostile && me->IsHostileTo(unit))) - { - if (e.event.los.playerOnly && unit->GetTypeId() != TYPEID_PLAYER) - return; - RecalcTimer(e, e.event.los.cooldownMin, e.event.los.cooldownMax); - ProcessAction(e, unit); - } - } - break; - } - case SMART_EVENT_RESPAWN: - { - if (!GetBaseObject()) - return; - if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_MAP && GetBaseObject()->GetMapId() != e.event.respawn.map) - return; - if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_AREA && GetBaseObject()->GetZoneId() != e.event.respawn.area) - return; - ProcessAction(e); - break; - } - case SMART_EVENT_SUMMONED_UNIT: - { - if (!IsCreature(unit)) - return; - if (e.event.summoned.creature && unit->GetEntry() != e.event.summoned.creature) - return; - RecalcTimer(e, e.event.summoned.cooldownMin, e.event.summoned.cooldownMax); - ProcessAction(e, unit); - break; - } - case SMART_EVENT_RECEIVE_HEAL: - case SMART_EVENT_DAMAGED: - case SMART_EVENT_DAMAGED_TARGET: - { - if (var0 > e.event.minMaxRepeat.max || var0 < e.event.minMaxRepeat.min) - return; - RecalcTimer(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); - ProcessAction(e, unit); - break; - } - case SMART_EVENT_MOVEMENTINFORM: - { - if ((e.event.movementInform.type && var0 != e.event.movementInform.type) || (e.event.movementInform.id && var1 != e.event.movementInform.id)) - return; - ProcessAction(e, unit, var0, var1); - break; - } - case SMART_EVENT_TRANSPORT_RELOCATE: - case SMART_EVENT_WAYPOINT_START: - { - if (e.event.waypoint.pathID && var0 != e.event.waypoint.pathID) - return; - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_WAYPOINT_REACHED: - case SMART_EVENT_WAYPOINT_RESUMED: - case SMART_EVENT_WAYPOINT_PAUSED: - case SMART_EVENT_WAYPOINT_STOPPED: - case SMART_EVENT_WAYPOINT_ENDED: - { - if (!me || (e.event.waypoint.pointID && var0 != e.event.waypoint.pointID) || (e.event.waypoint.pathID && GetPathId() != e.event.waypoint.pathID)) - return; - ProcessAction(e, unit); - break; - } - case SMART_EVENT_SUMMON_DESPAWNED: - { - if (e.event.summoned.creature && e.event.summoned.creature != var0) - return; - RecalcTimer(e, e.event.summoned.cooldownMin, e.event.summoned.cooldownMax); - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_INSTANCE_PLAYER_ENTER: - { - if (e.event.instancePlayerEnter.team && var0 != e.event.instancePlayerEnter.team) - return; - RecalcTimer(e, e.event.instancePlayerEnter.cooldownMin, e.event.instancePlayerEnter.cooldownMax); - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_ACCEPTED_QUEST: - case SMART_EVENT_REWARD_QUEST: - { - if (e.event.quest.quest && var0 != e.event.quest.quest) - return; - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_TRANSPORT_ADDCREATURE: - { - if (e.event.transportAddCreature.creature && var0 != e.event.transportAddCreature.creature) - return; - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_AREATRIGGER_ONTRIGGER: - { - if (e.event.areatrigger.id && var0 != e.event.areatrigger.id) - return; - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_TEXT_OVER: - { - if (var0 != e.event.textOver.textGroupID || (e.event.textOver.creatureEntry && e.event.textOver.creatureEntry != var1)) - return; - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_DATA_SET: - { - if (e.event.dataSet.id != var0 || e.event.dataSet.value != var1) - return; - RecalcTimer(e, e.event.dataSet.cooldownMin, e.event.dataSet.cooldownMax); - ProcessAction(e, unit, var0, var1); - break; - } - case SMART_EVENT_PASSENGER_REMOVED: - case SMART_EVENT_PASSENGER_BOARDED: - { - if (!unit) - return; - RecalcTimer(e, e.event.minMax.repeatMin, e.event.minMax.repeatMax); - ProcessAction(e, unit); - break; - } - case SMART_EVENT_TIMED_EVENT_TRIGGERED: - { - if (e.event.timedEvent.id == var0) - ProcessAction(e, unit); - break; - } - case SMART_EVENT_GOSSIP_SELECT: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript: Gossip Select: menu %u action %u", var0, var1); //little help for scripters -#endif - if (e.event.gossip.sender != var0 || e.event.gossip.action != var1) - return; - ProcessAction(e, unit, var0, var1); - break; - } - case SMART_EVENT_GAME_EVENT_START: - case SMART_EVENT_GAME_EVENT_END: - { - if (e.event.gameEvent.gameEventId != var0) - return; - ProcessAction(e, NULL, var0); - break; - } - case SMART_EVENT_GO_STATE_CHANGED: - { - if (e.event.goStateChanged.state != var0) - return; - ProcessAction(e, unit, var0, var1); - break; - } - case SMART_EVENT_GO_EVENT_INFORM: - { - if (e.event.eventInform.eventId != var0) - return; - ProcessAction(e, NULL, var0); - break; - } - case SMART_EVENT_ACTION_DONE: - { - if (e.event.doAction.eventId != var0) - return; - ProcessAction(e, unit, var0); - break; - } - case SMART_EVENT_FRIENDLY_HEALTH_PCT: - { - if (!me || !me->IsInCombat()) - return; - - ObjectList* _targets = nullptr; - - switch (e.GetTargetType()) - { - case SMART_TARGET_CREATURE_RANGE: - case SMART_TARGET_CREATURE_GUID: - case SMART_TARGET_CREATURE_DISTANCE: - case SMART_TARGET_CLOSEST_CREATURE: - case SMART_TARGET_CLOSEST_PLAYER: - case SMART_TARGET_PLAYER_RANGE: - case SMART_TARGET_PLAYER_DISTANCE: - _targets = GetTargets(e); + case SMART_EVENT_LINK://special handling + ProcessAction(e, unit, var0, var1, bvar, spell, gob); break; - default: - return; - } - - if (!_targets) - return; - - Unit* target = nullptr; - - for (ObjectList::const_iterator itr = _targets->begin(); itr != _targets->end(); ++itr) - { - if (IsUnit(*itr) && me->IsFriendlyTo((*itr)->ToUnit()) && (*itr)->ToUnit()->IsAlive() && (*itr)->ToUnit()->IsInCombat()) + //called from Update tick + case SMART_EVENT_UPDATE: + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); + break; + case SMART_EVENT_UPDATE_OOC: + if (me && me->IsInCombat()) + return; + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); + break; + case SMART_EVENT_UPDATE_IC: + if (!me || !me->IsInCombat()) + return; + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); + break; + case SMART_EVENT_HEALTH_PCT: { - uint32 healthPct = uint32((*itr)->ToUnit()->GetHealthPct()); - - if (healthPct > e.event.friendlyHealthPct.maxHpPct || healthPct < e.event.friendlyHealthPct.minHpPct) - continue; - - target = (*itr)->ToUnit(); + if (!me || !me->IsInCombat() || !me->GetMaxHealth()) + return; + uint32 perc = (uint32)me->GetHealthPct(); + if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) + return; + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); break; } - } + case SMART_EVENT_TARGET_HEALTH_PCT: + { + if (!me || !me->IsInCombat() || !me->GetVictim() || !me->GetVictim()->GetMaxHealth()) + return; + uint32 perc = (uint32)me->GetVictim()->GetHealthPct(); + if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) + return; + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax, me->GetVictim()); + break; + } + case SMART_EVENT_MANA_PCT: + { + if (!me || !me->IsInCombat() || !me->GetMaxPower(POWER_MANA)) + return; + uint32 perc = uint32(me->GetPowerPct(POWER_MANA)); + if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) + return; + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); + break; + } + case SMART_EVENT_TARGET_MANA_PCT: + { + if (!me || !me->IsInCombat() || !me->GetVictim() || !me->GetVictim()->GetMaxPower(POWER_MANA)) + return; + uint32 perc = uint32(me->GetVictim()->GetPowerPct(POWER_MANA)); + if (perc > e.event.minMaxRepeat.max || perc < e.event.minMaxRepeat.min) + return; + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax, me->GetVictim()); + break; + } + case SMART_EVENT_RANGE: + { + if (!me || !me->IsInCombat() || !me->GetVictim()) + return; - delete _targets; + if (me->IsInRange(me->GetVictim(), (float)e.event.minMaxRepeat.min, (float)e.event.minMaxRepeat.max)) + ProcessTimedAction(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax, me->GetVictim()); + else // xinef: make it predictable + RecalcTimer(e, 500, 500); + break; + } + case SMART_EVENT_VICTIM_CASTING: + { + if (!me || !me->IsInCombat()) + return; - if (!target) - return; + Unit* victim = me->GetVictim(); - ProcessTimedAction(e, e.event.friendlyHealthPct.repeatMin, e.event.friendlyHealthPct.repeatMax, target); - break; - } - case SMART_EVENT_DISTANCE_CREATURE: - { - if (!me) - return; + if (!victim || !victim->IsNonMeleeSpellCast(false, false, true)) + return; - WorldObject* creature = nullptr; + if (e.event.targetCasting.spellId > 0) + if (Spell* currSpell = victim->GetCurrentSpell(CURRENT_GENERIC_SPELL)) + if (currSpell->m_spellInfo->Id != e.event.targetCasting.spellId) + return; - if (e.event.distance.guid != 0) - { - creature = FindCreatureNear(me, e.event.distance.guid); + ProcessTimedAction(e, e.event.targetCasting.repeatMin, e.event.targetCasting.repeatMax, me->GetVictim()); + break; + } + case SMART_EVENT_FRIENDLY_HEALTH: + { + if (!me || !me->IsInCombat()) + return; - if (!creature) + Unit* target = DoSelectLowestHpFriendly((float)e.event.friendlyHealth.radius, e.event.friendlyHealth.hpDeficit); + if (!target || !target->IsInCombat()) + { + // Xinef: if there are at least two same npcs, they will perform the same action immediately even if this is useless... + RecalcTimer(e, 1000, 3000); + return; + } + ProcessTimedAction(e, e.event.friendlyHealth.repeatMin, e.event.friendlyHealth.repeatMax, target); + break; + } + case SMART_EVENT_FRIENDLY_IS_CC: + { + if (!me || !me->IsInCombat()) + return; + + std::list pList; + DoFindFriendlyCC(pList, (float)e.event.friendlyCC.radius); + if (pList.empty()) + { + // Xinef: if there are at least two same npcs, they will perform the same action immediately even if this is useless... + RecalcTimer(e, 1000, 3000); + return; + } + ProcessTimedAction(e, e.event.friendlyCC.repeatMin, e.event.friendlyCC.repeatMax, acore::Containers::SelectRandomContainerElement(pList)); + break; + } + case SMART_EVENT_FRIENDLY_MISSING_BUFF: + { + std::list pList; + DoFindFriendlyMissingBuff(pList, (float)e.event.missingBuff.radius, e.event.missingBuff.spell); + + if (pList.empty()) + return; + + ProcessTimedAction(e, e.event.missingBuff.repeatMin, e.event.missingBuff.repeatMax, acore::Containers::SelectRandomContainerElement(pList)); + break; + } + case SMART_EVENT_HAS_AURA: + { + if (!me) + return; + uint32 count = me->GetAuraCount(e.event.aura.spell); + if ((!e.event.aura.count && !count) || (e.event.aura.count && count >= e.event.aura.count)) + ProcessTimedAction(e, e.event.aura.repeatMin, e.event.aura.repeatMax); + break; + } + case SMART_EVENT_TARGET_BUFFED: + { + if (!me || !me->GetVictim()) + return; + uint32 count = me->GetVictim()->GetAuraCount(e.event.aura.spell); + if (count < e.event.aura.count) + return; + ProcessTimedAction(e, e.event.aura.repeatMin, e.event.aura.repeatMax); + break; + } + //no params + case SMART_EVENT_AGGRO: + case SMART_EVENT_DEATH: + case SMART_EVENT_EVADE: + case SMART_EVENT_REACHED_HOME: + case SMART_EVENT_CHARMED: + case SMART_EVENT_CHARMED_TARGET: + case SMART_EVENT_CORPSE_REMOVED: + case SMART_EVENT_AI_INIT: + case SMART_EVENT_TRANSPORT_ADDPLAYER: + case SMART_EVENT_TRANSPORT_REMOVE_PLAYER: + case SMART_EVENT_QUEST_ACCEPTED: + case SMART_EVENT_QUEST_OBJ_COPLETETION: + case SMART_EVENT_QUEST_COMPLETION: + case SMART_EVENT_QUEST_REWARDED: + case SMART_EVENT_QUEST_FAIL: + case SMART_EVENT_JUST_SUMMONED: + case SMART_EVENT_RESET: + case SMART_EVENT_JUST_CREATED: + case SMART_EVENT_FOLLOW_COMPLETED: + case SMART_EVENT_ON_SPELLCLICK: + ProcessAction(e, unit, var0, var1, bvar, spell, gob); + break; + // Xinef: added no report use distinction for gameobjects + case SMART_EVENT_GOSSIP_HELLO: + if (e.event.gossipHello.noReportUse && var0) return; + ProcessAction(e, unit, var0, var1, bvar, spell, gob); + break; + case SMART_EVENT_IS_BEHIND_TARGET: + { + if (!me) + return; - if (!me->IsInRange(creature, 0, (float)e.event.distance.dist)) - return; - } - else if (e.event.distance.entry != 0) - { - std::list list; - me->GetCreatureListWithEntryInGrid(list, e.event.distance.entry, (float)e.event.distance.dist); - - if (!list.empty()) - creature = list.front(); - } - - if (creature) - ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat); - - break; - } - case SMART_EVENT_DISTANCE_GAMEOBJECT: - { - if (!me) - return; - - WorldObject* gameobject = nullptr; - - if (e.event.distance.guid != 0) - { - gameobject = FindGameObjectNear(me, e.event.distance.guid); - - if (!gameobject) - return; - - if (!me->IsInRange(gameobject, 0, (float)e.event.distance.dist)) - return; - } - else if (e.event.distance.entry != 0) - { - std::list list; - me->GetGameObjectListWithEntryInGrid(list, e.event.distance.entry, (float)e.event.distance.dist); - - if (!list.empty()) - gameobject = list.front(); - } - - if (gameobject) - ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat); - - break; - } - case SMART_EVENT_COUNTER_SET: - if (e.event.counter.id != var0 || GetCounterValue(e.event.counter.id) != e.event.counter.value) - return; - - ProcessTimedAction(e, e.event.counter.cooldownMin, e.event.counter.cooldownMax); - break; - case SMART_EVENT_NEAR_PLAYERS: - { - float range = (float)e.event.nearPlayer.radius; - ObjectList* units = GetWorldObjectsInDist(range); - if (!units->empty()) - { - units->remove_if([](WorldObject* unit) { return unit->GetTypeId() != TYPEID_PLAYER; }); - - if (units->size() >= e.event.nearPlayer.minCount) + if (Unit* victim = me->GetVictim()) + { + if (!victim->HasInArc(static_cast(M_PI), me)) + ProcessTimedAction(e, e.event.behindTarget.cooldownMin, e.event.behindTarget.cooldownMax, victim); + } + break; + } + case SMART_EVENT_RECEIVE_EMOTE: + if (e.event.emote.emote == var0) + { ProcessAction(e, unit); - } - RecalcTimer(e, e.event.nearPlayer.checkTimer, e.event.nearPlayer.checkTimer); - break; - } - case SMART_EVENT_NEAR_PLAYERS_NEGATION: - { - float range = (float)e.event.nearPlayerNegation.radius; - ObjectList* units = GetWorldObjectsInDist(range); - if (!units->empty()) - { - units->remove_if([](WorldObject* unit) { return unit->GetTypeId() != TYPEID_PLAYER; }); - - if (units->size() < e.event.nearPlayerNegation.minCount) + RecalcTimer(e, e.event.emote.cooldownMin, e.event.emote.cooldownMax); + } + break; + case SMART_EVENT_KILL: + { + if (!me || !unit) + return; + if (e.event.kill.playerOnly && unit->GetTypeId() != TYPEID_PLAYER) + return; + if (e.event.kill.creature && unit->GetEntry() != e.event.kill.creature) + return; + RecalcTimer(e, e.event.kill.cooldownMin, e.event.kill.cooldownMax); ProcessAction(e, unit); - } - RecalcTimer(e, e.event.nearPlayerNegation.checkTimer, e.event.nearPlayerNegation.checkTimer); - break; - } - default: - sLog->outErrorDb("SmartScript::ProcessEvent: Unhandled Event type %u", e.GetEventType()); - break; + break; + } + case SMART_EVENT_SPELLHIT_TARGET: + case SMART_EVENT_SPELLHIT: + { + if (!spell) + return; + if ((!e.event.spellHit.spell || spell->Id == e.event.spellHit.spell) && + (!e.event.spellHit.school || (spell->SchoolMask & e.event.spellHit.school))) + { + RecalcTimer(e, e.event.spellHit.cooldownMin, e.event.spellHit.cooldownMax); + ProcessAction(e, unit, 0, 0, bvar, spell); + } + break; + } + case SMART_EVENT_OOC_LOS: + { + if (!me || me->IsInCombat()) + return; + //can trigger if closer than fMaxAllowedRange + float range = (float)e.event.los.maxDist; + + //if range is ok and we are actually in LOS + if (me->IsWithinDistInMap(unit, range) && me->IsWithinLOSInMap(unit)) + { + //if friendly event&&who is not hostile OR hostile event&&who is hostile + if ((e.event.los.noHostile && !me->IsHostileTo(unit)) || + (!e.event.los.noHostile && me->IsHostileTo(unit))) + { + if (e.event.los.playerOnly && unit->GetTypeId() != TYPEID_PLAYER) + return; + RecalcTimer(e, e.event.los.cooldownMin, e.event.los.cooldownMax); + ProcessAction(e, unit); + } + } + break; + } + case SMART_EVENT_IC_LOS: + { + if (!me || !me->IsInCombat()) + return; + //can trigger if closer than fMaxAllowedRange + float range = (float)e.event.los.maxDist; + + //if range is ok and we are actually in LOS + if (me->IsWithinDistInMap(unit, range) && me->IsWithinLOSInMap(unit)) + { + //if friendly event&&who is not hostile OR hostile event&&who is hostile + if ((e.event.los.noHostile && !me->IsHostileTo(unit)) || + (!e.event.los.noHostile && me->IsHostileTo(unit))) + { + if (e.event.los.playerOnly && unit->GetTypeId() != TYPEID_PLAYER) + return; + RecalcTimer(e, e.event.los.cooldownMin, e.event.los.cooldownMax); + ProcessAction(e, unit); + } + } + break; + } + case SMART_EVENT_RESPAWN: + { + if (!GetBaseObject()) + return; + if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_MAP && GetBaseObject()->GetMapId() != e.event.respawn.map) + return; + if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_AREA && GetBaseObject()->GetZoneId() != e.event.respawn.area) + return; + ProcessAction(e); + break; + } + case SMART_EVENT_SUMMONED_UNIT: + { + if (!IsCreature(unit)) + return; + if (e.event.summoned.creature && unit->GetEntry() != e.event.summoned.creature) + return; + RecalcTimer(e, e.event.summoned.cooldownMin, e.event.summoned.cooldownMax); + ProcessAction(e, unit); + break; + } + case SMART_EVENT_RECEIVE_HEAL: + case SMART_EVENT_DAMAGED: + case SMART_EVENT_DAMAGED_TARGET: + { + if (var0 > e.event.minMaxRepeat.max || var0 < e.event.minMaxRepeat.min) + return; + RecalcTimer(e, e.event.minMaxRepeat.repeatMin, e.event.minMaxRepeat.repeatMax); + ProcessAction(e, unit); + break; + } + case SMART_EVENT_MOVEMENTINFORM: + { + if ((e.event.movementInform.type && var0 != e.event.movementInform.type) || (e.event.movementInform.id && var1 != e.event.movementInform.id)) + return; + ProcessAction(e, unit, var0, var1); + break; + } + case SMART_EVENT_TRANSPORT_RELOCATE: + case SMART_EVENT_WAYPOINT_START: + { + if (e.event.waypoint.pathID && var0 != e.event.waypoint.pathID) + return; + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_WAYPOINT_REACHED: + case SMART_EVENT_WAYPOINT_RESUMED: + case SMART_EVENT_WAYPOINT_PAUSED: + case SMART_EVENT_WAYPOINT_STOPPED: + case SMART_EVENT_WAYPOINT_ENDED: + { + if (!me || (e.event.waypoint.pointID && var0 != e.event.waypoint.pointID) || (e.event.waypoint.pathID && GetPathId() != e.event.waypoint.pathID)) + return; + ProcessAction(e, unit); + break; + } + case SMART_EVENT_SUMMON_DESPAWNED: + { + if (e.event.summoned.creature && e.event.summoned.creature != var0) + return; + RecalcTimer(e, e.event.summoned.cooldownMin, e.event.summoned.cooldownMax); + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_INSTANCE_PLAYER_ENTER: + { + if (e.event.instancePlayerEnter.team && var0 != e.event.instancePlayerEnter.team) + return; + RecalcTimer(e, e.event.instancePlayerEnter.cooldownMin, e.event.instancePlayerEnter.cooldownMax); + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_ACCEPTED_QUEST: + case SMART_EVENT_REWARD_QUEST: + { + if (e.event.quest.quest && var0 != e.event.quest.quest) + return; + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_TRANSPORT_ADDCREATURE: + { + if (e.event.transportAddCreature.creature && var0 != e.event.transportAddCreature.creature) + return; + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_AREATRIGGER_ONTRIGGER: + { + if (e.event.areatrigger.id && var0 != e.event.areatrigger.id) + return; + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_TEXT_OVER: + { + if (var0 != e.event.textOver.textGroupID || (e.event.textOver.creatureEntry && e.event.textOver.creatureEntry != var1)) + return; + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_DATA_SET: + { + if (e.event.dataSet.id != var0 || e.event.dataSet.value != var1) + return; + RecalcTimer(e, e.event.dataSet.cooldownMin, e.event.dataSet.cooldownMax); + ProcessAction(e, unit, var0, var1); + break; + } + case SMART_EVENT_PASSENGER_REMOVED: + case SMART_EVENT_PASSENGER_BOARDED: + { + if (!unit) + return; + RecalcTimer(e, e.event.minMax.repeatMin, e.event.minMax.repeatMax); + ProcessAction(e, unit); + break; + } + case SMART_EVENT_TIMED_EVENT_TRIGGERED: + { + if (e.event.timedEvent.id == var0) + ProcessAction(e, unit); + break; + } + case SMART_EVENT_GOSSIP_SELECT: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript: Gossip Select: menu %u action %u", var0, var1); //little help for scripters +#endif + if (e.event.gossip.sender != var0 || e.event.gossip.action != var1) + return; + ProcessAction(e, unit, var0, var1); + break; + } + case SMART_EVENT_GAME_EVENT_START: + case SMART_EVENT_GAME_EVENT_END: + { + if (e.event.gameEvent.gameEventId != var0) + return; + ProcessAction(e, NULL, var0); + break; + } + case SMART_EVENT_GO_STATE_CHANGED: + { + if (e.event.goStateChanged.state != var0) + return; + ProcessAction(e, unit, var0, var1); + break; + } + case SMART_EVENT_GO_EVENT_INFORM: + { + if (e.event.eventInform.eventId != var0) + return; + ProcessAction(e, NULL, var0); + break; + } + case SMART_EVENT_ACTION_DONE: + { + if (e.event.doAction.eventId != var0) + return; + ProcessAction(e, unit, var0); + break; + } + case SMART_EVENT_FRIENDLY_HEALTH_PCT: + { + if (!me || !me->IsInCombat()) + return; + + ObjectList* _targets = nullptr; + + switch (e.GetTargetType()) + { + case SMART_TARGET_CREATURE_RANGE: + case SMART_TARGET_CREATURE_GUID: + case SMART_TARGET_CREATURE_DISTANCE: + case SMART_TARGET_CLOSEST_CREATURE: + case SMART_TARGET_CLOSEST_PLAYER: + case SMART_TARGET_PLAYER_RANGE: + case SMART_TARGET_PLAYER_DISTANCE: + _targets = GetTargets(e); + break; + default: + return; + } + + if (!_targets) + return; + + Unit* target = nullptr; + + for (ObjectList::const_iterator itr = _targets->begin(); itr != _targets->end(); ++itr) + { + if (IsUnit(*itr) && me->IsFriendlyTo((*itr)->ToUnit()) && (*itr)->ToUnit()->IsAlive() && (*itr)->ToUnit()->IsInCombat()) + { + uint32 healthPct = uint32((*itr)->ToUnit()->GetHealthPct()); + + if (healthPct > e.event.friendlyHealthPct.maxHpPct || healthPct < e.event.friendlyHealthPct.minHpPct) + continue; + + target = (*itr)->ToUnit(); + break; + } + } + + delete _targets; + + if (!target) + return; + + ProcessTimedAction(e, e.event.friendlyHealthPct.repeatMin, e.event.friendlyHealthPct.repeatMax, target); + break; + } + case SMART_EVENT_DISTANCE_CREATURE: + { + if (!me) + return; + + WorldObject* creature = nullptr; + + if (e.event.distance.guid != 0) + { + creature = FindCreatureNear(me, e.event.distance.guid); + + if (!creature) + return; + + if (!me->IsInRange(creature, 0, (float)e.event.distance.dist)) + return; + } + else if (e.event.distance.entry != 0) + { + std::list list; + me->GetCreatureListWithEntryInGrid(list, e.event.distance.entry, (float)e.event.distance.dist); + + if (!list.empty()) + creature = list.front(); + } + + if (creature) + ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat); + + break; + } + case SMART_EVENT_DISTANCE_GAMEOBJECT: + { + if (!me) + return; + + WorldObject* gameobject = nullptr; + + if (e.event.distance.guid != 0) + { + gameobject = FindGameObjectNear(me, e.event.distance.guid); + + if (!gameobject) + return; + + if (!me->IsInRange(gameobject, 0, (float)e.event.distance.dist)) + return; + } + else if (e.event.distance.entry != 0) + { + std::list list; + me->GetGameObjectListWithEntryInGrid(list, e.event.distance.entry, (float)e.event.distance.dist); + + if (!list.empty()) + gameobject = list.front(); + } + + if (gameobject) + ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat); + + break; + } + case SMART_EVENT_COUNTER_SET: + if (e.event.counter.id != var0 || GetCounterValue(e.event.counter.id) != e.event.counter.value) + return; + + ProcessTimedAction(e, e.event.counter.cooldownMin, e.event.counter.cooldownMax); + break; + case SMART_EVENT_NEAR_PLAYERS: + { + float range = (float)e.event.nearPlayer.radius; + ObjectList* units = GetWorldObjectsInDist(range); + if (!units->empty()) + { + units->remove_if([](WorldObject * unit) { return unit->GetTypeId() != TYPEID_PLAYER; }); + + if (units->size() >= e.event.nearPlayer.minCount) + ProcessAction(e, unit); + } + RecalcTimer(e, e.event.nearPlayer.checkTimer, e.event.nearPlayer.checkTimer); + break; + } + case SMART_EVENT_NEAR_PLAYERS_NEGATION: + { + float range = (float)e.event.nearPlayerNegation.radius; + ObjectList* units = GetWorldObjectsInDist(range); + if (!units->empty()) + { + units->remove_if([](WorldObject * unit) { return unit->GetTypeId() != TYPEID_PLAYER; }); + + if (units->size() < e.event.nearPlayerNegation.minCount) + ProcessAction(e, unit); + } + RecalcTimer(e, e.event.nearPlayerNegation.checkTimer, e.event.nearPlayerNegation.checkTimer); + break; + } + default: + sLog->outErrorDb("SmartScript::ProcessEvent: Unhandled Event type %u", e.GetEventType()); + break; } } @@ -4477,28 +4477,28 @@ void SmartScript::InitTimer(SmartScriptHolder& e) { switch (e.GetEventType()) { - //set only events which have initial timers - case SMART_EVENT_NEAR_PLAYERS: - case SMART_EVENT_NEAR_PLAYERS_NEGATION: - RecalcTimer(e, e.event.nearPlayer.firstTimer, e.event.nearPlayer.firstTimer); - break; - case SMART_EVENT_UPDATE: - case SMART_EVENT_UPDATE_IC: - case SMART_EVENT_UPDATE_OOC: - RecalcTimer(e, e.event.minMaxRepeat.min, e.event.minMaxRepeat.max); - break; - case SMART_EVENT_OOC_LOS: - case SMART_EVENT_IC_LOS: + //set only events which have initial timers + case SMART_EVENT_NEAR_PLAYERS: + case SMART_EVENT_NEAR_PLAYERS_NEGATION: + RecalcTimer(e, e.event.nearPlayer.firstTimer, e.event.nearPlayer.firstTimer); + break; + case SMART_EVENT_UPDATE: + case SMART_EVENT_UPDATE_IC: + case SMART_EVENT_UPDATE_OOC: + RecalcTimer(e, e.event.minMaxRepeat.min, e.event.minMaxRepeat.max); + break; + case SMART_EVENT_OOC_LOS: + case SMART_EVENT_IC_LOS: // Xinef: wtf is this bullshit? cooldown should be processed AFTER action is done, not before... //RecalcTimer(e, e.event.los.cooldownMin, e.event.los.cooldownMax); //break; - case SMART_EVENT_DISTANCE_CREATURE: - case SMART_EVENT_DISTANCE_GAMEOBJECT: - RecalcTimer(e, e.event.distance.repeat, e.event.distance.repeat); - break; - default: - e.active = true; - break; + case SMART_EVENT_DISTANCE_CREATURE: + case SMART_EVENT_DISTANCE_GAMEOBJECT: + RecalcTimer(e, e.event.distance.repeat, e.event.distance.repeat); + break; + default: + e.active = true; + break; } } void SmartScript::RecalcTimer(SmartScriptHolder& e, uint32 min, uint32 max) @@ -4540,43 +4540,43 @@ void SmartScript::UpdateTimer(SmartScriptHolder& e, uint32 const diff) e.active = true;//activate events with cooldown switch (e.GetEventType())//process ONLY timed events { - case SMART_EVENT_NEAR_PLAYERS: - case SMART_EVENT_NEAR_PLAYERS_NEGATION: - case SMART_EVENT_UPDATE: - case SMART_EVENT_UPDATE_OOC: - case SMART_EVENT_UPDATE_IC: - case SMART_EVENT_HEALTH_PCT: - case SMART_EVENT_TARGET_HEALTH_PCT: - case SMART_EVENT_MANA_PCT: - case SMART_EVENT_TARGET_MANA_PCT: - case SMART_EVENT_RANGE: - case SMART_EVENT_VICTIM_CASTING: - case SMART_EVENT_FRIENDLY_HEALTH: - case SMART_EVENT_FRIENDLY_IS_CC: - case SMART_EVENT_FRIENDLY_MISSING_BUFF: - case SMART_EVENT_HAS_AURA: - case SMART_EVENT_TARGET_BUFFED: - case SMART_EVENT_IS_BEHIND_TARGET: - case SMART_EVENT_FRIENDLY_HEALTH_PCT: - case SMART_EVENT_DISTANCE_CREATURE: - case SMART_EVENT_DISTANCE_GAMEOBJECT: - { - ProcessEvent(e); - if (e.GetScriptType() == SMART_SCRIPT_TYPE_TIMED_ACTIONLIST) - { - e.enableTimed = false;//disable event if it is in an ActionList and was processed once - for (SmartAIEventList::iterator i = mTimedActionList.begin(); i != mTimedActionList.end(); ++i) + case SMART_EVENT_NEAR_PLAYERS: + case SMART_EVENT_NEAR_PLAYERS_NEGATION: + case SMART_EVENT_UPDATE: + case SMART_EVENT_UPDATE_OOC: + case SMART_EVENT_UPDATE_IC: + case SMART_EVENT_HEALTH_PCT: + case SMART_EVENT_TARGET_HEALTH_PCT: + case SMART_EVENT_MANA_PCT: + case SMART_EVENT_TARGET_MANA_PCT: + case SMART_EVENT_RANGE: + case SMART_EVENT_VICTIM_CASTING: + case SMART_EVENT_FRIENDLY_HEALTH: + case SMART_EVENT_FRIENDLY_IS_CC: + case SMART_EVENT_FRIENDLY_MISSING_BUFF: + case SMART_EVENT_HAS_AURA: + case SMART_EVENT_TARGET_BUFFED: + case SMART_EVENT_IS_BEHIND_TARGET: + case SMART_EVENT_FRIENDLY_HEALTH_PCT: + case SMART_EVENT_DISTANCE_CREATURE: + case SMART_EVENT_DISTANCE_GAMEOBJECT: { - //find the first event which is not the current one and enable it - if (i->event_id > e.event_id) + ProcessEvent(e); + if (e.GetScriptType() == SMART_SCRIPT_TYPE_TIMED_ACTIONLIST) { - i->enableTimed = true; - break; + e.enableTimed = false;//disable event if it is in an ActionList and was processed once + for (SmartAIEventList::iterator i = mTimedActionList.begin(); i != mTimedActionList.end(); ++i) + { + //find the first event which is not the current one and enable it + if (i->event_id > e.event_id) + { + i->enableTimed = true; + break; + } + } } + break; } - } - break; - } } } else @@ -4728,23 +4728,23 @@ void SmartScript::OnInitialize(WorldObject* obj, AreaTrigger const* at) { switch (obj->GetTypeId()) { - case TYPEID_UNIT: - mScriptType = SMART_SCRIPT_TYPE_CREATURE; - me = obj->ToCreature(); + case TYPEID_UNIT: + mScriptType = SMART_SCRIPT_TYPE_CREATURE; + me = obj->ToCreature(); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::OnInitialize: source is Creature %u", me->GetEntry()); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::OnInitialize: source is Creature %u", me->GetEntry()); #endif - break; - case TYPEID_GAMEOBJECT: - mScriptType = SMART_SCRIPT_TYPE_GAMEOBJECT; - go = obj->ToGameObject(); + break; + case TYPEID_GAMEOBJECT: + mScriptType = SMART_SCRIPT_TYPE_GAMEOBJECT; + go = obj->ToGameObject(); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::OnInitialize: source is GameObject %u", go->GetEntry()); + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartScript::OnInitialize: source is GameObject %u", go->GetEntry()); #endif - break; - default: - sLog->outError("SmartScript::OnInitialize: Unhandled TypeID !WARNING!"); - return; + break; + default: + sLog->outError("SmartScript::OnInitialize: Unhandled TypeID !WARNING!"); + return; } } else if (at) diff --git a/src/server/game/AI/SmartScripts/SmartScript.h b/src/server/game/AI/SmartScripts/SmartScript.h index dd2bc9a00..573a7897d 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.h +++ b/src/server/game/AI/SmartScripts/SmartScript.h @@ -19,314 +19,314 @@ class SmartScript { - public: - SmartScript(); - ~SmartScript(); +public: + SmartScript(); + ~SmartScript(); - void OnInitialize(WorldObject* obj, AreaTrigger const* at = nullptr); - void GetScript(); - void FillScript(SmartAIEventList e, WorldObject* obj, AreaTrigger const* at); + void OnInitialize(WorldObject* obj, AreaTrigger const* at = nullptr); + void GetScript(); + void FillScript(SmartAIEventList e, WorldObject* obj, AreaTrigger const* at); - void ProcessEventsFor(SMART_EVENT e, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); - void ProcessEvent(SmartScriptHolder& e, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); - bool CheckTimer(SmartScriptHolder const& e) const; - void RecalcTimer(SmartScriptHolder& e, uint32 min, uint32 max); - void UpdateTimer(SmartScriptHolder& e, uint32 const diff); - void InitTimer(SmartScriptHolder& e); - void ProcessAction(SmartScriptHolder& e, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); - void ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); - ObjectList* GetTargets(SmartScriptHolder const& e, Unit* invoker = nullptr); - ObjectList* GetWorldObjectsInDist(float dist); - void InstallTemplate(SmartScriptHolder const& e); - SmartScriptHolder CreateSmartEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 target_param4, uint32 phaseMask); - void AddEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 target_param4, uint32 phaseMask); - void SetPathId(uint32 id) { mPathId = id; } - uint32 GetPathId() const { return mPathId; } - WorldObject* GetBaseObject() + void ProcessEventsFor(SMART_EVENT e, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); + void ProcessEvent(SmartScriptHolder& e, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); + bool CheckTimer(SmartScriptHolder const& e) const; + void RecalcTimer(SmartScriptHolder& e, uint32 min, uint32 max); + void UpdateTimer(SmartScriptHolder& e, uint32 const diff); + void InitTimer(SmartScriptHolder& e); + void ProcessAction(SmartScriptHolder& e, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); + void ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit = NULL, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = NULL, GameObject* gob = nullptr); + ObjectList* GetTargets(SmartScriptHolder const& e, Unit* invoker = nullptr); + ObjectList* GetWorldObjectsInDist(float dist); + void InstallTemplate(SmartScriptHolder const& e); + SmartScriptHolder CreateSmartEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 target_param4, uint32 phaseMask); + void AddEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 target_param4, uint32 phaseMask); + void SetPathId(uint32 id) { mPathId = id; } + uint32 GetPathId() const { return mPathId; } + WorldObject* GetBaseObject() + { + WorldObject* obj = nullptr; + if (me) + obj = me; + else if (go) + obj = go; + return obj; + } + + bool IsUnit(WorldObject* obj) + { + return obj && obj->IsInWorld() && (obj->GetTypeId() == TYPEID_UNIT || obj->GetTypeId() == TYPEID_PLAYER); + } + + bool IsPlayer(WorldObject* obj) + { + return obj && obj->IsInWorld() && obj->GetTypeId() == TYPEID_PLAYER; + } + + bool IsCreature(WorldObject* obj) + { + return obj && obj->IsInWorld() && obj->GetTypeId() == TYPEID_UNIT; + } + + bool IsGameObject(WorldObject* obj) + { + return obj && obj->IsInWorld() && obj->GetTypeId() == TYPEID_GAMEOBJECT; + } + + void OnUpdate(const uint32 diff); + void OnMoveInLineOfSight(Unit* who); + + Unit* DoSelectLowestHpFriendly(float range, uint32 MinHPDiff); + void DoFindFriendlyCC(std::list& _list, float range); + void DoFindFriendlyMissingBuff(std::list& list, float range, uint32 spellid); + Unit* DoFindClosestFriendlyInRange(float range, bool playerOnly); + + void StoreTargetList(ObjectList* targets, uint32 id) + { + if (!targets) + return; + + if (mTargetStorage->find(id) != mTargetStorage->end()) { - WorldObject* obj = nullptr; - if (me) - obj = me; - else if (go) - obj = go; - return obj; - } - - bool IsUnit(WorldObject* obj) - { - return obj && obj->IsInWorld() && (obj->GetTypeId() == TYPEID_UNIT || obj->GetTypeId() == TYPEID_PLAYER); - } - - bool IsPlayer(WorldObject* obj) - { - return obj && obj->IsInWorld() && obj->GetTypeId() == TYPEID_PLAYER; - } - - bool IsCreature(WorldObject* obj) - { - return obj && obj->IsInWorld() && obj->GetTypeId() == TYPEID_UNIT; - } - - bool IsGameObject(WorldObject* obj) - { - return obj && obj->IsInWorld() && obj->GetTypeId() == TYPEID_GAMEOBJECT; - } - - void OnUpdate(const uint32 diff); - void OnMoveInLineOfSight(Unit* who); - - Unit* DoSelectLowestHpFriendly(float range, uint32 MinHPDiff); - void DoFindFriendlyCC(std::list& _list, float range); - void DoFindFriendlyMissingBuff(std::list& list, float range, uint32 spellid); - Unit* DoFindClosestFriendlyInRange(float range, bool playerOnly); - - void StoreTargetList(ObjectList* targets, uint32 id) - { - if (!targets) + // check if already stored + if ((*mTargetStorage)[id]->Equals(targets)) return; - if (mTargetStorage->find(id) != mTargetStorage->end()) + delete (*mTargetStorage)[id]; + } + + (*mTargetStorage)[id] = new ObjectGuidList(targets, GetBaseObject()); + } + + bool IsSmart(Creature* c = nullptr) + { + bool smart = true; + if (c && c->GetAIName() != "SmartAI") + smart = false; + + if (!me || me->GetAIName() != "SmartAI") + smart = false; + + if (!smart) + sLog->outErrorDb("SmartScript: Action target Creature(entry: %u) is not using SmartAI, action skipped to prevent crash.", c ? c->GetEntry() : (me ? me->GetEntry() : 0)); + + return smart; + } + + bool IsSmartGO(GameObject* g = nullptr) + { + bool smart = true; + if (g && g->GetAIName() != "SmartGameObjectAI") + smart = false; + + if (!go || go->GetAIName() != "SmartGameObjectAI") + smart = false; + if (!smart) + sLog->outErrorDb("SmartScript: Action target GameObject(entry: %u) is not using SmartGameObjectAI, action skipped to prevent crash.", g ? g->GetEntry() : (go ? go->GetEntry() : 0)); + + return smart; + } + + ObjectList* GetTargetList(uint32 id) + { + ObjectListMap::iterator itr = mTargetStorage->find(id); + if (itr != mTargetStorage->end()) + return (*itr).second->GetObjectList(); + return nullptr; + } + + void StoreCounter(uint32 id, uint32 value, uint32 reset) + { + CounterMap::iterator itr = mCounterList.find(id); + if (itr != mCounterList.end()) + { + if (reset == 0) + itr->second += value; + else + itr->second = value; + } + else + mCounterList.insert(std::make_pair(id, value)); + + ProcessEventsFor(SMART_EVENT_COUNTER_SET, NULL, id); + } + + uint32 GetCounterValue(uint32 id) + { + CounterMap::iterator itr = mCounterList.find(id); + if (itr != mCounterList.end()) + return itr->second; + return 0; + } + + GameObject* FindGameObjectNear(WorldObject* searchObject, uint32 guid) const + { + GameObject* gameObject = nullptr; + + CellCoord p(acore::ComputeCellCoord(searchObject->GetPositionX(), searchObject->GetPositionY())); + Cell cell(p); + + acore::GameObjectWithDbGUIDCheck goCheck(guid); + acore::GameObjectSearcher checker(searchObject, gameObject, goCheck); + + TypeContainerVisitor, GridTypeMapContainer > objectChecker(checker); + cell.Visit(p, objectChecker, *searchObject->GetMap(), *searchObject, searchObject->GetVisibilityRange()); + + return gameObject; + } + + Creature* FindCreatureNear(WorldObject* searchObject, uint32 guid) const + { + Creature* creature = nullptr; + CellCoord p(acore::ComputeCellCoord(searchObject->GetPositionX(), searchObject->GetPositionY())); + Cell cell(p); + + acore::CreatureWithDbGUIDCheck target_check(guid); + acore::CreatureSearcher checker(searchObject, creature, target_check); + + TypeContainerVisitor, GridTypeMapContainer > unit_checker(checker); + cell.Visit(p, unit_checker, *searchObject->GetMap(), *searchObject, searchObject->GetVisibilityRange()); + + return creature; + } + + ObjectListMap* mTargetStorage; + + void OnReset(); + void ResetBaseObject() + { + if (meOrigGUID) + { + if (Creature* m = HashMapHolder::Find(meOrigGUID)) { - // check if already stored - if ((*mTargetStorage)[id]->Equals(targets)) + me = m; + go = nullptr; + } + } + if (goOrigGUID) + { + if (GameObject* o = HashMapHolder::Find(goOrigGUID)) + { + me = nullptr; + go = o; + } + } + goOrigGUID = 0; + meOrigGUID = 0; + } + + //TIMED_ACTIONLIST (script type 9 aka script9) + void SetScript9(SmartScriptHolder& e, uint32 entry); + Unit* GetLastInvoker(Unit* invoker = nullptr); + uint64 mLastInvoker; + typedef std::unordered_map CounterMap; + CounterMap mCounterList; + + // Xinef: Fix Combat Movement + void SetActualCombatDist(uint32 dist) { mActualCombatDist = dist; } + void RestoreMaxCombatDist() { mActualCombatDist = mMaxCombatDist; } + uint32 GetActualCombatDist() const { return mActualCombatDist; } + uint32 GetMaxCombatDist() const { return mMaxCombatDist; } + + // Xinef: SmartCasterAI, replace above + void SetCasterActualDist(float dist) { smartCasterActualDist = dist; } + void RestoreCasterMaxDist() { smartCasterActualDist = smartCasterMaxDist; } + Powers GetCasterPowerType() const { return smartCasterPowerType; } + float GetCasterActualDist() const { return smartCasterActualDist; } + float GetCasterMaxDist() const { return smartCasterMaxDist; } + + bool AllowPhaseReset() const { return _allowPhaseReset; } + void SetPhaseReset(bool allow) { _allowPhaseReset = allow; } + +private: + void IncPhase(uint32 p) + { + // Xinef: protect phase from overflowing + mEventPhase = std::min(SMART_EVENT_PHASE_12, mEventPhase + p); + } + + void DecPhase(uint32 p) + { + if (p >= mEventPhase) + mEventPhase = 0; + else + mEventPhase -= p; + } + bool IsInPhase(uint32 p) const + { + if (mEventPhase == 0) + return false; + return (1 << (mEventPhase - 1)) & p; + } + void SetPhase(uint32 p = 0) { mEventPhase = p; } + + SmartAIEventList mEvents; + SmartAIEventList mInstallEvents; + SmartAIEventList mTimedActionList; + bool isProcessingTimedActionList; + Creature* me; + uint64 meOrigGUID; + GameObject* go; + uint64 goOrigGUID; + AreaTrigger const* trigger; + SmartScriptType mScriptType; + uint32 mEventPhase; + + std::unordered_map mStoredDecimals; + uint32 mPathId; + SmartAIEventStoredList mStoredEvents; + std::list mRemIDs; + + uint32 mTextTimer; + uint32 mLastTextID; + uint32 mTalkerEntry; + bool mUseTextTimer; + + // Xinef: Fix Combat Movement + uint32 mActualCombatDist; + uint32 mMaxCombatDist; + + // Xinef: SmartCasterAI, replace above in future + uint32 smartCasterActualDist; + uint32 smartCasterMaxDist; + Powers smartCasterPowerType; + + // Xinef: misc + bool _allowPhaseReset; + + SMARTAI_TEMPLATE mTemplate; + void InstallEvents(); + + void RemoveStoredEvent (uint32 id) + { + if (!mStoredEvents.empty()) + { + for (SmartAIEventStoredList::iterator i = mStoredEvents.begin(); i != mStoredEvents.end(); ++i) + { + if (i->event_id == id) + { + mStoredEvents.erase(i); return; - - delete (*mTargetStorage)[id]; - } - - (*mTargetStorage)[id] = new ObjectGuidList(targets, GetBaseObject()); - } - - bool IsSmart(Creature* c = nullptr) - { - bool smart = true; - if (c && c->GetAIName() != "SmartAI") - smart = false; - - if (!me || me->GetAIName() != "SmartAI") - smart = false; - - if (!smart) - sLog->outErrorDb("SmartScript: Action target Creature(entry: %u) is not using SmartAI, action skipped to prevent crash.", c ? c->GetEntry() : (me ? me->GetEntry() : 0)); - - return smart; - } - - bool IsSmartGO(GameObject* g = nullptr) - { - bool smart = true; - if (g && g->GetAIName() != "SmartGameObjectAI") - smart = false; - - if (!go || go->GetAIName() != "SmartGameObjectAI") - smart = false; - if (!smart) - sLog->outErrorDb("SmartScript: Action target GameObject(entry: %u) is not using SmartGameObjectAI, action skipped to prevent crash.", g ? g->GetEntry() : (go ? go->GetEntry() : 0)); - - return smart; - } - - ObjectList* GetTargetList(uint32 id) - { - ObjectListMap::iterator itr = mTargetStorage->find(id); - if (itr != mTargetStorage->end()) - return (*itr).second->GetObjectList(); - return nullptr; - } - - void StoreCounter(uint32 id, uint32 value, uint32 reset) - { - CounterMap::iterator itr = mCounterList.find(id); - if (itr != mCounterList.end()) - { - if (reset == 0) - itr->second += value; - else - itr->second = value; - } - else - mCounterList.insert(std::make_pair(id, value)); - - ProcessEventsFor(SMART_EVENT_COUNTER_SET, NULL, id); - } - - uint32 GetCounterValue(uint32 id) - { - CounterMap::iterator itr = mCounterList.find(id); - if (itr != mCounterList.end()) - return itr->second; - return 0; - } - - GameObject* FindGameObjectNear(WorldObject* searchObject, uint32 guid) const - { - GameObject* gameObject = nullptr; - - CellCoord p(acore::ComputeCellCoord(searchObject->GetPositionX(), searchObject->GetPositionY())); - Cell cell(p); - - acore::GameObjectWithDbGUIDCheck goCheck(guid); - acore::GameObjectSearcher checker(searchObject, gameObject, goCheck); - - TypeContainerVisitor, GridTypeMapContainer > objectChecker(checker); - cell.Visit(p, objectChecker, *searchObject->GetMap(), *searchObject, searchObject->GetVisibilityRange()); - - return gameObject; - } - - Creature* FindCreatureNear(WorldObject* searchObject, uint32 guid) const - { - Creature* creature = nullptr; - CellCoord p(acore::ComputeCellCoord(searchObject->GetPositionX(), searchObject->GetPositionY())); - Cell cell(p); - - acore::CreatureWithDbGUIDCheck target_check(guid); - acore::CreatureSearcher checker(searchObject, creature, target_check); - - TypeContainerVisitor, GridTypeMapContainer > unit_checker(checker); - cell.Visit(p, unit_checker, *searchObject->GetMap(), *searchObject, searchObject->GetVisibilityRange()); - - return creature; - } - - ObjectListMap* mTargetStorage; - - void OnReset(); - void ResetBaseObject() - { - if (meOrigGUID) - { - if (Creature* m = HashMapHolder::Find(meOrigGUID)) - { - me = m; - go = nullptr; } + } - if (goOrigGUID) + } + } + SmartScriptHolder FindLinkedEvent (uint32 link) + { + if (!mEvents.empty()) + { + for (SmartAIEventList::iterator i = mEvents.begin(); i != mEvents.end(); ++i) { - if (GameObject* o = HashMapHolder::Find(goOrigGUID)) + if (i->event_id == link) { - me = nullptr; - go = o; + return (*i); } - } - goOrigGUID = 0; - meOrigGUID = 0; - } - //TIMED_ACTIONLIST (script type 9 aka script9) - void SetScript9(SmartScriptHolder& e, uint32 entry); - Unit* GetLastInvoker(Unit* invoker = nullptr); - uint64 mLastInvoker; - typedef std::unordered_map CounterMap; - CounterMap mCounterList; - - // Xinef: Fix Combat Movement - void SetActualCombatDist(uint32 dist) { mActualCombatDist = dist; } - void RestoreMaxCombatDist() { mActualCombatDist = mMaxCombatDist; } - uint32 GetActualCombatDist() const { return mActualCombatDist; } - uint32 GetMaxCombatDist() const { return mMaxCombatDist; } - - // Xinef: SmartCasterAI, replace above - void SetCasterActualDist(float dist) { smartCasterActualDist = dist; } - void RestoreCasterMaxDist() { smartCasterActualDist = smartCasterMaxDist; } - Powers GetCasterPowerType() const { return smartCasterPowerType; } - float GetCasterActualDist() const { return smartCasterActualDist; } - float GetCasterMaxDist() const { return smartCasterMaxDist; } - - bool AllowPhaseReset() const { return _allowPhaseReset; } - void SetPhaseReset(bool allow) { _allowPhaseReset = allow; } - - private: - void IncPhase(uint32 p) - { - // Xinef: protect phase from overflowing - mEventPhase = std::min(SMART_EVENT_PHASE_12, mEventPhase + p); - } - - void DecPhase(uint32 p) - { - if (p >= mEventPhase) - mEventPhase = 0; - else - mEventPhase -= p; - } - bool IsInPhase(uint32 p) const - { - if (mEventPhase == 0) - return false; - return (1 << (mEventPhase - 1)) & p; - } - void SetPhase(uint32 p = 0) { mEventPhase = p; } - - SmartAIEventList mEvents; - SmartAIEventList mInstallEvents; - SmartAIEventList mTimedActionList; - bool isProcessingTimedActionList; - Creature* me; - uint64 meOrigGUID; - GameObject* go; - uint64 goOrigGUID; - AreaTrigger const* trigger; - SmartScriptType mScriptType; - uint32 mEventPhase; - - std::unordered_map mStoredDecimals; - uint32 mPathId; - SmartAIEventStoredList mStoredEvents; - std::list mRemIDs; - - uint32 mTextTimer; - uint32 mLastTextID; - uint32 mTalkerEntry; - bool mUseTextTimer; - - // Xinef: Fix Combat Movement - uint32 mActualCombatDist; - uint32 mMaxCombatDist; - - // Xinef: SmartCasterAI, replace above in future - uint32 smartCasterActualDist; - uint32 smartCasterMaxDist; - Powers smartCasterPowerType; - - // Xinef: misc - bool _allowPhaseReset; - - SMARTAI_TEMPLATE mTemplate; - void InstallEvents(); - - void RemoveStoredEvent (uint32 id) - { - if (!mStoredEvents.empty()) - { - for (SmartAIEventStoredList::iterator i = mStoredEvents.begin(); i != mStoredEvents.end(); ++i) - { - if (i->event_id == id) - { - mStoredEvents.erase(i); - return; - } - - } } } - SmartScriptHolder FindLinkedEvent (uint32 link) - { - if (!mEvents.empty()) - { - for (SmartAIEventList::iterator i = mEvents.begin(); i != mEvents.end(); ++i) - { - if (i->event_id == link) - { - return (*i); - } - - } - } - SmartScriptHolder s; - return s; - } + SmartScriptHolder s; + return s; + } }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp index 234d16b64..dbec12da7 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp @@ -80,8 +80,7 @@ void SmartWaypointMgr::LoadFromDB() last_entry = entry; total++; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u SmartAI waypoint paths (total %u waypoints) in %u ms", count, total, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -141,32 +140,32 @@ void SmartAIMgr::LoadSmartAIFromDB() switch (source_type) { case SMART_SCRIPT_TYPE_CREATURE: - { - if (!sObjectMgr->GetCreatureTemplate((uint32)temp.entryOrGuid)) { - sLog->outErrorDb("SmartAIMgr::LoadSmartAIFromDB: Creature entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); - continue; + if (!sObjectMgr->GetCreatureTemplate((uint32)temp.entryOrGuid)) + { + sLog->outErrorDb("SmartAIMgr::LoadSmartAIFromDB: Creature entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); + continue; + } + break; } - break; - } case SMART_SCRIPT_TYPE_GAMEOBJECT: - { - if (!sObjectMgr->GetGameObjectTemplate((uint32)temp.entryOrGuid)) { - sLog->outErrorDb("SmartAIMgr::LoadSmartAIFromDB: GameObject entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); - continue; + if (!sObjectMgr->GetGameObjectTemplate((uint32)temp.entryOrGuid)) + { + sLog->outErrorDb("SmartAIMgr::LoadSmartAIFromDB: GameObject entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); + continue; + } + break; } - break; - } case SMART_SCRIPT_TYPE_AREATRIGGER: - { - if (!sObjectMgr->GetAreaTrigger((uint32)temp.entryOrGuid)) { - sLog->outErrorDb("SmartAIMgr::LoadSmartAIFromDB: AreaTrigger entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); - continue; + if (!sObjectMgr->GetAreaTrigger((uint32)temp.entryOrGuid)) + { + sLog->outErrorDb("SmartAIMgr::LoadSmartAIFromDB: AreaTrigger entry (%u) does not exist, skipped loading.", uint32(temp.entryOrGuid)); + continue; + } + break; } - break; - } case SMART_SCRIPT_TYPE_TIMED_ACTIONLIST: break;//nothing to check, really default: @@ -269,8 +268,7 @@ void SmartAIMgr::LoadSmartAIFromDB() } // store the new event mEventMap[source_type][temp.entryOrGuid].push_back(temp); - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u SmartAI scripts in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -284,46 +282,46 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { case SMART_TARGET_CREATURE_DISTANCE: case SMART_TARGET_CREATURE_RANGE: - { - if (e.target.unitDistance.creature && !sObjectMgr->GetCreatureTemplate(e.target.unitDistance.creature)) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.unitDistance.creature); - return false; + if (e.target.unitDistance.creature && !sObjectMgr->GetCreatureTemplate(e.target.unitDistance.creature)) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.unitDistance.creature); + return false; + } + break; } - break; - } case SMART_TARGET_GAMEOBJECT_DISTANCE: case SMART_TARGET_GAMEOBJECT_RANGE: - { - if (e.target.goDistance.entry && !sObjectMgr->GetGameObjectTemplate(e.target.goDistance.entry)) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.goDistance.entry); - return false; + if (e.target.goDistance.entry && !sObjectMgr->GetGameObjectTemplate(e.target.goDistance.entry)) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.goDistance.entry); + return false; + } + break; } - break; - } case SMART_TARGET_CREATURE_GUID: - { - if (e.target.unitGUID.entry && !IsCreatureValid(e, e.target.unitGUID.entry)) - return false; - break; - } + { + if (e.target.unitGUID.entry && !IsCreatureValid(e, e.target.unitGUID.entry)) + return false; + break; + } case SMART_TARGET_GAMEOBJECT_GUID: - { - if (e.target.goGUID.entry && !IsGameObjectValid(e, e.target.goGUID.entry)) - return false; - break; - } + { + if (e.target.goGUID.entry && !IsGameObjectValid(e, e.target.goGUID.entry)) + return false; + break; + } case SMART_TARGET_PLAYER_DISTANCE: case SMART_TARGET_CLOSEST_PLAYER: - { - if (e.target.playerDistance.dist == 0) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u has maxDist 0 as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); - return false; + if (e.target.playerDistance.dist == 0) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u has maxDist 0 as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + return false; + } + break; } - break; - } case SMART_TARGET_PLAYER_RANGE: case SMART_TARGET_SELF: case SMART_TARGET_VICTIM: @@ -369,8 +367,8 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return false; } if (e.action.type <= 0 - || (e.action.type >= SMART_ACTION_TC_END && e.action.type <= SMART_ACTION_AC_START) - || e.action.type >= SMART_ACTION_AC_END) + || (e.action.type >= SMART_ACTION_TC_END && e.action.type <= SMART_ACTION_AC_START) + || e.action.type >= SMART_ACTION_AC_END) { sLog->outErrorDb("SmartAIMgr: EntryOrGuid %d using event(%u) has an invalid action type (%u), skipped.", e.entryOrGuid, e.event_id, e.GetActionType()); return false; @@ -402,12 +400,13 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (e.target.type < 0 || (e.target.type >= SMART_TARGET_TC_END && e.target.type < SMART_TARGET_AC_START) || e.target.type >= SMART_TARGET_AC_END) { sLog->outErrorDb("SmartAIMgr: EntryOrGuid %d using event(%u) has an invalid target type (%u), skipped.", - e.entryOrGuid, e.event_id, e.GetTargetType()); + e.entryOrGuid, e.event_id, e.GetTargetType()); return false; } - if (e.target.type == SMART_TARGET_LOOT_RECIPIENTS || e.target.type == SMART_TARGET_VEHICLE_PASSENGER) { + if (e.target.type == SMART_TARGET_LOOT_RECIPIENTS || e.target.type == SMART_TARGET_VEHICLE_PASSENGER) + { sLog->outErrorDb("SmartAIMgr: EntryOrGuid %d using event(%u) has a target type that is not yet supported on AzerothCore (%u), skipped.", - e.entryOrGuid, e.event_id, e.GetTargetType()); + e.entryOrGuid, e.event_id, e.GetTargetType()); return false; } if (e.event.event_phase_mask > SMART_EVENT_PHASE_ALL) @@ -472,7 +471,8 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) break; case SMART_EVENT_OOC_LOS: case SMART_EVENT_IC_LOS: - if (!IsMinMaxValid(e, e.event.los.cooldownMin, e.event.los.cooldownMax)) { + if (!IsMinMaxValid(e, e.event.los.cooldownMin, e.event.los.cooldownMax)) + { return false; } @@ -501,17 +501,17 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return false; break; case SMART_EVENT_FRIENDLY_MISSING_BUFF: - { - if (!IsSpellValid(e, e.event.missingBuff.spell)) - return false; + { + if (!IsSpellValid(e, e.event.missingBuff.spell)) + return false; - if (!NotNULL(e, e.event.missingBuff.radius)) - return false; + if (!NotNULL(e, e.event.missingBuff.radius)) + return false; - if (!IsMinMaxValid(e, e.event.missingBuff.repeatMin, e.event.missingBuff.repeatMax)) - return false; - break; - } + if (!IsMinMaxValid(e, e.event.missingBuff.repeatMin, e.event.missingBuff.repeatMax)) + return false; + break; + } case SMART_EVENT_KILL: if (!IsMinMaxValid(e, e.event.kill.cooldownMin, e.event.kill.cooldownMax)) return false; @@ -548,84 +548,84 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return false; break; case SMART_EVENT_RECEIVE_EMOTE: - { - if (e.event.emote.emote && !IsTextEmoteValid(e, e.event.emote.emote)) - return false; + { + if (e.event.emote.emote && !IsTextEmoteValid(e, e.event.emote.emote)) + return false; - if (!IsMinMaxValid(e, e.event.emote.cooldownMin, e.event.emote.cooldownMax)) - return false; - break; - } + if (!IsMinMaxValid(e, e.event.emote.cooldownMin, e.event.emote.cooldownMax)) + return false; + break; + } case SMART_EVENT_HAS_AURA: case SMART_EVENT_TARGET_BUFFED: - { - if (!IsSpellValid(e, e.event.aura.spell)) - return false; - - if (!IsMinMaxValid(e, e.event.aura.repeatMin, e.event.aura.repeatMax)) - return false; - break; - } - case SMART_EVENT_TRANSPORT_ADDCREATURE: - { - if (e.event.transportAddCreature.creature && !IsCreatureValid(e, e.event.transportAddCreature.creature)) - return false; - break; - } - case SMART_EVENT_MOVEMENTINFORM: - { - if (e.event.movementInform.type > NULL_MOTION_TYPE) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid Motion type %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.movementInform.type); - return false; + if (!IsSpellValid(e, e.event.aura.spell)) + return false; + + if (!IsMinMaxValid(e, e.event.aura.repeatMin, e.event.aura.repeatMax)) + return false; + break; + } + case SMART_EVENT_TRANSPORT_ADDCREATURE: + { + if (e.event.transportAddCreature.creature && !IsCreatureValid(e, e.event.transportAddCreature.creature)) + return false; + break; + } + case SMART_EVENT_MOVEMENTINFORM: + { + if (e.event.movementInform.type > NULL_MOTION_TYPE) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid Motion type %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.movementInform.type); + return false; + } + break; } - break; - } case SMART_EVENT_DATA_SET: - { - if (!IsMinMaxValid(e, e.event.dataSet.cooldownMin, e.event.dataSet.cooldownMax)) - return false; - break; - } + { + if (!IsMinMaxValid(e, e.event.dataSet.cooldownMin, e.event.dataSet.cooldownMax)) + return false; + break; + } case SMART_EVENT_AREATRIGGER_ONTRIGGER: - { - if (e.event.areatrigger.id && !IsAreaTriggerValid(e, e.event.areatrigger.id)) - return false; - break; - } + { + if (e.event.areatrigger.id && !IsAreaTriggerValid(e, e.event.areatrigger.id)) + return false; + break; + } case SMART_EVENT_TEXT_OVER: //if (e.event.textOver.textGroupID && !IsTextValid(e, e.event.textOver.textGroupID)) return false;// 0 is a valid text group! break; case SMART_EVENT_LINK: - { - if (e.link && e.link == e.event_id) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u, Event %u, Link Event is linking self (infinite loop), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id); - return false; + if (e.link && e.link == e.event_id) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u, Event %u, Link Event is linking self (infinite loop), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id); + return false; + } + break; } - break; - } case SMART_EVENT_IS_BEHIND_TARGET: if (!IsMinMaxValid(e, e.event.behindTarget.cooldownMin, e.event.behindTarget.cooldownMax)) return false; break; case SMART_EVENT_GAME_EVENT_START: case SMART_EVENT_GAME_EVENT_END: - { - GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); - if (e.event.gameEvent.gameEventId >= events.size() || !events[e.event.gameEvent.gameEventId].isValid()) - return false; - break; - } - case SMART_EVENT_ACTION_DONE: - { - if (e.event.doAction.eventId > EVENT_CHARGE) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid event id %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.doAction.eventId); - return false; + GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); + if (e.event.gameEvent.gameEventId >= events.size() || !events[e.event.gameEvent.gameEventId].isValid()) + return false; + break; + } + case SMART_EVENT_ACTION_DONE: + { + if (e.event.doAction.eventId > EVENT_CHARGE) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid event id %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.doAction.eventId); + return false; + } + break; } - break; - } case SMART_EVENT_FRIENDLY_HEALTH_PCT: if (!IsMinMaxValid(e, e.event.friendlyHealthPct.repeatMin, e.event.friendlyHealthPct.repeatMax)) return false; @@ -898,7 +898,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_SET_EVENT_PHASE: if (e.action.setEventPhase.phase >= SMART_EVENT_PHASE_MAX) { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set phase %u. Phase mask cannot be used past phase %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setEventPhase.phase, SMART_EVENT_PHASE_MAX-1); + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set phase %u. Phase mask cannot be used past phase %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setEventPhase.phase, SMART_EVENT_PHASE_MAX - 1); return false; } break; @@ -921,21 +921,21 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_RANDOM_PHASE: { if (e.action.randomPhase.phase1 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase2 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase3 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase4 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase5 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase6 >= SMART_EVENT_PHASE_MAX) + e.action.randomPhase.phase2 >= SMART_EVENT_PHASE_MAX || + e.action.randomPhase.phase3 >= SMART_EVENT_PHASE_MAX || + e.action.randomPhase.phase4 >= SMART_EVENT_PHASE_MAX || + e.action.randomPhase.phase5 >= SMART_EVENT_PHASE_MAX || + e.action.randomPhase.phase6 >= SMART_EVENT_PHASE_MAX) { sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } if (e.action.randomPhase.phase1 == 0 && - e.action.randomPhase.phase2 == 0 && - e.action.randomPhase.phase3 == 0 && - e.action.randomPhase.phase4 == 0 && - e.action.randomPhase.phase5 == 0 && - e.action.randomPhase.phase6 == 0) + e.action.randomPhase.phase2 == 0 && + e.action.randomPhase.phase3 == 0 && + e.action.randomPhase.phase4 == 0 && + e.action.randomPhase.phase5 == 0 && + e.action.randomPhase.phase6 == 0) { sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; @@ -945,7 +945,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_RANDOM_PHASE_RANGE: //PhaseMin, PhaseMax { if (e.action.randomPhaseRange.phaseMin >= SMART_EVENT_PHASE_MAX || - e.action.randomPhaseRange.phaseMax >= SMART_EVENT_PHASE_MAX) + e.action.randomPhaseRange.phaseMax >= SMART_EVENT_PHASE_MAX) { sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; @@ -1034,20 +1034,20 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) break; } case SMART_ACTION_CREATE_TIMED_EVENT: - { - if (!IsMinMaxValid(e, e.action.timeEvent.min, e.action.timeEvent.max)) - return false; + { + if (!IsMinMaxValid(e, e.action.timeEvent.min, e.action.timeEvent.max)) + return false; - if (!IsMinMaxValid(e, e.action.timeEvent.repeatMin, e.action.timeEvent.repeatMax)) - return false; - break; - } + if (!IsMinMaxValid(e, e.action.timeEvent.repeatMin, e.action.timeEvent.repeatMax)) + return false; + break; + } case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: - { - if (!IsMinMaxValid(e, e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2)) - return false; - break; - } + { + if (!IsMinMaxValid(e, e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2)) + return false; + break; + } case SMART_ACTION_SET_POWER: case SMART_ACTION_ADD_POWER: case SMART_ACTION_REMOVE_POWER: @@ -1058,82 +1058,82 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } break; case SMART_ACTION_GAME_EVENT_STOP: - { - return false; - uint32 eventId = e.action.gameEventStop.id; - - GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); - if (eventId < 1 || eventId >= events.size()) { - sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStop.id); return false; - } + uint32 eventId = e.action.gameEventStop.id; - GameEventData const& eventData = events[eventId]; - if (!eventData.isValid()) - { - sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStop.id); - return false; - } - break; - } - case SMART_ACTION_GAME_EVENT_START: - { - return false; - uint32 eventId = e.action.gameEventStart.id; - - GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); - if (eventId < 1 || eventId >= events.size()) - { - sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStart.id); - return false; - } - - GameEventData const& eventData = events[eventId]; - if (!eventData.isValid()) - { - sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStart.id); - return false; - } - break; - } - case SMART_ACTION_EQUIP: - { - - if (e.GetScriptType() == SMART_SCRIPT_TYPE_CREATURE) - { - int8 equipId = (int8)e.action.equip.entry; - - if (equipId) + GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); + if (eventId < 1 || eventId >= events.size()) { - EquipmentInfo const* einfo = sObjectMgr->GetEquipmentInfo(e.entryOrGuid, equipId); - if (!einfo) + sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStop.id); + return false; + } + + GameEventData const& eventData = events[eventId]; + if (!eventData.isValid()) + { + sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStop.id); + return false; + } + break; + } + case SMART_ACTION_GAME_EVENT_START: + { + return false; + uint32 eventId = e.action.gameEventStart.id; + + GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); + if (eventId < 1 || eventId >= events.size()) + { + sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStart.id); + return false; + } + + GameEventData const& eventData = events[eventId]; + if (!eventData.isValid()) + { + sLog->outError("SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent event, eventId %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.gameEventStart.id); + return false; + } + break; + } + case SMART_ACTION_EQUIP: + { + + if (e.GetScriptType() == SMART_SCRIPT_TYPE_CREATURE) + { + int8 equipId = (int8)e.action.equip.entry; + + if (equipId) { - sLog->outError("SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id %u for creature %u, skipped.", equipId, e.entryOrGuid); - return false; + EquipmentInfo const* einfo = sObjectMgr->GetEquipmentInfo(e.entryOrGuid, equipId); + if (!einfo) + { + sLog->outError("SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id %u for creature %u, skipped.", equipId, e.entryOrGuid); + return false; + } } } + break; } - break; - } case SMART_ACTION_LOAD_GRID: - { - if (!acore::IsValidMapCoord(e.target.x, e.target.y)) { - sLog->outError("SmartScript: SMART_ACTION_LOAD_GRID uses invalid map coords: %u, skipped.", e.entryOrGuid); - return false; + if (!acore::IsValidMapCoord(e.target.x, e.target.y)) + { + sLog->outError("SmartScript: SMART_ACTION_LOAD_GRID uses invalid map coords: %u, skipped.", e.entryOrGuid); + return false; + } + break; } - break; - } case SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: - { - if (e.GetScriptType() == SMART_SCRIPT_TYPE_GAMEOBJECT) { - sLog->outErrorDb("SmartScript: action_type %u is not allowed with source_type %u. Entry %u, skipped.", e.GetActionType(), e.GetScriptType(), e.entryOrGuid); - return false; + if (e.GetScriptType() == SMART_SCRIPT_TYPE_GAMEOBJECT) + { + sLog->outErrorDb("SmartScript: action_type %u is not allowed with source_type %u. Entry %u, skipped.", e.GetActionType(), e.GetScriptType(), e.entryOrGuid); + return false; + } + break; } - break; - } case SMART_ACTION_START_CLOSEST_WAYPOINT: case SMART_ACTION_FOLLOW: case SMART_ACTION_SET_ORIENTATION: diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index 92d2d9172..60aa0e5f2 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -1227,12 +1227,14 @@ struct SmartAction uint32 coneAngle; } coneSummon; - struct { + struct + { uint32 textId; uint32 flag; } playerTalk; - struct { + struct + { uint32 spell; uint32 flags; uint32 bp1; @@ -1240,7 +1242,8 @@ struct SmartAction uint32 bp3; } castCustom; - struct { + struct + { uint32 summonEntry; uint32 summonDuration; uint32 a; @@ -1653,8 +1656,8 @@ enum SmartEventFlags SMART_EVENT_FLAG_DEBUG_ONLY = 0x080, //Event only occurs in debug build SMART_EVENT_FLAG_DONT_RESET = 0x100, //Event will not reset in SmartScript::OnReset() - SMART_EVENT_FLAG_DIFFICULTY_ALL = (SMART_EVENT_FLAG_DIFFICULTY_0|SMART_EVENT_FLAG_DIFFICULTY_1|SMART_EVENT_FLAG_DIFFICULTY_2|SMART_EVENT_FLAG_DIFFICULTY_3), - SMART_EVENT_FLAGS_ALL = (SMART_EVENT_FLAG_NOT_REPEATABLE|SMART_EVENT_FLAG_DIFFICULTY_ALL|SMART_EVENT_FLAG_RESERVED_5|SMART_EVENT_FLAG_RESERVED_6|SMART_EVENT_FLAG_DEBUG_ONLY|SMART_EVENT_FLAG_DONT_RESET) + SMART_EVENT_FLAG_DIFFICULTY_ALL = (SMART_EVENT_FLAG_DIFFICULTY_0 | SMART_EVENT_FLAG_DIFFICULTY_1 | SMART_EVENT_FLAG_DIFFICULTY_2 | SMART_EVENT_FLAG_DIFFICULTY_3), + SMART_EVENT_FLAGS_ALL = (SMART_EVENT_FLAG_NOT_REPEATABLE | SMART_EVENT_FLAG_DIFFICULTY_ALL | SMART_EVENT_FLAG_RESERVED_5 | SMART_EVENT_FLAG_RESERVED_6 | SMART_EVENT_FLAG_DEBUG_ONLY | SMART_EVENT_FLAG_DONT_RESET) }; enum SmartCastFlags @@ -1684,11 +1687,11 @@ struct SmartScriptHolder SmartAction action; SmartTarget target; - public: - uint32 GetScriptType() const { return (uint32)source_type; } - uint32 GetEventType() const { return (uint32)event.type; } - uint32 GetActionType() const { return (uint32)action.type; } - uint32 GetTargetType() const { return (uint32)target.type; } +public: + uint32 GetScriptType() const { return (uint32)source_type; } + uint32 GetEventType() const { return (uint32)event.type; } + uint32 GetActionType() const { return (uint32)action.type; } + uint32 GetTargetType() const { return (uint32)target.type; } uint32 timer; bool active; @@ -1758,22 +1761,22 @@ typedef std::unordered_map ObjectListMap; class SmartWaypointMgr { SmartWaypointMgr() {} - public: - ~SmartWaypointMgr(); +public: + ~SmartWaypointMgr(); - static SmartWaypointMgr* instance(); + static SmartWaypointMgr* instance(); - void LoadFromDB(); + void LoadFromDB(); - WPPath* GetPath(uint32 id) - { - if (waypoint_map.find(id) != waypoint_map.end()) - return waypoint_map[id]; - else return 0; - } + WPPath* GetPath(uint32 id) + { + if (waypoint_map.find(id) != waypoint_map.end()) + return waypoint_map[id]; + else return 0; + } - private: - std::unordered_map waypoint_map; +private: + std::unordered_map waypoint_map; }; // all events for a single entry @@ -1785,167 +1788,167 @@ typedef std::unordered_map SmartAIEventMap; class SmartAIMgr { - SmartAIMgr(){}; - public: - ~SmartAIMgr(){}; + SmartAIMgr() {}; +public: + ~SmartAIMgr() {}; - static SmartAIMgr* instance(); + static SmartAIMgr* instance(); - void LoadSmartAIFromDB(); + void LoadSmartAIFromDB(); - SmartAIEventList GetScript(int32 entry, SmartScriptType type) + SmartAIEventList GetScript(int32 entry, SmartScriptType type) + { + SmartAIEventList temp; + if (mEventMap[uint32(type)].find(entry) != mEventMap[uint32(type)].end()) + return mEventMap[uint32(type)][entry]; + else { - SmartAIEventList temp; - if (mEventMap[uint32(type)].find(entry) != mEventMap[uint32(type)].end()) - return mEventMap[uint32(type)][entry]; - else - { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - if (entry > 0) //first search is for guid (negative), do not drop error if not found - sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartAIMgr::GetScript: Could not load Script for Entry %d ScriptType %u.", entry, uint32(type)); + if (entry > 0) //first search is for guid (negative), do not drop error if not found + sLog->outDebug(LOG_FILTER_DATABASE_AI, "SmartAIMgr::GetScript: Could not load Script for Entry %d ScriptType %u.", entry, uint32(type)); #endif - return temp; - } + return temp; } + } - private: - //event stores - SmartAIEventMap mEventMap[SMART_SCRIPT_TYPE_MAX]; +private: + //event stores + SmartAIEventMap mEventMap[SMART_SCRIPT_TYPE_MAX]; - bool IsEventValid(SmartScriptHolder& e); - bool IsTargetValid(SmartScriptHolder const& e); + bool IsEventValid(SmartScriptHolder& e); + bool IsTargetValid(SmartScriptHolder const& e); - /*inline bool IsTargetValid(SmartScriptHolder e, int32 target) + /*inline bool IsTargetValid(SmartScriptHolder e, int32 target) + { + if (target < SMART_TARGET_NONE || target >= SMART_TARGET_END) { - if (target < SMART_TARGET_NONE || target >= SMART_TARGET_END) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid Target type %d, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), target); - return false; - } - return true; - }*/ - - bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max) - { - if (max < min) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses min/max params wrong (%u/%u), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses invalid Target type %d, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), target); + return false; } + return true; + }*/ - /*inline bool IsPercentValid(SmartScriptHolder e, int32 pct) + bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max) + { + if (max < min) { - if (pct < -100 || pct > 100) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u has invalid Percent set (%d), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), pct); - return false; - } - return true; - }*/ - - bool NotNULL(SmartScriptHolder const& e, uint32 data) - { - if (!data) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u Parameter can not be NULL, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses min/max params wrong (%u/%u), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); + return false; } + return true; + } - bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry) + /*inline bool IsPercentValid(SmartScriptHolder e, int32 pct) + { + if (pct < -100 || pct > 100) { - if (!sObjectMgr->GetCreatureTemplate(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u has invalid Percent set (%d), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), pct); + return false; } + return true; + }*/ - bool IsQuestValid(SmartScriptHolder const& e, uint32 entry) + bool NotNULL(SmartScriptHolder const& e, uint32 data) + { + if (!data) { - if (!sObjectMgr->GetQuestTemplate(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u Parameter can not be NULL, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + return false; } + return true; + } - bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry) + bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sObjectMgr->GetCreatureTemplate(entry)) { - if (!sObjectMgr->GetGameObjectTemplate(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - bool IsSpellValid(SmartScriptHolder const& e, uint32 entry) + bool IsQuestValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sObjectMgr->GetQuestTemplate(entry)) { - if (!sSpellMgr->GetSpellInfo(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - bool IsItemValid(SmartScriptHolder const& e, uint32 entry) + bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sObjectMgr->GetGameObjectTemplate(entry)) { - if (!sObjectMgr->GetItemTemplate(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Item entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry) + bool IsSpellValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sSpellMgr->GetSpellInfo(entry)) { - if (!sEmotesTextStore.LookupEntry(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Text Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry) + bool IsItemValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sObjectMgr->GetItemTemplate(entry)) { - if (!sEmotesStore.LookupEntry(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Item entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry) + bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sEmotesTextStore.LookupEntry(entry)) { - if (!sObjectMgr->GetAreaTrigger(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent AreaTrigger entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Text Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - bool IsSoundValid(SmartScriptHolder const& e, uint32 entry) + bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sEmotesStore.LookupEntry(entry)) { - if (!sSoundEntriesStore.LookupEntry(entry)) - { - sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Sound entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; } + return true; + } - //bool IsTextValid(SmartScriptHolder const& e, uint32 id); + bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sObjectMgr->GetAreaTrigger(entry)) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent AreaTrigger entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; + } + + bool IsSoundValid(SmartScriptHolder const& e, uint32 entry) + { + if (!sSoundEntriesStore.LookupEntry(entry)) + { + sLog->outErrorDb("SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Sound entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; + } + + //bool IsTextValid(SmartScriptHolder const& e, uint32 id); }; #define sSmartScriptMgr SmartAIMgr::instance() diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index 30be2a96f..810afd663 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -36,21 +36,21 @@ namespace acore { class AchievementChatBuilder { - public: - AchievementChatBuilder(Player const& player, ChatMsg msgtype, int32 textId, uint32 ach_id) - : i_player(player), i_msgtype(msgtype), i_textId(textId), i_achievementId(ach_id) {} + public: + AchievementChatBuilder(Player const& player, ChatMsg msgtype, int32 textId, uint32 ach_id) + : i_player(player), i_msgtype(msgtype), i_textId(textId), i_achievementId(ach_id) {} - void operator()(WorldPacket& data, LocaleConstant loc_idx) - { - std::string text = sObjectMgr->GetAcoreString(i_textId, loc_idx); - ChatHandler::BuildChatPacket(data, i_msgtype, LANG_UNIVERSAL, &i_player, &i_player, text, i_achievementId); - } + void operator()(WorldPacket& data, LocaleConstant loc_idx) + { + std::string text = sObjectMgr->GetAcoreString(i_textId, loc_idx); + ChatHandler::BuildChatPacket(data, i_msgtype, LANG_UNIVERSAL, &i_player, &i_player, text, i_achievementId); + } - private: - Player const& i_player; - ChatMsg i_msgtype; - int32 i_textId; - uint32 i_achievementId; + private: + Player const& i_player; + ChatMsg i_msgtype; + int32 i_textId; + uint32 i_achievementId; }; } // namespace acore @@ -109,21 +109,21 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id)) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, creature.id); + criteria->ID, criteria->requiredType, dataType, creature.id); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE: - if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) + if (classRace.class_id && ((1 << (classRace.class_id - 1)) & CLASSMASK_ALL_PLAYABLE) == 0) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.class_id); + criteria->ID, criteria->requiredType, dataType, classRace.class_id); return false; } - if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) + if (classRace.race_id && ((1 << (classRace.race_id - 1)) & RACEMASK_ALL_PLAYABLE) == 0) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.race_id); + criteria->ID, criteria->requiredType, dataType, classRace.race_id); return false; } return true; @@ -131,7 +131,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (health.percent < 1 || health.percent > 100) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, health.percent); + criteria->ID, criteria->requiredType, dataType, health.percent); return false; } return true; @@ -139,39 +139,39 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (player_dead.own_team_flag > 1) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD (%u) has wrong boolean value1 (%u).", - criteria->ID, criteria->requiredType, dataType, player_dead.own_team_flag); + criteria->ID, criteria->requiredType, dataType, player_dead.own_team_flag); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA: case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA: - { - SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id); - if (!spellEntry) { - sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); - return false; + SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id); + if (!spellEntry) + { + sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.", + criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ? "ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" : "ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); + return false; + } + if (aura.effect_idx >= 3) + { + sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.", + criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ? "ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" : "ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); + return false; + } + if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName) + { + sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.", + criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ? "ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" : "ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); + return false; + } + return true; } - if (aura.effect_idx >= 3) - { - sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.", - criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); - return false; - } - if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName) - { - sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.", - criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); - return false; - } - return true; - } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA: if (!sAreaTableStore.LookupEntry(area.id)) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA (%u) has wrong area id in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, area.id); + criteria->ID, criteria->requiredType, dataType, area.id); return false; } return true; @@ -179,7 +179,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (value.compType >= COMP_TYPE_MAX) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE (%u) has wrong ComparisionType in value2 (%u), ignored.", - value.compType, criteria->requiredType, dataType, value.value); + value.compType, criteria->requiredType, dataType, value.value); return false; } return true; @@ -187,7 +187,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (level.minlevel > STRONG_MAX_LEVEL) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, level.minlevel); + criteria->ID, criteria->requiredType, dataType, level.minlevel); return false; } return true; @@ -195,7 +195,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (gender.gender > GENDER_NONE) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, gender.gender); + criteria->ID, criteria->requiredType, dataType, gender.gender); return false; } return true; @@ -203,7 +203,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!ScriptId) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.", - criteria->ID, criteria->requiredType, dataType); + criteria->ID, criteria->requiredType, dataType); return false; } return true; @@ -211,7 +211,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (difficulty.difficulty >= MAX_DIFFICULTY) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY (%u) has wrong difficulty in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, difficulty.difficulty); + criteria->ID, criteria->requiredType, dataType, difficulty.difficulty); return false; } return true; @@ -219,7 +219,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (map_players.maxcount <= 0) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, map_players.maxcount); + criteria->ID, criteria->requiredType, dataType, map_players.maxcount); return false; } return true; @@ -227,7 +227,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (team.team != ALLIANCE && team.team != HORDE) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, team.team); + criteria->ID, criteria->requiredType, dataType, team.team); return false; } return true; @@ -235,7 +235,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (drunk.state >= MAX_DRUNKEN) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, drunk.state); + criteria->ID, criteria->requiredType, dataType, drunk.state); return false; } return true; @@ -243,7 +243,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!sHolidaysStore.LookupEntry(holiday.id)) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, holiday.id); + criteria->ID, criteria->requiredType, dataType, holiday.id); return false; } return true; @@ -253,7 +253,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (equipped_item.item_quality >= MAX_ITEM_QUALITY) { sLog->outErrorDb("Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, equipped_item.item_quality); + criteria->ID, criteria->requiredType, dataType, equipped_item.item_quality); return false; } return true; @@ -261,7 +261,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!sMapStore.LookupEntry(map_id.mapId)) { sLog->outErrorDb("Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID (%u) has unknown map id in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, map_id.mapId); + criteria->ID, criteria->requiredType, dataType, map_id.mapId); return false; } return true; @@ -269,32 +269,32 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!classRace.class_id && !classRace.race_id) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.", - criteria->ID, criteria->requiredType, dataType); + criteria->ID, criteria->requiredType, dataType); return false; } - if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) + if (classRace.class_id && ((1 << (classRace.class_id - 1)) & CLASSMASK_ALL_PLAYABLE) == 0) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.class_id); + criteria->ID, criteria->requiredType, dataType, classRace.class_id); return false; } - if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) + if (classRace.race_id && ((1 << (classRace.race_id - 1)) & RACEMASK_ALL_PLAYABLE) == 0) { sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.race_id); + criteria->ID, criteria->requiredType, dataType, classRace.race_id); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE: - { - if (!sCharTitlesStore.LookupEntry(known_title.title_id)) { - sLog->outErrorDb("Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE (%u) have unknown title_id in value1 (%u), ignore.", - criteria->ID, criteria->requiredType, dataType, known_title.title_id); - return false; + if (!sCharTitlesStore.LookupEntry(known_title.title_id)) + { + sLog->outErrorDb("Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE (%u) have unknown title_id in value1 (%u), ignore.", + criteria->ID, criteria->requiredType, dataType, known_title.title_id); + return false; + } + return true; } - return true; - } default: sLog->outErrorDb("Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->requiredType, dataType); return false; @@ -341,11 +341,11 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA: return source->HasAuraEffect(aura.spell_id, aura.effect_idx); case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA: - { - uint32 zone_id, area_id; - source->GetZoneAndAreaId(zone_id, area_id); - return area.id == zone_id || area.id == area_id; - } + { + uint32 zone_id, area_id; + source->GetZoneAndAreaId(zone_id, area_id); + return area.id == zone_id || area.id == area_id; + } case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA: return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx); case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE: @@ -361,89 +361,89 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT: return sScriptMgr->OnCriteriaCheck(ScriptId, const_cast(source), const_cast(target)); case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY: - { - if (source->GetMap()->IsRaid()) - if (source->GetMap()->Is25ManRaid() != ((difficulty.difficulty & RAID_DIFFICULTY_MASK_25MAN) != 0)) - return false; + { + if (source->GetMap()->IsRaid()) + if (source->GetMap()->Is25ManRaid() != ((difficulty.difficulty & RAID_DIFFICULTY_MASK_25MAN) != 0)) + return false; - AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(criteria_id); - uint8 spawnMode = source->GetMap()->GetSpawnMode(); - // Dungeons completed on heroic mode count towards both in general achievement, but not in statistics. - return sAchievementMgr->IsStatisticCriteria(criteria) ? spawnMode == difficulty.difficulty : spawnMode >= difficulty.difficulty; - } + AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(criteria_id); + uint8 spawnMode = source->GetMap()->GetSpawnMode(); + // Dungeons completed on heroic mode count towards both in general achievement, but not in statistics. + return sAchievementMgr->IsStatisticCriteria(criteria) ? spawnMode == difficulty.difficulty : spawnMode >= difficulty.difficulty; + } case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT: return source->GetMap()->GetPlayersCountExceptGMs() <= map_players.maxcount; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM: - { - if (!target || target->GetTypeId() != TYPEID_PLAYER) - return false; + { + if (!target || target->GetTypeId() != TYPEID_PLAYER) + return false; - // DB data compatibility... - uint32 teamOld = target->ToPlayer()->GetTeamId() == TEAM_ALLIANCE ? ALLIANCE : HORDE; - return teamOld == team.team; - } + // DB data compatibility... + uint32 teamOld = target->ToPlayer()->GetTeamId() == TEAM_ALLIANCE ? ALLIANCE : HORDE; + return teamOld == team.team; + } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK: return Player::GetDrunkenstateByValue(source->GetDrunkValue()) >= DrunkenState(drunk.state); case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY: return IsHolidayActive(HolidayIds(holiday.id)); case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE: - { - Battleground* bg = source->GetBattleground(); - if (!bg) - return false; - - uint32 score = bg->GetTeamScore(source->GetTeamId() == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE); - return score >= bg_loss_team_score.min_score && score <= bg_loss_team_score.max_score; - } - case ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT: - { - if (!source->IsInWorld()) - return false; - Map* map = source->GetMap(); - if (!map->IsDungeon()) { - sLog->outErrorDb("Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u", - ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT, criteria_id, map->GetId()); + Battleground* bg = source->GetBattleground(); + if (!bg) return false; + + uint32 score = bg->GetTeamScore(source->GetTeamId() == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE); + return score >= bg_loss_team_score.min_score && score <= bg_loss_team_score.max_score; } - InstanceScript* instance = map->ToInstanceMap()->GetInstanceScript(); - if (!instance) + case ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT: { - sLog->outErrorDb("Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script", - ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT, criteria_id, map->GetId()); - return false; + if (!source->IsInWorld()) + return false; + Map* map = source->GetMap(); + if (!map->IsDungeon()) + { + sLog->outErrorDb("Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u", + ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT, criteria_id, map->GetId()); + return false; + } + InstanceScript* instance = map->ToInstanceMap()->GetInstanceScript(); + if (!instance) + { + sLog->outErrorDb("Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script", + ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT, criteria_id, map->GetId()); + return false; + } + return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscvalue1); } - return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscvalue1); - } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM: - { - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscvalue1); - if (!pProto) - return false; - return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality; - } + { + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscvalue1); + if (!pProto) + return false; + return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality; + } case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID: return source->GetMapId() == map_id.mapId; case ACHIEVEMENT_CRITERIA_DATA_TYPE_NTH_BIRTHDAY: - { - time_t birthday_start = time_t(sWorld->getIntConfig(CONFIG_BIRTHDAY_TIME)); - tm birthday_tm; - localtime_r(&birthday_start, &birthday_tm); + { + time_t birthday_start = time_t(sWorld->getIntConfig(CONFIG_BIRTHDAY_TIME)); + tm birthday_tm; + localtime_r(&birthday_start, &birthday_tm); - // exactly N birthday - birthday_tm.tm_year += birthday_login.nth_birthday; + // exactly N birthday + birthday_tm.tm_year += birthday_login.nth_birthday; - time_t birthday = mktime(&birthday_tm); - time_t now = sWorld->GetGameTime(); - return now <= birthday + DAY && now >= birthday; - } + time_t birthday = mktime(&birthday_tm); + time_t now = sWorld->GetGameTime(); + return now <= birthday + DAY && now >= birthday; + } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE: - { - if (CharTitlesEntry const* titleInfo = sCharTitlesStore.LookupEntry(known_title.title_id)) - return source && source->HasTitle(titleInfo->bit_index); + { + if (CharTitlesEntry const* titleInfo = sCharTitlesStore.LookupEntry(known_title.title_id)) + return source && source->HasTitle(titleInfo->bit_index); - return false; - } + return false; + } default: break; } @@ -662,9 +662,9 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN) return; - #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) && defined(ACORE_DEBUG) - sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::SendAchievementEarned(%u)", achievement->ID); - #endif +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) && defined(ACORE_DEBUG) + sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::SendAchievementEarned(%u)", achievement->ID); +#endif if (Guild* guild = sGuildMgr->GetGuildById(GetPlayer()->GetGuildId())) { @@ -704,7 +704,7 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) cell.Visit(p, message, *GetPlayer()->GetMap(), *GetPlayer(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY)); } - WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8+4+8); + WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8 + 4 + 8); data.append(GetPlayer()->GetPackGUID()); data << uint32(achievement->ID); data.AppendPackedTime(time(nullptr)); @@ -714,7 +714,7 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) void AchievementMgr::SendCriteriaUpdate(AchievementCriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const { - WorldPacket data(SMSG_CRITERIA_UPDATE, 8+4+8); + WorldPacket data(SMSG_CRITERIA_UPDATE, 8 + 4 + 8); data << uint32(entry->ID); // the counter is packed like a packed Guid @@ -737,7 +737,7 @@ void AchievementMgr::SendCriteriaUpdate(AchievementCriteriaEntry const* entry, C void AchievementMgr::CheckAllAchievementCriteria() { // suppress sending packets - for (uint32 i=0; icategoryId == CATEGORY_CHILDRENS_WEEK) { - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), nullptr)) + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) continue; + + if (achievement->categoryId == CATEGORY_CHILDRENS_WEEK) + { + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), nullptr)) + continue; + } + + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; } - - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (achievementCriteria->win_bg.bgMapID != GetPlayer()->GetMapId()) - continue; + { + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) + continue; + if (achievementCriteria->win_bg.bgMapID != GetPlayer()->GetMapId()) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (achievementCriteria->kill_creature.creatureID != miscValue1) - continue; + { + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) + continue; + if (achievementCriteria->kill_creature.creatureID != miscValue1) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; - SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue2) - continue; + { + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue2) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit, miscValue1)) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit, miscValue1)) + continue; - SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) if (!data->Meets(GetPlayer(), unit)) @@ -975,58 +975,58 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, 1); break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: - { - SetCriteriaProgress(achievementCriteria, GetPlayer()->GetRewardedQuestCount()); - break; - } + { + SetCriteriaProgress(achievementCriteria, GetPlayer()->GetRewardedQuestCount()); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: - { - time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime(); - CriteriaProgress* progress = GetCriteriaProgress(achievementCriteria); - - if (!miscValue1) // Login case. { - // reset if player missed one day. - if (progress && progress->date < (nextDailyResetTime - 2 * DAY)) - SetCriteriaProgress(achievementCriteria, 0, PROGRESS_SET); - continue; + time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime(); + CriteriaProgress* progress = GetCriteriaProgress(achievementCriteria); + + if (!miscValue1) // Login case. + { + // reset if player missed one day. + if (progress && progress->date < (nextDailyResetTime - 2 * DAY)) + SetCriteriaProgress(achievementCriteria, 0, PROGRESS_SET); + continue; + } + + ProgressType progressType; + if (!progress) + // 1st time. Start count. + progressType = PROGRESS_SET; + else if (progress->date < (nextDailyResetTime - 2 * DAY)) + // last progress is older than 2 days. Player missed 1 day => Retart count. + progressType = PROGRESS_RESET; + else if (progress->date < (nextDailyResetTime - DAY)) + // last progress is between 1 and 2 days. => 1st time of the day. + progressType = PROGRESS_ACCUMULATE; + else + // last progress is within the day before the reset => Already counted today. + continue; + + SetCriteriaProgress(achievementCriteria, 1, progressType); + break; } - - ProgressType progressType; - if (!progress) - // 1st time. Start count. - progressType = PROGRESS_SET; - else if (progress->date < (nextDailyResetTime - 2 * DAY)) - // last progress is older than 2 days. Player missed 1 day => Retart count. - progressType = PROGRESS_RESET; - else if (progress->date < (nextDailyResetTime - DAY)) - // last progress is between 1 and 2 days. => 1st time of the day. - progressType = PROGRESS_ACCUMULATE; - else - // last progress is within the day before the reset => Already counted today. - continue; - - SetCriteriaProgress(achievementCriteria, 1, progressType); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: - { - // speedup for non-login case - if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID) - continue; - - uint32 counter = 0; - - const RewardedQuestSet &rewQuests = GetPlayer()->getRewardedQuests(); - for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) { - Quest const* quest = sObjectMgr->GetQuestTemplate(*itr); - if (quest && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID) - ++counter; + // speedup for non-login case + if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID) + continue; + + uint32 counter = 0; + + const RewardedQuestSet& rewQuests = GetPlayer()->getRewardedQuests(); + for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) + { + Quest const* quest = sObjectMgr->GetQuestTemplate(*itr); + if (quest && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID) + ++counter; + } + SetCriteriaProgress(achievementCriteria, counter); + break; } - SetCriteriaProgress(achievementCriteria, counter); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscValue1) @@ -1044,78 +1044,78 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_DEATH: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - // skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter - bool notfit = false; - for (int j = 0; j < MAX_ARENA_SLOT; ++j) { - if (achievIdByArenaSlot[j] == achievement->ID) + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) + continue; + // skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter + bool notfit = false; + for (int j = 0; j < MAX_ARENA_SLOT; ++j) { - Battleground* bg = GetPlayer()->GetBattleground(); - if (!bg || !bg->isArena() || ArenaTeam::GetSlotByType(bg->GetArenaType()) != j) - notfit = true; + if (achievIdByArenaSlot[j] == achievement->ID) + { + Battleground* bg = GetPlayer()->GetBattleground(); + if (!bg || !bg->isArena() || ArenaTeam::GetSlotByType(bg->GetArenaType()) != j) + notfit = true; - break; + break; + } } - } - if (notfit) - continue; + if (notfit) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - Map const* map = GetPlayer()->IsInWorld() ? GetPlayer()->GetMap() : sMapMgr->FindMap(GetPlayer()->GetMapId(), GetPlayer()->GetInstanceId()); - if (!map || !map->IsDungeon()) - continue; - - // search case - bool found = false; - for (int j = 0; achievIdForDungeon[j][0]; ++j) { - if (achievIdForDungeon[j][0] == achievement->ID) + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) + continue; + + Map const* map = GetPlayer()->IsInWorld() ? GetPlayer()->GetMap() : sMapMgr->FindMap(GetPlayer()->GetMapId(), GetPlayer()->GetInstanceId()); + if (!map || !map->IsDungeon()) + continue; + + // search case + bool found = false; + for (int j = 0; achievIdForDungeon[j][0]; ++j) { - if (map->IsRaid()) + if (achievIdForDungeon[j][0] == achievement->ID) { - // if raid accepted (ignore difficulty) - if (!achievIdForDungeon[j][2]) - break; // for - } - else if (GetPlayer()->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL) - { - // dungeon in normal mode accepted - if (!achievIdForDungeon[j][1]) - break; // for - } - else - { - // dungeon in heroic mode accepted - if (!achievIdForDungeon[j][3]) - break; // for - } + if (map->IsRaid()) + { + // if raid accepted (ignore difficulty) + if (!achievIdForDungeon[j][2]) + break; // for + } + else if (GetPlayer()->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL) + { + // dungeon in normal mode accepted + if (!achievIdForDungeon[j][1]) + break; // for + } + else + { + // dungeon in heroic mode accepted + if (!achievIdForDungeon[j][3]) + break; // for + } - found = true; - break; // for + found = true; + break; // for + } } + if (!found) + continue; + + //FIXME: work only for instances where max == min for players + if (map->ToInstanceMap()->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit) + continue; + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } - if (!found) - continue; - - //FIXME: work only for instances where max == min for players - if (map->ToInstanceMap()->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit) - continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - - } case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscValue1) @@ -1136,20 +1136,20 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; + { + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; - // miscvalue1 is the ingame fallheight*100 as stored in dbc - SetCriteriaProgress(achievementCriteria, miscValue1); - break; - } + // miscvalue1 is the ingame fallheight*100 as stored in dbc + SetCriteriaProgress(achievementCriteria, miscValue1); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscValue1) @@ -1159,61 +1159,61 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: - { - // if miscvalues != 0, it contains the questID. - if (miscValue1) { - if (miscValue1 != achievementCriteria->complete_quest.questID) - continue; - } - else - { - // login case. - if (!GetPlayer()->GetQuestRewardStatus(achievementCriteria->complete_quest.questID)) - continue; - } + // if miscvalues != 0, it contains the questID. + if (miscValue1) + { + if (miscValue1 != achievementCriteria->complete_quest.questID) + continue; + } + else + { + // login case. + if (!GetPlayer()->GetQuestRewardStatus(achievementCriteria->complete_quest.questID)) + continue; + } + + if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) + if (!data->Meets(GetPlayer(), unit)) + continue; + + SetCriteriaProgress(achievementCriteria, 1); + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: + { + if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID) + continue; + + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data) + continue; - if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) if (!data->Meets(GetPlayer(), unit)) continue; - SetCriteriaProgress(achievementCriteria, 1); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: - case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: - { - if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID) - continue; - - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data) - continue; - - if (!data->Meets(GetPlayer(), unit)) - continue; - - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: - { - if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID) - continue; + { + if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data) + continue; - if (!data->Meets(GetPlayer(), unit)) - continue; + if (!data->Meets(GetPlayer(), unit)) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID) continue; @@ -1222,26 +1222,26 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, 1); break; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: - { - // miscvalue1=loot_type (note: 0 = LOOT_CORPSE and then it ignored) - // miscvalue2=count of item loot - if (!miscValue1 || !miscValue2) - continue; - if (miscValue1 != achievementCriteria->loot_type.lootType) - continue; - - // zone specific - if (achievementCriteria->loot_type.lootTypeCount == 1) { - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) + // miscvalue1=loot_type (note: 0 = LOOT_CORPSE and then it ignored) + // miscvalue2=count of item loot + if (!miscValue1 || !miscValue2) + continue; + if (miscValue1 != achievementCriteria->loot_type.lootType) continue; - } - SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); - break; - } + // zone specific + if (achievementCriteria->loot_type.lootTypeCount == 1) + { + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; + } + + SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: // speedup for non-login case if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1) @@ -1295,139 +1295,139 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, miscValue2, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: - { - WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference); - if (!worldOverlayEntry) - break; - - bool matchFound = false; - for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) { - AreaTableEntry const* area = sAreaTableStore.LookupEntry(worldOverlayEntry->areatableID[j]); - if (!area) + WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference); + if (!worldOverlayEntry) break; - uint32 playerIndexOffset = uint32(area->exploreFlag) / 32; - if (playerIndexOffset >= PLAYER_EXPLORED_ZONES_SIZE) - continue; - - uint32 mask = 1 << (uint32(area->exploreFlag) % 32); - if (GetPlayer()->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask) + bool matchFound = false; + for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) { - matchFound = true; - break; - } - } + AreaTableEntry const* area = sAreaTableStore.LookupEntry(worldOverlayEntry->areatableID[j]); + if (!area) + break; - if (matchFound) - SetCriteriaProgress(achievementCriteria, 1); - break; - } + uint32 playerIndexOffset = uint32(area->exploreFlag) / 32; + if (playerIndexOffset >= PLAYER_EXPLORED_ZONES_SIZE) + continue; + + uint32 mask = 1 << (uint32(area->exploreFlag) % 32); + if (GetPlayer()->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask) + { + matchFound = true; + break; + } + } + + if (matchFound) + SetCriteriaProgress(achievementCriteria, 1); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: SetCriteriaProgress(achievementCriteria, GetPlayer()->GetBankBagSlotCount()); break; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: - { - // skip faction check only at loading - if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID) - continue; + { + // skip faction check only at loading + if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID) + continue; - int32 reputation = GetPlayer()->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID); - if (reputation > 0) - SetCriteriaProgress(achievementCriteria, reputation); - break; - } + int32 reputation = GetPlayer()->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID); + if (reputation > 0) + SetCriteriaProgress(achievementCriteria, reputation); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: - { - SetCriteriaProgress(achievementCriteria, GetPlayer()->GetReputationMgr().GetExaltedFactionCount()); - break; - } + { + SetCriteriaProgress(achievementCriteria, GetPlayer()->GetReputationMgr().GetExaltedFactionCount()); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: - { - // skip for login case - if (!miscValue1) - continue; - SetCriteriaProgress(achievementCriteria, 1); - break; - } + { + // skip for login case + if (!miscValue1) + continue; + SetCriteriaProgress(achievementCriteria, 1); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: - { - // miscvalue1 = itemid - // miscvalue2 = itemSlot - if (!miscValue1) - continue; + { + // miscvalue1 = itemid + // miscvalue2 = itemSlot + if (!miscValue1) + continue; - if (miscValue2 != achievementCriteria->equip_epic_item.itemSlot) - continue; + if (miscValue2 != achievementCriteria->equip_epic_item.itemSlot) + continue; - // check item level and quality via achievement_criteria_data - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), 0, miscValue1)) - continue; + // check item level and quality via achievement_criteria_data + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), 0, miscValue1)) + continue; - SetCriteriaProgress(achievementCriteria, 1); - break; - } + SetCriteriaProgress(achievementCriteria, 1); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: - { - // miscvalue1 = itemid - // miscvalue2 = diced value - if (!miscValue1) - continue; - if (miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue) - continue; - - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1); - if (!pProto) - continue; - - // check item level via achievement_criteria_data - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), 0, pProto->ItemLevel)) - continue; - - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: - { - // miscvalue1 = emote - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->do_emote.emoteID) - continue; - if (achievementCriteria->do_emote.count) { - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) + // miscvalue1 = itemid + // miscvalue2 = diced value + if (!miscValue1) + continue; + if (miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue) continue; - } - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1); + if (!pProto) + continue; + + // check item level via achievement_criteria_data + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), 0, pProto->ItemLevel)) + continue; + + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: + { + // miscvalue1 = emote + if (!miscValue1) + continue; + if (miscValue1 != achievementCriteria->do_emote.emoteID) + continue; + if (achievementCriteria->do_emote.count) + { + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; + } + + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: - { - if (!miscValue1) - continue; - - if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP) { - if (GetPlayer()->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value) + if (!miscValue1) continue; - // map specific case (BG in fact) expected player targeted damage/heal - if (!unit || unit->GetTypeId() != TYPEID_PLAYER) - continue; + if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP) + { + if (GetPlayer()->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value) + continue; + + // map specific case (BG in fact) expected player targeted damage/heal + if (!unit || unit->GetTypeId() != TYPEID_PLAYER) + continue; + } + + SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_ACCUMULATE); + break; } - - SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: // miscvalue1 = item_id if (!miscValue1) @@ -1455,28 +1455,28 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: - { - if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine) - continue; - - uint32 spellCount = 0; - for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); spellIter != GetPlayer()->GetSpellMap().end(); ++spellIter) { - SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first); - for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) + if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine) + continue; + + uint32 spellCount = 0; + for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); spellIter != GetPlayer()->GetSpellMap().end(); ++spellIter) { - if (skillIter->second->skillId == achievementCriteria->learn_skillline_spell.skillLine) + SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first); + for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) { - // xinef: do not add couter twice if by any chance skill is listed twice in dbc (eg. skill 777 and spell 22717) - ++spellCount; - break; + if (skillIter->second->skillId == achievementCriteria->learn_skillline_spell.skillLine) + { + // xinef: do not add couter twice if by any chance skill is listed twice in dbc (eg. skill 777 and spell 22717) + ++spellCount; + break; + } } } - } - SetCriteriaProgress(achievementCriteria, spellCount); - break; - } + SetCriteriaProgress(achievementCriteria, spellCount); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscValue1) @@ -1506,39 +1506,39 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui break; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(miscValue1); - if (!proto || proto->Quality < ITEM_QUALITY_EPIC) - continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: - { - if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine) - continue; - - uint32 spellCount = 0; - for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); spellIter != GetPlayer()->GetSpellMap().end(); ++spellIter) { - SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first); - for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) + // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case + if (!miscValue1) + continue; + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(miscValue1); + if (!proto || proto->Quality < ITEM_QUALITY_EPIC) + continue; + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: + { + if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine) + continue; + + uint32 spellCount = 0; + for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); spellIter != GetPlayer()->GetSpellMap().end(); ++spellIter) { - if (skillIter->second->skillId == achievementCriteria->learn_skill_line.skillLine) + SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first); + for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) { - // xinef: do not add couter twice if by any chance skill is listed twice in dbc (eg. skill 777 and spell 22717) - ++spellCount; - break; + if (skillIter->second->skillId == achievementCriteria->learn_skill_line.skillLine) + { + // xinef: do not add couter twice if by any chance skill is listed twice in dbc (eg. skill 777 and spell 22717) + ++spellCount; + break; + } } } - } - SetCriteriaProgress(achievementCriteria, spellCount); - break; - } + SetCriteriaProgress(achievementCriteria, spellCount); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL: SetCriteriaProgress(achievementCriteria, GetPlayer()->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS)); break; @@ -1558,146 +1558,146 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui SetCriteriaProgress(achievementCriteria, GetPlayer()->GetMoney(), PROGRESS_HIGHEST); break; case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: - { - if (!miscValue1) { - uint32 points = 0; - for (CompletedAchievementMap::iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) - if (AchievementEntry const* pAchievement = sAchievementStore.LookupEntry(itr->first)) - points += pAchievement->points; - SetCriteriaProgress(achievementCriteria, points, PROGRESS_SET); + if (!miscValue1) + { + uint32 points = 0; + for (CompletedAchievementMap::iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) + if (AchievementEntry const* pAchievement = sAchievementStore.LookupEntry(itr->first)) + points += pAchievement->points; + SetCriteriaProgress(achievementCriteria, points, PROGRESS_SET); + } + else + SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_ACCUMULATE); + break; } - else - SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: - { - if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId) - continue; + { + if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: - { - // skip login update - if (!miscValue1) - continue; + { + // skip login update + if (!miscValue1) + continue; - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) - continue; + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: - { - if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID) - continue; + { + if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: - { - uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype; - - if (miscValue1) { - if (miscValue2 != reqTeamType) - continue; + uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype; - SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_HIGHEST); - } - else // login case - { - for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) + if (miscValue1) { - uint32 arenaTeamId = GetPlayer()->GetArenaTeamId(arena_slot); - if (!arenaTeamId) + if (miscValue2 != reqTeamType) continue; - ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(arenaTeamId); - if (!team || team->GetType() != reqTeamType) - continue; - - SetCriteriaProgress(achievementCriteria, team->GetStats().Rating, PROGRESS_HIGHEST); - break; + SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_HIGHEST); } - } - - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: - { - uint32 reqTeamType = achievementCriteria->highest_personal_rating.teamtype; - - if (miscValue1) - { - if (miscValue2 != reqTeamType) - continue; - - SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_HIGHEST); - } - else // login case - { - for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) + else // login case { - uint32 arenaTeamId = GetPlayer()->GetArenaTeamId(arena_slot); - if (!arenaTeamId) - continue; - - ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(arenaTeamId); - if (!team || team->GetType() != reqTeamType) - continue; - - if (ArenaTeamMember const* member = team->GetMember(GetPlayer()->GetGUID())) + for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { - SetCriteriaProgress(achievementCriteria, member->PersonalRating, PROGRESS_HIGHEST); + uint32 arenaTeamId = GetPlayer()->GetArenaTeamId(arena_slot); + if (!arenaTeamId) + continue; + + ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(arenaTeamId); + if (!team || team->GetType() != reqTeamType) + continue; + + SetCriteriaProgress(achievementCriteria, team->GetStats().Rating, PROGRESS_HIGHEST); break; } } + + break; } + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: + { + uint32 reqTeamType = achievementCriteria->highest_personal_rating.teamtype; - break; - } + if (miscValue1) + { + if (miscValue2 != reqTeamType) + continue; + + SetCriteriaProgress(achievementCriteria, miscValue1, PROGRESS_HIGHEST); + } + else // login case + { + for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) + { + uint32 arenaTeamId = GetPlayer()->GetArenaTeamId(arena_slot); + if (!arenaTeamId) + continue; + + ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(arenaTeamId); + if (!team || team->GetType() != reqTeamType) + continue; + + if (ArenaTeamMember const* member = team->GetMember(GetPlayer()->GetGUID())) + { + SetCriteriaProgress(achievementCriteria, member->PersonalRating, PROGRESS_HIGHEST); + break; + } + } + } + + break; + } case ACHIEVEMENT_CRITERIA_TYPE_ON_LOGIN: - { - // This criteria is only called directly after login - with expected miscvalue1 == 1 - if (!miscValue1) - continue; + { + // This criteria is only called directly after login - with expected miscvalue1 == 1 + if (!miscValue1) + continue; - // They have no proper requirements in dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), unit)) - continue; + // They have no proper requirements in dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), unit)) + continue; - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA: case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: // This also behaves like ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA - { - // those requirements couldn't be found in the dbc - AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); - if (!data || !data->Meets(GetPlayer(), nullptr)) - continue; + { + // those requirements couldn't be found in the dbc + AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria); + if (!data || !data->Meets(GetPlayer(), nullptr)) + continue; - // Check map id requirement - if (miscValue1 == achievementCriteria->win_arena.mapID) - SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); - break; - } + // Check map id requirement + if (miscValue1 == achievementCriteria->win_arena.mapID) + SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE); + break; + } // std case: not exist in DBC, not triggered in code as result case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALTH: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_SPELLPOWER: @@ -1978,7 +1978,7 @@ bool AchievementMgr::IsCompletedAchievement(AchievementEntry const* entry) // completed as have req. count of completed criterias if (achievmentForTestCount > 0 && achievmentForTestCount <= count) - return true; + return true; } // all criterias completed requirement @@ -2030,12 +2030,12 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entry, newValue = changeValue; break; case PROGRESS_ACCUMULATE: - { - // avoid overflow - uint32 max_value = std::numeric_limits::max(); - newValue = max_value - progress->counter > changeValue ? progress->counter + changeValue : max_value; - break; - } + { + // avoid overflow + uint32 max_value = std::numeric_limits::max(); + newValue = max_value - progress->counter > changeValue ? progress->counter + changeValue : max_value; + break; + } case PROGRESS_HIGHEST: newValue = progress->counter < changeValue ? changeValue : progress->counter; break; @@ -2059,7 +2059,7 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entry, // has to exist else we wouldn't be here timedCompleted = IsCompletedCriteria(entry, sAchievementStore.LookupEntry(entry->referredAchievement)); // Client expects this in packet - timeElapsed = entry->timeLimit - (timedIter->second/IN_MILLISECONDS); + timeElapsed = entry->timeLimit - (timedIter->second / IN_MILLISECONDS); // Remove the timer, we wont need it anymore if (timedCompleted) @@ -2132,7 +2132,7 @@ void AchievementMgr::StartTimedAchievement(AchievementCriteriaTimedTypes type, u void AchievementMgr::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type); - for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i!=achievementCriteriaList.end(); ++i) + for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { if ((*i)->timerStartEvent != entry) continue; @@ -2261,14 +2261,14 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) void AchievementMgr::SendAllAchievementData() const { - WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, m_completedAchievements.size()*8+4+m_criteriaProgress.size()*38+4); + WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, m_completedAchievements.size() * 8 + 4 + m_criteriaProgress.size() * 38 + 4); BuildAllDataPacket(&data); GetPlayer()->GetSession()->SendPacket(&data); } void AchievementMgr::SendRespondInspectAchievements(Player* player) const { - WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 9+m_completedAchievements.size()*8+4+4); + WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 9 + m_completedAchievements.size() * 8 + 4 + 4); data.append(GetPlayer()->GetPackGUID()); BuildAllDataPacket(&data, true); player->GetSession()->SendPacket(&data); @@ -2324,7 +2324,7 @@ bool AchievementMgr::CanUpdateCriteria(AchievementCriteriaEntry const* criteria, return false; if ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && GetPlayer()->GetTeamId() != TEAM_HORDE) || - (achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && GetPlayer()->GetTeamId() != TEAM_ALLIANCE)) + (achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && GetPlayer()->GetTeamId() != TEAM_ALLIANCE)) return false; for (uint32 i = 0; i < MAX_CRITERIA_REQUIREMENTS; ++i) @@ -2371,8 +2371,10 @@ bool AchievementGlobalMgr::isStatisticAchievement(AchievementEntry const* achiev return false; AchievementCategoryEntry const* cat = sAchievementCategoryStore.LookupEntry(achievement->categoryId); - do { - switch(cat->ID) { + do + { + switch(cat->ID) + { case ACHIEVEMENT_CATEGORY_STATISTICS: return true; case ACHIEVEMENT_CATEOGRY_GENERAL: @@ -2441,7 +2443,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaList() if (criteria->additionalRequirements[0].additionalRequirement_type != ACHIEVEMENT_CRITERIA_CONDITION_NONE) m_AchievementCriteriasByCondition[criteria->additionalRequirements[0].additionalRequirement_type][criteria->additionalRequirements[0].additionalRequirement_value].push_back(criteria); if (criteria->additionalRequirements[1].additionalRequirement_type != ACHIEVEMENT_CRITERIA_CONDITION_NONE && - criteria->additionalRequirements[1].additionalRequirement_type != criteria->additionalRequirements[0].additionalRequirement_type) + criteria->additionalRequirements[1].additionalRequirement_type != criteria->additionalRequirements[0].additionalRequirement_type) m_AchievementCriteriasByCondition[criteria->additionalRequirements[1].additionalRequirement_type][criteria->additionalRequirements[1].additionalRequirement_value].push_back(criteria); switch (criteria->requiredType) @@ -2507,7 +2509,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaList() if (worldOverlayEntry->areatableID[j]) { bool valid = true; - for (uint8 i=0; iareatableID[j] == worldOverlayEntry->areatableID[i]) valid = false; if (valid) @@ -2650,8 +2652,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() // counting data by and data types ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // post loading checks for (uint32 entryId = 0; entryId < sAchievementCriteriaStore.GetNumRows(); ++entryId) @@ -2681,17 +2682,17 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() // achievement requires db data break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: - { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(criteria->referredAchievement); - if (!achievement) + { + AchievementEntry const* achievement = sAchievementStore.LookupEntry(criteria->referredAchievement); + if (!achievement) + continue; + + // exist many achievements with this criteria, use at this moment hardcoded check to skil simple case + if (achievement->ID == 1282) + break; + continue; - - // exist many achievements with this criteria, use at this moment hardcoded check to skil simple case - if (achievement->ID == 1282) - break; - - continue; - } + } case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: // need skip generic cases if (criteria->additionalRequirements[0].additionalRequirement_type != ACHIEVEMENT_CRITERIA_CONDITION_NO_LOSE) continue; @@ -2710,14 +2711,14 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: // only Children's Week achievements - { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(criteria->referredAchievement); - if (!achievement) - continue; - if (achievement->categoryId != CATEGORY_CHILDRENS_WEEK) - continue; - break; - } + { + AchievementEntry const* achievement = sAchievementStore.LookupEntry(criteria->referredAchievement); + if (!achievement) + continue; + if (achievement->categoryId != CATEGORY_CHILDRENS_WEEK) + continue; + break; + } default: // type not use DB data, ignore continue; } @@ -2894,8 +2895,7 @@ void AchievementGlobalMgr::LoadRewards() m_achievementRewards[entry] = reward; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u achievement rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index 0523e5de6..345e5cf56 100644 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -29,11 +29,12 @@ struct CriteriaProgress }; enum AchievementCriteriaDataType -{ // value1 value2 comment +{ + // value1 value2 comment ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE = 0, // 0 0 ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE = 1, // creature_id 0 ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE = 2, // class_id race_id - ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH= 3, // health_percent 0 + ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH = 3, // health_percent 0 ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD = 4, // own_team 0 not corpse (not released body), own_team == false if enemy team expected ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA = 5, // spell_id effect_idx ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA = 6, // area id 0 @@ -58,7 +59,7 @@ enum AchievementCriteriaDataType #define MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE 24 // maximum value in AchievementCriteriaDataType enum enum AchievementCommonCategories -{ +{ ACHIEVEMENT_CATEOGRY_GENERAL = -1, ACHIEVEMENT_CATEGORY_STATISTICS = 1 }; @@ -205,14 +206,14 @@ struct AchievementCriteriaData struct AchievementCriteriaDataSet { - AchievementCriteriaDataSet() : criteria_id(0) {} - typedef std::vector Storage; - void Add(AchievementCriteriaData const& data) { storage.push_back(data); } - bool Meets(Player const* source, Unit const* target, uint32 miscvalue = 0) const; - void SetCriteriaId(uint32 id) {criteria_id = id;} - private: - uint32 criteria_id; - Storage storage; + AchievementCriteriaDataSet() : criteria_id(0) {} + typedef std::vector Storage; + void Add(AchievementCriteriaData const& data) { storage.push_back(data); } + bool Meets(Player const* source, Unit const* target, uint32 miscvalue = 0) const; + void SetCriteriaId(uint32 id) {criteria_id = id;} +private: + uint32 criteria_id; + Storage storage; }; typedef std::map AchievementCriteriaDataMap; @@ -252,140 +253,140 @@ class WorldPacket; class AchievementMgr { - public: - AchievementMgr(Player* player); - ~AchievementMgr(); +public: + AchievementMgr(Player* player); + ~AchievementMgr(); - void Reset(); - static void DeleteFromDB(uint32 lowguid); - void LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult); - void SaveToDB(SQLTransaction& trans); - void ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete = false); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); - void CompletedAchievement(AchievementEntry const* entry); - void CheckAllAchievementCriteria(); - void SendAllAchievementData() const; - void SendRespondInspectAchievements(Player* player) const; - bool HasAchieved(uint32 achievementId) const; - Player* GetPlayer() const { return m_player; } - void UpdateTimedAchievements(uint32 timeDiff); - void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost = 0); - void RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); // used for quest and scripted timed achievements + void Reset(); + static void DeleteFromDB(uint32 lowguid); + void LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult); + void SaveToDB(SQLTransaction& trans); + void ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete = false); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); + void CompletedAchievement(AchievementEntry const* entry); + void CheckAllAchievementCriteria(); + void SendAllAchievementData() const; + void SendRespondInspectAchievements(Player* player) const; + bool HasAchieved(uint32 achievementId) const; + Player* GetPlayer() const { return m_player; } + void UpdateTimedAchievements(uint32 timeDiff); + void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost = 0); + void RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); // used for quest and scripted timed achievements - void RemoveCriteriaProgress(AchievementCriteriaEntry const* entry); - private: - enum ProgressType { PROGRESS_SET, PROGRESS_ACCUMULATE, PROGRESS_HIGHEST, PROGRESS_RESET }; - void SendAchievementEarned(AchievementEntry const* achievement) const; - void SendCriteriaUpdate(AchievementCriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const; - CriteriaProgress* GetCriteriaProgress(AchievementCriteriaEntry const* entry); - void SetCriteriaProgress(AchievementCriteriaEntry const* entry, uint32 changeValue, ProgressType ptype = PROGRESS_SET); - void CompletedCriteriaFor(AchievementEntry const* achievement); - bool IsCompletedCriteria(AchievementCriteriaEntry const* achievementCriteria, AchievementEntry const* achievement); - bool IsCompletedAchievement(AchievementEntry const* entry); - bool CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement); - void BuildAllDataPacket(WorldPacket* data, bool inspect = false) const; + void RemoveCriteriaProgress(AchievementCriteriaEntry const* entry); +private: + enum ProgressType { PROGRESS_SET, PROGRESS_ACCUMULATE, PROGRESS_HIGHEST, PROGRESS_RESET }; + void SendAchievementEarned(AchievementEntry const* achievement) const; + void SendCriteriaUpdate(AchievementCriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const; + CriteriaProgress* GetCriteriaProgress(AchievementCriteriaEntry const* entry); + void SetCriteriaProgress(AchievementCriteriaEntry const* entry, uint32 changeValue, ProgressType ptype = PROGRESS_SET); + void CompletedCriteriaFor(AchievementEntry const* achievement); + bool IsCompletedCriteria(AchievementCriteriaEntry const* achievementCriteria, AchievementEntry const* achievement); + bool IsCompletedAchievement(AchievementEntry const* entry); + bool CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement); + void BuildAllDataPacket(WorldPacket* data, bool inspect = false) const; - Player* m_player; - CriteriaProgressMap m_criteriaProgress; - CompletedAchievementMap m_completedAchievements; - typedef std::map TimedAchievementMap; - TimedAchievementMap m_timedAchievements; // Criteria id/time left in MS + Player* m_player; + CriteriaProgressMap m_criteriaProgress; + CompletedAchievementMap m_completedAchievements; + typedef std::map TimedAchievementMap; + TimedAchievementMap m_timedAchievements; // Criteria id/time left in MS }; class AchievementGlobalMgr { - AchievementGlobalMgr() {} - ~AchievementGlobalMgr() {} + AchievementGlobalMgr() {} + ~AchievementGlobalMgr() {} - public: - static AchievementGlobalMgr* instance(); +public: + static AchievementGlobalMgr* instance(); - bool IsStatisticCriteria(AchievementCriteriaEntry const* achievementCriteria) const; - bool isStatisticAchievement(AchievementEntry const* achievement) const; - - AchievementCriteriaEntryList const* GetAchievementCriteriaByType(AchievementCriteriaTypes type) const - { - return &m_AchievementCriteriasByType[type]; - } + bool IsStatisticCriteria(AchievementCriteriaEntry const* achievementCriteria) const; + bool isStatisticAchievement(AchievementEntry const* achievement) const; - AchievementCriteriaEntryList const* GetSpecialAchievementCriteriaByType(AchievementCriteriaTypes type, uint32 val) - { - if (m_SpecialList[type].find(val) != m_SpecialList[type].end()) - return &m_SpecialList[type][val]; - return nullptr; - } + AchievementCriteriaEntryList const* GetAchievementCriteriaByType(AchievementCriteriaTypes type) const + { + return &m_AchievementCriteriasByType[type]; + } - AchievementCriteriaEntryList const* GetAchievementCriteriaByCondition(AchievementCriteriaCondition condition, uint32 val) - { - if (m_AchievementCriteriasByCondition[condition].find(val) != m_AchievementCriteriasByCondition[condition].end()) - return &m_AchievementCriteriasByCondition[condition][val]; - return nullptr; - } + AchievementCriteriaEntryList const* GetSpecialAchievementCriteriaByType(AchievementCriteriaTypes type, uint32 val) + { + if (m_SpecialList[type].find(val) != m_SpecialList[type].end()) + return &m_SpecialList[type][val]; + return nullptr; + } - AchievementCriteriaEntryList const& GetTimedAchievementCriteriaByType(AchievementCriteriaTimedTypes type) const - { - return m_AchievementCriteriasByTimedType[type]; - } + AchievementCriteriaEntryList const* GetAchievementCriteriaByCondition(AchievementCriteriaCondition condition, uint32 val) + { + if (m_AchievementCriteriasByCondition[condition].find(val) != m_AchievementCriteriasByCondition[condition].end()) + return &m_AchievementCriteriasByCondition[condition][val]; + return nullptr; + } - AchievementCriteriaEntryList const* GetAchievementCriteriaByAchievement(uint32 id) const - { - AchievementCriteriaListByAchievement::const_iterator itr = m_AchievementCriteriaListByAchievement.find(id); - return itr != m_AchievementCriteriaListByAchievement.end() ? &itr->second : nullptr; - } + AchievementCriteriaEntryList const& GetTimedAchievementCriteriaByType(AchievementCriteriaTimedTypes type) const + { + return m_AchievementCriteriasByTimedType[type]; + } - AchievementEntryList const* GetAchievementByReferencedId(uint32 id) const - { - AchievementListByReferencedId::const_iterator itr = m_AchievementListByReferencedId.find(id); - return itr != m_AchievementListByReferencedId.end() ? &itr->second : nullptr; - } + AchievementCriteriaEntryList const* GetAchievementCriteriaByAchievement(uint32 id) const + { + AchievementCriteriaListByAchievement::const_iterator itr = m_AchievementCriteriaListByAchievement.find(id); + return itr != m_AchievementCriteriaListByAchievement.end() ? &itr->second : nullptr; + } - AchievementReward const* GetAchievementReward(AchievementEntry const* achievement) const - { - AchievementRewards::const_iterator iter = m_achievementRewards.find(achievement->ID); - return iter != m_achievementRewards.end() ? &iter->second : nullptr; - } + AchievementEntryList const* GetAchievementByReferencedId(uint32 id) const + { + AchievementListByReferencedId::const_iterator itr = m_AchievementListByReferencedId.find(id); + return itr != m_AchievementListByReferencedId.end() ? &itr->second : nullptr; + } - AchievementRewardLocale const* GetAchievementRewardLocale(AchievementEntry const* achievement) const - { - AchievementRewardLocales::const_iterator iter = m_achievementRewardLocales.find(achievement->ID); - return iter != m_achievementRewardLocales.end() ? &iter->second : nullptr; - } + AchievementReward const* GetAchievementReward(AchievementEntry const* achievement) const + { + AchievementRewards::const_iterator iter = m_achievementRewards.find(achievement->ID); + return iter != m_achievementRewards.end() ? &iter->second : nullptr; + } - AchievementCriteriaDataSet const* GetCriteriaDataSet(AchievementCriteriaEntry const* achievementCriteria) const - { - AchievementCriteriaDataMap::const_iterator iter = m_criteriaDataMap.find(achievementCriteria->ID); - return iter != m_criteriaDataMap.end() ? &iter->second : nullptr; - } + AchievementRewardLocale const* GetAchievementRewardLocale(AchievementEntry const* achievement) const + { + AchievementRewardLocales::const_iterator iter = m_achievementRewardLocales.find(achievement->ID); + return iter != m_achievementRewardLocales.end() ? &iter->second : nullptr; + } - bool IsRealmCompleted(AchievementEntry const* achievement) const; - void SetRealmCompleted(AchievementEntry const* achievement); + AchievementCriteriaDataSet const* GetCriteriaDataSet(AchievementCriteriaEntry const* achievementCriteria) const + { + AchievementCriteriaDataMap::const_iterator iter = m_criteriaDataMap.find(achievementCriteria->ID); + return iter != m_criteriaDataMap.end() ? &iter->second : nullptr; + } - void LoadAchievementCriteriaList(); - void LoadAchievementCriteriaData(); - void LoadAchievementReferenceList(); - void LoadCompletedAchievements(); - void LoadRewards(); - void LoadRewardLocales(); - private: - AchievementCriteriaDataMap m_criteriaDataMap; + bool IsRealmCompleted(AchievementEntry const* achievement) const; + void SetRealmCompleted(AchievementEntry const* achievement); - // store achievement criterias by type to speed up lookup - AchievementCriteriaEntryList m_AchievementCriteriasByType[ACHIEVEMENT_CRITERIA_TYPE_TOTAL]; - AchievementCriteriaEntryList m_AchievementCriteriasByTimedType[ACHIEVEMENT_TIMED_TYPE_MAX]; - // store achievement criterias by achievement to speed up lookup - AchievementCriteriaListByAchievement m_AchievementCriteriaListByAchievement; - // store achievements by referenced achievement id to speed up lookup - AchievementListByReferencedId m_AchievementListByReferencedId; + void LoadAchievementCriteriaList(); + void LoadAchievementCriteriaData(); + void LoadAchievementReferenceList(); + void LoadCompletedAchievements(); + void LoadRewards(); + void LoadRewardLocales(); +private: + AchievementCriteriaDataMap m_criteriaDataMap; - typedef std::unordered_map AllCompletedAchievements; - AllCompletedAchievements m_allCompletedAchievements; + // store achievement criterias by type to speed up lookup + AchievementCriteriaEntryList m_AchievementCriteriasByType[ACHIEVEMENT_CRITERIA_TYPE_TOTAL]; + AchievementCriteriaEntryList m_AchievementCriteriasByTimedType[ACHIEVEMENT_TIMED_TYPE_MAX]; + // store achievement criterias by achievement to speed up lookup + AchievementCriteriaListByAchievement m_AchievementCriteriaListByAchievement; + // store achievements by referenced achievement id to speed up lookup + AchievementListByReferencedId m_AchievementListByReferencedId; - AchievementRewards m_achievementRewards; - AchievementRewardLocales m_achievementRewardLocales; + typedef std::unordered_map AllCompletedAchievements; + AllCompletedAchievements m_allCompletedAchievements; - // pussywizard: - std::map m_SpecialList[ACHIEVEMENT_CRITERIA_TYPE_TOTAL]; - std::map m_AchievementCriteriasByCondition[ACHIEVEMENT_CRITERIA_CONDITION_TOTAL]; + AchievementRewards m_achievementRewards; + AchievementRewardLocales m_achievementRewardLocales; + + // pussywizard: + std::map m_SpecialList[ACHIEVEMENT_CRITERIA_TYPE_TOTAL]; + std::map m_AchievementCriteriasByCondition[ACHIEVEMENT_CRITERIA_CONDITION_TOTAL]; }; #define sAchievementMgr AchievementGlobalMgr::instance() diff --git a/src/server/game/Addons/AddonMgr.cpp b/src/server/game/Addons/AddonMgr.cpp index e2157719c..942a1a61c 100644 --- a/src/server/game/Addons/AddonMgr.cpp +++ b/src/server/game/Addons/AddonMgr.cpp @@ -15,106 +15,105 @@ namespace AddonMgr { -// Anonymous namespace ensures file scope of all the stuff inside it, even -// if you add something more to this namespace somewhere else. -namespace -{ - // List of saved addons (in DB). - typedef std::list SavedAddonsList; - - SavedAddonsList m_knownAddons; - BannedAddonList m_bannedAddons; -} - -void LoadFromDB() -{ - uint32 oldMSTime = getMSTime(); - - QueryResult result = CharacterDatabase.Query("SELECT name, crc FROM addons"); - if (!result) + // Anonymous namespace ensures file scope of all the stuff inside it, even + // if you add something more to this namespace somewhere else. + namespace { - sLog->outString(">> Loaded 0 known addons. DB table `addons` is empty!"); - sLog->outString(); - return; + // List of saved addons (in DB). + typedef std::list SavedAddonsList; + + SavedAddonsList m_knownAddons; + BannedAddonList m_bannedAddons; } - uint32 count = 0; - - do + void LoadFromDB() { - Field* fields = result->Fetch(); + uint32 oldMSTime = getMSTime(); - std::string name = fields[0].GetString(); - uint32 crc = fields[1].GetUInt32(); + QueryResult result = CharacterDatabase.Query("SELECT name, crc FROM addons"); + if (!result) + { + sLog->outString(">> Loaded 0 known addons. DB table `addons` is empty!"); + sLog->outString(); + return; + } - m_knownAddons.push_back(SavedAddon(name, crc)); - - ++count; - } - while (result->NextRow()); - - sLog->outString(">> Loaded %u known addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - - oldMSTime = getMSTime(); - result = CharacterDatabase.Query("SELECT id, name, version, UNIX_TIMESTAMP(timestamp) FROM banned_addons"); - if (result) - { uint32 count = 0; - uint32 offset = 102; do { Field* fields = result->Fetch(); - BannedAddon addon; - addon.Id = fields[0].GetUInt32() + offset; - addon.Timestamp = uint32(fields[3].GetUInt64()); + std::string name = fields[0].GetString(); + uint32 crc = fields[1].GetUInt32(); - std::string name = fields[1].GetString(); - std::string version = fields[2].GetString(); - - MD5(reinterpret_cast(name.c_str()), name.length(), addon.NameMD5); - MD5(reinterpret_cast(version.c_str()), version.length(), addon.VersionMD5); - - m_bannedAddons.push_back(addon); + m_knownAddons.push_back(SavedAddon(name, crc)); ++count; } while (result->NextRow()); - sLog->outString(">> Loaded %u banned addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - sLog->outString(); + sLog->outString(">> Loaded %u known addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + + oldMSTime = getMSTime(); + result = CharacterDatabase.Query("SELECT id, name, version, UNIX_TIMESTAMP(timestamp) FROM banned_addons"); + if (result) + { + uint32 count = 0; + uint32 offset = 102; + + do + { + Field* fields = result->Fetch(); + + BannedAddon addon; + addon.Id = fields[0].GetUInt32() + offset; + addon.Timestamp = uint32(fields[3].GetUInt64()); + + std::string name = fields[1].GetString(); + std::string version = fields[2].GetString(); + + MD5(reinterpret_cast(name.c_str()), name.length(), addon.NameMD5); + MD5(reinterpret_cast(version.c_str()), version.length(), addon.VersionMD5); + + m_bannedAddons.push_back(addon); + + ++count; + } while (result->NextRow()); + + sLog->outString(">> Loaded %u banned addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + sLog->outString(); + } } -} -void SaveAddon(AddonInfo const& addon) -{ - std::string name = addon.Name; - - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ADDON); - - stmt->setString(0, name); - stmt->setUInt32(1, addon.CRC); - - CharacterDatabase.Execute(stmt); - - m_knownAddons.push_back(SavedAddon(addon.Name, addon.CRC)); -} - -SavedAddon const* GetAddonInfo(const std::string& name) -{ - for (SavedAddonsList::const_iterator it = m_knownAddons.begin(); it != m_knownAddons.end(); ++it) + void SaveAddon(AddonInfo const& addon) { - SavedAddon const& addon = (*it); - if (addon.Name == name) - return &addon; + std::string name = addon.Name; + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ADDON); + + stmt->setString(0, name); + stmt->setUInt32(1, addon.CRC); + + CharacterDatabase.Execute(stmt); + + m_knownAddons.push_back(SavedAddon(addon.Name, addon.CRC)); } - return nullptr; -} + SavedAddon const* GetAddonInfo(const std::string& name) + { + for (SavedAddonsList::const_iterator it = m_knownAddons.begin(); it != m_knownAddons.end(); ++it) + { + SavedAddon const& addon = (*it); + if (addon.Name == name) + return &addon; + } -BannedAddonList const* GetBannedAddons() -{ - return &m_bannedAddons; -} + return nullptr; + } + + BannedAddonList const* GetBannedAddons() + { + return &m_bannedAddons; + } } // Namespace diff --git a/src/server/game/ArenaSpectator/ArenaSpectator.h b/src/server/game/ArenaSpectator/ArenaSpectator.h index 9ed6e88ea..4400aab08 100644 --- a/src/server/game/ArenaSpectator/ArenaSpectator.h +++ b/src/server/game/ArenaSpectator/ArenaSpectator.h @@ -57,7 +57,7 @@ namespace ArenaSpectator void CreatePacket(WorldPacket& data, const char* m) { size_t len = strlen(m); - data.Initialize(SMSG_MESSAGECHAT, 1+4+8+4+8+4+1+len+1); + data.Initialize(SMSG_MESSAGECHAT, 1 + 4 + 8 + 4 + 8 + 4 + 1 + len + 1); data << uint8(CHAT_MSG_WHISPER); data << uint32(LANG_ADDON); data << uint64(0); @@ -87,7 +87,7 @@ namespace ArenaSpectator bg->SpectatorsSendPacket(data); } - template + template void SendCommand_String(T* o, uint64 targetGUID, const char* prefix, const char* c) { if (!IS_PLAYER_GUID(targetGUID)) @@ -163,29 +163,29 @@ namespace ArenaSpectator SendCommand_UInt32Value(p, itr->first, "STA", plr->IsAlive() ? 1 : 0); Powers ptype = plr->getPowerType(); SendCommand_UInt32Value(p, itr->first, "PWT", ptype); - SendCommand_UInt32Value(p, itr->first, "MPW", ptype == POWER_RAGE || ptype == POWER_RUNIC_POWER ? plr->GetMaxPower(ptype)/10 : plr->GetMaxPower(ptype)); - SendCommand_UInt32Value(p, itr->first, "CPW", ptype == POWER_RAGE || ptype == POWER_RUNIC_POWER ? plr->GetPower(ptype)/10 : plr->GetPower(ptype)); + SendCommand_UInt32Value(p, itr->first, "MPW", ptype == POWER_RAGE || ptype == POWER_RUNIC_POWER ? plr->GetMaxPower(ptype) / 10 : plr->GetMaxPower(ptype)); + SendCommand_UInt32Value(p, itr->first, "CPW", ptype == POWER_RAGE || ptype == POWER_RUNIC_POWER ? plr->GetPower(ptype) / 10 : plr->GetPower(ptype)); Pet* pet = plr->GetPet(); SendCommand_UInt32Value(p, itr->first, "PHP", pet && pet->GetCreatureTemplate()->family ? (uint32)pet->GetHealthPct() : 0); SendCommand_UInt32Value(p, itr->first, "PET", pet ? pet->GetCreatureTemplate()->family : 0); SendCommand_GUID(p, itr->first, "TRG", plr->GetTarget()); SendCommand_UInt32Value(p, itr->first, "RES", 1); SendCommand_UInt32Value(p, itr->first, "CDC", 1); - SendCommand_UInt32Value(p, itr->first, "TIM", (bg->GetStartTime() < 46*MINUTE*IN_MILLISECONDS) ? (46*MINUTE*IN_MILLISECONDS-bg->GetStartTime())/IN_MILLISECONDS : 0); + SendCommand_UInt32Value(p, itr->first, "TIM", (bg->GetStartTime() < 46 * MINUTE * IN_MILLISECONDS) ? (46 * MINUTE * IN_MILLISECONDS - bg->GetStartTime()) / IN_MILLISECONDS : 0); // "SPE" not here (only possible to send starting a new cast) // send all "CD" SpellCooldowns const& sc = plr->GetSpellCooldownMap(); for (SpellCooldowns::const_iterator itrc = sc.begin(); itrc != sc.end(); ++itrc) - if (itrc->second.sendToSpectator && itrc->second.maxduration >= SPECTATOR_COOLDOWN_MIN*IN_MILLISECONDS && itrc->second.maxduration <= SPECTATOR_COOLDOWN_MAX*IN_MILLISECONDS) - if (uint32 cd = (getMSTimeDiff(World::GetGameTimeMS(), itrc->second.end)/1000)) - SendCommand_Cooldown(p, itr->first, "ACD", itrc->first, cd, itrc->second.maxduration/1000); + if (itrc->second.sendToSpectator && itrc->second.maxduration >= SPECTATOR_COOLDOWN_MIN * IN_MILLISECONDS && itrc->second.maxduration <= SPECTATOR_COOLDOWN_MAX * IN_MILLISECONDS) + if (uint32 cd = (getMSTimeDiff(World::GetGameTimeMS(), itrc->second.end) / 1000)) + SendCommand_Cooldown(p, itr->first, "ACD", itrc->first, cd, itrc->second.maxduration / 1000); // send all visible "AUR" - Unit::VisibleAuraMap const *visibleAuras = plr->GetVisibleAuras(); + Unit::VisibleAuraMap const* visibleAuras = plr->GetVisibleAuras(); for (Unit::VisibleAuraMap::const_iterator aitr = visibleAuras->begin(); aitr != visibleAuras->end(); ++aitr) { - Aura *aura = aitr->second->GetBase(); + Aura* aura = aitr->second->GetBase(); if (ShouldSendAura(aura, aitr->second->GetEffectMask(), plr->GetGUID(), false)) SendCommand_Aura(p, itr->first, "AUR", aura->GetCasterGUID(), aura->GetSpellInfo()->Id, aura->GetSpellInfo()->IsPositive(), aura->GetSpellInfo()->Dispel, aura->GetDuration(), aura->GetMaxDuration(), (aura->GetCharges() > 1 ? aura->GetCharges() : aura->GetStackAmount()), false); } @@ -200,13 +200,13 @@ namespace ArenaSpectator if (remove || aura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_CU_DONT_BREAK_STEALTH) || aura->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_GENERIC) return true; - for(uint8 i=EFFECT_0; iGetEffect(i)->GetAuraType(); - if ((aura->GetEffect(i)->GetAmount() && (aura->GetSpellInfo()->IsPositive() || targetGUID != aura->GetCasterGUID())) || - at == SPELL_AURA_MECHANIC_IMMUNITY || at == SPELL_AURA_EFFECT_IMMUNITY || at == SPELL_AURA_STATE_IMMUNITY || at == SPELL_AURA_SCHOOL_IMMUNITY || at == SPELL_AURA_DISPEL_IMMUNITY) + if ((aura->GetEffect(i)->GetAmount() && (aura->GetSpellInfo()->IsPositive() || targetGUID != aura->GetCasterGUID())) || + at == SPELL_AURA_MECHANIC_IMMUNITY || at == SPELL_AURA_EFFECT_IMMUNITY || at == SPELL_AURA_STATE_IMMUNITY || at == SPELL_AURA_SCHOOL_IMMUNITY || at == SPELL_AURA_DISPEL_IMMUNITY) return true; } } diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index bcc7a3fe1..d43d4ce62 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -121,8 +121,8 @@ void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry* auction, SQLTransaction& if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_WON), AuctionEntry::BuildAuctionMailBody(auction->owner, auction->bid, auction->buyout, 0, 0)) - .AddItem(pItem) - .SendMailTo(trans, MailReceiver(bidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED); + .AddItem(pItem) + .SendMailTo(trans, MailReceiver(bidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED); } else sAuctionMgr->RemoveAItem(auction->item_guidlow, true); @@ -139,7 +139,7 @@ void AuctionHouseMgr::SendAuctionSalePendingMail(AuctionEntry* auction, SQLTrans sScriptMgr->OnBeforeAuctionHouseMgrSendAuctionSalePendingMail(this, auction, owner, owner_accId, sendMail); if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_SALE_PENDING), AuctionEntry::BuildAuctionMailBody(auction->bidder, auction->bid, auction->buyout, auction->deposit, auction->GetAuctionCut())) - .SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED); + .SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED); } } @@ -169,10 +169,10 @@ void AuctionHouseMgr::SendAuctionSuccessfulMail(AuctionEntry* auction, SQLTransa if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_SUCCESSFUL), AuctionEntry::BuildAuctionMailBody(auction->bidder, auction->bid, auction->buyout, auction->deposit, auction->GetAuctionCut())) - .AddMoney(profit) - .SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, sWorld->getIntConfig(CONFIG_MAIL_DELIVERY_DELAY)); + .AddMoney(profit) + .SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, sWorld->getIntConfig(CONFIG_MAIL_DELIVERY_DELAY)); - if (auction->bid >= 500*GOLD) + if (auction->bid >= 500 * GOLD) if (const GlobalPlayerData* gpd = sWorld->GetGlobalPlayerData(auction->bidder)) { uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER); @@ -184,7 +184,7 @@ void AuctionHouseMgr::SendAuctionSuccessfulMail(AuctionEntry* auction, SQLTransa owner_name = gpd_owner->name; owner_level = gpd_owner->level; } - CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" profit: %ug, bidder: %s %u lvl (guid: %u), seller: %s %u lvl (guid: %u), item %u (%u)\", NOW())", gpd->accountId, auction->bidder, gpd->name.c_str(), bidder ? bidder->GetSession()->GetRemoteAddress().c_str() : "", owner_accId, owner_name.c_str(), auction->bid, (profit/GOLD), gpd->name.c_str(), gpd->level, auction->bidder, owner_name.c_str(), owner_level, auction->owner, auction->item_template, auction->itemCount); + CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" profit: %ug, bidder: %s %u lvl (guid: %u), seller: %s %u lvl (guid: %u), item %u (%u)\", NOW())", gpd->accountId, auction->bidder, gpd->name.c_str(), bidder ? bidder->GetSession()->GetRemoteAddress().c_str() : "", owner_accId, owner_name.c_str(), auction->bid, (profit / GOLD), gpd->name.c_str(), gpd->level, auction->bidder, owner_name.c_str(), owner_level, auction->owner, auction->item_template, auction->itemCount); } } } @@ -211,8 +211,8 @@ void AuctionHouseMgr::SendAuctionExpiredMail(AuctionEntry* auction, SQLTransacti if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_EXPIRED), AuctionEntry::BuildAuctionMailBody(0, 0, auction->buyout, auction->deposit, 0)) - .AddItem(pItem) - .SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, 0); + .AddItem(pItem) + .SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, 0); } else sAuctionMgr->RemoveAItem(auction->item_guidlow, true); @@ -238,8 +238,8 @@ void AuctionHouseMgr::SendAuctionOutbiddedMail(AuctionEntry* auction, uint32 new if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_OUTBIDDED), AuctionEntry::BuildAuctionMailBody(auction->owner, auction->bid, auction->buyout, auction->deposit, auction->GetAuctionCut())) - .AddMoney(auction->bid) - .SendMailTo(trans, MailReceiver(oldBidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED); + .AddMoney(auction->bid) + .SendMailTo(trans, MailReceiver(oldBidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED); } } @@ -259,8 +259,8 @@ void AuctionHouseMgr::SendAuctionCancelledToBidderMail(AuctionEntry* auction, SQ sScriptMgr->OnBeforeAuctionHouseMgrSendAuctionCancelledToBidderMail(this, auction, bidder, bidder_accId, sendMail); if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_CANCELLED_TO_BIDDER), AuctionEntry::BuildAuctionMailBody(auction->owner, auction->bid, auction->buyout, auction->deposit, 0)) - .AddMoney(auction->bid) - .SendMailTo(trans, MailReceiver(bidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED); + .AddMoney(auction->bid) + .SendMailTo(trans, MailReceiver(bidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED); } } @@ -314,8 +314,7 @@ void AuctionHouseMgr::LoadAuctionItems() AddAItem(item); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u auction items in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -404,29 +403,49 @@ AuctionHouseEntry const* AuctionHouseMgr::GetAuctionHouseEntry(uint32 factionTem // but no easy way convert creature faction to player race faction for specific city switch (factionTemplateId) { - case 12: houseid = 1; break; // human - case 29: houseid = 6; break; // orc, and generic for horde - case 55: houseid = 2; break; // dwarf, and generic for alliance - case 68: houseid = 4; break; // undead - case 80: houseid = 3; break; // n-elf - case 104: houseid = 5; break; // trolls - case 120: houseid = 7; break; // booty bay, neutral - case 474: houseid = 7; break; // gadgetzan, neutral - case 855: houseid = 7; break; // everlook, neutral - case 1604: houseid = 6; break; // b-elfs, + case 12: + houseid = 1; + break; // human + case 29: + houseid = 6; + break; // orc, and generic for horde + case 55: + houseid = 2; + break; // dwarf, and generic for alliance + case 68: + houseid = 4; + break; // undead + case 80: + houseid = 3; + break; // n-elf + case 104: + houseid = 5; + break; // trolls + case 120: + houseid = 7; + break; // booty bay, neutral + case 474: + houseid = 7; + break; // gadgetzan, neutral + case 855: + houseid = 7; + break; // everlook, neutral + case 1604: + houseid = 6; + break; // b-elfs, default: // for unknown case - { - FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId); - if (!u_entry) - houseid = 7; // goblin auction house - else if (u_entry->ourMask & FACTION_MASK_ALLIANCE) - houseid = 1; // human auction house - else if (u_entry->ourMask & FACTION_MASK_HORDE) - houseid = 6; // orc auction house - else - houseid = 7; // goblin auction house - break; - } + { + FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId); + if (!u_entry) + houseid = 7; // goblin auction house + else if (u_entry->ourMask & FACTION_MASK_ALLIANCE) + houseid = 1; // human auction house + else if (u_entry->ourMask & FACTION_MASK_HORDE) + houseid = 6; // orc auction house + else + houseid = 7; // goblin auction house + break; + } } } @@ -530,9 +549,9 @@ void AuctionHouseObject::BuildListOwnerItems(WorldPacket& data, Player* player, } bool AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player, - std::wstring const& wsearchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable, - uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, - uint32& count, uint32& totalcount, uint8 /*getAll*/) + std::wstring const& wsearchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable, + uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, + uint32& count, uint32& totalcount, uint8 /*getAll*/) { uint32 itrcounter = 0; diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.h b/src/server/game/AuctionHouse/AuctionHouseMgr.h index 110f1ce91..29d02daf4 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.h +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.h @@ -72,7 +72,7 @@ struct AuctionEntry uint32 GetHouseFaction() const { return auctionHouseEntry->faction; } uint32 GetAuctionCut() const; uint32 GetAuctionOutBid() const; - bool BuildAuctionInfo(WorldPacket & data) const; + bool BuildAuctionInfo(WorldPacket& data) const; void DeleteFromDB(SQLTransaction& trans) const; void SaveToDB(SQLTransaction& trans) const; bool LoadFromDB(Field* fields); @@ -85,7 +85,7 @@ struct AuctionEntry //this class is used as auctionhouse instance class AuctionHouseObject { - public: +public: // Initialize storage AuctionHouseObject() { next = AuctionsMap.begin(); } ~AuctionHouseObject() @@ -116,11 +116,11 @@ class AuctionHouseObject void BuildListBidderItems(WorldPacket& data, Player* player, uint32& count, uint32& totalcount); void BuildListOwnerItems(WorldPacket& data, Player* player, uint32& count, uint32& totalcount); bool BuildListAuctionItems(WorldPacket& data, Player* player, - std::wstring const& searchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable, - uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, - uint32& count, uint32& totalcount, uint8 getAll); + std::wstring const& searchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable, + uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, + uint32& count, uint32& totalcount, uint8 getAll); - private: +private: AuctionEntryMap AuctionsMap; // storage for "next" auction item for next Update() @@ -129,57 +129,57 @@ class AuctionHouseObject class AuctionHouseMgr { - private: - AuctionHouseMgr(); - ~AuctionHouseMgr(); +private: + AuctionHouseMgr(); + ~AuctionHouseMgr(); - public: +public: - typedef std::unordered_map ItemMap; + typedef std::unordered_map ItemMap; - static AuctionHouseMgr* instance(); + static AuctionHouseMgr* instance(); - AuctionHouseObject* GetAuctionsMap(uint32 factionTemplateId); - AuctionHouseObject* GetBidsMap(uint32 factionTemplateId); + AuctionHouseObject* GetAuctionsMap(uint32 factionTemplateId); + AuctionHouseObject* GetBidsMap(uint32 factionTemplateId); - Item* GetAItem(uint32 id) - { - ItemMap::const_iterator itr = mAitems.find(id); - if (itr != mAitems.end()) - return itr->second; + Item* GetAItem(uint32 id) + { + ItemMap::const_iterator itr = mAitems.find(id); + if (itr != mAitems.end()) + return itr->second; - return nullptr; - } + return nullptr; + } - //auction messages - void SendAuctionWonMail(AuctionEntry* auction, SQLTransaction& trans, bool sendNotification = true, bool updateAchievementCriteria = true, bool sendMail = true); - void SendAuctionSalePendingMail(AuctionEntry* auction, SQLTransaction& trans, bool sendMail = true); - void SendAuctionSuccessfulMail(AuctionEntry* auction, SQLTransaction& trans, bool sendNotification = true, bool updateAchievementCriteria = true, bool sendMail = true); - void SendAuctionExpiredMail(AuctionEntry* auction, SQLTransaction& trans, bool sendNotification = true, bool sendMail = true); - void SendAuctionOutbiddedMail(AuctionEntry* auction, uint32 newPrice, Player* newBidder, SQLTransaction& trans, bool sendNotification = true, bool sendMail = true); - void SendAuctionCancelledToBidderMail(AuctionEntry* auction, SQLTransaction& trans, bool sendMail = true); + //auction messages + void SendAuctionWonMail(AuctionEntry* auction, SQLTransaction& trans, bool sendNotification = true, bool updateAchievementCriteria = true, bool sendMail = true); + void SendAuctionSalePendingMail(AuctionEntry* auction, SQLTransaction& trans, bool sendMail = true); + void SendAuctionSuccessfulMail(AuctionEntry* auction, SQLTransaction& trans, bool sendNotification = true, bool updateAchievementCriteria = true, bool sendMail = true); + void SendAuctionExpiredMail(AuctionEntry* auction, SQLTransaction& trans, bool sendNotification = true, bool sendMail = true); + void SendAuctionOutbiddedMail(AuctionEntry* auction, uint32 newPrice, Player* newBidder, SQLTransaction& trans, bool sendNotification = true, bool sendMail = true); + void SendAuctionCancelledToBidderMail(AuctionEntry* auction, SQLTransaction& trans, bool sendMail = true); - static uint32 GetAuctionDeposit(AuctionHouseEntry const* entry, uint32 time, Item* pItem, uint32 count); - static AuctionHouseEntry const* GetAuctionHouseEntry(uint32 factionTemplateId); + static uint32 GetAuctionDeposit(AuctionHouseEntry const* entry, uint32 time, Item* pItem, uint32 count); + static AuctionHouseEntry const* GetAuctionHouseEntry(uint32 factionTemplateId); - public: +public: - //load first auction items, because of check if item exists, when loading - void LoadAuctionItems(); - void LoadAuctions(); + //load first auction items, because of check if item exists, when loading + void LoadAuctionItems(); + void LoadAuctions(); - void AddAItem(Item* it); - bool RemoveAItem(uint32 id, bool deleteFromDB = false); + void AddAItem(Item* it); + bool RemoveAItem(uint32 id, bool deleteFromDB = false); - void Update(); + void Update(); - private: +private: - AuctionHouseObject mHordeAuctions; - AuctionHouseObject mAllianceAuctions; - AuctionHouseObject mNeutralAuctions; + AuctionHouseObject mHordeAuctions; + AuctionHouseObject mAllianceAuctions; + AuctionHouseObject mNeutralAuctions; - ItemMap mAitems; + ItemMap mAitems; }; #define sAuctionMgr AuctionHouseMgr::instance() diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index 5bf286d8d..371777173 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -67,7 +67,7 @@ void Battlefield::HandlePlayerEnterZone(Player* player, uint32 /*zone*/) // Xinef: do not invite players on taxi if (!player->IsInFlight()) { - // If battle is started, + // If battle is started, // If not full of players > invite player to join the war // If full of players > announce to player that BF is full and kick him after a few second if he desn't leave if (IsWarTime()) @@ -77,7 +77,7 @@ void Battlefield::HandlePlayerEnterZone(Player* player, uint32 /*zone*/) else // No more vacant places { // TODO: Send a packet to announce it to player - m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + (player->IsGameMaster() ? 30*MINUTE : 10); + m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + (player->IsGameMaster() ? 30 * MINUTE : 10); InvitePlayerToQueue(player); } } @@ -424,11 +424,14 @@ void Battlefield::PlayerAcceptInviteToWar(Player* player) void Battlefield::TeamCastSpell(TeamId team, int32 spellId) { - if (spellId > 0) { + if (spellId > 0) + { for (GuidSet::const_iterator itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr) if (Player* player = ObjectAccessor::FindPlayer(*itr)) player->CastSpell(player, uint32(spellId), true); - } else { + } + else + { for (GuidSet::const_iterator itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr) if (Player* player = ObjectAccessor::FindPlayer(*itr)) player->RemoveAuraFromStack(uint32(-spellId)); @@ -591,7 +594,7 @@ BfGraveyard* Battlefield::GetGraveyardById(uint32 id) const return nullptr; } -GraveyardStruct const * Battlefield::GetClosestGraveyard(Player* player) +GraveyardStruct const* Battlefield::GetClosestGraveyard(Player* player) { BfGraveyard* closestGY = nullptr; float maxdist = -1; @@ -647,7 +650,7 @@ void Battlefield::RemovePlayerFromResurrectQueue(uint64 playerGuid) } } -void Battlefield::SendAreaSpiritHealerQueryOpcode(Player* player, const uint64 &guid) +void Battlefield::SendAreaSpiritHealerQueryOpcode(Player* player, const uint64& guid) { WorldPacket data(SMSG_AREA_SPIRIT_HEALER_TIME, 12); uint32 time = m_LastResurectTimer; // resurrect every 30 seconds @@ -875,9 +878,9 @@ GuidSet::iterator BfCapturePoint::HandlePlayerLeave(Player* player) { if (GameObject* go = GetCapturePointGo(player)) player->SendUpdateWorldState(go->GetGOInfo()->capturePoint.worldState1, 0); - + GuidSet::iterator current = m_activePlayers[player->GetTeamId()].find(player->GetGUID()); - + if (current == m_activePlayers[player->GetTeamId()].end()) return current; // return end() diff --git a/src/server/game/Battlefield/Battlefield.h b/src/server/game/Battlefield/Battlefield.h index d8e03f741..b3d65433e 100644 --- a/src/server/game/Battlefield/Battlefield.h +++ b/src/server/game/Battlefield/Battlefield.h @@ -23,7 +23,7 @@ enum BattlefieldTypes enum BattlefieldIDs { - BATTLEFIELD_BATTLEID_WG = 1, // Wintergrasp battle + BATTLEFIELD_BATTLEID_WG = 1, // Wintergrasp battle }; enum BattlefieldObjectiveStates @@ -72,356 +72,356 @@ typedef std::map PlayerTimerMap; class BfCapturePoint { - public: - BfCapturePoint(Battlefield* bf); +public: + BfCapturePoint(Battlefield* bf); - virtual ~BfCapturePoint() { } + virtual ~BfCapturePoint() { } - virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} + virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} - // Send world state update to all players present - void SendUpdateWorldState(uint32 field, uint32 value); + // Send world state update to all players present + void SendUpdateWorldState(uint32 field, uint32 value); - // Send kill notify to players in the controlling faction - void SendObjectiveComplete(uint32 id, uint64 guid); + // Send kill notify to players in the controlling faction + void SendObjectiveComplete(uint32 id, uint64 guid); - // Used when player is activated/inactivated in the area - virtual bool HandlePlayerEnter(Player* player); - virtual GuidSet::iterator HandlePlayerLeave(Player* player); - //virtual void HandlePlayerActivityChanged(Player* player); + // Used when player is activated/inactivated in the area + virtual bool HandlePlayerEnter(Player* player); + virtual GuidSet::iterator HandlePlayerLeave(Player* player); + //virtual void HandlePlayerActivityChanged(Player* player); - // Checks if player is in range of a capture credit marker - bool IsInsideObjective(Player* player) const; + // Checks if player is in range of a capture credit marker + bool IsInsideObjective(Player* player) const; - // Returns true if the state of the objective has changed, in this case, the OutdoorPvP must send a world state ui update. - virtual bool Update(uint32 diff); - virtual void ChangeTeam(TeamId /*oldTeam*/) {} - virtual void SendChangePhase(); + // Returns true if the state of the objective has changed, in this case, the OutdoorPvP must send a world state ui update. + virtual bool Update(uint32 diff); + virtual void ChangeTeam(TeamId /*oldTeam*/) {} + virtual void SendChangePhase(); - bool SetCapturePointData(GameObject* capturePoint); - GameObject* GetCapturePointGo() { return ObjectAccessor::GetObjectInWorld(m_capturePoint, (GameObject*)NULL); } - GameObject* GetCapturePointGo(WorldObject* obj) { return ObjectAccessor::GetGameObject(*obj, m_capturePoint); } + bool SetCapturePointData(GameObject* capturePoint); + GameObject* GetCapturePointGo() { return ObjectAccessor::GetObjectInWorld(m_capturePoint, (GameObject*)NULL); } + GameObject* GetCapturePointGo(WorldObject* obj) { return ObjectAccessor::GetGameObject(*obj, m_capturePoint); } - TeamId GetTeamId() { return m_team; } - protected: - bool DelCapturePoint(); + TeamId GetTeamId() { return m_team; } +protected: + bool DelCapturePoint(); - // active Players in the area of the objective, 0 - alliance, 1 - horde - GuidSet m_activePlayers[2]; + // active Players in the area of the objective, 0 - alliance, 1 - horde + GuidSet m_activePlayers[2]; - // Total shift needed to capture the objective - float m_maxValue; - float m_minValue; + // Total shift needed to capture the objective + float m_maxValue; + float m_minValue; - // Maximum speed of capture - float m_maxSpeed; + // Maximum speed of capture + float m_maxSpeed; - // The status of the objective - float m_value; - TeamId m_team; + // The status of the objective + float m_value; + TeamId m_team; - // Objective states - BattlefieldObjectiveStates m_OldState; - BattlefieldObjectiveStates m_State; + // Objective states + BattlefieldObjectiveStates m_OldState; + BattlefieldObjectiveStates m_State; - // Neutral value on capture bar - uint32 m_neutralValuePct; + // Neutral value on capture bar + uint32 m_neutralValuePct; - // Pointer to the Battlefield this objective belongs to - Battlefield* m_Bf; + // Pointer to the Battlefield this objective belongs to + Battlefield* m_Bf; - // Capture point entry - uint32 m_capturePointEntry; + // Capture point entry + uint32 m_capturePointEntry; - // Gameobject related to that capture point - uint64 m_capturePoint; + // Gameobject related to that capture point + uint64 m_capturePoint; }; class BfGraveyard { - public: - BfGraveyard(Battlefield* Bf); +public: + BfGraveyard(Battlefield* Bf); - // Method to changing who controls the graveyard - void GiveControlTo(TeamId team); - TeamId GetControlTeamId() const { return m_ControlTeam; } + // Method to changing who controls the graveyard + void GiveControlTo(TeamId team); + TeamId GetControlTeamId() const { return m_ControlTeam; } - // Find the nearest graveyard to a player - float GetDistance(Player* player); + // Find the nearest graveyard to a player + float GetDistance(Player* player); - // Initialize the graveyard - void Initialize(TeamId startcontrol, uint32 gy); + // Initialize the graveyard + void Initialize(TeamId startcontrol, uint32 gy); - // Set spirit service for the graveyard - void SetSpirit(Creature* spirit, TeamId team); + // Set spirit service for the graveyard + void SetSpirit(Creature* spirit, TeamId team); - // Add a player to the graveyard - void AddPlayer(uint64 player_guid); + // Add a player to the graveyard + void AddPlayer(uint64 player_guid); - // Remove a player from the graveyard - void RemovePlayer(uint64 player_guid); + // Remove a player from the graveyard + void RemovePlayer(uint64 player_guid); - // Resurrect players - void Resurrect(); + // Resurrect players + void Resurrect(); - // Move players waiting to that graveyard on the nearest one - void RelocateDeadPlayers(); + // Move players waiting to that graveyard on the nearest one + void RelocateDeadPlayers(); - // Check if this graveyard has a spirit guide - bool HasNpc(uint64 guid) - { - if (!m_SpiritGuide[0] && !m_SpiritGuide[1]) - return false; + // Check if this graveyard has a spirit guide + bool HasNpc(uint64 guid) + { + if (!m_SpiritGuide[0] && !m_SpiritGuide[1]) + return false; - // performance - /*if (!ObjectAccessor::FindUnit(m_SpiritGuide[0]) && - !ObjectAccessor::FindUnit(m_SpiritGuide[1])) - return false;*/ + // performance + /*if (!ObjectAccessor::FindUnit(m_SpiritGuide[0]) && + !ObjectAccessor::FindUnit(m_SpiritGuide[1])) + return false;*/ - return (m_SpiritGuide[0] == guid || m_SpiritGuide[1] == guid); - } + return (m_SpiritGuide[0] == guid || m_SpiritGuide[1] == guid); + } - // Check if a player is in this graveyard's resurrect queue - bool HasPlayer(uint64 guid) const { return m_ResurrectQueue.find(guid) != m_ResurrectQueue.end(); } + // Check if a player is in this graveyard's resurrect queue + bool HasPlayer(uint64 guid) const { return m_ResurrectQueue.find(guid) != m_ResurrectQueue.end(); } - // Get the graveyard's ID. - uint32 GetGraveyardId() const { return m_GraveyardId; } + // Get the graveyard's ID. + uint32 GetGraveyardId() const { return m_GraveyardId; } - protected: - TeamId m_ControlTeam; - uint32 m_GraveyardId; - uint64 m_SpiritGuide[2]; - GuidSet m_ResurrectQueue; - Battlefield* m_Bf; +protected: + TeamId m_ControlTeam; + uint32 m_GraveyardId; + uint64 m_SpiritGuide[2]; + GuidSet m_ResurrectQueue; + Battlefield* m_Bf; }; class Battlefield : public ZoneScript { friend class BattlefieldMgr; - public: - /// Constructor - Battlefield(); - /// Destructor - virtual ~Battlefield(); +public: + /// Constructor + Battlefield(); + /// Destructor + virtual ~Battlefield(); - /// typedef of map witch store capturepoint and the associate gameobject entry - typedef std::map BfCapturePointMap; + /// typedef of map witch store capturepoint and the associate gameobject entry + typedef std::map BfCapturePointMap; - /// Call this to init the Battlefield - virtual bool SetupBattlefield() { return true; } + /// Call this to init the Battlefield + virtual bool SetupBattlefield() { return true; } - /// Update data of a worldstate to all players present in zone - void SendUpdateWorldState(uint32 field, uint32 value); + /// Update data of a worldstate to all players present in zone + void SendUpdateWorldState(uint32 field, uint32 value); - /** - * \brief Called every time for update bf data and time - * - Update timer for start/end battle - * - Invite player in zone to queue m_StartGroupingTimer minutes before start - * - Kick Afk players - * \param diff : time ellapsed since last call (in ms) - */ - virtual bool Update(uint32 diff); + /** + * \brief Called every time for update bf data and time + * - Update timer for start/end battle + * - Invite player in zone to queue m_StartGroupingTimer minutes before start + * - Kick Afk players + * \param diff : time ellapsed since last call (in ms) + */ + virtual bool Update(uint32 diff); - /// Invite all players in zone to join the queue, called x minutes before battle start in Update() - void InvitePlayersInZoneToQueue(); - /// Invite all players in queue to join battle on battle start - void InvitePlayersInQueueToWar(); - /// Invite all players in zone to join battle on battle start - void InvitePlayersInZoneToWar(); + /// Invite all players in zone to join the queue, called x minutes before battle start in Update() + void InvitePlayersInZoneToQueue(); + /// Invite all players in queue to join battle on battle start + void InvitePlayersInQueueToWar(); + /// Invite all players in zone to join battle on battle start + void InvitePlayersInZoneToWar(); - /// Called when a Unit is kill in battlefield zone - virtual void HandleKill(Player* /*killer*/, Unit* /*killed*/) {}; + /// Called when a Unit is kill in battlefield zone + virtual void HandleKill(Player* /*killer*/, Unit* /*killed*/) {}; - uint32 GetTypeId() { return m_TypeId; } - uint32 GetZoneId() { return m_ZoneId; } + uint32 GetTypeId() { return m_TypeId; } + uint32 GetZoneId() { return m_ZoneId; } - void TeamApplyBuff(TeamId team, uint32 spellId, uint32 spellId2 = 0); + void TeamApplyBuff(TeamId team, uint32 spellId, uint32 spellId2 = 0); - /// Return true if battle is start, false if battle is not started - bool IsWarTime() { return m_isActive; } + /// Return true if battle is start, false if battle is not started + bool IsWarTime() { return m_isActive; } - /// Enable or Disable battlefield - void ToggleBattlefield(bool enable) { m_IsEnabled = enable; } - /// Return if battlefield is enable - bool IsEnabled() { return m_IsEnabled; } + /// Enable or Disable battlefield + void ToggleBattlefield(bool enable) { m_IsEnabled = enable; } + /// Return if battlefield is enable + bool IsEnabled() { return m_IsEnabled; } - /** - * \brief Kick player from battlefield and teleport him to kick-point location - * \param guid : guid of player who must be kick - */ - void KickPlayerFromBattlefield(uint64 guid); + /** + * \brief Kick player from battlefield and teleport him to kick-point location + * \param guid : guid of player who must be kick + */ + void KickPlayerFromBattlefield(uint64 guid); - /// Called when player (player) enter in zone - void HandlePlayerEnterZone(Player* player, uint32 zone); - /// Called when player (player) leave the zone - void HandlePlayerLeaveZone(Player* player, uint32 zone); + /// Called when player (player) enter in zone + void HandlePlayerEnterZone(Player* player, uint32 zone); + /// Called when player (player) leave the zone + void HandlePlayerLeaveZone(Player* player, uint32 zone); - // All-purpose data storage 64 bit - virtual uint64 GetData64(uint32 dataId) const { return m_Data64[dataId]; } - virtual void SetData64(uint32 dataId, uint64 value) { m_Data64[dataId] = value; } + // All-purpose data storage 64 bit + virtual uint64 GetData64(uint32 dataId) const { return m_Data64[dataId]; } + virtual void SetData64(uint32 dataId, uint64 value) { m_Data64[dataId] = value; } - // All-purpose data storage 32 bit - virtual uint32 GetData(uint32 dataId) const { return m_Data32[dataId]; } - virtual void SetData(uint32 dataId, uint32 value) { m_Data32[dataId] = value; } - virtual void UpdateData(uint32 index, int32 pad) { m_Data32[index] += pad; } + // All-purpose data storage 32 bit + virtual uint32 GetData(uint32 dataId) const { return m_Data32[dataId]; } + virtual void SetData(uint32 dataId, uint32 value) { m_Data32[dataId] = value; } + virtual void UpdateData(uint32 index, int32 pad) { m_Data32[index] += pad; } - // Battlefield - generic methods - TeamId GetDefenderTeam() { return m_DefenderTeam; } - TeamId GetAttackerTeam() { return TeamId(1 - m_DefenderTeam); } - TeamId GetOtherTeam(TeamId team) { return (team == TEAM_HORDE ? TEAM_ALLIANCE : TEAM_HORDE); } - void SetDefenderTeam(TeamId team) { m_DefenderTeam = team; } + // Battlefield - generic methods + TeamId GetDefenderTeam() { return m_DefenderTeam; } + TeamId GetAttackerTeam() { return TeamId(1 - m_DefenderTeam); } + TeamId GetOtherTeam(TeamId team) { return (team == TEAM_HORDE ? TEAM_ALLIANCE : TEAM_HORDE); } + void SetDefenderTeam(TeamId team) { m_DefenderTeam = team; } - // Group methods - /** - * \brief Find a not full battlefield group, if there is no, create one - * \param TeamId : Id of player team for who we search a group (player->GetTeamId()) - */ - Group* GetFreeBfRaid(TeamId TeamId); - /// Return battlefield group where player is. - Group* GetGroupPlayer(uint64 guid, TeamId TeamId); - /// Force player to join a battlefield group - bool AddOrSetPlayerToCorrectBfGroup(Player* player); + // Group methods + /** + * \brief Find a not full battlefield group, if there is no, create one + * \param TeamId : Id of player team for who we search a group (player->GetTeamId()) + */ + Group* GetFreeBfRaid(TeamId TeamId); + /// Return battlefield group where player is. + Group* GetGroupPlayer(uint64 guid, TeamId TeamId); + /// Force player to join a battlefield group + bool AddOrSetPlayerToCorrectBfGroup(Player* player); - // Graveyard methods - // Find which graveyard the player must be teleported to to be resurrected by spiritguide - GraveyardStruct const * GetClosestGraveyard(Player* player); + // Graveyard methods + // Find which graveyard the player must be teleported to to be resurrected by spiritguide + GraveyardStruct const* GetClosestGraveyard(Player* player); - virtual void AddPlayerToResurrectQueue(uint64 npc_guid, uint64 player_guid); - void RemovePlayerFromResurrectQueue(uint64 player_guid); - void SetGraveyardNumber(uint32 number) { m_GraveyardList.resize(number); } - BfGraveyard* GetGraveyardById(uint32 id) const; + virtual void AddPlayerToResurrectQueue(uint64 npc_guid, uint64 player_guid); + void RemovePlayerFromResurrectQueue(uint64 player_guid); + void SetGraveyardNumber(uint32 number) { m_GraveyardList.resize(number); } + BfGraveyard* GetGraveyardById(uint32 id) const; - // Misc methods - Creature* SpawnCreature(uint32 entry, float x, float y, float z, float o, TeamId teamId); - Creature* SpawnCreature(uint32 entry, Position pos, TeamId teamId); - GameObject* SpawnGameObject(uint32 entry, float x, float y, float z, float o); + // Misc methods + Creature* SpawnCreature(uint32 entry, float x, float y, float z, float o, TeamId teamId); + Creature* SpawnCreature(uint32 entry, Position pos, TeamId teamId); + GameObject* SpawnGameObject(uint32 entry, float x, float y, float z, float o); - // Script-methods + // Script-methods - /// Called on start - virtual void OnBattleStart() {}; - /// Called at the end of battle - virtual void OnBattleEnd(bool /*endByTimer*/) {}; - /// Called x minutes before battle start when player in zone are invite to join queue - virtual void OnStartGrouping() {}; - /// Called when a player accept to join the battle - virtual void OnPlayerJoinWar(Player* /*player*/) {}; - /// Called when a player leave the battle - virtual void OnPlayerLeaveWar(Player* /*player*/) {}; - /// Called when a player leave battlefield zone - virtual void OnPlayerLeaveZone(Player* /*player*/) {}; - /// Called when a player enter in battlefield zone - virtual void OnPlayerEnterZone(Player* /*player*/) {}; + /// Called on start + virtual void OnBattleStart() {}; + /// Called at the end of battle + virtual void OnBattleEnd(bool /*endByTimer*/) {}; + /// Called x minutes before battle start when player in zone are invite to join queue + virtual void OnStartGrouping() {}; + /// Called when a player accept to join the battle + virtual void OnPlayerJoinWar(Player* /*player*/) {}; + /// Called when a player leave the battle + virtual void OnPlayerLeaveWar(Player* /*player*/) {}; + /// Called when a player leave battlefield zone + virtual void OnPlayerLeaveZone(Player* /*player*/) {}; + /// Called when a player enter in battlefield zone + virtual void OnPlayerEnterZone(Player* /*player*/) {}; - void SendWarningToAllInZone(uint32 entry); - void SendWarningToPlayer(Player* player, uint32 entry); + void SendWarningToAllInZone(uint32 entry); + void SendWarningToPlayer(Player* player, uint32 entry); - void PlayerAcceptInviteToQueue(Player* player); - void PlayerAcceptInviteToWar(Player* player); - uint32 GetBattleId() { return m_BattleId; } - void AskToLeaveQueue(Player* player); - void PlayerAskToLeave(Player* player); + void PlayerAcceptInviteToQueue(Player* player); + void PlayerAcceptInviteToWar(Player* player); + uint32 GetBattleId() { return m_BattleId; } + void AskToLeaveQueue(Player* player); + void PlayerAskToLeave(Player* player); - //virtual void DoCompleteOrIncrementAchievement(uint32 /*achievement*/, Player* /*player*/, uint8 /*incrementNumber = 1*/) {}; + //virtual void DoCompleteOrIncrementAchievement(uint32 /*achievement*/, Player* /*player*/, uint8 /*incrementNumber = 1*/) {}; - /// Send all worldstate data to all player in zone. - virtual void SendInitWorldStatesToAll() = 0; - virtual void FillInitialWorldStates(WorldPacket& /*data*/) = 0; + /// Send all worldstate data to all player in zone. + virtual void SendInitWorldStatesToAll() = 0; + virtual void FillInitialWorldStates(WorldPacket& /*data*/) = 0; - /// Return if we can use mount in battlefield - bool CanFlyIn() { return !m_isActive; } + /// Return if we can use mount in battlefield + bool CanFlyIn() { return !m_isActive; } - void SendAreaSpiritHealerQueryOpcode(Player* player, const uint64 & guid); + void SendAreaSpiritHealerQueryOpcode(Player* player, const uint64& guid); - void StartBattle(); - void EndBattle(bool endByTimer); + void StartBattle(); + void EndBattle(bool endByTimer); - void HideNpc(Creature* creature); - void ShowNpc(Creature* creature, bool aggressive); + void HideNpc(Creature* creature); + void ShowNpc(Creature* creature, bool aggressive); - GraveyardVect GetGraveyardVector() { return m_GraveyardList; } + GraveyardVect GetGraveyardVector() { return m_GraveyardList; } - uint32 GetTimer() { return m_Timer; } - void SetTimer(uint32 timer) { m_Timer = timer; } + uint32 GetTimer() { return m_Timer; } + void SetTimer(uint32 timer) { m_Timer = timer; } - void DoPlaySoundToAll(uint32 SoundID); + void DoPlaySoundToAll(uint32 SoundID); - void InvitePlayerToQueue(Player* player); - void InvitePlayerToWar(Player* player); + void InvitePlayerToQueue(Player* player); + void InvitePlayerToWar(Player* player); - void InitStalker(uint32 entry, float x, float y, float z, float o); + void InitStalker(uint32 entry, float x, float y, float z, float o); - protected: - uint64 StalkerGuid; - uint32 m_Timer; // Global timer for event - bool m_IsEnabled; - bool m_isActive; - TeamId m_DefenderTeam; +protected: + uint64 StalkerGuid; + uint32 m_Timer; // Global timer for event + bool m_IsEnabled; + bool m_isActive; + TeamId m_DefenderTeam; - // Map of the objectives belonging to this OutdoorPvP - BfCapturePointMap m_capturePoints; + // Map of the objectives belonging to this OutdoorPvP + BfCapturePointMap m_capturePoints; - // Players info maps - GuidSet m_players[BG_TEAMS_COUNT]; // Players in zone - GuidSet m_PlayersInQueue[BG_TEAMS_COUNT]; // Players in the queue - GuidSet m_PlayersInWar[BG_TEAMS_COUNT]; // Players in WG combat - PlayerTimerMap m_InvitedPlayers[BG_TEAMS_COUNT]; - PlayerTimerMap m_PlayersWillBeKick[BG_TEAMS_COUNT]; + // Players info maps + GuidSet m_players[BG_TEAMS_COUNT]; // Players in zone + GuidSet m_PlayersInQueue[BG_TEAMS_COUNT]; // Players in the queue + GuidSet m_PlayersInWar[BG_TEAMS_COUNT]; // Players in WG combat + PlayerTimerMap m_InvitedPlayers[BG_TEAMS_COUNT]; + PlayerTimerMap m_PlayersWillBeKick[BG_TEAMS_COUNT]; - // Variables that must exist for each battlefield - uint32 m_TypeId; // See enum BattlefieldTypes - uint32 m_BattleId; // BattleID (for packet) - uint32 m_ZoneId; // ZoneID of Wintergrasp = 4197 - uint32 m_MapId; // MapId where is Battlefield - uint32 m_MaxPlayer; // Maximum number of player that participated to Battlefield - uint32 m_MinPlayer; // Minimum number of player for Battlefield start - uint32 m_MinLevel; // Required level to participate at Battlefield - uint32 m_BattleTime; // Length of a battle - uint32 m_NoWarBattleTime; // Time between two battles - uint32 m_RestartAfterCrash; // Delay to restart Wintergrasp if the server crashed during a running battle. - uint32 m_TimeForAcceptInvite; - uint32 m_uiKickDontAcceptTimer; - WorldLocation KickPosition; // Position where players are teleported if they switch to afk during the battle or if they don't accept invitation + // Variables that must exist for each battlefield + uint32 m_TypeId; // See enum BattlefieldTypes + uint32 m_BattleId; // BattleID (for packet) + uint32 m_ZoneId; // ZoneID of Wintergrasp = 4197 + uint32 m_MapId; // MapId where is Battlefield + uint32 m_MaxPlayer; // Maximum number of player that participated to Battlefield + uint32 m_MinPlayer; // Minimum number of player for Battlefield start + uint32 m_MinLevel; // Required level to participate at Battlefield + uint32 m_BattleTime; // Length of a battle + uint32 m_NoWarBattleTime; // Time between two battles + uint32 m_RestartAfterCrash; // Delay to restart Wintergrasp if the server crashed during a running battle. + uint32 m_TimeForAcceptInvite; + uint32 m_uiKickDontAcceptTimer; + WorldLocation KickPosition; // Position where players are teleported if they switch to afk during the battle or if they don't accept invitation - uint32 m_uiKickAfkPlayersTimer; // Timer for check Afk in war + uint32 m_uiKickAfkPlayersTimer; // Timer for check Afk in war - // Graveyard variables - GraveyardVect m_GraveyardList; // Vector witch contain the different GY of the battle - uint32 m_LastResurectTimer; // Timer for resurect player every 30 sec + // Graveyard variables + GraveyardVect m_GraveyardList; // Vector witch contain the different GY of the battle + uint32 m_LastResurectTimer; // Timer for resurect player every 30 sec - uint32 m_StartGroupingTimer; // Timer for invite players in area 15 minute before start battle - bool m_StartGrouping; // bool for know if all players in area has been invited + uint32 m_StartGroupingTimer; // Timer for invite players in area 15 minute before start battle + bool m_StartGrouping; // bool for know if all players in area has been invited - GuidSet m_Groups[BG_TEAMS_COUNT]; // Contain different raid group + GuidSet m_Groups[BG_TEAMS_COUNT]; // Contain different raid group - std::vector m_Data64; - std::vector m_Data32; + std::vector m_Data64; + std::vector m_Data32; - void KickAfkPlayers(); + void KickAfkPlayers(); - // use for switch off all worldstate for client - virtual void SendRemoveWorldStates(Player* /*player*/) {} + // use for switch off all worldstate for client + virtual void SendRemoveWorldStates(Player* /*player*/) {} - // use for send a packet for all player list - void BroadcastPacketToZone(WorldPacket& data) const; - void BroadcastPacketToQueue(WorldPacket& data) const; - void BroadcastPacketToWar(WorldPacket& data) const; + // use for send a packet for all player list + void BroadcastPacketToZone(WorldPacket& data) const; + void BroadcastPacketToQueue(WorldPacket& data) const; + void BroadcastPacketToWar(WorldPacket& data) const; - // CapturePoint system - void AddCapturePoint(BfCapturePoint* cp, GameObject* go) { m_capturePoints[go->GetEntry()] = cp; } + // CapturePoint system + void AddCapturePoint(BfCapturePoint* cp, GameObject* go) { m_capturePoints[go->GetEntry()] = cp; } - BfCapturePoint* GetCapturePoint(uint32 lowguid) const - { - Battlefield::BfCapturePointMap::const_iterator itr = m_capturePoints.find(lowguid); - if (itr != m_capturePoints.end()) - return itr->second; - return nullptr; - } + BfCapturePoint* GetCapturePoint(uint32 lowguid) const + { + Battlefield::BfCapturePointMap::const_iterator itr = m_capturePoints.find(lowguid); + if (itr != m_capturePoints.end()) + return itr->second; + return nullptr; + } - void RegisterZone(uint32 zoneid); - bool HasPlayer(Player* player) const; - void TeamCastSpell(TeamId team, int32 spellId); + void RegisterZone(uint32 zoneid); + bool HasPlayer(Player* player) const; + void TeamCastSpell(TeamId team, int32 spellId); }; #endif diff --git a/src/server/game/Battlefield/BattlefieldHandler.cpp b/src/server/game/Battlefield/BattlefieldHandler.cpp index ca234bacd..dedf000f7 100644 --- a/src/server/game/Battlefield/BattlefieldHandler.cpp +++ b/src/server/game/Battlefield/BattlefieldHandler.cpp @@ -21,7 +21,7 @@ //Param3:(time) Time in second that the player have for accept void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint32 p_time) { - //Send packet + //Send packet WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 12); data << uint32(BattleId); data << uint32(ZoneId); @@ -49,22 +49,22 @@ void WorldSession::SendBfInvitePlayerToQueue(uint32 BattleId) //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(CanQueue) if able to queue //Param4:(Full) on log in is full -void WorldSession::SendBfQueueInviteResponse(uint32 BattleId,uint32 ZoneId, bool CanQueue, bool Full) +void WorldSession::SendBfQueueInviteResponse(uint32 BattleId, uint32 ZoneId, bool CanQueue, bool Full) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 11); data << uint32(BattleId); data << uint32(ZoneId); - data << uint8((CanQueue ? 1 : 0)); //Accepted //0 you cannot queue wg //1 you are queued + data << uint8((CanQueue ? 1 : 0)); //Accepted //0 you cannot queue wg //1 you are queued data << uint8((Full ? 0 : 1)); //Logging In //0 wg full //1 queue for upcoming data << uint8(1); //Warmup SendPacket(&data); } -//This is call when player accept to join war +//This is call when player accept to join war //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfEntered(uint32 BattleId) { -// m_PlayerInWar[player->GetTeamId()].insert(player->GetGUID()); + // m_PlayerInWar[player->GetTeamId()].insert(player->GetGUID()); WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 7); data << uint32(BattleId); data << uint8(1); //unk @@ -84,7 +84,7 @@ void WorldSession::SendBfLeaveMessage(uint32 BattleId, BFLeaveReason reason) } //Send by client when he click on accept for queue -void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recvData) +void WorldSession::HandleBfQueueInviteResponse(WorldPacket& recvData) { uint32 BattleId; uint8 Accepted; @@ -102,7 +102,7 @@ void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recvData) } //Send by client on clicking in accept or refuse of invitation windows for join game -void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recvData) +void WorldSession::HandleBfEntryInviteResponse(WorldPacket& recvData) { uint32 BattleId; uint8 Accepted; @@ -125,7 +125,7 @@ void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recvData) } } -void WorldSession::HandleBfExitRequest(WorldPacket & recvData) +void WorldSession::HandleBfExitRequest(WorldPacket& recvData) { uint32 BattleId; diff --git a/src/server/game/Battlefield/BattlefieldMgr.cpp b/src/server/game/Battlefield/BattlefieldMgr.cpp index 5e3bb1e90..5fa433801 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.cpp +++ b/src/server/game/Battlefield/BattlefieldMgr.cpp @@ -50,26 +50,26 @@ void BattlefieldMgr::InitBattlefield() // respawn, init variables if(!pBf->SetupBattlefield()) { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_BATTLEFIELD, "Battlefield : Tol Barad init failed."); -#endif + #endif delete pBf; } else { m_BattlefieldSet.push_back(pBf); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_BATTLEFIELD, "Battlefield : Tol Barad successfully initiated."); -#endif + #endif } */ } -void BattlefieldMgr::AddZone(uint32 zoneid, Battlefield *handle) +void BattlefieldMgr::AddZone(uint32 zoneid, Battlefield* handle) { m_BattlefieldMap[zoneid] = handle; } -void BattlefieldMgr::HandlePlayerEnterZone(Player * player, uint32 zoneid) +void BattlefieldMgr::HandlePlayerEnterZone(Player* player, uint32 zoneid) { BattlefieldMap::iterator itr = m_BattlefieldMap.find(zoneid); if (itr == m_BattlefieldMap.end()) @@ -84,7 +84,7 @@ void BattlefieldMgr::HandlePlayerEnterZone(Player * player, uint32 zoneid) #endif } -void BattlefieldMgr::HandlePlayerLeaveZone(Player * player, uint32 zoneid) +void BattlefieldMgr::HandlePlayerLeaveZone(Player* player, uint32 zoneid) { BattlefieldMap::iterator itr = m_BattlefieldMap.find(zoneid); if (itr == m_BattlefieldMap.end()) @@ -99,7 +99,7 @@ void BattlefieldMgr::HandlePlayerLeaveZone(Player * player, uint32 zoneid) #endif } -Battlefield *BattlefieldMgr::GetBattlefieldToZoneId(uint32 zoneid) +Battlefield* BattlefieldMgr::GetBattlefieldToZoneId(uint32 zoneid) { BattlefieldMap::iterator itr = m_BattlefieldMap.find(zoneid); if (itr == m_BattlefieldMap.end()) @@ -112,7 +112,7 @@ Battlefield *BattlefieldMgr::GetBattlefieldToZoneId(uint32 zoneid) return itr->second; } -Battlefield *BattlefieldMgr::GetBattlefieldByBattleId(uint32 battleid) +Battlefield* BattlefieldMgr::GetBattlefieldByBattleId(uint32 battleid) { for (BattlefieldSet::iterator itr = m_BattlefieldSet.begin(); itr != m_BattlefieldSet.end(); ++itr) { @@ -129,12 +129,12 @@ void BattlefieldMgr::Update(uint32 diff) { for (BattlefieldSet::iterator itr = m_BattlefieldSet.begin(); itr != m_BattlefieldSet.end(); ++itr) //if ((*itr)->IsEnabled()) - (*itr)->Update(m_UpdateTimer); + (*itr)->Update(m_UpdateTimer); m_UpdateTimer = 0; } } -ZoneScript *BattlefieldMgr::GetZoneScript(uint32 zoneId) +ZoneScript* BattlefieldMgr::GetZoneScript(uint32 zoneId) { BattlefieldMap::iterator itr = m_BattlefieldMap.find(zoneId); if (itr != m_BattlefieldMap.end()) diff --git a/src/server/game/Battlefield/BattlefieldMgr.h b/src/server/game/Battlefield/BattlefieldMgr.h index 2819da608..ce168de62 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.h +++ b/src/server/game/Battlefield/BattlefieldMgr.h @@ -18,7 +18,7 @@ struct GossipMenuItems; // class to handle player enter / leave / areatrigger / GO use events class BattlefieldMgr { - public: +public: // ctor BattlefieldMgr(); // dtor @@ -29,33 +29,33 @@ class BattlefieldMgr // create battlefield events void InitBattlefield(); // called when a player enters an battlefield area - void HandlePlayerEnterZone(Player * player, uint32 areaflag); + void HandlePlayerEnterZone(Player* player, uint32 areaflag); // called when player leaves an battlefield area - void HandlePlayerLeaveZone(Player * player, uint32 areaflag); + void HandlePlayerLeaveZone(Player* player, uint32 areaflag); // called when player resurrects - void HandlePlayerResurrects(Player * player, uint32 areaflag); + void HandlePlayerResurrects(Player* player, uint32 areaflag); // return assigned battlefield Battlefield* GetBattlefieldToZoneId(uint32 zoneid); Battlefield* GetBattlefieldByBattleId(uint32 battleid); ZoneScript* GetZoneScript(uint32 zoneId); - void AddZone(uint32 zoneid, Battlefield * handle); + void AddZone(uint32 zoneid, Battlefield* handle); void Update(uint32 diff); - void HandleGossipOption(Player * player, uint64 guid, uint32 gossipid); + void HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); - bool CanTalkTo(Player * player, Creature * creature, GossipMenuItems gso); + bool CanTalkTo(Player* player, Creature* creature, GossipMenuItems gso); - void HandleDropFlag(Player * player, uint32 spellId); + void HandleDropFlag(Player* player, uint32 spellId); - typedef std::vector < Battlefield * >BattlefieldSet; - typedef std::map < uint32 /* zoneid */ , Battlefield * >BattlefieldMap; - private: + typedef std::vector < Battlefield* >BattlefieldSet; + typedef std::map < uint32 /* zoneid */, Battlefield* >BattlefieldMap; +private: // contains all initiated battlefield events // used when initing / cleaning up - BattlefieldSet m_BattlefieldSet; + BattlefieldSet m_BattlefieldSet; // maps the zone ids to an battlefield event // used in player event handling BattlefieldMap m_BattlefieldMap; diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp index 1c02f79b6..c6eaeae39 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp @@ -386,7 +386,7 @@ void BattlefieldWG::OnBattleEnd(bool endByTimer) // Update portal defender faction for (GameObjectSet::const_iterator itr = DefenderPortalList.begin(); itr != DefenderPortalList.end(); ++itr) (*itr)->SetUInt32Value(GAMEOBJECT_FACTION, WintergraspFaction[GetDefenderTeam()]); - + // Saving data for (GameObjectBuilding::const_iterator itr = BuildingsInZone.begin(); itr != BuildingsInZone.end(); ++itr) { @@ -433,7 +433,7 @@ void BattlefieldWG::OnBattleEnd(bool endByTimer) { // Victory in Wintergrasp player->AreaExploredOrEventHappens(GetDefenderTeam() ? 13183 : 13181); // HORDE / ALLY win wg quest id - + player->CastSpell(player, SPELL_ESSENCE_OF_WINTERGRASP, true); player->CastSpell(player, SPELL_VICTORY_REWARD, true); RemoveAurasFromPlayer(player); @@ -542,17 +542,17 @@ void BattlefieldWG::OnCreatureCreate(Creature* creature) { case NPC_DWARVEN_SPIRIT_GUIDE: case NPC_TAUNKA_SPIRIT_GUIDE: - { - TeamId teamId = (creature->GetEntry() == NPC_DWARVEN_SPIRIT_GUIDE ? TEAM_ALLIANCE : TEAM_HORDE); - uint8 graveyardId = GetSpiritGraveyardId(creature->GetAreaId(true)); - // xinef: little workaround, there are 2 spirit guides in same area - if (creature->IsWithinDist2d(5103.0f, 3461.5f, 5.0f)) - graveyardId = BATTLEFIELD_WG_GY_WORKSHOP_NW; + { + TeamId teamId = (creature->GetEntry() == NPC_DWARVEN_SPIRIT_GUIDE ? TEAM_ALLIANCE : TEAM_HORDE); + uint8 graveyardId = GetSpiritGraveyardId(creature->GetAreaId(true)); + // xinef: little workaround, there are 2 spirit guides in same area + if (creature->IsWithinDist2d(5103.0f, 3461.5f, 5.0f)) + graveyardId = BATTLEFIELD_WG_GY_WORKSHOP_NW; - if (m_GraveyardList[graveyardId]) - m_GraveyardList[graveyardId]->SetSpirit(creature, teamId); - break; - } + if (m_GraveyardList[graveyardId]) + m_GraveyardList[graveyardId]->SetSpirit(creature, teamId); + break; + } } // untested code - not sure if it is valid. @@ -564,92 +564,92 @@ void BattlefieldWG::OnCreatureCreate(Creature* creature) case NPC_WINTERGRASP_SIEGE_ENGINE_HORDE: case NPC_WINTERGRASP_CATAPULT: case NPC_WINTERGRASP_DEMOLISHER: - { - if (!creature->IsSummon() || !creature->ToTempSummon()->GetSummonerGUID()) - return; - - Player* creator = ObjectAccessor::FindPlayer(creature->ToTempSummon()->GetSummonerGUID()); - if (!creator) - return; - TeamId team = creator->GetTeamId(); - - if (team == TEAM_HORDE) { - if (GetData(BATTLEFIELD_WG_DATA_VEHICLE_H) < GetData(BATTLEFIELD_WG_DATA_MAX_VEHICLE_H)) + if (!creature->IsSummon() || !creature->ToTempSummon()->GetSummonerGUID()) + return; + + Player* creator = ObjectAccessor::FindPlayer(creature->ToTempSummon()->GetSummonerGUID()); + if (!creator) + return; + TeamId team = creator->GetTeamId(); + + if (team == TEAM_HORDE) { - UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H, 1); - creature->CastSpell(creature, SPELL_HORDE_FLAG, true); - m_vehicles[team].insert(creature->GetGUID()); - UpdateVehicleCountWG(); + if (GetData(BATTLEFIELD_WG_DATA_VEHICLE_H) < GetData(BATTLEFIELD_WG_DATA_MAX_VEHICLE_H)) + { + UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H, 1); + creature->CastSpell(creature, SPELL_HORDE_FLAG, true); + m_vehicles[team].insert(creature->GetGUID()); + UpdateVehicleCountWG(); + } + else + { + creature->DespawnOrUnsummon(); + return; + } } else { - creature->DespawnOrUnsummon(); - return; + if (GetData(BATTLEFIELD_WG_DATA_VEHICLE_A) < GetData(BATTLEFIELD_WG_DATA_MAX_VEHICLE_A)) + { + UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A, 1); + creature->CastSpell(creature, SPELL_ALLIANCE_FLAG, true); + m_vehicles[team].insert(creature->GetGUID()); + UpdateVehicleCountWG(); + } + else + { + creature->DespawnOrUnsummon(); + return; + } } + break; } - else - { - if (GetData(BATTLEFIELD_WG_DATA_VEHICLE_A) < GetData(BATTLEFIELD_WG_DATA_MAX_VEHICLE_A)) - { - UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A, 1); - creature->CastSpell(creature, SPELL_ALLIANCE_FLAG, true); - m_vehicles[team].insert(creature->GetGUID()); - UpdateVehicleCountWG(); - } - else - { - creature->DespawnOrUnsummon(); - return; - } - } - break; - } case NPC_WINTERGRASP_SIEGE_ENGINE_TURRET_HORDE: case NPC_WINTERGRASP_SIEGE_ENGINE_TURRET_ALLIANCE: - { - if (!creature->IsSummon() || !creature->ToTempSummon()->GetSummonerGUID()) - return; + { + if (!creature->IsSummon() || !creature->ToTempSummon()->GetSummonerGUID()) + return; - if (Unit* owner = creature->ToTempSummon()->GetSummoner()) - creature->setFaction(owner->getFaction()); - break; - } + if (Unit* owner = creature->ToTempSummon()->GetSummoner()) + creature->setFaction(owner->getFaction()); + break; + } } } } void BattlefieldWG::OnCreatureRemove(Creature* /*creature*/) { -/* possibly can be used later - if (IsWarTime()) - { - switch (creature->GetEntry()) + /* possibly can be used later + if (IsWarTime()) { - case NPC_WINTERGRASP_SIEGE_ENGINE_ALLIANCE: - case NPC_WINTERGRASP_SIEGE_ENGINE_HORDE: - case NPC_WINTERGRASP_CATAPULT: - case NPC_WINTERGRASP_DEMOLISHER: + switch (creature->GetEntry()) { - uint8 team; - if (creature->getFaction() == WintergraspFaction[TEAM_ALLIANCE]) - team = TEAM_ALLIANCE; - else if (creature->getFaction() == WintergraspFaction[TEAM_HORDE]) - team = TEAM_HORDE; - else - return; + case NPC_WINTERGRASP_SIEGE_ENGINE_ALLIANCE: + case NPC_WINTERGRASP_SIEGE_ENGINE_HORDE: + case NPC_WINTERGRASP_CATAPULT: + case NPC_WINTERGRASP_DEMOLISHER: + { + uint8 team; + if (creature->getFaction() == WintergraspFaction[TEAM_ALLIANCE]) + team = TEAM_ALLIANCE; + else if (creature->getFaction() == WintergraspFaction[TEAM_HORDE]) + team = TEAM_HORDE; + else + return; - m_vehicles[team].erase(creature->GetGUID()); - if (team == TEAM_HORDE) - UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H, -1); - else - UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A, -1); - UpdateVehicleCountWG(); + m_vehicles[team].erase(creature->GetGUID()); + if (team == TEAM_HORDE) + UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H, -1); + else + UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A, -1); + UpdateVehicleCountWG(); - break; + break; + } } - } - }*/ + }*/ } void BattlefieldWG::OnGameObjectCreate(GameObject* go) @@ -729,9 +729,9 @@ bool BattlefieldWG::FindAndRemoveVehicleFromList(Unit* vehicle) { //m_vehicles[itr].erase(vehicle->GetGUID()); if (itr == TEAM_HORDE) - UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H,-1); + UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H, -1); else - UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A,-1); + UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A, -1); return true; } } @@ -813,7 +813,7 @@ void BattlefieldWG::OnPlayerJoinWar(Player* player) else { if (GetData(BATTLEFIELD_WG_DATA_BROKEN_TOWER_ATT) > 0) - player->SetAuraStack(SPELL_TOWER_CONTROL, player, GetData(BATTLEFIELD_WG_DATA_BROKEN_TOWER_ATT)); + player->SetAuraStack(SPELL_TOWER_CONTROL, player, GetData(BATTLEFIELD_WG_DATA_BROKEN_TOWER_ATT)); } SendInitWorldStatesTo(player); } @@ -927,15 +927,15 @@ void BattlefieldWG::SendInitWorldStatesToAll() void BattlefieldWG::BrokenWallOrTower(TeamId /*team*/) { -// might be some use for this in the future. old code commented out below. KL -/* if (team == GetDefenderTeam()) - { - for (GuidSet::const_iterator itr = m_PlayersInWar[GetAttackerTeam()].begin(); itr != m_PlayersInWar[GetAttackerTeam()].end(); ++itr) + // might be some use for this in the future. old code commented out below. KL + /* if (team == GetDefenderTeam()) { - if (Player* player = ObjectAccessor::FindPlayer(*itr)) - IncrementQuest(player, WGQuest[player->GetTeamId()][2], true); - } - }*/ + for (GuidSet::const_iterator itr = m_PlayersInWar[GetAttackerTeam()].begin(); itr != m_PlayersInWar[GetAttackerTeam()].end(); ++itr) + { + if (Player* player = ObjectAccessor::FindPlayer(*itr)) + IncrementQuest(player, WGQuest[player->GetTeamId()][2], true); + } + }*/ } // Called when a tower is broke @@ -989,7 +989,7 @@ void BattlefieldWG::UpdatedDestroyedTowerCount(TeamId team, GameObject* go) } } -void BattlefieldWG::ProcessEvent(WorldObject *obj, uint32 eventId) +void BattlefieldWG::ProcessEvent(WorldObject* obj, uint32 eventId) { if (!obj || !IsWarTime()) return; @@ -1004,7 +1004,7 @@ void BattlefieldWG::ProcessEvent(WorldObject *obj, uint32 eventId) { if (CanInteractWithRelic()) EndBattle(false); - else if (GameObject*go = GetRelic()) + else if (GameObject* go = GetRelic()) go->SetRespawnTime(RESPAWN_IMMEDIATELY); } diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.h b/src/server/game/Battlefield/Zones/BattlefieldWG.h index 91a8223b9..ace9cdc27 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.h +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.h @@ -122,13 +122,13 @@ enum WintergraspAreaIds class BfGraveyardWG : public BfGraveyard { - public: - BfGraveyardWG(BattlefieldWG *Bf); +public: + BfGraveyardWG(BattlefieldWG* Bf); - void SetTextId(uint32 textid) { m_GossipTextId = textid; } - uint32 GetTextId() { return m_GossipTextId; } - protected: - uint32 m_GossipTextId; + void SetTextId(uint32 textid) { m_GossipTextId = textid; } + uint32 GetTextId() { return m_GossipTextId; } +protected: + uint32 m_GossipTextId; }; enum WGGraveyardId @@ -222,12 +222,14 @@ struct BfWGCoordGY TeamId startcontrol; }; -const uint32 WGQuest[2][6] = { +const uint32 WGQuest[2][6] = +{ { 13186, 13181, 13222, 13538, 13177, 13179 }, { 13185, 13183, 13223, 13539, 13178, 13180 }, }; // 7 in sql, 7 in header -const BfWGCoordGY WGGraveYard[BATTLEFIELD_WG_GRAVEYARD_MAX] = { +const BfWGCoordGY WGGraveYard[BATTLEFIELD_WG_GRAVEYARD_MAX] = +{ { 5104.750f, 2300.940f, 368.579f, 0.733038f, 1329, BATTLEFIELD_WG_GY_WORKSHOP_NE, BATTLEFIELD_WG_GOSSIPTEXT_GY_NE, TEAM_NEUTRAL }, { 5099.120f, 3466.036f, 368.484f, 5.317802f, 1330, BATTLEFIELD_WG_GY_WORKSHOP_NW, BATTLEFIELD_WG_GOSSIPTEXT_GY_NW, TEAM_NEUTRAL }, { 4314.648f, 2408.522f, 392.642f, 6.268125f, 1333, BATTLEFIELD_WG_GY_WORKSHOP_SE, BATTLEFIELD_WG_GOSSIPTEXT_GY_SE, TEAM_NEUTRAL }, @@ -243,16 +245,16 @@ const BfWGCoordGY WGGraveYard[BATTLEFIELD_WG_GRAVEYARD_MAX] = { class WintergraspCapturePoint : public BfCapturePoint { - public: - WintergraspCapturePoint(BattlefieldWG* battlefield, TeamId teamInControl); +public: + WintergraspCapturePoint(BattlefieldWG* battlefield, TeamId teamInControl); - void LinkToWorkshop(WGWorkshop* workshop) { m_Workshop = workshop; } + void LinkToWorkshop(WGWorkshop* workshop) { m_Workshop = workshop; } - void ChangeTeam(TeamId oldteam); - TeamId GetTeam() const { return m_team; } + void ChangeTeam(TeamId oldteam); + TeamId GetTeam() const { return m_team; } - protected: - WGWorkshop* m_Workshop; +protected: + WGWorkshop* m_Workshop; }; /* ######################### * @@ -261,206 +263,206 @@ class WintergraspCapturePoint : public BfCapturePoint class BattlefieldWG : public Battlefield { - public: - ~BattlefieldWG(); - /** - * \brief Called when the battle start - * - Spawn relic and turret - * - Rebuild tower and wall - * - Invite player to war - */ - void OnBattleStart(); +public: + ~BattlefieldWG(); + /** + * \brief Called when the battle start + * - Spawn relic and turret + * - Rebuild tower and wall + * - Invite player to war + */ + void OnBattleStart(); - /** - * \brief Called when battle end - * - Remove relic and turret - * - Change banner/npc in keep if it needed - * - Saving battlestate - * - Reward honor/mark to player - * - Remove vehicle - * \param endByTimer : true if battle ended when timer is at 00:00, false if battle ended by clicking on relic - */ - void OnBattleEnd(bool endByTimer); + /** + * \brief Called when battle end + * - Remove relic and turret + * - Change banner/npc in keep if it needed + * - Saving battlestate + * - Reward honor/mark to player + * - Remove vehicle + * \param endByTimer : true if battle ended when timer is at 00:00, false if battle ended by clicking on relic + */ + void OnBattleEnd(bool endByTimer); - /** - * \brief Called when grouping starts (15 minutes before battlestart) - * - Invite all player in zone to join queue - */ - void OnStartGrouping(); + /** + * \brief Called when grouping starts (15 minutes before battlestart) + * - Invite all player in zone to join queue + */ + void OnStartGrouping(); - /** - * \brief Called when player accept invite to join battle - * - Update aura - * - Teleport if it needed - * - Update worldstate - * - Update tenacity - * \param player: Player who accepted invite - */ - void OnPlayerJoinWar(Player* player); + /** + * \brief Called when player accept invite to join battle + * - Update aura + * - Teleport if it needed + * - Update worldstate + * - Update tenacity + * \param player: Player who accepted invite + */ + void OnPlayerJoinWar(Player* player); - /** - * \brief Called when player left the battle - * - Update player aura - * \param player : Player who left the battle - */ - void OnPlayerLeaveWar(Player* player); + /** + * \brief Called when player left the battle + * - Update player aura + * \param player : Player who left the battle + */ + void OnPlayerLeaveWar(Player* player); - /** - * \brief Called when player left the WG zone - * \param player : Player who left the zone - */ - void OnPlayerLeaveZone(Player* player); + /** + * \brief Called when player left the WG zone + * \param player : Player who left the zone + */ + void OnPlayerLeaveZone(Player* player); - /** - * \brief Called when player enters in WG zone - * - Update aura - * - Update worldstate - * \param player : Player who enters the zone - */ - void OnPlayerEnterZone(Player* player); + /** + * \brief Called when player enters in WG zone + * - Update aura + * - Update worldstate + * \param player : Player who enters the zone + */ + void OnPlayerEnterZone(Player* player); - /** - * \brief Called for update battlefield data - * - Save battle timer in database every minutes - * - Update imunity aura from graveyard - * \param diff : time elapsed since the last call (in ms) - */ - bool Update(uint32 diff); + /** + * \brief Called for update battlefield data + * - Save battle timer in database every minutes + * - Update imunity aura from graveyard + * \param diff : time elapsed since the last call (in ms) + */ + bool Update(uint32 diff); - /** - * \brief Called when a creature is created - * - Update vehicle count - */ - void OnCreatureCreate(Creature* creature); + /** + * \brief Called when a creature is created + * - Update vehicle count + */ + void OnCreatureCreate(Creature* creature); - /** - * \brief Called when a creature is removed - * - Update vehicle count - */ - void OnCreatureRemove(Creature* creature); + /** + * \brief Called when a creature is removed + * - Update vehicle count + */ + void OnCreatureRemove(Creature* creature); - /** - * \brief Called when a gameobject is created - */ - void OnGameObjectCreate(GameObject* go); + /** + * \brief Called when a gameobject is created + */ + void OnGameObjectCreate(GameObject* go); - /** - * \brief Called when a wall/tower is broken - * - Update quest - */ - void BrokenWallOrTower(TeamId team); + /** + * \brief Called when a wall/tower is broken + * - Update quest + */ + void BrokenWallOrTower(TeamId team); - /** - * \brief Called when a tower is damaged - * - Update tower count (for reward calcul) - */ - void UpdateDamagedTowerCount(TeamId team); + /** + * \brief Called when a tower is damaged + * - Update tower count (for reward calcul) + */ + void UpdateDamagedTowerCount(TeamId team); - /** - * \brief Called when tower is broken - * - Update tower buff - * - check if three south tower is down for remove 10 minutes to wg - */ - void UpdatedDestroyedTowerCount(TeamId team, GameObject* go); + /** + * \brief Called when tower is broken + * - Update tower buff + * - check if three south tower is down for remove 10 minutes to wg + */ + void UpdatedDestroyedTowerCount(TeamId team, GameObject* go); - //void DoCompleteOrIncrementAchievement(uint32 achievement, Player* player, uint8 incrementNumber = 1); - - void RemoveAurasFromPlayer(Player* player); + //void DoCompleteOrIncrementAchievement(uint32 achievement, Player* player, uint8 incrementNumber = 1); - /** - * \brief Called when battlefield is setup, at server start - */ - bool SetupBattlefield(); + void RemoveAurasFromPlayer(Player* player); - /// Return pointer to relic object - GameObject* GetRelic() { return ObjectAccessor::GetObjectInWorld(m_titansRelic, (GameObject*)NULL); } + /** + * \brief Called when battlefield is setup, at server start + */ + bool SetupBattlefield(); - /// Define relic object - //void SetRelic(GameObject* relic) { m_titansRelic = relic; } + /// Return pointer to relic object + GameObject* GetRelic() { return ObjectAccessor::GetObjectInWorld(m_titansRelic, (GameObject*)NULL); } - /// Check if players can interact with the relic (Only if the last door has been broken) - bool CanInteractWithRelic() { return m_isRelicInteractible; } + /// Define relic object + //void SetRelic(GameObject* relic) { m_titansRelic = relic; } - /// Define if player can interact with the relic - void SetRelicInteractible(bool allow) { m_isRelicInteractible = allow; } + /// Check if players can interact with the relic (Only if the last door has been broken) + bool CanInteractWithRelic() { return m_isRelicInteractible; } - /// Vehicle world states update - void UpdateCounterVehicle(bool init); - void UpdateVehicleCountWG(); - void CapturePointTaken(uint32 areaId); + /// Define if player can interact with the relic + void SetRelicInteractible(bool allow) { m_isRelicInteractible = allow; } - void SendInitWorldStatesTo(Player* player); - void SendInitWorldStatesToAll(); - void FillInitialWorldStates(WorldPacket& data); + /// Vehicle world states update + void UpdateCounterVehicle(bool init); + void UpdateVehicleCountWG(); + void CapturePointTaken(uint32 areaId); - void HandleKill(Player* killer, Unit* victim); - void OnUnitDeath(Unit* unit); - void PromotePlayer(Player* killer); + void SendInitWorldStatesTo(Player* player); + void SendInitWorldStatesToAll(); + void FillInitialWorldStates(WorldPacket& data); - uint32 GetHonorBuff(int32 stack) const; - void UpdateTenacity(); - void AddUpdateTenacity(Player* player); - void RemoveUpdateTenacity(Player* player); - void ProcessEvent(WorldObject *obj, uint32 eventId); + void HandleKill(Player* killer, Unit* victim); + void OnUnitDeath(Unit* unit); + void PromotePlayer(Player* killer); - bool FindAndRemoveVehicleFromList(Unit* vehicle); + uint32 GetHonorBuff(int32 stack) const; + void UpdateTenacity(); + void AddUpdateTenacity(Player* player); + void RemoveUpdateTenacity(Player* player); + void ProcessEvent(WorldObject* obj, uint32 eventId); - // returns the graveyardId in the specified area. - uint8 GetSpiritGraveyardId(uint32 areaId) const; - uint32 GetAreaByGraveyardId(uint8 gId) const; + bool FindAndRemoveVehicleFromList(Unit* vehicle); - uint32 GetData(uint32 data) const; + // returns the graveyardId in the specified area. + uint8 GetSpiritGraveyardId(uint32 areaId) const; + uint32 GetAreaByGraveyardId(uint8 gId) const; - bool IsKeepNpc(uint32 entry) + uint32 GetData(uint32 data) const; + + bool IsKeepNpc(uint32 entry) + { + switch (entry) { - switch (entry) - { - case BATTLEFIELD_WG_NPC_GUARD_H: - case BATTLEFIELD_WG_NPC_GUARD_A: - case BATTLEFIELD_WG_NPC_VIERON_BLAZEFEATHER: - case BATTLEFIELD_WG_NPC_BOWYER_RANDOLPH: - case BATTLEFIELD_WG_NPC_STONE_GUARD_MUKAR: - case BATTLEFIELD_WG_NPC_KNIGHT_DAMERON: - case BATTLEFIELD_WG_NPC_HOODOO_MASTER_FU_JIN: - case BATTLEFIELD_WG_NPC_SORCERESS_KAYLANA: - case BATTLEFIELD_WG_NPC_CHAMPION_ROS_SLAI: - case BATTLEFIELD_WG_NPC_MARSHAL_MAGRUDER: - case BATTLEFIELD_WG_NPC_COMMANDER_DARDOSH: - case BATTLEFIELD_WG_NPC_COMMANDER_ZANNETH: - case BATTLEFIELD_WG_NPC_TACTICAL_OFFICER_KILRATH: - case BATTLEFIELD_WG_NPC_TACTICAL_OFFICER_AHBRAMIS: - case BATTLEFIELD_WG_NPC_HORDE_WARBRINGER: - case BATTLEFIELD_WG_NPC_BRIGADIER_GENERAL: - case BATTLEFIELD_WG_NPC_SIEGESMITH_STRONGHOOF: - case BATTLEFIELD_WG_NPC_SIEGE_MASTER_STOUTHANDLE: - case BATTLEFIELD_WG_NPC_PRIMALIST_MULFORT: - case BATTLEFIELD_WG_NPC_ANCHORITE_TESSA: - case BATTLEFIELD_WG_NPC_LIEUTENANT_MURP: - case BATTLEFIELD_WG_NPC_SENIOR_DEMOLITIONIST_LEGOSO: - return true; - } - return false; + case BATTLEFIELD_WG_NPC_GUARD_H: + case BATTLEFIELD_WG_NPC_GUARD_A: + case BATTLEFIELD_WG_NPC_VIERON_BLAZEFEATHER: + case BATTLEFIELD_WG_NPC_BOWYER_RANDOLPH: + case BATTLEFIELD_WG_NPC_STONE_GUARD_MUKAR: + case BATTLEFIELD_WG_NPC_KNIGHT_DAMERON: + case BATTLEFIELD_WG_NPC_HOODOO_MASTER_FU_JIN: + case BATTLEFIELD_WG_NPC_SORCERESS_KAYLANA: + case BATTLEFIELD_WG_NPC_CHAMPION_ROS_SLAI: + case BATTLEFIELD_WG_NPC_MARSHAL_MAGRUDER: + case BATTLEFIELD_WG_NPC_COMMANDER_DARDOSH: + case BATTLEFIELD_WG_NPC_COMMANDER_ZANNETH: + case BATTLEFIELD_WG_NPC_TACTICAL_OFFICER_KILRATH: + case BATTLEFIELD_WG_NPC_TACTICAL_OFFICER_AHBRAMIS: + case BATTLEFIELD_WG_NPC_HORDE_WARBRINGER: + case BATTLEFIELD_WG_NPC_BRIGADIER_GENERAL: + case BATTLEFIELD_WG_NPC_SIEGESMITH_STRONGHOOF: + case BATTLEFIELD_WG_NPC_SIEGE_MASTER_STOUTHANDLE: + case BATTLEFIELD_WG_NPC_PRIMALIST_MULFORT: + case BATTLEFIELD_WG_NPC_ANCHORITE_TESSA: + case BATTLEFIELD_WG_NPC_LIEUTENANT_MURP: + case BATTLEFIELD_WG_NPC_SENIOR_DEMOLITIONIST_LEGOSO: + return true; } - protected: - bool m_isRelicInteractible; + return false; + } +protected: + bool m_isRelicInteractible; - Workshop WorkshopsList; + Workshop WorkshopsList; - GameObjectSet DefenderPortalList; - GameObjectSet m_KeepGameObject[2]; - GameObjectBuilding BuildingsInZone; + GameObjectSet DefenderPortalList; + GameObjectSet m_KeepGameObject[2]; + GameObjectBuilding BuildingsInZone; - GuidSet m_vehicles[2]; - GuidSet CanonList; - GuidSet KeepCreature[2]; - GuidSet OutsideCreature[2]; - GuidSet m_updateTenacityList; + GuidSet m_vehicles[2]; + GuidSet CanonList; + GuidSet KeepCreature[2]; + GuidSet OutsideCreature[2]; + GuidSet m_updateTenacityList; - int32 m_tenacityStack; - uint32 m_tenacityUpdateTimer; - uint32 m_saveTimer; + int32 m_tenacityStack; + uint32 m_tenacityUpdateTimer; + uint32 m_saveTimer; - uint64 m_titansRelic; + uint64 m_titansRelic; }; const uint8 WG_MAX_OBJ = 32; @@ -593,7 +595,8 @@ struct WintergraspBuildingSpawnData uint32 destroyText; }; -const WintergraspBuildingSpawnData WGGameObjectBuilding[WG_MAX_OBJ] = { +const WintergraspBuildingSpawnData WGGameObjectBuilding[WG_MAX_OBJ] = +{ // Wall (Not spawned in db) // Entry WS X Y Z O type NameID { 190219, 3749, 5371.46f, 3047.47f, 407.571f, 3.14159f, BATTLEFIELD_WG_OBJECTTYPE_WALL, 0, 0 }, @@ -640,7 +643,8 @@ const WintergraspBuildingSpawnData WGGameObjectBuilding[WG_MAX_OBJ] = { { 191810, 3773, 5397.11f, 2841.54f, 425.899f, 3.14159f, BATTLEFIELD_WG_OBJECTTYPE_DOOR_LAST, 0, 0 }, }; -const Position WGTurret[WG_MAX_TURRET] = { +const Position WGTurret[WG_MAX_TURRET] = +{ { 5391.19f, 3060.8f, 419.616f, 1.69557f }, { 5266.75f, 2976.5f, 421.067f, 3.20354f }, { 5234.86f, 2948.8f, 420.88f, 1.61311f }, @@ -784,7 +788,8 @@ struct WintergraspTowerData uint8 const WG_MAX_ATTACKTOWERS = 3; // 192414 : 0 in sql, 1 in header // 192278 : 0 in sql, 3 in header -const WintergraspTowerData AttackTowers[WG_MAX_ATTACKTOWERS] = { +const WintergraspTowerData AttackTowers[WG_MAX_ATTACKTOWERS] = +{ // West tower { 190356, @@ -1072,7 +1077,7 @@ const WGWorkshopData WorkshopsData[WG_MAX_WORKSHOP] = // Structure for different buildings that can be destroyed during battle struct BfWGGameObjectBuilding { - BfWGGameObjectBuilding(BattlefieldWG *WG) + BfWGGameObjectBuilding(BattlefieldWG* WG) { m_WG = WG; m_Team = TEAM_ALLIANCE; @@ -1088,7 +1093,7 @@ struct BfWGGameObjectBuilding TeamId m_Team; // WG object - BattlefieldWG *m_WG; + BattlefieldWG* m_WG; // Linked gameobject uint64 m_Build; @@ -1206,7 +1211,7 @@ struct BfWGGameObjectBuilding m_WG->BrokenWallOrTower(TeamId(m_Team)); } - void Init(GameObject *gobj, uint32 type, uint32 worldstate, uint8 damageText, uint8 destroyText) + void Init(GameObject* gobj, uint32 type, uint32 worldstate, uint8 damageText, uint8 destroyText) { // GameObject associated to object m_Build = gobj->GetGUID(); @@ -1335,7 +1340,7 @@ struct BfWGGameObjectBuilding { Position towerCannonPos; TowerCannon[towerid].TurretTop[i].GetPosition(&towerCannonPos); - if (Creature *turret = m_WG->SpawnCreature(NPC_WINTERGRASP_TOWER_CANNON, towerCannonPos, TEAM_ALLIANCE)) + if (Creature* turret = m_WG->SpawnCreature(NPC_WINTERGRASP_TOWER_CANNON, towerCannonPos, TEAM_ALLIANCE)) { m_TurretTopList.insert(turret->GetGUID()); m_WG->HideNpc(turret); @@ -1459,31 +1464,31 @@ struct WGWorkshop switch (team) { case TEAM_NEUTRAL: - { - // Send warning message to all player to inform a faction attack to a workshop - // alliance / horde attacking a workshop - bf->SendWarningToAllInZone(teamControl ? WorkshopsData[workshopId].attackText : (WorkshopsData[workshopId].attackText + 2)); - break; - } + { + // Send warning message to all player to inform a faction attack to a workshop + // alliance / horde attacking a workshop + bf->SendWarningToAllInZone(teamControl ? WorkshopsData[workshopId].attackText : (WorkshopsData[workshopId].attackText + 2)); + break; + } case TEAM_ALLIANCE: case TEAM_HORDE: - { - // Updating worldstate - state = team == TEAM_ALLIANCE ? BATTLEFIELD_WG_OBJECTSTATE_ALLIANCE_INTACT : BATTLEFIELD_WG_OBJECTSTATE_HORDE_INTACT; - bf->SendUpdateWorldState(WorkshopsData[workshopId].worldstate, state); + { + // Updating worldstate + state = team == TEAM_ALLIANCE ? BATTLEFIELD_WG_OBJECTSTATE_ALLIANCE_INTACT : BATTLEFIELD_WG_OBJECTSTATE_HORDE_INTACT; + bf->SendUpdateWorldState(WorkshopsData[workshopId].worldstate, state); - // Warning message - if (!init) // workshop taken - alliance - bf->SendWarningToAllInZone(team == TEAM_ALLIANCE ? WorkshopsData[workshopId].takenText : (WorkshopsData[workshopId].takenText + 2)); + // Warning message + if (!init) // workshop taken - alliance + bf->SendWarningToAllInZone(team == TEAM_ALLIANCE ? WorkshopsData[workshopId].takenText : (WorkshopsData[workshopId].takenText + 2)); - // Found associate graveyard and update it - if (workshopId < BATTLEFIELD_WG_WORKSHOP_KEEP_WEST) - if (bf->GetGraveyardById(workshopId)) - bf->GetGraveyardById(workshopId)->GiveControlTo(team); + // Found associate graveyard and update it + if (workshopId < BATTLEFIELD_WG_WORKSHOP_KEEP_WEST) + if (bf->GetGraveyardById(workshopId)) + bf->GetGraveyardById(workshopId)->GiveControlTo(team); - teamControl = team; - break; - } + teamControl = team; + break; + } } if (!init) diff --git a/src/server/game/Battlegrounds/ArenaTeam.cpp b/src/server/game/Battlegrounds/ArenaTeam.cpp index 5fddb6ae1..412191b8f 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.cpp +++ b/src/server/game/Battlegrounds/ArenaTeam.cpp @@ -17,7 +17,7 @@ ArenaTeam::ArenaTeam() : TeamId(0), Type(0), TeamName(), CaptainGuid(0), BackgroundColor(0), EmblemStyle(0), EmblemColor(0), - BorderStyle(0), BorderColor(0) + BorderStyle(0), BorderColor(0) { Stats.WeekGames = 0; Stats.SeasonGames = 0; @@ -250,8 +250,7 @@ bool ArenaTeam::LoadMembersFromDB(QueryResult result) // Put the player in the team Members.push_back(newMember); sWorld->UpdateGlobalPlayerArenaTeam(GUID_LOPART(newMember.Guid), GetSlot(), GetId()); - } - while (result->NextRow()); + } while (result->NextRow()); if (Empty() || !captainPresentInTeam) { @@ -434,7 +433,7 @@ void ArenaTeam::Roster(WorldSession* session) void ArenaTeam::Query(WorldSession* session) { - WorldPacket data(SMSG_ARENA_TEAM_QUERY_RESPONSE, 4*7+GetName().size()+1); + WorldPacket data(SMSG_ARENA_TEAM_QUERY_RESPONSE, 4 * 7 + GetName().size() + 1); data << uint32(GetId()); // team id data << GetName(); // team name data << uint32(GetType()); // arena team type (2=2x2, 3=3x3 or 5=5x5) @@ -451,7 +450,7 @@ void ArenaTeam::Query(WorldSession* session) void ArenaTeam::SendStats(WorldSession* session) { - WorldPacket data(SMSG_ARENA_TEAM_STATS, 4*7); + WorldPacket data(SMSG_ARENA_TEAM_STATS, 4 * 7); data << uint32(GetId()); // team id data << uint32(Stats.Rating); // rating data << uint32(Stats.WeekGames); // games this week @@ -477,7 +476,7 @@ void ArenaTeam::Inspect(WorldSession* session, uint64 guid) if (!member) return; - WorldPacket data(MSG_INSPECT_ARENA_TEAMS, 8+1+4*6); + WorldPacket data(MSG_INSPECT_ARENA_TEAMS, 8 + 1 + 4 * 6); data << uint64(guid); // player guid data << uint8(GetSlot()); // slot (0...2) data << uint32(GetId()); // arena team id @@ -530,7 +529,7 @@ void ArenaTeam::BroadcastPacket(WorldPacket* packet) void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, uint64 guid, uint8 strCount, std::string const& str1, std::string const& str2, std::string const& str3) { - WorldPacket data(SMSG_ARENA_TEAM_EVENT, 1+1+1); + WorldPacket data(SMSG_ARENA_TEAM_EVENT, 1 + 1 + 1); data << uint8(event); data << uint8(strCount); switch (strCount) @@ -582,9 +581,12 @@ uint8 ArenaTeam::GetSlotByType(uint32 type) { switch (type) { - case ARENA_TEAM_2v2: return 0; - case ARENA_TEAM_3v3: return 1; - case ARENA_TEAM_5v5: return 2; + case ARENA_TEAM_2v2: + return 0; + case ARENA_TEAM_3v3: + return 1; + case ARENA_TEAM_5v5: + return 2; default: break; } @@ -803,8 +805,8 @@ void ArenaTeam::MemberLost(Player* player, uint32 againstMatchmakerRating, int32 itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot()); // Update personal played stats - itr->WeekGames +=1; - itr->SeasonGames +=1; + itr->WeekGames += 1; + itr->SeasonGames += 1; // update the unit fields player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->WeekGames); @@ -833,8 +835,8 @@ void ArenaTeam::MemberWon(Player* player, uint32 againstMatchmakerRating, int32 } // update personal stats - itr->WeekGames +=1; - itr->SeasonGames +=1; + itr->WeekGames += 1; + itr->SeasonGames += 1; itr->SeasonWins += 1; itr->WeekWins += 1; // update unit fields diff --git a/src/server/game/Battlegrounds/ArenaTeam.h b/src/server/game/Battlegrounds/ArenaTeam.h index bf3dab21a..02a189a5b 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.h +++ b/src/server/game/Battlegrounds/ArenaTeam.h @@ -104,91 +104,91 @@ struct ArenaTeamStats class ArenaTeam { - public: - ArenaTeam(); - ~ArenaTeam(); +public: + ArenaTeam(); + ~ArenaTeam(); - bool Create(uint64 captainGuid, uint8 type, std::string const& teamName, uint32 backgroundColor, uint8 emblemStyle, uint32 emblemColor, uint8 borderStyle, uint32 borderColor); - void Disband(WorldSession* session); - void Disband(); + bool Create(uint64 captainGuid, uint8 type, std::string const& teamName, uint32 backgroundColor, uint8 emblemStyle, uint32 emblemColor, uint8 borderStyle, uint32 borderColor); + void Disband(WorldSession* session); + void Disband(); - typedef std::list MemberList; + typedef std::list MemberList; - uint32 GetId() const { return TeamId; } - uint32 GetType() const { return Type; } - uint8 GetSlot() const { return GetSlotByType(GetType()); } - static uint8 GetSlotByType(uint32 type); - uint64 GetCaptain() const { return CaptainGuid; } - std::string const& GetName() const { return TeamName; } - const ArenaTeamStats& GetStats() const { return Stats; } + uint32 GetId() const { return TeamId; } + uint32 GetType() const { return Type; } + uint8 GetSlot() const { return GetSlotByType(GetType()); } + static uint8 GetSlotByType(uint32 type); + uint64 GetCaptain() const { return CaptainGuid; } + std::string const& GetName() const { return TeamName; } + const ArenaTeamStats& GetStats() const { return Stats; } - uint32 GetRating() const { return Stats.Rating; } - uint32 GetAverageMMR(Group* group) const; + uint32 GetRating() const { return Stats.Rating; } + uint32 GetAverageMMR(Group* group) const; - void SetCaptain(uint64 guid); - bool SetName(std::string const& name); - bool AddMember(uint64 playerGuid); + void SetCaptain(uint64 guid); + bool SetName(std::string const& name); + bool AddMember(uint64 playerGuid); - // Shouldn't be uint64 ed, because than can reference guid from members on Disband - // and this method removes given record from list. So invalid reference can happen. - void DelMember(uint64 guid, bool cleanDb); + // Shouldn't be uint64 ed, because than can reference guid from members on Disband + // and this method removes given record from list. So invalid reference can happen. + void DelMember(uint64 guid, bool cleanDb); - size_t GetMembersSize() const { return Members.size(); } - bool Empty() const { return Members.empty(); } - MemberList::iterator m_membersBegin() { return Members.begin(); } - MemberList::iterator m_membersEnd() { return Members.end(); } - bool IsMember(uint64 guid) const; + size_t GetMembersSize() const { return Members.size(); } + bool Empty() const { return Members.empty(); } + MemberList::iterator m_membersBegin() { return Members.begin(); } + MemberList::iterator m_membersEnd() { return Members.end(); } + bool IsMember(uint64 guid) const; - ArenaTeamMember* GetMember(uint64 guid); - ArenaTeamMember* GetMember(std::string const& name); + ArenaTeamMember* GetMember(uint64 guid); + ArenaTeamMember* GetMember(std::string const& name); - bool IsFighting() const; + bool IsFighting() const; - bool LoadArenaTeamFromDB(QueryResult arenaTeamDataResult); - bool LoadMembersFromDB(QueryResult arenaTeamMembersResult); - void LoadStatsFromDB(uint32 ArenaTeamId); - void SaveToDB(); + bool LoadArenaTeamFromDB(QueryResult arenaTeamDataResult); + bool LoadMembersFromDB(QueryResult arenaTeamMembersResult); + void LoadStatsFromDB(uint32 ArenaTeamId); + void SaveToDB(); - void BroadcastPacket(WorldPacket* packet); - void BroadcastEvent(ArenaTeamEvents event, uint64 guid, uint8 strCount, std::string const& str1, std::string const& str2, std::string const& str3); - void NotifyStatsChanged(); + void BroadcastPacket(WorldPacket* packet); + void BroadcastEvent(ArenaTeamEvents event, uint64 guid, uint8 strCount, std::string const& str1, std::string const& str2, std::string const& str3); + void NotifyStatsChanged(); - void MassInviteToEvent(WorldSession* session); + void MassInviteToEvent(WorldSession* session); - void Roster(WorldSession* session); - void Query(WorldSession* session); - void SendStats(WorldSession* session); - void Inspect(WorldSession* session, uint64 guid); + void Roster(WorldSession* session); + void Query(WorldSession* session); + void SendStats(WorldSession* session); + void Inspect(WorldSession* session, uint64 guid); - uint32 GetPoints(uint32 MemberRating); - int32 GetMatchmakerRatingMod(uint32 ownRating, uint32 opponentRating, bool won); - int32 GetRatingMod(uint32 ownRating, uint32 opponentRating, bool won); - float GetChanceAgainst(uint32 ownRating, uint32 opponentRating); - int32 WonAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change, const Map* bgMap); - void MemberWon(Player* player, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange); - int32 LostAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change, const Map* bgMap); - void MemberLost(Player* player, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange = -12); + uint32 GetPoints(uint32 MemberRating); + int32 GetMatchmakerRatingMod(uint32 ownRating, uint32 opponentRating, bool won); + int32 GetRatingMod(uint32 ownRating, uint32 opponentRating, bool won); + float GetChanceAgainst(uint32 ownRating, uint32 opponentRating); + int32 WonAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change, const Map* bgMap); + void MemberWon(Player* player, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange); + int32 LostAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change, const Map* bgMap); + void MemberLost(Player* player, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange = -12); - void UpdateArenaPointsHelper(std::map & PlayerPoints); + void UpdateArenaPointsHelper(std::map& PlayerPoints); - void FinishWeek(); - void FinishGame(int32 mod, const Map* bgMap); + void FinishWeek(); + void FinishGame(int32 mod, const Map* bgMap); - protected: +protected: - uint32 TeamId; - uint8 Type; - std::string TeamName; - uint64 CaptainGuid; + uint32 TeamId; + uint8 Type; + std::string TeamName; + uint64 CaptainGuid; - uint32 BackgroundColor; // ARGB format - uint8 EmblemStyle; // icon id - uint32 EmblemColor; // ARGB format - uint8 BorderStyle; // border image id - uint32 BorderColor; // ARGB format + uint32 BackgroundColor; // ARGB format + uint8 EmblemStyle; // icon id + uint32 EmblemColor; // ARGB format + uint8 BorderStyle; // border image id + uint32 BorderColor; // ARGB format - MemberList Members; - ArenaTeamStats Stats; + MemberList Members; + ArenaTeamStats Stats; }; #endif diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp index 2535e8736..60af82552 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp @@ -94,8 +94,8 @@ void ArenaTeamMgr::LoadArenaTeams() // 0 1 2 3 4 5 6 7 8 QueryResult result = CharacterDatabase.Query("SELECT arenaTeamId, name, captainGuid, type, backgroundColor, emblemStyle, emblemColor, borderStyle, borderColor, " - // 9 10 11 12 13 14 - "rating, weekGames, weekWins, seasonGames, seasonWins, `rank` FROM arena_team ORDER BY arenaTeamId ASC"); + // 9 10 11 12 13 14 + "rating, weekGames, weekWins, seasonGames, seasonWins, `rank` FROM arena_team ORDER BY arenaTeamId ASC"); if (!result) { @@ -105,12 +105,12 @@ void ArenaTeamMgr::LoadArenaTeams() } QueryResult result2 = CharacterDatabase.Query( - // 0 1 2 3 4 5 6 7 8 9 10 - "SELECT arenaTeamId, atm.guid, atm.weekGames, atm.weekWins, atm.seasonGames, atm.seasonWins, c.name, class, personalRating, matchMakerRating, maxMMR FROM arena_team_member atm" - " INNER JOIN arena_team ate USING (arenaTeamId)" - " LEFT JOIN characters AS c ON atm.guid = c.guid" - " LEFT JOIN character_arena_stats AS cas ON c.guid = cas.guid AND (cas.slot = 0 AND ate.type = 2 OR cas.slot = 1 AND ate.type = 3 OR cas.slot = 2 AND ate.type = 5)" - " ORDER BY atm.arenateamid ASC"); + // 0 1 2 3 4 5 6 7 8 9 10 + "SELECT arenaTeamId, atm.guid, atm.weekGames, atm.weekWins, atm.seasonGames, atm.seasonWins, c.name, class, personalRating, matchMakerRating, maxMMR FROM arena_team_member atm" + " INNER JOIN arena_team ate USING (arenaTeamId)" + " LEFT JOIN characters AS c ON atm.guid = c.guid" + " LEFT JOIN character_arena_stats AS cas ON c.guid = cas.guid AND (cas.slot = 0 AND ate.type = 2 OR cas.slot = 1 AND ate.type = 3 OR cas.slot = 2 AND ate.type = 5)" + " ORDER BY atm.arenateamid ASC"); uint32 count = 0; do @@ -127,8 +127,7 @@ void ArenaTeamMgr::LoadArenaTeams() AddArenaTeam(newArenaTeam); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u arena teams in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index b9a95b945..02b00904d 100644 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -40,65 +40,65 @@ namespace acore { class BattlegroundChatBuilder { - public: - BattlegroundChatBuilder(ChatMsg msgtype, uint32 textId, Player const* source, va_list* args = nullptr) - : _msgtype(msgtype), _textId(textId), _source(source), _args(args) { } + public: + BattlegroundChatBuilder(ChatMsg msgtype, uint32 textId, Player const* source, va_list* args = nullptr) + : _msgtype(msgtype), _textId(textId), _source(source), _args(args) { } - void operator()(WorldPacket& data, LocaleConstant loc_idx) + void operator()(WorldPacket& data, LocaleConstant loc_idx) + { + char const* text = sObjectMgr->GetAcoreString(_textId, loc_idx); + if (_args) { - char const* text = sObjectMgr->GetAcoreString(_textId, loc_idx); - if (_args) - { - // we need copy va_list before use or original va_list will corrupted - va_list ap; - va_copy(ap, *_args); + // we need copy va_list before use or original va_list will corrupted + va_list ap; + va_copy(ap, *_args); - char str[2048]; - vsnprintf(str, 2048, text, ap); - va_end(ap); + char str[2048]; + vsnprintf(str, 2048, text, ap); + va_end(ap); - do_helper(data, &str[0]); - } - else - do_helper(data, text); + do_helper(data, &str[0]); } + else + do_helper(data, text); + } - private: - void do_helper(WorldPacket& data, char const* text) - { - ChatHandler::BuildChatPacket(data, _msgtype, LANG_UNIVERSAL, _source, _source, text); - } + private: + void do_helper(WorldPacket& data, char const* text) + { + ChatHandler::BuildChatPacket(data, _msgtype, LANG_UNIVERSAL, _source, _source, text); + } - ChatMsg _msgtype; - uint32 _textId; - Player const* _source; - va_list* _args; + ChatMsg _msgtype; + uint32 _textId; + Player const* _source; + va_list* _args; }; class Battleground2ChatBuilder { - public: - Battleground2ChatBuilder(ChatMsg msgtype, uint32 textId, Player const* source, int32 arg1, int32 arg2) - : _msgtype(msgtype), _textId(textId), _source(source), _arg1(arg1), _arg2(arg2) {} + public: + Battleground2ChatBuilder(ChatMsg msgtype, uint32 textId, Player const* source, int32 arg1, int32 arg2) + : _msgtype(msgtype), _textId(textId), _source(source), _arg1(arg1), _arg2(arg2) {} - void operator()(WorldPacket& data, LocaleConstant loc_idx) - { - char const* text = sObjectMgr->GetAcoreString(_textId, loc_idx); - char const* arg1str = _arg1 ? sObjectMgr->GetAcoreString(_arg1, loc_idx) : ""; - char const* arg2str = _arg2 ? sObjectMgr->GetAcoreString(_arg2, loc_idx) : ""; + void operator()(WorldPacket& data, LocaleConstant loc_idx) + { + char const* text = sObjectMgr->GetAcoreString(_textId, loc_idx); + char const* arg1str = _arg1 ? sObjectMgr->GetAcoreString(_arg1, loc_idx) : ""; + char const* arg2str = _arg2 ? sObjectMgr->GetAcoreString(_arg2, loc_idx) : ""; - char str[2048]; - snprintf(str, 2048, text, arg1str, arg2str); + char str[2048]; + snprintf(str, 2048, text, arg1str, arg2str); - ChatHandler::BuildChatPacket(data, _msgtype, LANG_UNIVERSAL, _source, _source, str); - } + ChatHandler::BuildChatPacket(data, _msgtype, LANG_UNIVERSAL, _source, _source, str); + } - private: - ChatMsg _msgtype; - uint32 _textId; - Player const* _source; - uint32 _arg1; - uint32 _arg2; + private: + ChatMsg _msgtype; + uint32 _textId; + Player const* _source; + uint32 _arg1; + uint32 _arg2; }; } // namespace acore @@ -169,7 +169,7 @@ Battleground::Battleground() m_PlayersCount[TEAM_ALLIANCE] = 0; m_PlayersCount[TEAM_HORDE] = 0; - m_BgInvitedPlayers[TEAM_ALLIANCE]= 0; + m_BgInvitedPlayers[TEAM_ALLIANCE] = 0; m_BgInvitedPlayers[TEAM_HORDE] = 0; m_TeamScores[TEAM_ALLIANCE] = 0; @@ -256,7 +256,7 @@ void Battleground::Update(uint32 diff) case STATUS_IN_PROGRESS: if (isArena()) { - if (GetStartTime() >= 46*MINUTE*IN_MILLISECONDS) // pussywizard: 1min startup + 45min allowed duration + if (GetStartTime() >= 46 * MINUTE * IN_MILLISECONDS) // pussywizard: 1min startup + 45min allowed duration { UpdateArenaWorldState(); CheckArenaAfterTimerConditions(); @@ -529,16 +529,16 @@ inline void Battleground::_ProcessJoin(uint32 diff) player->RemoveAurasDueToSpell(SPELL_ARENA_PREPARATION); player->ResetAllPowers(); // remove auras with duration lower than 30s - Unit::AuraApplicationMap & auraMap = player->GetAppliedAuras(); + Unit::AuraApplicationMap& auraMap = player->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator iter = auraMap.begin(); iter != auraMap.end();) { - AuraApplication * aurApp = iter->second; + AuraApplication* aurApp = iter->second; Aura* aura = aurApp->GetBase(); if (!aura->IsPermanent() - && aura->GetDuration() <= 30*IN_MILLISECONDS - && aurApp->IsPositive() - // && (!aura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)) Xinef: bullshit condition, ALL buffs should be removed - && (!aura->HasEffectType(SPELL_AURA_MOD_INVISIBILITY))) + && aura->GetDuration() <= 30 * IN_MILLISECONDS + && aurApp->IsPositive() + // && (!aura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)) Xinef: bullshit condition, ALL buffs should be removed + && (!aura->HasEffectType(SPELL_AURA_MOD_INVISIBILITY))) player->RemoveAura(iter); else ++iter; @@ -564,10 +564,10 @@ inline void Battleground::_ProcessJoin(uint32 diff) p->SetSummonPoint(t->GetMapId(), t->GetPositionX(), t->GetPositionY(), t->GetPositionZ(), 15, true); - WorldPacket data(SMSG_SUMMON_REQUEST, 8+4+4); + WorldPacket data(SMSG_SUMMON_REQUEST, 8 + 4 + 4); data << uint64(t->GetGUID()); data << uint32(t->GetZoneId()); - data << uint32(15*IN_MILLISECONDS); + data << uint32(15 * IN_MILLISECONDS); p->GetSession()->SendPacket(&data); } m_ToBeTeleported.clear(); @@ -673,17 +673,17 @@ void Battleground::RewardHonorToTeam(uint32 honor, TeamId teamId) void Battleground::RewardReputationToTeam(uint32 factionId, uint32 reputation, TeamId teamId) { - for (BattlegroundPlayerMap::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) - if (itr->second->GetBgTeamId() == teamId) - { - uint32 realFactionId = GetRealRepFactionForPlayer(factionId, itr->second); + for (BattlegroundPlayerMap::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) + if (itr->second->GetBgTeamId() == teamId) + { + uint32 realFactionId = GetRealRepFactionForPlayer(factionId, itr->second); - uint32 repGain = reputation; - AddPct(repGain, itr->second->GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN)); - AddPct(repGain, itr->second->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, realFactionId)); - if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(realFactionId)) - itr->second->GetReputationMgr().ModifyReputation(factionEntry, repGain); - } + uint32 repGain = reputation; + AddPct(repGain, itr->second->GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN)); + AddPct(repGain, itr->second->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, realFactionId)); + if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(realFactionId)) + itr->second->GetReputationMgr().ModifyReputation(factionEntry, repGain); + } } uint32 Battleground::GetRealRepFactionForPlayer(uint32 factionId, Player* player) @@ -738,7 +738,7 @@ void Battleground::EndBattleground(TeamId winnerTeamId) if (GetStatus() == STATUS_WAIT_LEAVE) return; uint32 startDelay = GetStartDelayTime(); - bool bValidArena = isArena() && isRated() && GetStatus() == STATUS_IN_PROGRESS && GetStartTime() >= startDelay+15000; // pussywizard: only if arena lasted at least 15 secs + bool bValidArena = isArena() && isRated() && GetStatus() == STATUS_IN_PROGRESS && GetStartTime() >= startDelay + 15000; // pussywizard: only if arena lasted at least 15 secs SetStatus(STATUS_WAIT_LEAVE); ArenaTeam* winnerArenaTeam = nullptr; @@ -825,7 +825,7 @@ void Battleground::EndBattleground(TeamId winnerTeamId) PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_LOG_FIGHT); stmt->setUInt32(0, fightId); stmt->setUInt8(1, m_ArenaType); - stmt->setUInt32(2, ((GetStartTime() <= startDelay ? 0 : GetStartTime()-startDelay)/1000)); + stmt->setUInt32(2, ((GetStartTime() <= startDelay ? 0 : GetStartTime() - startDelay) / 1000)); stmt->setUInt32(3, winnerArenaTeam->GetId()); stmt->setUInt32(4, loserArenaTeam->GetId()); stmt->setUInt16(5, (uint16)winnerTeamRating); @@ -884,7 +884,7 @@ void Battleground::EndBattleground(TeamId winnerTeamId) PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_LOG_FIGHT); stmt->setUInt32(0, fightId); stmt->setUInt8(1, m_ArenaType); - stmt->setUInt32(2, ((GetStartTime() <= startDelay ? 0 : GetStartTime()-startDelay)/1000)); + stmt->setUInt32(2, ((GetStartTime() <= startDelay ? 0 : GetStartTime() - startDelay) / 1000)); stmt->setUInt32(3, winnerArenaTeam->GetId()); stmt->setUInt32(4, loserArenaTeam->GetId()); stmt->setUInt16(5, (uint16)winnerTeamRating); @@ -1364,7 +1364,7 @@ bool Battleground::HasFreeSlots() const { if (GetStatus() != STATUS_WAIT_JOIN && GetStatus() != STATUS_IN_PROGRESS) return false; - for (uint8 i=0; i 0) return true; return false; @@ -1382,12 +1382,12 @@ void Battleground::ReadyMarkerClicked(Player* p) return; readyMarkerClickedSet.insert(p->GetGUIDLow()); uint32 count = readyMarkerClickedSet.size(); - uint32 req = GetArenaType()*2; + uint32 req = GetArenaType() * 2; p->GetSession()->SendNotification("You are marked as ready %u/%u", count, req); if (count == req) { m_Events |= BG_STARTING_EVENT_2; - m_StartTime += GetStartDelayTime()-BG_START_DELAY_15S; + m_StartTime += GetStartDelayTime() - BG_START_DELAY_15S; SetStartDelayTime(BG_START_DELAY_15S); } } @@ -1427,7 +1427,7 @@ void Battleground::UpdatePlayerScore(Player* player, uint32 type, uint32 value, itr->second->BonusHonor += value; } break; - // used only in EY, but in MSG_PVP_LOG_DATA opcode + // used only in EY, but in MSG_PVP_LOG_DATA opcode case SCORE_DAMAGE_DONE: // Damage Done itr->second->DamageDone += value; if (isArena() && isRated() && GetStatus() == STATUS_IN_PROGRESS) @@ -1448,7 +1448,7 @@ void Battleground::UpdatePlayerScore(Player* player, uint32 type, uint32 value, break; default: sLog->outError("Battleground::UpdatePlayerScore: unknown score type (%u) for BG (map: %u, instance id: %u)!", - type, m_MapId, m_InstanceID); + type, m_MapId, m_InstanceID); break; } } @@ -1512,37 +1512,37 @@ bool Battleground::AddObject(uint32 type, uint32 entry, float x, float y, float // So we must create it specific for this instance GameObject* go = sObjectMgr->IsGameObjectStaticTransport(entry) ? new StaticTransport() : new GameObject(); if (!go->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), entry, GetBgMap(), - PHASEMASK_NORMAL, x, y, z, o, G3D::Quat(rotation0, rotation1, rotation2, rotation3), 100, goState)) + PHASEMASK_NORMAL, x, y, z, o, G3D::Quat(rotation0, rotation1, rotation2, rotation3), 100, goState)) { sLog->outErrorDb("Battleground::AddObject: cannot create gameobject (entry: %u) for BG (map: %u, instance id: %u)!", - entry, m_MapId, m_InstanceID); + entry, m_MapId, m_InstanceID); sLog->outError("Battleground::AddObject: cannot create gameobject (entry: %u) for BG (map: %u, instance id: %u)!", - entry, m_MapId, m_InstanceID); + entry, m_MapId, m_InstanceID); delete go; return false; } -/* - uint32 guid = go->GetGUIDLow(); + /* + uint32 guid = go->GetGUIDLow(); - // without this, UseButtonOrDoor caused the crash, since it tried to get go info from godata - // iirc that was changed, so adding to go data map is no longer required if that was the only function using godata from GameObject without checking if it existed - GameObjectData& data = sObjectMgr->NewGOData(guid); + // without this, UseButtonOrDoor caused the crash, since it tried to get go info from godata + // iirc that was changed, so adding to go data map is no longer required if that was the only function using godata from GameObject without checking if it existed + GameObjectData& data = sObjectMgr->NewGOData(guid); - data.id = entry; - data.mapid = GetMapId(); - data.posX = x; - data.posY = y; - data.posZ = z; - data.orientation = o; - data.rotation0 = rotation0; - data.rotation1 = rotation1; - data.rotation2 = rotation2; - data.rotation3 = rotation3; - data.spawntimesecs = respawnTime; - data.spawnMask = 1; - data.animprogress = 100; - data.go_state = 1; -*/ + data.id = entry; + data.mapid = GetMapId(); + data.posX = x; + data.posY = y; + data.posZ = z; + data.orientation = o; + data.rotation0 = rotation0; + data.rotation1 = rotation1; + data.rotation2 = rotation2; + data.rotation3 = rotation3; + data.spawntimesecs = respawnTime; + data.spawnMask = 1; + data.animprogress = 100; + data.go_state = 1; + */ // Add to world, so it can be later looked up from HashMapHolder if (!map->AddToMap(go)) { @@ -1568,7 +1568,7 @@ void Battleground::DoorClose(uint32 type) } else sLog->outError("Battleground::DoorClose: door gameobject (type: %u, GUID: %u) not found for BG (map: %u, instance id: %u)!", - type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); + type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); } void Battleground::DoorOpen(uint32 type) @@ -1580,7 +1580,7 @@ void Battleground::DoorOpen(uint32 type) } else sLog->outError("Battleground::DoorOpen: door gameobject (type: %u, GUID: %u) not found for BG (map: %u, instance id: %u)!", - type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); + type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); } GameObject* Battleground::GetBGObject(uint32 type) @@ -1588,7 +1588,7 @@ GameObject* Battleground::GetBGObject(uint32 type) GameObject* obj = GetBgMap()->GetGameObject(BgObjects[type]); if (!obj) sLog->outError("Battleground::GetBGObject: gameobject (type: %u, GUID: %u) not found for BG (map: %u, instance id: %u)!", - type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); + type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); return obj; } @@ -1597,7 +1597,7 @@ Creature* Battleground::GetBGCreature(uint32 type) Creature* creature = GetBgMap()->GetCreature(BgCreatures[type]); if (!creature) sLog->outError("Battleground::GetBGCreature: creature (type: %u, GUID: %u) not found for BG (map: %u, instance id: %u)!", - type, GUID_LOPART(BgCreatures[type]), m_MapId, m_InstanceID); + type, GUID_LOPART(BgCreatures[type]), m_MapId, m_InstanceID); return creature; } @@ -1608,10 +1608,9 @@ void Battleground::SpawnBGObject(uint32 type, uint32 respawntime) { if (respawntime) obj->SetLootState(GO_JUST_DEACTIVATED); - else - if (obj->getLootState() == GO_JUST_DEACTIVATED) - // Change state from GO_JUST_DEACTIVATED to GO_READY in case battleground is starting again - obj->SetLootState(GO_READY); + else if (obj->getLootState() == GO_JUST_DEACTIVATED) + // Change state from GO_JUST_DEACTIVATED to GO_READY in case battleground is starting again + obj->SetLootState(GO_READY); obj->SetRespawnTime(respawntime); map->AddToMap(obj); } @@ -1643,7 +1642,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, if (!creature->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT), map, PHASEMASK_NORMAL, entry, 0, x, y, z, o)) { sLog->outError("Battleground::AddCreature: cannot create creature (entry: %u) for BG (map: %u, instance id: %u)!", - entry, m_MapId, m_InstanceID); + entry, m_MapId, m_InstanceID); delete creature; return nullptr; } @@ -1654,7 +1653,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, if (!cinfo) { sLog->outError("Battleground::AddCreature: creature template (entry: %u) does not exist for BG (map: %u, instance id: %u)!", - entry, m_MapId, m_InstanceID); + entry, m_MapId, m_InstanceID); delete creature; return nullptr; } @@ -1693,7 +1692,7 @@ bool Battleground::DelCreature(uint32 type) } sLog->outError("Battleground::DelCreature: creature (type: %u, GUID: %u) not found for BG (map: %u, instance id: %u)!", - type, GUID_LOPART(BgCreatures[type]), m_MapId, m_InstanceID); + type, GUID_LOPART(BgCreatures[type]), m_MapId, m_InstanceID); BgCreatures[type] = 0; return false; } @@ -1711,7 +1710,7 @@ bool Battleground::DelObject(uint32 type) return true; } sLog->outError("Battleground::DelObject: gameobject (type: %u, GUID: %u) not found for BG (map: %u, instance id: %u)!", - type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); + type, GUID_LOPART(BgObjects[type]), m_MapId, m_InstanceID); BgObjects[type] = 0; return false; } @@ -1735,7 +1734,7 @@ bool Battleground::AddSpiritGuide(uint32 type, float x, float y, float z, float return true; } sLog->outError("Battleground::AddSpiritGuide: cannot create spirit guide (type: %u, entry: %u) for BG (map: %u, instance id: %u)!", - type, entry, m_MapId, m_InstanceID); + type, entry, m_MapId, m_InstanceID); EndNow(); return false; } @@ -1923,7 +1922,7 @@ int32 Battleground::GetObjectType(uint64 guid) if (BgObjects[i] == guid) return i; sLog->outError("Battleground::GetObjectType: player used gameobject (GUID: %u) which is not in internal data for BG (map: %u, instance id: %u), cheating?", - GUID_LOPART(guid), m_MapId, m_InstanceID); + GUID_LOPART(guid), m_MapId, m_InstanceID); return -1; } diff --git a/src/server/game/Battlegrounds/Battleground.h b/src/server/game/Battlegrounds/Battleground.h index 7a2fd35c1..6db4e6cb7 100644 --- a/src/server/game/Battlegrounds/Battleground.h +++ b/src/server/game/Battlegrounds/Battleground.h @@ -175,7 +175,7 @@ struct BattlegroundObjectInfo { BattlegroundObjectInfo() : object(nullptr), timer(0), spellid(0) {} - GameObject *object; + GameObject* object; int32 timer; uint32 spellid; }; @@ -271,25 +271,25 @@ struct BattlegroundScore class ArenaLogEntryData { - public: - ArenaLogEntryData() : Guid(0), ArenaTeamId(0), DamageDone(0), HealingDone(0), KillingBlows(0) {} - void Fill(const char* name, uint32 guid, uint32 acc, uint32 arenaTeamId, std::string ip) - { - Name = std::string(name); - Guid = guid; - Acc = acc; - ArenaTeamId = arenaTeamId; - IP = ip; - } +public: + ArenaLogEntryData() : Guid(0), ArenaTeamId(0), DamageDone(0), HealingDone(0), KillingBlows(0) {} + void Fill(const char* name, uint32 guid, uint32 acc, uint32 arenaTeamId, std::string ip) + { + Name = std::string(name); + Guid = guid; + Acc = acc; + ArenaTeamId = arenaTeamId; + IP = ip; + } - std::string Name; - uint32 Guid; - uint32 Acc; - uint32 ArenaTeamId; - std::string IP; - uint32 DamageDone; - uint32 HealingDone; - uint32 KillingBlows; + std::string Name; + uint32 Guid; + uint32 Acc; + uint32 ArenaTeamId; + std::string IP; + uint32 DamageDone; + uint32 HealingDone; + uint32 KillingBlows; }; enum BGHonorMode @@ -320,430 +320,430 @@ enum BattlegroundQueueInvitationType class Battleground { - public: - Battleground(); - virtual ~Battleground(); - - void Update(uint32 diff); - - virtual bool SetupBattleground() // must be implemented in BG subclass - { - return true; - } - virtual void Init(); - virtual void StartingEventCloseDoors() { } - virtual void StartingEventOpenDoors() { } - virtual void ResetBGSubclass() { } // must be implemented in BG subclass - - virtual void DestroyGate(Player* /*player*/, GameObject* /*go*/) {} - - /* achievement req. */ - virtual bool AllNodesConrolledByTeam(TeamId /*teamId*/) const { return false; } - void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); - - /* Battleground */ - // Get methods: - char const* GetName() const { return m_Name; } - BattlegroundTypeId GetBgTypeID(bool GetRandom = false) const { return GetRandom ? m_RandomTypeID : m_RealTypeID; } - uint32 GetInstanceID() const { return m_InstanceID; } - BattlegroundStatus GetStatus() const { return m_Status; } - uint32 GetClientInstanceID() const { return m_ClientInstanceID; } - uint32 GetStartTime() const { return m_StartTime; } - uint32 GetEndTime() const { return m_EndTime; } - uint32 GetLastResurrectTime() const { return m_LastResurrectTime; } - - uint32 GetMinLevel() const { return m_LevelMin; } - uint32 GetMaxLevel() const { return m_LevelMax; } - - uint32 GetMaxPlayersPerTeam() const { return m_MaxPlayersPerTeam; } - uint32 GetMinPlayersPerTeam() const { return m_MinPlayersPerTeam; } - - int32 GetStartDelayTime() const { return m_StartDelayTime; } - uint8 GetArenaType() const { return m_ArenaType; } - TeamId GetWinner() const { return m_WinnerId; } - uint32 GetScriptId() const { return ScriptId; } - uint32 GetBonusHonorFromKill(uint32 kills) const; - - bool IsRandom() { return m_IsRandom; } - - // Set methods: - void SetName(char const* Name) { m_Name = Name; } - void SetBgTypeID(BattlegroundTypeId TypeID) { m_RealTypeID = TypeID; } - void SetRandomTypeID(BattlegroundTypeId TypeID) { m_RandomTypeID = TypeID; } - void SetInstanceID(uint32 InstanceID) { m_InstanceID = InstanceID; } - void SetStatus(BattlegroundStatus Status) { m_Status = Status; } - void SetClientInstanceID(uint32 InstanceID) { m_ClientInstanceID = InstanceID; } - void SetStartTime(uint32 Time) { m_StartTime = Time; } - void SetEndTime(uint32 Time) { m_EndTime = Time; } - void SetLastResurrectTime(uint32 Time) { m_LastResurrectTime = Time; } - void SetLevelRange(uint32 min, uint32 max) { m_LevelMin = min; m_LevelMax = max; } - void SetRated(bool state) { m_IsRated = state; } - void SetArenaType(uint8 type) { m_ArenaType = type; } - void SetArenaorBGType(bool _isArena) { m_IsArena = _isArena; } - void SetWinner(TeamId winner) { m_WinnerId = winner; } - void SetScriptId(uint32 scriptId) { ScriptId = scriptId; } - void SetRandom(bool isRandom) { m_IsRandom = isRandom; } - - void ModifyStartDelayTime(int32 diff) { m_StartDelayTime -= diff; } - void SetStartDelayTime(int32 Time) { m_StartDelayTime = Time; } - - void SetMaxPlayersPerTeam(uint32 MaxPlayers) { m_MaxPlayersPerTeam = MaxPlayers; } - void SetMinPlayersPerTeam(uint32 MinPlayers) { m_MinPlayersPerTeam = MinPlayers; } - - void DecreaseInvitedCount(TeamId teamId) { if (m_BgInvitedPlayers[teamId]) --m_BgInvitedPlayers[teamId]; } - void IncreaseInvitedCount(TeamId teamId) { ++m_BgInvitedPlayers[teamId]; } - uint32 GetInvitedCount(TeamId teamId) const { return m_BgInvitedPlayers[teamId]; } - - bool HasFreeSlots() const; - uint32 GetFreeSlotsForTeam(TeamId teamId) const; - uint32 GetMaxFreeSlots() const; - - typedef std::set SpectatorList; - typedef std::map ToBeTeleportedMap; - void AddSpectator(Player* p) { m_Spectators.insert(p); } - void RemoveSpectator(Player* p) { m_Spectators.erase(p); } - bool HaveSpectators() { return !m_Spectators.empty(); } - const SpectatorList& GetSpectators() const { return m_Spectators; } - void AddToBeTeleported(uint64 spectator, uint64 participant) { m_ToBeTeleported[spectator] = participant; } - void RemoveToBeTeleported(uint64 spectator) { ToBeTeleportedMap::iterator itr = m_ToBeTeleported.find(spectator); if (itr != m_ToBeTeleported.end()) m_ToBeTeleported.erase(itr); } - void SpectatorsSendPacket(WorldPacket& data); - - bool isArena() const { return m_IsArena; } - bool isBattleground() const { return !m_IsArena; } - bool isRated() const { return m_IsRated; } - - typedef std::map BattlegroundPlayerMap; - BattlegroundPlayerMap const& GetPlayers() const { return m_Players; } - uint32 GetPlayersSize() const { return m_Players.size(); } - - void ReadyMarkerClicked(Player* p); // pussywizard - std::set readyMarkerClickedSet; // pussywizard - - typedef std::map BattlegroundScoreMap; - typedef std::map ArenaLogEntryDataMap;// pussywizard - ArenaLogEntryDataMap ArenaLogEntries; // pussywizard - BattlegroundScoreMap::const_iterator GetPlayerScoresBegin() const { return PlayerScores.begin(); } - BattlegroundScoreMap::const_iterator GetPlayerScoresEnd() const { return PlayerScores.end(); } - uint32 GetPlayerScoresSize() const { return PlayerScores.size(); } - - uint32 GetReviveQueueSize() const { return m_ReviveQueue.size(); } - - void AddPlayerToResurrectQueue(uint64 npc_guid, uint64 player_guid); - void RemovePlayerFromResurrectQueue(Player* player); - - /// Relocate all players in ReviveQueue to the closest graveyard - void RelocateDeadPlayers(uint64 queueIndex); - - void StartBattleground(); - - GameObject* GetBGObject(uint32 type); - Creature* GetBGCreature(uint32 type); - - // Location - void SetMapId(uint32 MapID) { m_MapId = MapID; } - uint32 GetMapId() const { return m_MapId; } - - // Map pointers - void SetBgMap(BattlegroundMap* map) { m_Map = map; } - BattlegroundMap* GetBgMap() const { ASSERT(m_Map); return m_Map; } - BattlegroundMap* FindBgMap() const { return m_Map; } - - void SetTeamStartLoc(TeamId teamId, float X, float Y, float Z, float O); - void GetTeamStartLoc(TeamId teamId, float &X, float &Y, float &Z, float &O) const - { - X = m_TeamStartLocX[teamId]; - Y = m_TeamStartLocY[teamId]; - Z = m_TeamStartLocZ[teamId]; - O = m_TeamStartLocO[teamId]; - } - - void SetStartMaxDist(float startMaxDist) { m_StartMaxDist = startMaxDist; } - float GetStartMaxDist() const { return m_StartMaxDist; } - - // Packet Transfer - // method that should fill worldpacket with actual world states (not yet implemented for all battlegrounds!) - virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} - void SendPacketToTeam(TeamId teamId, WorldPacket* packet, Player* sender = NULL, bool self = true); - void SendPacketToAll(WorldPacket* packet); - void YellToAll(Creature* creature, const char* text, uint32 language); - - template - void BroadcastWorker(Do& _do); - - void PlaySoundToAll(uint32 soundId); - void CastSpellOnTeam(uint32 spellId, TeamId teamId); - void RemoveAuraOnTeam(uint32 spellId, TeamId teamId); - void RewardHonorToTeam(uint32 honor, TeamId teamId); - void RewardReputationToTeam(uint32 factionId, uint32 reputation, TeamId teamId); - uint32 GetRealRepFactionForPlayer(uint32 factionId, Player* player); - - void UpdateWorldState(uint32 Field, uint32 Value); - void UpdateWorldStateForPlayer(uint32 Field, uint32 Value, Player* player); - - virtual void EndBattleground(TeamId winnerTeamId); - void BlockMovement(Player* player); - - void SendWarningToAll(uint32 entry, ...); - void SendMessageToAll(uint32 entry, ChatMsg type, Player const* source = nullptr); - void PSendMessageToAll(uint32 entry, ChatMsg type, Player const* source, ...); - - // specialized version with 2 string id args - void SendMessage2ToAll(uint32 entry, ChatMsg type, Player const* source, uint32 strId1 = 0, uint32 strId2 = 0); - - // Raid Group - Group* GetBgRaid(TeamId teamId) const { return m_BgRaids[teamId]; } - void SetBgRaid(TeamId teamId, Group* bg_raid); - - virtual void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); - - uint32 GetPlayersCountByTeam(TeamId teamId) const { return m_PlayersCount[teamId]; } - uint32 GetAlivePlayersCountByTeam(TeamId teamId) const; // used in arenas to correctly handle death in spirit of redemption / last stand etc. (killer = killed) cases - void UpdatePlayersCountByTeam(TeamId teamId, bool remove) - { - if (remove) - --m_PlayersCount[teamId]; - else - ++m_PlayersCount[teamId]; - } - - // used for rated arena battles - void SetArenaTeamIdForTeam(TeamId teamId, uint32 ArenaTeamId) { m_ArenaTeamIds[teamId] = ArenaTeamId; } - uint32 GetArenaTeamIdForTeam(TeamId teamId) const { return m_ArenaTeamIds[teamId]; } - void SetArenaTeamRatingChangeForTeam(TeamId teamId, int32 RatingChange) { m_ArenaTeamRatingChanges[teamId] = RatingChange; } - int32 GetArenaTeamRatingChangeForTeam(TeamId teamId) const { return m_ArenaTeamRatingChanges[teamId]; } - void SetArenaMatchmakerRating(TeamId teamId, uint32 MMR) { m_ArenaTeamMMR[teamId] = MMR; } - uint32 GetArenaMatchmakerRating(TeamId teamId) const { return m_ArenaTeamMMR[teamId]; } - void CheckArenaAfterTimerConditions(); - void CheckArenaWinConditions(); - virtual void UpdateArenaWorldState(); +public: + Battleground(); + virtual ~Battleground(); + + void Update(uint32 diff); + + virtual bool SetupBattleground() // must be implemented in BG subclass + { + return true; + } + virtual void Init(); + virtual void StartingEventCloseDoors() { } + virtual void StartingEventOpenDoors() { } + virtual void ResetBGSubclass() { } // must be implemented in BG subclass + + virtual void DestroyGate(Player* /*player*/, GameObject* /*go*/) {} + + /* achievement req. */ + virtual bool AllNodesConrolledByTeam(TeamId /*teamId*/) const { return false; } + void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); + + /* Battleground */ + // Get methods: + char const* GetName() const { return m_Name; } + BattlegroundTypeId GetBgTypeID(bool GetRandom = false) const { return GetRandom ? m_RandomTypeID : m_RealTypeID; } + uint32 GetInstanceID() const { return m_InstanceID; } + BattlegroundStatus GetStatus() const { return m_Status; } + uint32 GetClientInstanceID() const { return m_ClientInstanceID; } + uint32 GetStartTime() const { return m_StartTime; } + uint32 GetEndTime() const { return m_EndTime; } + uint32 GetLastResurrectTime() const { return m_LastResurrectTime; } + + uint32 GetMinLevel() const { return m_LevelMin; } + uint32 GetMaxLevel() const { return m_LevelMax; } + + uint32 GetMaxPlayersPerTeam() const { return m_MaxPlayersPerTeam; } + uint32 GetMinPlayersPerTeam() const { return m_MinPlayersPerTeam; } + + int32 GetStartDelayTime() const { return m_StartDelayTime; } + uint8 GetArenaType() const { return m_ArenaType; } + TeamId GetWinner() const { return m_WinnerId; } + uint32 GetScriptId() const { return ScriptId; } + uint32 GetBonusHonorFromKill(uint32 kills) const; + + bool IsRandom() { return m_IsRandom; } + + // Set methods: + void SetName(char const* Name) { m_Name = Name; } + void SetBgTypeID(BattlegroundTypeId TypeID) { m_RealTypeID = TypeID; } + void SetRandomTypeID(BattlegroundTypeId TypeID) { m_RandomTypeID = TypeID; } + void SetInstanceID(uint32 InstanceID) { m_InstanceID = InstanceID; } + void SetStatus(BattlegroundStatus Status) { m_Status = Status; } + void SetClientInstanceID(uint32 InstanceID) { m_ClientInstanceID = InstanceID; } + void SetStartTime(uint32 Time) { m_StartTime = Time; } + void SetEndTime(uint32 Time) { m_EndTime = Time; } + void SetLastResurrectTime(uint32 Time) { m_LastResurrectTime = Time; } + void SetLevelRange(uint32 min, uint32 max) { m_LevelMin = min; m_LevelMax = max; } + void SetRated(bool state) { m_IsRated = state; } + void SetArenaType(uint8 type) { m_ArenaType = type; } + void SetArenaorBGType(bool _isArena) { m_IsArena = _isArena; } + void SetWinner(TeamId winner) { m_WinnerId = winner; } + void SetScriptId(uint32 scriptId) { ScriptId = scriptId; } + void SetRandom(bool isRandom) { m_IsRandom = isRandom; } + + void ModifyStartDelayTime(int32 diff) { m_StartDelayTime -= diff; } + void SetStartDelayTime(int32 Time) { m_StartDelayTime = Time; } + + void SetMaxPlayersPerTeam(uint32 MaxPlayers) { m_MaxPlayersPerTeam = MaxPlayers; } + void SetMinPlayersPerTeam(uint32 MinPlayers) { m_MinPlayersPerTeam = MinPlayers; } + + void DecreaseInvitedCount(TeamId teamId) { if (m_BgInvitedPlayers[teamId]) --m_BgInvitedPlayers[teamId]; } + void IncreaseInvitedCount(TeamId teamId) { ++m_BgInvitedPlayers[teamId]; } + uint32 GetInvitedCount(TeamId teamId) const { return m_BgInvitedPlayers[teamId]; } + + bool HasFreeSlots() const; + uint32 GetFreeSlotsForTeam(TeamId teamId) const; + uint32 GetMaxFreeSlots() const; + + typedef std::set SpectatorList; + typedef std::map ToBeTeleportedMap; + void AddSpectator(Player* p) { m_Spectators.insert(p); } + void RemoveSpectator(Player* p) { m_Spectators.erase(p); } + bool HaveSpectators() { return !m_Spectators.empty(); } + const SpectatorList& GetSpectators() const { return m_Spectators; } + void AddToBeTeleported(uint64 spectator, uint64 participant) { m_ToBeTeleported[spectator] = participant; } + void RemoveToBeTeleported(uint64 spectator) { ToBeTeleportedMap::iterator itr = m_ToBeTeleported.find(spectator); if (itr != m_ToBeTeleported.end()) m_ToBeTeleported.erase(itr); } + void SpectatorsSendPacket(WorldPacket& data); + + bool isArena() const { return m_IsArena; } + bool isBattleground() const { return !m_IsArena; } + bool isRated() const { return m_IsRated; } + + typedef std::map BattlegroundPlayerMap; + BattlegroundPlayerMap const& GetPlayers() const { return m_Players; } + uint32 GetPlayersSize() const { return m_Players.size(); } + + void ReadyMarkerClicked(Player* p); // pussywizard + std::set readyMarkerClickedSet; // pussywizard + + typedef std::map BattlegroundScoreMap; + typedef std::map ArenaLogEntryDataMap;// pussywizard + ArenaLogEntryDataMap ArenaLogEntries; // pussywizard + BattlegroundScoreMap::const_iterator GetPlayerScoresBegin() const { return PlayerScores.begin(); } + BattlegroundScoreMap::const_iterator GetPlayerScoresEnd() const { return PlayerScores.end(); } + uint32 GetPlayerScoresSize() const { return PlayerScores.size(); } + + uint32 GetReviveQueueSize() const { return m_ReviveQueue.size(); } + + void AddPlayerToResurrectQueue(uint64 npc_guid, uint64 player_guid); + void RemovePlayerFromResurrectQueue(Player* player); + + /// Relocate all players in ReviveQueue to the closest graveyard + void RelocateDeadPlayers(uint64 queueIndex); + + void StartBattleground(); + + GameObject* GetBGObject(uint32 type); + Creature* GetBGCreature(uint32 type); + + // Location + void SetMapId(uint32 MapID) { m_MapId = MapID; } + uint32 GetMapId() const { return m_MapId; } + + // Map pointers + void SetBgMap(BattlegroundMap* map) { m_Map = map; } + BattlegroundMap* GetBgMap() const { ASSERT(m_Map); return m_Map; } + BattlegroundMap* FindBgMap() const { return m_Map; } + + void SetTeamStartLoc(TeamId teamId, float X, float Y, float Z, float O); + void GetTeamStartLoc(TeamId teamId, float& X, float& Y, float& Z, float& O) const + { + X = m_TeamStartLocX[teamId]; + Y = m_TeamStartLocY[teamId]; + Z = m_TeamStartLocZ[teamId]; + O = m_TeamStartLocO[teamId]; + } + + void SetStartMaxDist(float startMaxDist) { m_StartMaxDist = startMaxDist; } + float GetStartMaxDist() const { return m_StartMaxDist; } + + // Packet Transfer + // method that should fill worldpacket with actual world states (not yet implemented for all battlegrounds!) + virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} + void SendPacketToTeam(TeamId teamId, WorldPacket* packet, Player* sender = NULL, bool self = true); + void SendPacketToAll(WorldPacket* packet); + void YellToAll(Creature* creature, const char* text, uint32 language); + + template + void BroadcastWorker(Do& _do); + + void PlaySoundToAll(uint32 soundId); + void CastSpellOnTeam(uint32 spellId, TeamId teamId); + void RemoveAuraOnTeam(uint32 spellId, TeamId teamId); + void RewardHonorToTeam(uint32 honor, TeamId teamId); + void RewardReputationToTeam(uint32 factionId, uint32 reputation, TeamId teamId); + uint32 GetRealRepFactionForPlayer(uint32 factionId, Player* player); + + void UpdateWorldState(uint32 Field, uint32 Value); + void UpdateWorldStateForPlayer(uint32 Field, uint32 Value, Player* player); + + virtual void EndBattleground(TeamId winnerTeamId); + void BlockMovement(Player* player); + + void SendWarningToAll(uint32 entry, ...); + void SendMessageToAll(uint32 entry, ChatMsg type, Player const* source = nullptr); + void PSendMessageToAll(uint32 entry, ChatMsg type, Player const* source, ...); + + // specialized version with 2 string id args + void SendMessage2ToAll(uint32 entry, ChatMsg type, Player const* source, uint32 strId1 = 0, uint32 strId2 = 0); + + // Raid Group + Group* GetBgRaid(TeamId teamId) const { return m_BgRaids[teamId]; } + void SetBgRaid(TeamId teamId, Group* bg_raid); + + virtual void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); + + uint32 GetPlayersCountByTeam(TeamId teamId) const { return m_PlayersCount[teamId]; } + uint32 GetAlivePlayersCountByTeam(TeamId teamId) const; // used in arenas to correctly handle death in spirit of redemption / last stand etc. (killer = killed) cases + void UpdatePlayersCountByTeam(TeamId teamId, bool remove) + { + if (remove) + --m_PlayersCount[teamId]; + else + ++m_PlayersCount[teamId]; + } + + // used for rated arena battles + void SetArenaTeamIdForTeam(TeamId teamId, uint32 ArenaTeamId) { m_ArenaTeamIds[teamId] = ArenaTeamId; } + uint32 GetArenaTeamIdForTeam(TeamId teamId) const { return m_ArenaTeamIds[teamId]; } + void SetArenaTeamRatingChangeForTeam(TeamId teamId, int32 RatingChange) { m_ArenaTeamRatingChanges[teamId] = RatingChange; } + int32 GetArenaTeamRatingChangeForTeam(TeamId teamId) const { return m_ArenaTeamRatingChanges[teamId]; } + void SetArenaMatchmakerRating(TeamId teamId, uint32 MMR) { m_ArenaTeamMMR[teamId] = MMR; } + uint32 GetArenaMatchmakerRating(TeamId teamId) const { return m_ArenaTeamMMR[teamId]; } + void CheckArenaAfterTimerConditions(); + void CheckArenaWinConditions(); + virtual void UpdateArenaWorldState(); - // Triggers handle - // must be implemented in BG subclass - virtual void HandleAreaTrigger(Player* /*player*/, uint32 /*trigger*/) {} - // must be implemented in BG subclass if need AND call base class generic code - virtual void HandleKillPlayer(Player* player, Player* killer); - virtual void HandleKillUnit(Creature* /*unit*/, Player* /*killer*/); + // Triggers handle + // must be implemented in BG subclass + virtual void HandleAreaTrigger(Player* /*player*/, uint32 /*trigger*/) {} + // must be implemented in BG subclass if need AND call base class generic code + virtual void HandleKillPlayer(Player* player, Player* killer); + virtual void HandleKillUnit(Creature* /*unit*/, Player* /*killer*/); - // Battleground events - virtual void EventPlayerDroppedFlag(Player* /*player*/) {} - virtual void EventPlayerClickedOnFlag(Player* /*player*/, GameObject* /*gameObject*/) {} - virtual void EventPlayerDamagedGO(Player* /*player*/, GameObject* /*go*/, uint32 /*eventType*/) {} - virtual void EventPlayerUsedGO(Player* /*player*/, GameObject* /*go*/){} + // Battleground events + virtual void EventPlayerDroppedFlag(Player* /*player*/) {} + virtual void EventPlayerClickedOnFlag(Player* /*player*/, GameObject* /*gameObject*/) {} + virtual void EventPlayerDamagedGO(Player* /*player*/, GameObject* /*go*/, uint32 /*eventType*/) {} + virtual void EventPlayerUsedGO(Player* /*player*/, GameObject* /*go*/) {} - // this function can be used by spell to interact with the BG map - virtual void DoAction(uint32 /*action*/, uint64 /*var*/) {} - - virtual void HandlePlayerResurrect(Player* /*player*/) {} - - // Death related - virtual GraveyardStruct const* GetClosestGraveyard(Player* player); - - virtual void AddPlayer(Player* player); // must be implemented in BG subclass - - void AddOrSetPlayerToCorrectBgGroup(Player* player, TeamId teamId); - - void RemovePlayerAtLeave(Player* player); - // can be extended in in BG subclass - - void HandleTriggerBuff(GameObject* gameObject); - void SetHoliday(bool is_holiday); - - // TODO: make this protected: - typedef std::vector BGObjects; - typedef std::vector BGCreatures; - BGObjects BgObjects; - BGCreatures BgCreatures; - void SpawnBGObject(uint32 type, uint32 respawntime); - bool AddObject(uint32 type, uint32 entry, float x, float y, float z, float o, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime = 0, GOState goState = GO_STATE_READY); - Creature* AddCreature(uint32 entry, uint32 type, float x, float y, float z, float o, uint32 respawntime = 0, MotionTransport* transport = nullptr); - bool DelCreature(uint32 type); - bool DelObject(uint32 type); - bool AddSpiritGuide(uint32 type, float x, float y, float z, float o, TeamId teamId); - int32 GetObjectType(uint64 guid); - - void DoorOpen(uint32 type); - void DoorClose(uint32 type); - //to be removed - const char* GetAcoreString(int32 entry); - - virtual bool HandlePlayerUnderMap(Player* /*player*/) { return false; } - - // since arenas can be AvA or Hvh, we have to get the "temporary" team of a player - static TeamId GetOtherTeamId(TeamId teamId); - bool IsPlayerInBattleground(uint64 guid) const; - - bool ToBeDeleted() const { return m_SetDeleteThis; } - //void SetDeleteThis() { m_SetDeleteThis = true; } - - void RewardXPAtKill(Player* killer, Player* victim); - - virtual uint64 GetFlagPickerGUID(TeamId /*teamId*/ = TEAM_NEUTRAL) const { return 0; } - virtual void SetDroppedFlagGUID(uint64 /*guid*/, TeamId /*teamId*/ = TEAM_NEUTRAL) {} - uint32 GetTeamScore(TeamId teamId) const; - - virtual TeamId GetPrematureWinner(); - - // because BattleGrounds with different types and same level range has different m_BracketId - uint8 GetUniqueBracketId() const; - - BattlegroundAV* ToBattlegroundAV() { if (GetBgTypeID(true) == BATTLEGROUND_AV) return reinterpret_cast(this); else return nullptr; } - BattlegroundAV const* ToBattlegroundAV() const { if (GetBgTypeID(true) == BATTLEGROUND_AV) return reinterpret_cast(this); else return nullptr; } - - BattlegroundWS* ToBattlegroundWS() { if (GetBgTypeID(true) == BATTLEGROUND_WS) return reinterpret_cast(this); else return nullptr; } - BattlegroundWS const* ToBattlegroundWS() const { if (GetBgTypeID(true) == BATTLEGROUND_WS) return reinterpret_cast(this); else return nullptr; } - - BattlegroundAB* ToBattlegroundAB() { if (GetBgTypeID(true) == BATTLEGROUND_AB) return reinterpret_cast(this); else return nullptr; } - BattlegroundAB const* ToBattlegroundAB() const { if (GetBgTypeID(true) == BATTLEGROUND_AB) return reinterpret_cast(this); else return nullptr; } - - BattlegroundNA* ToBattlegroundNA() { if (GetBgTypeID(true) == BATTLEGROUND_NA) return reinterpret_cast(this); else return nullptr; } - BattlegroundNA const* ToBattlegroundNA() const { if (GetBgTypeID(true) == BATTLEGROUND_NA) return reinterpret_cast(this); else return nullptr; } - - BattlegroundBE* ToBattlegroundBE() { if (GetBgTypeID(true) == BATTLEGROUND_BE) return reinterpret_cast(this); else return nullptr; } - BattlegroundBE const* ToBattlegroundBE() const { if (GetBgTypeID(true) == BATTLEGROUND_BE) return reinterpret_cast(this); else return nullptr; } - - BattlegroundEY* ToBattlegroundEY() { if (GetBgTypeID(true) == BATTLEGROUND_EY) return reinterpret_cast(this); else return nullptr; } - BattlegroundEY const* ToBattlegroundEY() const { if (GetBgTypeID(true) == BATTLEGROUND_EY) return reinterpret_cast(this); else return nullptr; } - - BattlegroundRL* ToBattlegroundRL() { if (GetBgTypeID(true) == BATTLEGROUND_RL) return reinterpret_cast(this); else return nullptr; } - BattlegroundRL const* ToBattlegroundRL() const { if (GetBgTypeID(true) == BATTLEGROUND_RL) return reinterpret_cast(this); else return nullptr; } - - BattlegroundSA* ToBattlegroundSA() { if (GetBgTypeID(true) == BATTLEGROUND_SA) return reinterpret_cast(this); else return nullptr; } - BattlegroundSA const* ToBattlegroundSA() const { if (GetBgTypeID(true) == BATTLEGROUND_SA) return reinterpret_cast(this); else return nullptr; } - - BattlegroundDS* ToBattlegroundDS() { if (GetBgTypeID(true) == BATTLEGROUND_DS) return reinterpret_cast(this); else return nullptr; } - BattlegroundDS const* ToBattlegroundDS() const { if (GetBgTypeID(true) == BATTLEGROUND_DS) return reinterpret_cast(this); else return nullptr; } - - BattlegroundRV* ToBattlegroundRV() { if (GetBgTypeID(true) == BATTLEGROUND_RV) return reinterpret_cast(this); else return nullptr; } - BattlegroundRV const* ToBattlegroundRV() const { if (GetBgTypeID(true) == BATTLEGROUND_RV) return reinterpret_cast(this); else return nullptr; } - - BattlegroundIC* ToBattlegroundIC() { if (GetBgTypeID(true) == BATTLEGROUND_IC) return reinterpret_cast(this); else return nullptr; } - BattlegroundIC const* ToBattlegroundIC() const { if (GetBgTypeID(true) == BATTLEGROUND_IC) return reinterpret_cast(this); else return nullptr; } - - protected: - // this method is called, when BG cannot spawn its own spirit guide, or something is wrong, It correctly ends Battleground - void EndNow(); - void PlayerAddedToBGCheckIfBGIsRunning(Player* player); - - void _ProcessResurrect(uint32 diff); - void _ProcessProgress(uint32 diff); - void _ProcessLeave(uint32 diff); - void _ProcessJoin(uint32 diff); - void _CheckSafePositions(uint32 diff); - - // Scorekeeping - BattlegroundScoreMap PlayerScores; // Player scores - // must be implemented in BG subclass - virtual void RemovePlayer(Player* /*player*/) {} - - // Player lists, those need to be accessible by inherited classes - BattlegroundPlayerMap m_Players; - // Spirit Guide guid + Player list GUIDS - std::map > m_ReviveQueue; - - // these are important variables used for starting messages - uint8 m_Events; - BattlegroundStartTimeIntervals StartDelayTimes[BG_STARTING_EVENT_COUNT]; - // this must be filled in constructors! - uint32 StartMessageIds[BG_STARTING_EVENT_COUNT]; - - bool m_BuffChange; - bool m_IsRandom; - - BGHonorMode m_HonorMode; - int32 m_TeamScores[BG_TEAMS_COUNT]; - - // pussywizard: - uint32 m_UpdateTimer; - private: - // Battleground - BattlegroundTypeId m_RealTypeID; - BattlegroundTypeId m_RandomTypeID; // TypeID created from Random Battleground list - uint32 m_InstanceID; // Battleground Instance's GUID! - BattlegroundStatus m_Status; - uint32 m_ClientInstanceID; // the instance-id which is sent to the client and without any other internal use - uint32 m_StartTime; - uint32 m_ResetStatTimer; - uint32 m_ValidStartPositionTimer; - int32 m_EndTime; // it is set to 120000 when bg is ending and it decreases itself - uint32 m_LastResurrectTime; - uint8 m_ArenaType; // 2=2v2, 3=3v3, 5=5v5 - bool m_SetDeleteThis; // used for safe deletion of the bg after end / all players leave - bool m_IsArena; - TeamId m_WinnerId; - int32 m_StartDelayTime; - bool m_IsRated; // is this battle rated? - bool m_PrematureCountDown; - uint32 m_PrematureCountDownTimer; - char const* m_Name; - - /* Pre- and post-update hooks */ - - /** - * @brief Pre-update hook. - * - * Will be called before battleground update is started. Depending on - * the result of this call actual update body may be skipped. - * - * @param diff a time difference between two worldserver update loops in - * milliseconds. - * - * @return @c true if update must be performed, @c false otherwise. - * - * @see Update(), PostUpdateImpl(). - */ - virtual bool PreUpdateImpl(uint32 /* diff */) { return true; } - - /** - * @brief Post-update hook. - * - * Will be called after battleground update has passed. May be used to - * implement custom update effects in subclasses. - * - * @param diff a time difference between two worldserver update loops in - * milliseconds. - * - * @see Update(), PreUpdateImpl(). - */ - virtual void PostUpdateImpl(uint32 /* diff */) { } - - // Player lists - std::vector m_ResurrectQueue; // Player GUID - std::deque m_OfflineQueue; // 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 will be changed only when removing already invited player from queue, removing player from battleground and inviting player to BG - // Invited players counters - uint32 m_BgInvitedPlayers[BG_TEAMS_COUNT]; - - // Raid Group - Group* m_BgRaids[BG_TEAMS_COUNT]; // 0 - alliance, 1 - horde - - SpectatorList m_Spectators; - ToBeTeleportedMap m_ToBeTeleported; - - // Players count by team - uint32 m_PlayersCount[BG_TEAMS_COUNT]; - - // Arena team ids by team - uint32 m_ArenaTeamIds[BG_TEAMS_COUNT]; - - int32 m_ArenaTeamRatingChanges[BG_TEAMS_COUNT]; - uint32 m_ArenaTeamMMR[BG_TEAMS_COUNT]; - - // Limits - uint32 m_LevelMin; - uint32 m_LevelMax; - uint32 m_MaxPlayersPerTeam; - uint32 m_MinPlayersPerTeam; - - // Start location - uint32 m_MapId; - BattlegroundMap* m_Map; - float m_TeamStartLocX[BG_TEAMS_COUNT]; - float m_TeamStartLocY[BG_TEAMS_COUNT]; - float m_TeamStartLocZ[BG_TEAMS_COUNT]; - float m_TeamStartLocO[BG_TEAMS_COUNT]; - float m_StartMaxDist; - uint32 ScriptId; + // this function can be used by spell to interact with the BG map + virtual void DoAction(uint32 /*action*/, uint64 /*var*/) {} + + virtual void HandlePlayerResurrect(Player* /*player*/) {} + + // Death related + virtual GraveyardStruct const* GetClosestGraveyard(Player* player); + + virtual void AddPlayer(Player* player); // must be implemented in BG subclass + + void AddOrSetPlayerToCorrectBgGroup(Player* player, TeamId teamId); + + void RemovePlayerAtLeave(Player* player); + // can be extended in in BG subclass + + void HandleTriggerBuff(GameObject* gameObject); + void SetHoliday(bool is_holiday); + + // TODO: make this protected: + typedef std::vector BGObjects; + typedef std::vector BGCreatures; + BGObjects BgObjects; + BGCreatures BgCreatures; + void SpawnBGObject(uint32 type, uint32 respawntime); + bool AddObject(uint32 type, uint32 entry, float x, float y, float z, float o, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime = 0, GOState goState = GO_STATE_READY); + Creature* AddCreature(uint32 entry, uint32 type, float x, float y, float z, float o, uint32 respawntime = 0, MotionTransport* transport = nullptr); + bool DelCreature(uint32 type); + bool DelObject(uint32 type); + bool AddSpiritGuide(uint32 type, float x, float y, float z, float o, TeamId teamId); + int32 GetObjectType(uint64 guid); + + void DoorOpen(uint32 type); + void DoorClose(uint32 type); + //to be removed + const char* GetAcoreString(int32 entry); + + virtual bool HandlePlayerUnderMap(Player* /*player*/) { return false; } + + // since arenas can be AvA or Hvh, we have to get the "temporary" team of a player + static TeamId GetOtherTeamId(TeamId teamId); + bool IsPlayerInBattleground(uint64 guid) const; + + bool ToBeDeleted() const { return m_SetDeleteThis; } + //void SetDeleteThis() { m_SetDeleteThis = true; } + + void RewardXPAtKill(Player* killer, Player* victim); + + virtual uint64 GetFlagPickerGUID(TeamId /*teamId*/ = TEAM_NEUTRAL) const { return 0; } + virtual void SetDroppedFlagGUID(uint64 /*guid*/, TeamId /*teamId*/ = TEAM_NEUTRAL) {} + uint32 GetTeamScore(TeamId teamId) const; + + virtual TeamId GetPrematureWinner(); + + // because BattleGrounds with different types and same level range has different m_BracketId + uint8 GetUniqueBracketId() const; + + BattlegroundAV* ToBattlegroundAV() { if (GetBgTypeID(true) == BATTLEGROUND_AV) return reinterpret_cast(this); else return nullptr; } + BattlegroundAV const* ToBattlegroundAV() const { if (GetBgTypeID(true) == BATTLEGROUND_AV) return reinterpret_cast(this); else return nullptr; } + + BattlegroundWS* ToBattlegroundWS() { if (GetBgTypeID(true) == BATTLEGROUND_WS) return reinterpret_cast(this); else return nullptr; } + BattlegroundWS const* ToBattlegroundWS() const { if (GetBgTypeID(true) == BATTLEGROUND_WS) return reinterpret_cast(this); else return nullptr; } + + BattlegroundAB* ToBattlegroundAB() { if (GetBgTypeID(true) == BATTLEGROUND_AB) return reinterpret_cast(this); else return nullptr; } + BattlegroundAB const* ToBattlegroundAB() const { if (GetBgTypeID(true) == BATTLEGROUND_AB) return reinterpret_cast(this); else return nullptr; } + + BattlegroundNA* ToBattlegroundNA() { if (GetBgTypeID(true) == BATTLEGROUND_NA) return reinterpret_cast(this); else return nullptr; } + BattlegroundNA const* ToBattlegroundNA() const { if (GetBgTypeID(true) == BATTLEGROUND_NA) return reinterpret_cast(this); else return nullptr; } + + BattlegroundBE* ToBattlegroundBE() { if (GetBgTypeID(true) == BATTLEGROUND_BE) return reinterpret_cast(this); else return nullptr; } + BattlegroundBE const* ToBattlegroundBE() const { if (GetBgTypeID(true) == BATTLEGROUND_BE) return reinterpret_cast(this); else return nullptr; } + + BattlegroundEY* ToBattlegroundEY() { if (GetBgTypeID(true) == BATTLEGROUND_EY) return reinterpret_cast(this); else return nullptr; } + BattlegroundEY const* ToBattlegroundEY() const { if (GetBgTypeID(true) == BATTLEGROUND_EY) return reinterpret_cast(this); else return nullptr; } + + BattlegroundRL* ToBattlegroundRL() { if (GetBgTypeID(true) == BATTLEGROUND_RL) return reinterpret_cast(this); else return nullptr; } + BattlegroundRL const* ToBattlegroundRL() const { if (GetBgTypeID(true) == BATTLEGROUND_RL) return reinterpret_cast(this); else return nullptr; } + + BattlegroundSA* ToBattlegroundSA() { if (GetBgTypeID(true) == BATTLEGROUND_SA) return reinterpret_cast(this); else return nullptr; } + BattlegroundSA const* ToBattlegroundSA() const { if (GetBgTypeID(true) == BATTLEGROUND_SA) return reinterpret_cast(this); else return nullptr; } + + BattlegroundDS* ToBattlegroundDS() { if (GetBgTypeID(true) == BATTLEGROUND_DS) return reinterpret_cast(this); else return nullptr; } + BattlegroundDS const* ToBattlegroundDS() const { if (GetBgTypeID(true) == BATTLEGROUND_DS) return reinterpret_cast(this); else return nullptr; } + + BattlegroundRV* ToBattlegroundRV() { if (GetBgTypeID(true) == BATTLEGROUND_RV) return reinterpret_cast(this); else return nullptr; } + BattlegroundRV const* ToBattlegroundRV() const { if (GetBgTypeID(true) == BATTLEGROUND_RV) return reinterpret_cast(this); else return nullptr; } + + BattlegroundIC* ToBattlegroundIC() { if (GetBgTypeID(true) == BATTLEGROUND_IC) return reinterpret_cast(this); else return nullptr; } + BattlegroundIC const* ToBattlegroundIC() const { if (GetBgTypeID(true) == BATTLEGROUND_IC) return reinterpret_cast(this); else return nullptr; } + +protected: + // this method is called, when BG cannot spawn its own spirit guide, or something is wrong, It correctly ends Battleground + void EndNow(); + void PlayerAddedToBGCheckIfBGIsRunning(Player* player); + + void _ProcessResurrect(uint32 diff); + void _ProcessProgress(uint32 diff); + void _ProcessLeave(uint32 diff); + void _ProcessJoin(uint32 diff); + void _CheckSafePositions(uint32 diff); + + // Scorekeeping + BattlegroundScoreMap PlayerScores; // Player scores + // must be implemented in BG subclass + virtual void RemovePlayer(Player* /*player*/) {} + + // Player lists, those need to be accessible by inherited classes + BattlegroundPlayerMap m_Players; + // Spirit Guide guid + Player list GUIDS + std::map > m_ReviveQueue; + + // these are important variables used for starting messages + uint8 m_Events; + BattlegroundStartTimeIntervals StartDelayTimes[BG_STARTING_EVENT_COUNT]; + // this must be filled in constructors! + uint32 StartMessageIds[BG_STARTING_EVENT_COUNT]; + + bool m_BuffChange; + bool m_IsRandom; + + BGHonorMode m_HonorMode; + int32 m_TeamScores[BG_TEAMS_COUNT]; + + // pussywizard: + uint32 m_UpdateTimer; +private: + // Battleground + BattlegroundTypeId m_RealTypeID; + BattlegroundTypeId m_RandomTypeID; // TypeID created from Random Battleground list + uint32 m_InstanceID; // Battleground Instance's GUID! + BattlegroundStatus m_Status; + uint32 m_ClientInstanceID; // the instance-id which is sent to the client and without any other internal use + uint32 m_StartTime; + uint32 m_ResetStatTimer; + uint32 m_ValidStartPositionTimer; + int32 m_EndTime; // it is set to 120000 when bg is ending and it decreases itself + uint32 m_LastResurrectTime; + uint8 m_ArenaType; // 2=2v2, 3=3v3, 5=5v5 + bool m_SetDeleteThis; // used for safe deletion of the bg after end / all players leave + bool m_IsArena; + TeamId m_WinnerId; + int32 m_StartDelayTime; + bool m_IsRated; // is this battle rated? + bool m_PrematureCountDown; + uint32 m_PrematureCountDownTimer; + char const* m_Name; + + /* Pre- and post-update hooks */ + + /** + * @brief Pre-update hook. + * + * Will be called before battleground update is started. Depending on + * the result of this call actual update body may be skipped. + * + * @param diff a time difference between two worldserver update loops in + * milliseconds. + * + * @return @c true if update must be performed, @c false otherwise. + * + * @see Update(), PostUpdateImpl(). + */ + virtual bool PreUpdateImpl(uint32 /* diff */) { return true; } + + /** + * @brief Post-update hook. + * + * Will be called after battleground update has passed. May be used to + * implement custom update effects in subclasses. + * + * @param diff a time difference between two worldserver update loops in + * milliseconds. + * + * @see Update(), PreUpdateImpl(). + */ + virtual void PostUpdateImpl(uint32 /* diff */) { } + + // Player lists + std::vector m_ResurrectQueue; // Player GUID + std::deque m_OfflineQueue; // 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 will be changed only when removing already invited player from queue, removing player from battleground and inviting player to BG + // Invited players counters + uint32 m_BgInvitedPlayers[BG_TEAMS_COUNT]; + + // Raid Group + Group* m_BgRaids[BG_TEAMS_COUNT]; // 0 - alliance, 1 - horde + + SpectatorList m_Spectators; + ToBeTeleportedMap m_ToBeTeleported; + + // Players count by team + uint32 m_PlayersCount[BG_TEAMS_COUNT]; + + // Arena team ids by team + uint32 m_ArenaTeamIds[BG_TEAMS_COUNT]; + + int32 m_ArenaTeamRatingChanges[BG_TEAMS_COUNT]; + uint32 m_ArenaTeamMMR[BG_TEAMS_COUNT]; + + // Limits + uint32 m_LevelMin; + uint32 m_LevelMax; + uint32 m_MaxPlayersPerTeam; + uint32 m_MinPlayersPerTeam; + + // Start location + uint32 m_MapId; + BattlegroundMap* m_Map; + float m_TeamStartLocX[BG_TEAMS_COUNT]; + float m_TeamStartLocY[BG_TEAMS_COUNT]; + float m_TeamStartLocZ[BG_TEAMS_COUNT]; + float m_TeamStartLocO[BG_TEAMS_COUNT]; + float m_StartMaxDist; + uint32 ScriptId; }; #endif diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 8bf8fe798..2d4fe2d80 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -47,7 +47,7 @@ /*********************************************************/ BattlegroundMgr::BattlegroundMgr() : m_ArenaTesting(false), m_Testing(false), - m_lastClientVisibleInstanceId(0), m_NextAutoDistributionTime(0), m_AutoDistributionTimeChecker(0), m_NextPeriodicQueueUpdateTime(5*IN_MILLISECONDS) + m_lastClientVisibleInstanceId(0), m_NextAutoDistributionTime(0), m_AutoDistributionTimeChecker(0), m_NextPeriodicQueueUpdateTime(5 * IN_MILLISECONDS) { for (uint32 qtype = BATTLEGROUND_QUEUE_NONE; qtype < MAX_BATTLEGROUND_QUEUE_TYPES; ++qtype) m_BattlegroundQueues[qtype].SetBgTypeIdAndArenaType(BGTemplateId(BattlegroundQueueTypeId(qtype)), BGArenaType(BattlegroundQueueTypeId(qtype))); @@ -124,7 +124,7 @@ void BattlegroundMgr::Update(uint32 diff) for (uint32 bracket = BG_BRACKET_ID_FIRST; bracket < MAX_BATTLEGROUND_BRACKETS; ++bracket) m_BattlegroundQueues[qtype].BattlegroundQueueUpdate(BattlegroundBracketId(bracket), false, 0); - m_NextPeriodicQueueUpdateTime = 5*IN_MILLISECONDS; + m_NextPeriodicQueueUpdateTime = 5 * IN_MILLISECONDS; } else m_NextPeriodicQueueUpdateTime -= diff; @@ -143,7 +143,7 @@ void BattlegroundMgr::Update(uint32 diff) m_AutoDistributionTimeChecker = 600000; // 10 minutes check } else - m_AutoDistributionTimeChecker -= diff; + m_AutoDistributionTimeChecker -= diff; } } @@ -154,13 +154,13 @@ void BattlegroundMgr::BuildBattlegroundStatusPacket(WorldPacket* data, Battlegro if (StatusID == STATUS_NONE || !bg) { - data->Initialize(SMSG_BATTLEFIELD_STATUS, 4+8); + data->Initialize(SMSG_BATTLEFIELD_STATUS, 4 + 8); *data << uint32(QueueSlot); *data << uint64(0); return; } - data->Initialize(SMSG_BATTLEFIELD_STATUS, (4+8+1+1+4+1+4+4+4)); + data->Initialize(SMSG_BATTLEFIELD_STATUS, (4 + 8 + 1 + 1 + 4 + 1 + 4 + 4 + 4)); *data << uint32(QueueSlot); // The following segment is read as uint64 in client but can be appended as their original type. *data << uint8(arenatype); @@ -203,13 +203,13 @@ void BattlegroundMgr::BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg) { uint8 type = (bg->isArena() ? 1 : 0); - data->Initialize(MSG_PVP_LOG_DATA, (1+1+4+40*bg->GetPlayerScoresSize())); + data->Initialize(MSG_PVP_LOG_DATA, (1 + 1 + 4 + 40 * bg->GetPlayerScoresSize())); *data << uint8(type); // type (battleground=0/arena=1) if (type) // arena { // it seems this must be according to BG_WINNER_A/H and _NOT_ TEAM_A/H - for (TeamId iTeamId = TEAM_ALLIANCE; iTeamId <= TEAM_HORDE; iTeamId = TeamId(iTeamId+1)) + for (TeamId iTeamId = TEAM_ALLIANCE; iTeamId <= TEAM_HORDE; iTeamId = TeamId(iTeamId + 1)) { // Xinef: oryginally this was looping in reverse order, loop order was changed so we have to change checked teamId int32 rating_change = bg->GetArenaTeamRatingChangeForTeam(Battleground::GetOtherTeamId(iTeamId)); @@ -222,10 +222,10 @@ void BattlegroundMgr::BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg) *data << uint32(pointsGained); // Rating gained *data << uint32(MatchmakerRating); // Matchmaking Value } - for (TeamId iTeamId = TEAM_ALLIANCE; iTeamId <= TEAM_HORDE; iTeamId = TeamId(iTeamId+1)) + for (TeamId iTeamId = TEAM_ALLIANCE; iTeamId <= TEAM_HORDE; iTeamId = TeamId(iTeamId + 1)) { if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(bg->GetArenaTeamIdForTeam(Battleground::GetOtherTeamId(iTeamId)))) - *data << at->GetName(); + * data << at->GetName(); else *data << uint8(0); } @@ -362,9 +362,9 @@ void BattlegroundMgr::BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg) break; } // should never happen - if (++scoreCount >= bg->GetMaxPlayersPerTeam()*2 && itr != bg->GetPlayerScoresEnd()) + if (++scoreCount >= bg->GetMaxPlayersPerTeam() * 2 && itr != bg->GetPlayerScoresEnd()) { - sLog->outMisc("Battleground %u scoreboard has more entries (%u) than allowed players in this bg (%u)", bgTypeId, bg->GetPlayerScoresSize(), bg->GetMaxPlayersPerTeam()*2); + sLog->outMisc("Battleground %u scoreboard has more entries (%u) than allowed players in this bg (%u)", bgTypeId, bg->GetPlayerScoresSize(), bg->GetMaxPlayersPerTeam() * 2); break; } } @@ -382,7 +382,7 @@ void BattlegroundMgr::BuildGroupJoinedBattlegroundPacket(WorldPacket* data, Grou void BattlegroundMgr::BuildUpdateWorldStatePacket(WorldPacket* data, uint32 field, uint32 value) { - data->Initialize(SMSG_UPDATE_WORLD_STATE, 4+4); + data->Initialize(SMSG_UPDATE_WORLD_STATE, 4 + 4); *data << uint32(field); *data << uint32(value); } @@ -412,7 +412,7 @@ Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId) BattlegroundContainer::const_iterator itr = m_Battlegrounds.find(instanceId); if (itr != m_Battlegrounds.end()) - return itr->second; + return itr->second; return nullptr; } @@ -446,7 +446,8 @@ Battleground* BattlegroundMgr::CreateNewBattleground(BattlegroundTypeId original Battleground* bg = nullptr; // create a copy of the BG template - if (BattlegroundMgr::bgTypeToTemplate.find(bgTypeId) == BattlegroundMgr::bgTypeToTemplate.end()) { + if (BattlegroundMgr::bgTypeToTemplate.find(bgTypeId) == BattlegroundMgr::bgTypeToTemplate.end()) + { return nullptr; } @@ -572,14 +573,14 @@ void BattlegroundMgr::CreateInitialBattlegrounds() if (data.MaxPlayersPerTeam == 0 || data.MinPlayersPerTeam > data.MaxPlayersPerTeam) { sLog->outError("Table `battleground_template` for id %u has bad values for MinPlayersPerTeam (%u) and MaxPlayersPerTeam(%u)", - data.bgTypeId, data.MinPlayersPerTeam, data.MaxPlayersPerTeam); + data.bgTypeId, data.MinPlayersPerTeam, data.MaxPlayersPerTeam); continue; } if (data.LevelMin == 0 || data.LevelMax == 0 || data.LevelMin > data.LevelMax) { sLog->outError("Table `battleground_template` for id %u has bad values for LevelMin (%u) and LevelMax(%u)", - data.bgTypeId, data.LevelMin, data.LevelMax); + data.bgTypeId, data.LevelMin, data.LevelMax); continue; } @@ -634,8 +635,7 @@ void BattlegroundMgr::CreateInitialBattlegrounds() _battlegroundMapTemplates[bl->mapid[0]] = &_battlegroundTemplates[BattlegroundTypeId(bgTypeId)]; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u battlegrounds in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -655,7 +655,7 @@ void BattlegroundMgr::InitAutomaticArenaPointDistribution() } else m_NextAutoDistributionTime = wstime; - sLog->outString("AzerothCore Battleground: Automatic Arena Point Distribution initialized."); + sLog->outString("AzerothCore Battleground: Automatic Arena Point Distribution initialized."); } void BattlegroundMgr::BuildBattlegroundListPacket(WorldPacket* data, uint64 guid, Player* player, BattlegroundTypeId bgTypeId, uint8 fromWhere) @@ -739,17 +739,19 @@ void BattlegroundMgr::SendAreaSpiritHealerQueryOpcode(Player* player, Battlegrou bool BattlegroundMgr::IsArenaType(BattlegroundTypeId bgTypeId) { return bgTypeId == BATTLEGROUND_AA - || bgTypeId == BATTLEGROUND_BE - || bgTypeId == BATTLEGROUND_NA - || bgTypeId == BATTLEGROUND_DS - || bgTypeId == BATTLEGROUND_RV - || bgTypeId == BATTLEGROUND_RL; + || bgTypeId == BATTLEGROUND_BE + || bgTypeId == BATTLEGROUND_NA + || bgTypeId == BATTLEGROUND_DS + || bgTypeId == BATTLEGROUND_RV + || bgTypeId == BATTLEGROUND_RL; } BattlegroundQueueTypeId BattlegroundMgr::BGQueueTypeId(BattlegroundTypeId bgTypeId, uint8 arenaType) { - if (arenaType) { - switch (arenaType) { + if (arenaType) + { + switch (arenaType) + { case ARENA_TYPE_2v2: return BATTLEGROUND_QUEUE_2v2; case ARENA_TYPE_3v3: @@ -761,7 +763,8 @@ BattlegroundQueueTypeId BattlegroundMgr::BGQueueTypeId(BattlegroundTypeId bgType } } - if (BattlegroundMgr::bgToQueue.find(bgTypeId) == BattlegroundMgr::bgToQueue.end()) { + if (BattlegroundMgr::bgToQueue.find(bgTypeId) == BattlegroundMgr::bgToQueue.end()) + { return BATTLEGROUND_QUEUE_NONE; } @@ -770,7 +773,8 @@ BattlegroundQueueTypeId BattlegroundMgr::BGQueueTypeId(BattlegroundTypeId bgType BattlegroundTypeId BattlegroundMgr::BGTemplateId(BattlegroundQueueTypeId bgQueueTypeId) { - if (BattlegroundMgr::queueToBg.find(bgQueueTypeId) == BattlegroundMgr::queueToBg.end()) { + if (BattlegroundMgr::queueToBg.find(bgQueueTypeId) == BattlegroundMgr::queueToBg.end()) + { return BattlegroundTypeId(0); } @@ -891,8 +895,7 @@ void BattlegroundMgr::LoadBattleMastersEntry() } mBattleMastersMap[entry] = BattlegroundTypeId(bgTypeId); - } - while (result->NextRow()); + } while (result->NextRow()); CheckBattleMasters(); @@ -917,13 +920,20 @@ HolidayIds BattlegroundMgr::BGTypeToWeekendHolidayId(BattlegroundTypeId bgTypeId { switch (bgTypeId) { - case BATTLEGROUND_AV: return HOLIDAY_CALL_TO_ARMS_AV; - case BATTLEGROUND_EY: return HOLIDAY_CALL_TO_ARMS_EY; - case BATTLEGROUND_WS: return HOLIDAY_CALL_TO_ARMS_WS; - case BATTLEGROUND_SA: return HOLIDAY_CALL_TO_ARMS_SA; - case BATTLEGROUND_AB: return HOLIDAY_CALL_TO_ARMS_AB; - case BATTLEGROUND_IC: return HOLIDAY_CALL_TO_ARMS_IC; - default: return HOLIDAY_NONE; + case BATTLEGROUND_AV: + return HOLIDAY_CALL_TO_ARMS_AV; + case BATTLEGROUND_EY: + return HOLIDAY_CALL_TO_ARMS_EY; + case BATTLEGROUND_WS: + return HOLIDAY_CALL_TO_ARMS_WS; + case BATTLEGROUND_SA: + return HOLIDAY_CALL_TO_ARMS_SA; + case BATTLEGROUND_AB: + return HOLIDAY_CALL_TO_ARMS_AB; + case BATTLEGROUND_IC: + return HOLIDAY_CALL_TO_ARMS_IC; + default: + return HOLIDAY_NONE; } } @@ -931,13 +941,20 @@ BattlegroundTypeId BattlegroundMgr::WeekendHolidayIdToBGType(HolidayIds holiday) { switch (holiday) { - case HOLIDAY_CALL_TO_ARMS_AV: return BATTLEGROUND_AV; - case HOLIDAY_CALL_TO_ARMS_EY: return BATTLEGROUND_EY; - case HOLIDAY_CALL_TO_ARMS_WS: return BATTLEGROUND_WS; - case HOLIDAY_CALL_TO_ARMS_SA: return BATTLEGROUND_SA; - case HOLIDAY_CALL_TO_ARMS_AB: return BATTLEGROUND_AB; - case HOLIDAY_CALL_TO_ARMS_IC: return BATTLEGROUND_IC; - default: return BATTLEGROUND_TYPE_NONE; + case HOLIDAY_CALL_TO_ARMS_AV: + return BATTLEGROUND_AV; + case HOLIDAY_CALL_TO_ARMS_EY: + return BATTLEGROUND_EY; + case HOLIDAY_CALL_TO_ARMS_WS: + return BATTLEGROUND_WS; + case HOLIDAY_CALL_TO_ARMS_SA: + return BATTLEGROUND_SA; + case HOLIDAY_CALL_TO_ARMS_AB: + return BATTLEGROUND_AB; + case HOLIDAY_CALL_TO_ARMS_IC: + return BATTLEGROUND_IC; + default: + return BATTLEGROUND_TYPE_NONE; } } @@ -1052,7 +1069,8 @@ void BattlegroundMgr::InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, T // init/update unordered_map // Battlegrounds -std::unordered_map BattlegroundMgr::bgToQueue = { +std::unordered_map BattlegroundMgr::bgToQueue = +{ { BATTLEGROUND_AV, BATTLEGROUND_QUEUE_AV}, { BATTLEGROUND_WS, BATTLEGROUND_QUEUE_WS}, { BATTLEGROUND_AB, BATTLEGROUND_QUEUE_AB}, @@ -1069,7 +1087,8 @@ std::unordered_map BattlegroundMgr::bgToQueue = { { BATTLEGROUND_RV, BattlegroundQueueTypeId(0)}, // Ring of Valor }; -std::unordered_map BattlegroundMgr::queueToBg = { +std::unordered_map BattlegroundMgr::queueToBg = +{ { BATTLEGROUND_QUEUE_NONE, BATTLEGROUND_TYPE_NONE }, { BATTLEGROUND_QUEUE_AV, BATTLEGROUND_AV }, { BATTLEGROUND_QUEUE_WS, BATTLEGROUND_WS }, @@ -1083,7 +1102,8 @@ std::unordered_map BattlegroundMgr::queueToBg = { { BATTLEGROUND_QUEUE_5v5, BATTLEGROUND_AA }, }; -std::unordered_map BattlegroundMgr::bgtypeToBattleground = { +std::unordered_map BattlegroundMgr::bgtypeToBattleground = +{ { BATTLEGROUND_AV, new BattlegroundAV }, { BATTLEGROUND_WS, new BattlegroundWS }, { BATTLEGROUND_AB, new BattlegroundAB }, @@ -1099,29 +1119,31 @@ std::unordered_map BattlegroundMgr::bgtypeToBattleground = { { BATTLEGROUND_RB, new Battleground }, }; -std::unordered_map BattlegroundMgr::bgTypeToTemplate = { - { BATTLEGROUND_AV, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundAV(*(BattlegroundAV*)bg_t); } }, - { BATTLEGROUND_WS, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundWS(*(BattlegroundWS*)bg_t); } }, - { BATTLEGROUND_AB, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundAB(*(BattlegroundAB*)bg_t); } }, - { BATTLEGROUND_NA, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundNA(*(BattlegroundNA*)bg_t); } }, - { BATTLEGROUND_BE, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundBE(*(BattlegroundBE*)bg_t); } }, - { BATTLEGROUND_EY, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundEY(*(BattlegroundEY*)bg_t); } }, - { BATTLEGROUND_RL, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundRL(*(BattlegroundRL*)bg_t); } }, - { BATTLEGROUND_SA, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundSA(*(BattlegroundSA*)bg_t); } }, - { BATTLEGROUND_DS, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundDS(*(BattlegroundDS*)bg_t); } }, - { BATTLEGROUND_RV, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundRV(*(BattlegroundRV*)bg_t); } }, - { BATTLEGROUND_IC, [](Battleground *bg_t) -> Battleground*{ return new BattlegroundIC(*(BattlegroundIC*)bg_t); } }, +std::unordered_map BattlegroundMgr::bgTypeToTemplate = +{ + { BATTLEGROUND_AV, [](Battleground * bg_t) -> Battleground* { return new BattlegroundAV(*(BattlegroundAV*)bg_t); } }, + { BATTLEGROUND_WS, [](Battleground * bg_t) -> Battleground* { return new BattlegroundWS(*(BattlegroundWS*)bg_t); } }, + { BATTLEGROUND_AB, [](Battleground * bg_t) -> Battleground* { return new BattlegroundAB(*(BattlegroundAB*)bg_t); } }, + { BATTLEGROUND_NA, [](Battleground * bg_t) -> Battleground* { return new BattlegroundNA(*(BattlegroundNA*)bg_t); } }, + { BATTLEGROUND_BE, [](Battleground * bg_t) -> Battleground* { return new BattlegroundBE(*(BattlegroundBE*)bg_t); } }, + { BATTLEGROUND_EY, [](Battleground * bg_t) -> Battleground* { return new BattlegroundEY(*(BattlegroundEY*)bg_t); } }, + { BATTLEGROUND_RL, [](Battleground * bg_t) -> Battleground* { return new BattlegroundRL(*(BattlegroundRL*)bg_t); } }, + { BATTLEGROUND_SA, [](Battleground * bg_t) -> Battleground* { return new BattlegroundSA(*(BattlegroundSA*)bg_t); } }, + { BATTLEGROUND_DS, [](Battleground * bg_t) -> Battleground* { return new BattlegroundDS(*(BattlegroundDS*)bg_t); } }, + { BATTLEGROUND_RV, [](Battleground * bg_t) -> Battleground* { return new BattlegroundRV(*(BattlegroundRV*)bg_t); } }, + { BATTLEGROUND_IC, [](Battleground * bg_t) -> Battleground* { return new BattlegroundIC(*(BattlegroundIC*)bg_t); } }, - { BATTLEGROUND_RB, [](Battleground *bg_t) -> Battleground*{ return new Battleground(*bg_t); }, }, - { BATTLEGROUND_AA, [](Battleground *bg_t) -> Battleground*{ return new Battleground(*bg_t); }, }, + { BATTLEGROUND_RB, [](Battleground * bg_t) -> Battleground* { return new Battleground(*bg_t); }, }, + { BATTLEGROUND_AA, [](Battleground * bg_t) -> Battleground* { return new Battleground(*bg_t); }, }, }; std::unordered_map BattlegroundMgr::getBgFromMap = {}; -std::unordered_map BattlegroundMgr::getBgFromTypeID = { +std::unordered_map BattlegroundMgr::getBgFromTypeID = +{ { BATTLEGROUND_RB, - [](WorldPacket* data, Battleground::BattlegroundScoreMap::const_iterator itr2, Battleground* bg) + [](WorldPacket * data, Battleground::BattlegroundScoreMap::const_iterator itr2, Battleground * bg) { if (BattlegroundMgr::getBgFromMap.find(bg->GetMapId()) == BattlegroundMgr::getBgFromMap.end()) // this should not happen { diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.h b/src/server/game/Battlegrounds/BattlegroundMgr.h index b5151e4f9..7c2561c75 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.h +++ b/src/server/game/Battlegrounds/BattlegroundMgr.h @@ -16,7 +16,7 @@ typedef std::map BattlegroundContainer; typedef std::unordered_map BattleMastersMap; -typedef Battleground*(*bgRef)(Battleground*); +typedef Battleground* (*bgRef)(Battleground*); typedef void(*bgMapRef)(WorldPacket*, Battleground::BattlegroundScoreMap::const_iterator); typedef void(*bgTypeRef)(WorldPacket*, Battleground::BattlegroundScoreMap::const_iterator, Battleground*); @@ -50,126 +50,126 @@ struct GroupQueueInfo; class BattlegroundMgr { - private: - BattlegroundMgr(); - ~BattlegroundMgr(); +private: + BattlegroundMgr(); + ~BattlegroundMgr(); - public: - static BattlegroundMgr* instance(); +public: + static BattlegroundMgr* instance(); - void Update(uint32 diff); + void Update(uint32 diff); - /* Packet Building */ - void BuildPlayerJoinedBattlegroundPacket(WorldPacket* data, Player* player); - void BuildPlayerLeftBattlegroundPacket(WorldPacket* data, uint64 guid); - void BuildBattlegroundListPacket(WorldPacket* data, uint64 guid, Player* player, BattlegroundTypeId bgTypeId, uint8 fromWhere); - void BuildGroupJoinedBattlegroundPacket(WorldPacket* data, GroupJoinBattlegroundResult result); - void BuildUpdateWorldStatePacket(WorldPacket* data, uint32 field, uint32 value); - void BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg); - void BuildBattlegroundStatusPacket(WorldPacket* data, Battleground* bg, uint8 queueSlot, uint8 statusId, uint32 time1, uint32 time2, uint8 arenaType, TeamId teamId, bool isRated = false, BattlegroundTypeId forceBgTypeId = BATTLEGROUND_TYPE_NONE); - void BuildPlaySoundPacket(WorldPacket* data, uint32 soundid); - void SendAreaSpiritHealerQueryOpcode(Player* player, Battleground* bg, uint64 guid); + /* Packet Building */ + void BuildPlayerJoinedBattlegroundPacket(WorldPacket* data, Player* player); + void BuildPlayerLeftBattlegroundPacket(WorldPacket* data, uint64 guid); + void BuildBattlegroundListPacket(WorldPacket* data, uint64 guid, Player* player, BattlegroundTypeId bgTypeId, uint8 fromWhere); + void BuildGroupJoinedBattlegroundPacket(WorldPacket* data, GroupJoinBattlegroundResult result); + void BuildUpdateWorldStatePacket(WorldPacket* data, uint32 field, uint32 value); + void BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg); + void BuildBattlegroundStatusPacket(WorldPacket* data, Battleground* bg, uint8 queueSlot, uint8 statusId, uint32 time1, uint32 time2, uint8 arenaType, TeamId teamId, bool isRated = false, BattlegroundTypeId forceBgTypeId = BATTLEGROUND_TYPE_NONE); + void BuildPlaySoundPacket(WorldPacket* data, uint32 soundid); + void SendAreaSpiritHealerQueryOpcode(Player* player, Battleground* bg, uint64 guid); - /* Battlegrounds */ - Battleground* GetBattleground(uint32 InstanceID); - Battleground* GetBattlegroundTemplate(BattlegroundTypeId bgTypeId); - Battleground* CreateNewBattleground(BattlegroundTypeId bgTypeId, uint32 minLevel, uint32 maxLevel, uint8 arenaType, bool isRated); + /* Battlegrounds */ + Battleground* GetBattleground(uint32 InstanceID); + Battleground* GetBattlegroundTemplate(BattlegroundTypeId bgTypeId); + Battleground* CreateNewBattleground(BattlegroundTypeId bgTypeId, uint32 minLevel, uint32 maxLevel, uint8 arenaType, bool isRated); - void AddBattleground(Battleground* bg); - void RemoveBattleground(BattlegroundTypeId bgTypeId, uint32 instanceId); + void AddBattleground(Battleground* bg); + void RemoveBattleground(BattlegroundTypeId bgTypeId, uint32 instanceId); - void CreateInitialBattlegrounds(); - void DeleteAllBattlegrounds(); + void CreateInitialBattlegrounds(); + void DeleteAllBattlegrounds(); - void SendToBattleground(Player* player, uint32 InstanceID, BattlegroundTypeId bgTypeId); + void SendToBattleground(Player* player, uint32 InstanceID, BattlegroundTypeId bgTypeId); - /* Battleground queues */ - BattlegroundQueue& GetBattlegroundQueue(BattlegroundQueueTypeId bgQueueTypeId) { return m_BattlegroundQueues[bgQueueTypeId]; } - void ScheduleArenaQueueUpdate(uint32 arenaRatedTeamId, BattlegroundQueueTypeId bgQueueTypeId, BattlegroundBracketId bracket_id); - uint32 GetPrematureFinishTime() const; + /* Battleground queues */ + BattlegroundQueue& GetBattlegroundQueue(BattlegroundQueueTypeId bgQueueTypeId) { return m_BattlegroundQueues[bgQueueTypeId]; } + void ScheduleArenaQueueUpdate(uint32 arenaRatedTeamId, BattlegroundQueueTypeId bgQueueTypeId, BattlegroundBracketId bracket_id); + uint32 GetPrematureFinishTime() const; - static void InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, TeamId teamId); + static void InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, TeamId teamId); - void ToggleArenaTesting(); - void ToggleTesting(); + void ToggleArenaTesting(); + void ToggleTesting(); - void SetHolidayWeekends(uint32 mask); + void SetHolidayWeekends(uint32 mask); - bool isArenaTesting() const { return m_ArenaTesting; } - bool isTesting() const { return m_Testing; } + bool isArenaTesting() const { return m_ArenaTesting; } + bool isTesting() const { return m_Testing; } - static BattlegroundQueueTypeId BGQueueTypeId(BattlegroundTypeId bgTypeId, uint8 arenaType); - static BattlegroundTypeId BGTemplateId(BattlegroundQueueTypeId bgQueueTypeId); - static bool IsArenaType(BattlegroundTypeId bgTypeId); - static uint8 BGArenaType(BattlegroundQueueTypeId bgQueueTypeId); + static BattlegroundQueueTypeId BGQueueTypeId(BattlegroundTypeId bgTypeId, uint8 arenaType); + static BattlegroundTypeId BGTemplateId(BattlegroundQueueTypeId bgQueueTypeId); + static bool IsArenaType(BattlegroundTypeId bgTypeId); + static uint8 BGArenaType(BattlegroundQueueTypeId bgQueueTypeId); - static HolidayIds BGTypeToWeekendHolidayId(BattlegroundTypeId bgTypeId); - static BattlegroundTypeId WeekendHolidayIdToBGType(HolidayIds holiday); - static bool IsBGWeekend(BattlegroundTypeId bgTypeId); + static HolidayIds BGTypeToWeekendHolidayId(BattlegroundTypeId bgTypeId); + static BattlegroundTypeId WeekendHolidayIdToBGType(HolidayIds holiday); + static bool IsBGWeekend(BattlegroundTypeId bgTypeId); - uint32 GetRatingDiscardTimer() const; - void InitAutomaticArenaPointDistribution(); - void LoadBattleMastersEntry(); - void CheckBattleMasters(); - BattlegroundTypeId GetBattleMasterBG(uint32 entry) const - { - BattleMastersMap::const_iterator itr = mBattleMastersMap.find(entry); - if (itr != mBattleMastersMap.end()) - return itr->second; - return BATTLEGROUND_TYPE_NONE; - } + uint32 GetRatingDiscardTimer() const; + void InitAutomaticArenaPointDistribution(); + void LoadBattleMastersEntry(); + void CheckBattleMasters(); + BattlegroundTypeId GetBattleMasterBG(uint32 entry) const + { + BattleMastersMap::const_iterator itr = mBattleMastersMap.find(entry); + if (itr != mBattleMastersMap.end()) + return itr->second; + return BATTLEGROUND_TYPE_NONE; + } - const BattlegroundContainer& GetBattlegroundList() { return m_Battlegrounds; } // pussywizard + const BattlegroundContainer& GetBattlegroundList() { return m_Battlegrounds; } // pussywizard - static std::unordered_map bgToQueue; // BattlegroundTypeId -> BattlegroundQueueTypeId - static std::unordered_map queueToBg; // BattlegroundQueueTypeId -> BattlegroundTypeId - static std::unordered_map bgtypeToBattleground; // BattlegroundTypeId -> Battleground* - static std::unordered_map bgTypeToTemplate; // BattlegroundTypeId -> bgRef - static std::unordered_map getBgFromMap; // BattlegroundMapID -> bgMapRef - static std::unordered_map getBgFromTypeID; // BattlegroundTypeID -> bgTypeRef + static std::unordered_map bgToQueue; // BattlegroundTypeId -> BattlegroundQueueTypeId + static std::unordered_map queueToBg; // BattlegroundQueueTypeId -> BattlegroundTypeId + static std::unordered_map bgtypeToBattleground; // BattlegroundTypeId -> Battleground* + static std::unordered_map bgTypeToTemplate; // BattlegroundTypeId -> bgRef + static std::unordered_map getBgFromMap; // BattlegroundMapID -> bgMapRef + static std::unordered_map getBgFromTypeID; // BattlegroundTypeID -> bgTypeRef - private: - bool CreateBattleground(CreateBattlegroundData& data); - uint32 GetNextClientVisibleInstanceId(); - BattlegroundTypeId GetRandomBG(BattlegroundTypeId id); +private: + bool CreateBattleground(CreateBattlegroundData& data); + uint32 GetNextClientVisibleInstanceId(); + BattlegroundTypeId GetRandomBG(BattlegroundTypeId id); - typedef std::map BattlegroundTemplateContainer; - BattlegroundTemplateContainer m_BattlegroundTemplates; - BattlegroundContainer m_Battlegrounds; + typedef std::map BattlegroundTemplateContainer; + BattlegroundTemplateContainer m_BattlegroundTemplates; + BattlegroundContainer m_Battlegrounds; - BattlegroundQueue m_BattlegroundQueues[MAX_BATTLEGROUND_QUEUE_TYPES]; + BattlegroundQueue m_BattlegroundQueues[MAX_BATTLEGROUND_QUEUE_TYPES]; - std::vector m_ArenaQueueUpdateScheduler; - bool m_ArenaTesting; - bool m_Testing; - uint32 m_lastClientVisibleInstanceId; - time_t m_NextAutoDistributionTime; - uint32 m_AutoDistributionTimeChecker; - uint32 m_NextPeriodicQueueUpdateTime; - BattleMastersMap mBattleMastersMap; + std::vector m_ArenaQueueUpdateScheduler; + bool m_ArenaTesting; + bool m_Testing; + uint32 m_lastClientVisibleInstanceId; + time_t m_NextAutoDistributionTime; + uint32 m_AutoDistributionTimeChecker; + uint32 m_NextPeriodicQueueUpdateTime; + BattleMastersMap mBattleMastersMap; - CreateBattlegroundData const* GetBattlegroundTemplateByTypeId(BattlegroundTypeId id) - { - BattlegroundTemplateMap::const_iterator itr = _battlegroundTemplates.find(id); - if (itr != _battlegroundTemplates.end()) - return &itr->second; - return nullptr; - } + CreateBattlegroundData const* GetBattlegroundTemplateByTypeId(BattlegroundTypeId id) + { + BattlegroundTemplateMap::const_iterator itr = _battlegroundTemplates.find(id); + if (itr != _battlegroundTemplates.end()) + return &itr->second; + return nullptr; + } - CreateBattlegroundData const* GetBattlegroundTemplateByMapId(uint32 mapId) - { - BattlegroundMapTemplateContainer::const_iterator itr = _battlegroundMapTemplates.find(mapId); - if (itr != _battlegroundMapTemplates.end()) - return itr->second; - return nullptr; - } + CreateBattlegroundData const* GetBattlegroundTemplateByMapId(uint32 mapId) + { + BattlegroundMapTemplateContainer::const_iterator itr = _battlegroundMapTemplates.find(mapId); + if (itr != _battlegroundMapTemplates.end()) + return itr->second; + return nullptr; + } - typedef std::map BattlegroundSelectionWeightMap; + typedef std::map BattlegroundSelectionWeightMap; - typedef std::map BattlegroundTemplateMap; - typedef std::map BattlegroundMapTemplateContainer; - BattlegroundTemplateMap _battlegroundTemplates; - BattlegroundMapTemplateContainer _battlegroundMapTemplates; + typedef std::map BattlegroundTemplateMap; + typedef std::map BattlegroundMapTemplateContainer; + BattlegroundTemplateMap _battlegroundTemplates; + BattlegroundMapTemplateContainer _battlegroundMapTemplates; }; #define sBattlegroundMgr BattlegroundMgr::instance() diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index 79da4c952..140bb8d48 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -42,11 +42,11 @@ BattlegroundQueue::~BattlegroundQueue() m_events.KillAllEvents(false); m_QueuedPlayers.clear(); - for (auto & m_QueuedGroup : m_QueuedGroups) + for (auto& m_QueuedGroup : m_QueuedGroups) { - for (auto & j : m_QueuedGroup) + for (auto& j : m_QueuedGroup) { - for (auto & itr : j) + for (auto& itr : j) delete itr; j.clear(); } @@ -97,7 +97,7 @@ bool BattlegroundQueue::SelectionPool::KickGroup(const uint32 size) } // returns true if added or desired count not yet reached -bool BattlegroundQueue::SelectionPool::AddGroup(GroupQueueInfo * ginfo, uint32 desiredCount) +bool BattlegroundQueue::SelectionPool::AddGroup(GroupQueueInfo* ginfo, uint32 desiredCount) { // add if we don't exceed desiredCount if (!ginfo->IsInvitedToBGInstanceGUID && desiredCount >= PlayerCount + ginfo->Players.size()) @@ -114,7 +114,7 @@ bool BattlegroundQueue::SelectionPool::AddGroup(GroupQueueInfo * ginfo, uint32 d /*********************************************************/ // add group or player (grp == nullptr) to bg queue with the given leader and bg specifications -GroupQueueInfo* BattlegroundQueue::AddGroup(Player * leader, Group * grp, PvPDifficultyEntry const* bracketEntry, bool isRated, bool isPremade, uint32 ArenaRating, uint32 MatchmakerRating, uint32 arenateamid) +GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, PvPDifficultyEntry const* bracketEntry, bool isRated, bool isPremade, uint32 ArenaRating, uint32 MatchmakerRating, uint32 arenateamid) { BattlegroundBracketId bracketId = bracketEntry->GetBracketId(); @@ -190,7 +190,7 @@ GroupQueueInfo* BattlegroundQueue::AddGroup(Player * leader, Group * grp, PvPDif return ginfo; } -void BattlegroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo * ginfo) +void BattlegroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo) { uint32 timeInQueue = std::max(1, getMSTimeDiff(ginfo->JoinTime, World::GetGameTimeMS())); @@ -206,7 +206,7 @@ void BattlegroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo * return; // pointer to last index - uint32 * lastIndex = &m_WaitTimeLastIndex[team_index][ginfo->_bracketId]; + uint32* lastIndex = &m_WaitTimeLastIndex[team_index][ginfo->_bracketId]; // set time at index to new value m_WaitTimes[team_index][ginfo->_bracketId][*lastIndex] = timeInQueue; @@ -216,7 +216,7 @@ void BattlegroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo * (*lastIndex) %= COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME; } -uint32 BattlegroundQueue::GetAverageQueueWaitTime(GroupQueueInfo * ginfo) const +uint32 BattlegroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo) const { // team_index: bg alliance - TEAM_ALLIANCE, bg horde - TEAM_HORDE, arena skirmish - TEAM_ALLIANCE, arena rated - TEAM_HORDE uint8 team_index; @@ -246,7 +246,7 @@ void BattlegroundQueue::RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQu { // pussywizard: leave queue packet if (playerQueueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) - if (Player * p = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + if (Player* p = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) { WorldPacket data; sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, nullptr, playerQueueSlot, STATUS_NONE, 0, 0, 0, TEAM_NEUTRAL); @@ -291,7 +291,7 @@ void BattlegroundQueue::RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQu // if invited to bg, then always decrease invited count when removed from queue // sending player to bg will increase it again if (groupInfo->IsInvitedToBGInstanceGUID) - if (Battleground * bg = sBattlegroundMgr->GetBattleground(groupInfo->IsInvitedToBGInstanceGUID)) + if (Battleground* bg = sBattlegroundMgr->GetBattleground(groupInfo->IsInvitedToBGInstanceGUID)) bg->DecreaseInvitedCount(groupInfo->teamId); // remove player queue info @@ -299,14 +299,14 @@ void BattlegroundQueue::RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQu // announce to world if arena team left queue for rated match, show only once if (groupInfo->ArenaType && groupInfo->IsRated && groupInfo->Players.empty() && sWorld->getBoolConfig(CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE)) - if (ArenaTeam * team = sArenaTeamMgr->GetArenaTeamById(groupInfo->ArenaTeamId)) + if (ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(groupInfo->ArenaTeamId)) sWorld->SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, team->GetName().c_str(), groupInfo->ArenaType, groupInfo->ArenaType, groupInfo->ArenaTeamRating); // if player leaves queue and he is invited to a rated arena match, then count it as he lost if (groupInfo->IsInvitedToBGInstanceGUID && groupInfo->IsRated && !sentToBg) - if (ArenaTeam * at = sArenaTeamMgr->GetArenaTeamById(groupInfo->ArenaTeamId)) + if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(groupInfo->ArenaTeamId)) { - if (Player * player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) at->MemberLost(player, groupInfo->OpponentsMatchmakerRating); at->SaveToDB(); } @@ -325,7 +325,7 @@ void BattlegroundQueue::RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQu { uint32 queueSlot = PLAYER_MAX_BATTLEGROUND_QUEUES; - if (Player * plr = ObjectAccessor::FindPlayerInOrOutOfWorld(*(groupInfo->Players.begin()))) + if (Player* plr = ObjectAccessor::FindPlayerInOrOutOfWorld(*(groupInfo->Players.begin()))) { BattlegroundQueueTypeId bgQueueTypeId = BattlegroundMgr::BGQueueTypeId(groupInfo->BgTypeId, groupInfo->ArenaType); queueSlot = plr->GetBattlegroundQueueIndex(bgQueueTypeId); @@ -337,7 +337,7 @@ void BattlegroundQueue::RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQu } } -void BattlegroundQueue::AddEvent(BasicEvent * Event, uint64 e_time) +void BattlegroundQueue::AddEvent(BasicEvent* Event, uint64 e_time) { m_events.AddEvent(Event, m_events.CalculateTime(e_time)); } @@ -355,7 +355,7 @@ bool BattlegroundQueue::IsPlayerInvited(uint64 pl_guid, const uint32 bgInstanceG return qItr != m_QueuedPlayers.end() && qItr->second->IsInvitedToBGInstanceGUID == bgInstanceGuid && qItr->second->RemoveInviteTime == removeTime; } -bool BattlegroundQueue::GetPlayerGroupInfoData(uint64 guid, GroupQueueInfo * ginfo) +bool BattlegroundQueue::GetPlayerGroupInfoData(uint64 guid, GroupQueueInfo* ginfo) { auto qItr = m_QueuedPlayers.find(guid); if (qItr == m_QueuedPlayers.end()) @@ -377,7 +377,7 @@ void BattlegroundQueue::FillPlayersToBG(Battleground* bg, const int32 aliFree, c // quick check if nothing we can do: if (!sBattlegroundMgr->isTesting()) if ((aliFree > hordeFree && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].empty()) || - (hordeFree > aliFree && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].empty())) + (hordeFree > aliFree && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].empty())) return; // ally: at first fill as much as possible @@ -399,15 +399,15 @@ void BattlegroundQueue::FillPlayersToBG(Battleground* bg, const int32 aliFree, c // check balance configuration and set the max difference between teams switch (invType) { - case BG_QUEUE_INVITATION_TYPE_NO_BALANCE: - return; - case BG_QUEUE_INVITATION_TYPE_BALANCED: - invDiff = 1; - break; - case BG_QUEUE_INVITATION_TYPE_EVEN: - break; - default: - return; + case BG_QUEUE_INVITATION_TYPE_NO_BALANCE: + return; + case BG_QUEUE_INVITATION_TYPE_BALANCED: + invDiff = 1; + break; + case BG_QUEUE_INVITATION_TYPE_EVEN: + break; + default: + return; } // balance the teams based on the difference allowed @@ -454,7 +454,7 @@ void BattlegroundQueue::FillPlayersToBGWithSpecific(Battleground* bg, const int3 // quick check if nothing we can do: if (!sBattlegroundMgr->isTesting()) if ((m_QueuedGroups[thisBracketId][BG_QUEUE_NORMAL_ALLIANCE].empty() && specificQueue->m_QueuedGroups[specificBracketId][BG_QUEUE_NORMAL_ALLIANCE].empty()) || - (m_QueuedGroups[thisBracketId][BG_QUEUE_NORMAL_HORDE].empty() && specificQueue->m_QueuedGroups[specificBracketId][BG_QUEUE_NORMAL_HORDE].empty())) + (m_QueuedGroups[thisBracketId][BG_QUEUE_NORMAL_HORDE].empty() && specificQueue->m_QueuedGroups[specificBracketId][BG_QUEUE_NORMAL_HORDE].empty())) return; // copy groups from both queues to new joined container @@ -482,15 +482,15 @@ void BattlegroundQueue::FillPlayersToBGWithSpecific(Battleground* bg, const int3 // check balance configuration and set the max difference between teams switch (invType) { - case BG_QUEUE_INVITATION_TYPE_NO_BALANCE: - return; - case BG_QUEUE_INVITATION_TYPE_BALANCED: - invDiff = 1; - break; - case BG_QUEUE_INVITATION_TYPE_EVEN: - break; - default: - return; + case BG_QUEUE_INVITATION_TYPE_NO_BALANCE: + return; + case BG_QUEUE_INVITATION_TYPE_BALANCED: + invDiff = 1; + break; + case BG_QUEUE_INVITATION_TYPE_EVEN: + break; + default: + return; } // if free space differs too much, ballance @@ -580,7 +580,7 @@ bool BattlegroundQueue::CheckPremadeMatch(BattlegroundBracketId bracket_id, uint } // this method tries to create battleground or arena with MinPlayersPerTeam against MinPlayersPerTeam -bool BattlegroundQueue::CheckNormalMatch(Battleground * bgTemplate, BattlegroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers) +bool BattlegroundQueue::CheckNormalMatch(Battleground* bgTemplate, BattlegroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers) { uint32 Coef = 1; @@ -596,17 +596,17 @@ bool BattlegroundQueue::CheckNormalMatch(Battleground * bgTemplate, Battleground switch (sWorld->getIntConfig(CONFIG_BATTLEGROUND_INVITATION_TYPE)) { - case BG_QUEUE_INVITATION_TYPE_NO_BALANCE: // in this case, as soon as both teams have > mincount, start - return m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; + case BG_QUEUE_INVITATION_TYPE_NO_BALANCE: // in this case, as soon as both teams have > mincount, start + return m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; - case BG_QUEUE_INVITATION_TYPE_BALANCED: // check difference between selection pools - if = 1 or less start. - return abs(static_cast(m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount()) - static_cast(m_SelectionPools[TEAM_HORDE].GetPlayerCount())) <= 1 && m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; + case BG_QUEUE_INVITATION_TYPE_BALANCED: // check difference between selection pools - if = 1 or less start. + return abs(static_cast(m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount()) - static_cast(m_SelectionPools[TEAM_HORDE].GetPlayerCount())) <= 1 && m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; - case BG_QUEUE_INVITATION_TYPE_EVEN: // if both counts are same then it's an even match - return (m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() == m_SelectionPools[TEAM_HORDE].GetPlayerCount()) && m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; + case BG_QUEUE_INVITATION_TYPE_EVEN: // if both counts are same then it's an even match + return (m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() == m_SelectionPools[TEAM_HORDE].GetPlayerCount()) && m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; - default: // same as unbalanced (in case wrong setting is entered...) - return m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; + default: // same as unbalanced (in case wrong setting is entered...) + return m_SelectionPools[TEAM_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_HORDE].GetPlayerCount() >= minPlayers; } } @@ -693,7 +693,7 @@ void BattlegroundQueue::BattlegroundQueueUpdate(BattlegroundBracketId bracket_id { Battleground* bg = itr.second; if (!BattlegroundMgr::IsArenaType(bg->GetBgTypeID()) && (bg->GetBgTypeID(true) == m_bgTypeId || m_bgTypeId == BATTLEGROUND_RB) && - bg->HasFreeSlots() && bg->GetMinLevel() <= bracketEntry->minLevel && bg->GetMaxLevel() >= bracketEntry->maxLevel) + bg->HasFreeSlots() && bg->GetMinLevel() <= bracketEntry->minLevel && bg->GetMaxLevel() >= bracketEntry->maxLevel) bgsToCheck.insert(bg); } @@ -738,7 +738,7 @@ void BattlegroundQueue::BattlegroundQueueUpdate(BattlegroundBracketId bracket_id // invite players for (uint32 i = 0; i < BG_TEAMS_COUNT; i++) - for (auto & SelectedGroup : m_SelectionPools[TEAM_ALLIANCE + i].SelectedGroups) + for (auto& SelectedGroup : m_SelectionPools[TEAM_ALLIANCE + i].SelectedGroups) BattlegroundMgr::InviteGroupToBG(SelectedGroup, bg, SelectedGroup->teamId); bg->StartBattleground(); @@ -751,7 +751,7 @@ void BattlegroundQueue::BattlegroundQueueUpdate(BattlegroundBracketId bracket_id // invite players for (uint32 i = 0; i < BG_TEAMS_COUNT; i++) - for (auto & SelectedGroup : m_SelectionPools[TEAM_ALLIANCE + i].SelectedGroups) + for (auto& SelectedGroup : m_SelectionPools[TEAM_ALLIANCE + i].SelectedGroups) BattlegroundMgr::InviteGroupToBG(SelectedGroup, bg, SelectedGroup->teamId); } } @@ -760,7 +760,7 @@ void BattlegroundQueue::BattlegroundQueueUpdate(BattlegroundBracketId bracket_id if (!isRated) { if (CheckNormalMatch(bg_template, bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam) || - (bg_template->isArena() && CheckSkirmishForSameFaction(bracket_id, MinPlayersPerTeam))) + (bg_template->isArena() && CheckSkirmishForSameFaction(bracket_id, MinPlayersPerTeam))) { BattlegroundTypeId newBgTypeId = m_bgTypeId; uint32 minLvl = bracketEntry->minLevel; @@ -773,7 +773,7 @@ void BattlegroundQueue::BattlegroundQueueUpdate(BattlegroundBracketId bracket_id // invite players for (uint32 i = 0; i < BG_TEAMS_COUNT; i++) - for (auto & SelectedGroup : m_SelectionPools[TEAM_ALLIANCE + i].SelectedGroups) + for (auto& SelectedGroup : m_SelectionPools[TEAM_ALLIANCE + i].SelectedGroups) BattlegroundMgr::InviteGroupToBG(SelectedGroup, bg, SelectedGroup->teamId); bg->StartBattleground(); @@ -849,24 +849,32 @@ void BattlegroundQueue::BattlegroundQueueUpdate(BattlegroundBracketId bracket_id if (currMSTime - (*itr)->JoinTime >= 20 * MINUTE * IN_MILLISECONDS && (oponentValid < 3 || MMRDiff < minOponentMMRDiff)) // after 20 minutes of waiting, pair with closest mmr, regardless the difference { oponentValid = 3; - minOponentMMRDiff = MMRDiff; oponentItr = itr2; oponentQueue = j; + minOponentMMRDiff = MMRDiff; + oponentItr = itr2; + oponentQueue = j; } else if (MMR1 >= 2000 && MMR2 >= 2000 && longerWaitTime >= 2 * discardTime && (oponentValid < 2 || MMRDiff < minOponentMMRDiff)) // after 6 minutes of waiting, pair any 2000+ vs 2000+ { oponentValid = 2; - minOponentMMRDiff = MMRDiff; oponentItr = itr2; oponentQueue = j; + minOponentMMRDiff = MMRDiff; + oponentItr = itr2; + oponentQueue = j; } else if (oponentValid < 2 && MMRDiff < minOponentMMRDiff) { if (!oponentValid) { - minOponentMMRDiff = MMRDiff; oponentItr = itr2; oponentQueue = j; + minOponentMMRDiff = MMRDiff; + oponentItr = itr2; + oponentQueue = j; if (MMRDiff <= maxAllowedDiff) oponentValid = 1; } if ((MMR1 < 1800 || MMR2 < 1800) && MaxPlayersPerTeam == 2 && MMRDiff <= maxDefaultRatingDifference) // in 2v2 below 1800 mmr - priority for default allowed difference { - minOponentMMRDiff = MMRDiff; oponentItr = itr2; oponentQueue = j; + minOponentMMRDiff = MMRDiff; + oponentItr = itr2; + oponentQueue = j; brk = true; break; } @@ -939,8 +947,8 @@ uint32 BattlegroundQueue::GetPlayersCountInGroupsQueue(BattlegroundBracketId bra uint32 playersCount = 0; for (auto const& itr : m_QueuedGroups[bracketId][bgqueue]) - if (!itr->IsInvitedToBGInstanceGUID) - playersCount += static_cast(itr->Players.size()); + if (!itr->IsInvitedToBGInstanceGUID) + playersCount += static_cast(itr->Players.size()); return playersCount; } @@ -974,7 +982,7 @@ void BattlegroundQueue::SendMessageQueue(Player* leader, Battleground* bg, PvPDi if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY) || (bg->isArena() && !sWorld->getBoolConfig(CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE))) { ChatHandler(leader->GetSession()).PSendSysMessage(LANG_BG_QUEUE_ANNOUNCE_SELF, bgName, q_min_level, q_max_level, - qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0); + qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0); } else if (!bg->isArena()) // Show queue status to server (when joining battleground queue) { @@ -1055,7 +1063,7 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) { // track if player leaves the BG by not clicking enter button if (bg && bg->isBattleground() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS) && - (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)) + (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->setUInt32(0, player->GetGUIDLow()); diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.h b/src/server/game/Battlegrounds/BattlegroundQueue.h index 078dcd15b..70e60e2bc 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.h +++ b/src/server/game/Battlegrounds/BattlegroundQueue.h @@ -51,75 +51,75 @@ enum BattlegroundQueueGroupTypes class Battleground; class BattlegroundQueue { +public: + BattlegroundQueue(); + ~BattlegroundQueue(); + + void BattlegroundQueueUpdate(BattlegroundBracketId bracket_id, bool isRated, uint32 arenaRatedTeamId); + void UpdateEvents(uint32 diff); + + void FillPlayersToBG(Battleground* bg, int32 aliFree, int32 hordeFree, BattlegroundBracketId bracket_id); + void FillPlayersToBGWithSpecific(Battleground* bg, int32 aliFree, int32 hordeFree, BattlegroundBracketId thisBracketId, BattlegroundQueue* specificQueue, BattlegroundBracketId specificBracketId); + bool CheckPremadeMatch(BattlegroundBracketId bracket_id, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam); + bool CheckNormalMatch(Battleground* bgTemplate, BattlegroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers); + bool CheckSkirmishForSameFaction(BattlegroundBracketId bracket_id, uint32 minPlayersPerTeam); + GroupQueueInfo* AddGroup(Player* leader, Group* group, PvPDifficultyEntry const* bracketEntry, bool isRated, bool isPremade, uint32 ArenaRating, uint32 MatchmakerRating, uint32 ArenaTeamId); + void RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQueueSlot); + bool IsPlayerInvitedToRatedArena(uint64 pl_guid); + bool IsPlayerInvited(uint64 pl_guid, uint32 bgInstanceGuid, uint32 removeTime); + bool GetPlayerGroupInfoData(uint64 guid, GroupQueueInfo* ginfo); + void PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo); + uint32 GetAverageQueueWaitTime(GroupQueueInfo* ginfo) const; + uint32 GetPlayersCountInGroupsQueue(BattlegroundBracketId bracketId, BattlegroundQueueGroupTypes bgqueue); + bool IsAllQueuesEmpty(BattlegroundBracketId bracket_id); + void SendMessageQueue(Player* leader, Battleground* bg, PvPDifficultyEntry const* bracketEntry); + + void SetBgTypeIdAndArenaType(BattlegroundTypeId b, uint8 a) { m_bgTypeId = b; m_arenaType = ArenaType(a); } // pussywizard + void AddEvent(BasicEvent* Event, uint64 e_time); + + typedef std::map QueuedPlayersMap; + QueuedPlayersMap m_QueuedPlayers; + + //do NOT use deque because deque.erase() invalidates ALL iterators + typedef std::list GroupsQueueType; + + /* + This two dimensional array is used to store All queued groups + First dimension specifies the bgTypeId + Second dimension specifies the player's group types - + BG_QUEUE_PREMADE_ALLIANCE is used for premade alliance groups and alliance rated arena teams + BG_QUEUE_PREMADE_HORDE is used for premade horde groups and horde rated arena teams + BG_QUEUE_NORMAL_ALLIANCE is used for normal (or small) alliance groups or non-rated arena matches + BG_QUEUE_NORMAL_HORDE is used for normal (or small) horde groups or non-rated arena matches + */ + GroupsQueueType m_QueuedGroups[MAX_BATTLEGROUND_BRACKETS][BG_QUEUE_MAX]; + + // class to select and invite groups to bg + class SelectionPool + { public: - BattlegroundQueue(); - ~BattlegroundQueue(); - - void BattlegroundQueueUpdate(BattlegroundBracketId bracket_id, bool isRated, uint32 arenaRatedTeamId); - void UpdateEvents(uint32 diff); - - void FillPlayersToBG(Battleground* bg, int32 aliFree, int32 hordeFree, BattlegroundBracketId bracket_id); - void FillPlayersToBGWithSpecific(Battleground* bg, int32 aliFree, int32 hordeFree, BattlegroundBracketId thisBracketId, BattlegroundQueue* specificQueue, BattlegroundBracketId specificBracketId); - bool CheckPremadeMatch(BattlegroundBracketId bracket_id, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam); - bool CheckNormalMatch(Battleground* bgTemplate, BattlegroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers); - bool CheckSkirmishForSameFaction(BattlegroundBracketId bracket_id, uint32 minPlayersPerTeam); - GroupQueueInfo* AddGroup(Player* leader, Group* group, PvPDifficultyEntry const* bracketEntry, bool isRated, bool isPremade, uint32 ArenaRating, uint32 MatchmakerRating, uint32 ArenaTeamId); - void RemovePlayer(uint64 guid, bool sentToBg, uint32 playerQueueSlot); - bool IsPlayerInvitedToRatedArena(uint64 pl_guid); - bool IsPlayerInvited(uint64 pl_guid, uint32 bgInstanceGuid, uint32 removeTime); - bool GetPlayerGroupInfoData(uint64 guid, GroupQueueInfo* ginfo); - void PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo); - uint32 GetAverageQueueWaitTime(GroupQueueInfo* ginfo) const; - uint32 GetPlayersCountInGroupsQueue(BattlegroundBracketId bracketId, BattlegroundQueueGroupTypes bgqueue); - bool IsAllQueuesEmpty(BattlegroundBracketId bracket_id); - void SendMessageQueue(Player* leader, Battleground* bg, PvPDifficultyEntry const* bracketEntry); - - void SetBgTypeIdAndArenaType(BattlegroundTypeId b, uint8 a) { m_bgTypeId = b; m_arenaType = ArenaType(a); } // pussywizard - void AddEvent(BasicEvent* Event, uint64 e_time); - - typedef std::map QueuedPlayersMap; - QueuedPlayersMap m_QueuedPlayers; - - //do NOT use deque because deque.erase() invalidates ALL iterators - typedef std::list GroupsQueueType; - - /* - This two dimensional array is used to store All queued groups - First dimension specifies the bgTypeId - Second dimension specifies the player's group types - - BG_QUEUE_PREMADE_ALLIANCE is used for premade alliance groups and alliance rated arena teams - BG_QUEUE_PREMADE_HORDE is used for premade horde groups and horde rated arena teams - BG_QUEUE_NORMAL_ALLIANCE is used for normal (or small) alliance groups or non-rated arena matches - BG_QUEUE_NORMAL_HORDE is used for normal (or small) horde groups or non-rated arena matches - */ - GroupsQueueType m_QueuedGroups[MAX_BATTLEGROUND_BRACKETS][BG_QUEUE_MAX]; - - // class to select and invite groups to bg - class SelectionPool - { - public: - SelectionPool(): PlayerCount(0) {}; - void Init(); - bool AddGroup(GroupQueueInfo* ginfo, uint32 desiredCount); - bool KickGroup(uint32 size); - [[nodiscard]] uint32 GetPlayerCount() const { return PlayerCount; } - public: - GroupsQueueType SelectedGroups; - private: - uint32 PlayerCount; - }; - - //one selection pool for horde, other one for alliance - SelectionPool m_SelectionPools[BG_TEAMS_COUNT]; + SelectionPool(): PlayerCount(0) {}; + void Init(); + bool AddGroup(GroupQueueInfo* ginfo, uint32 desiredCount); + bool KickGroup(uint32 size); + [[nodiscard]] uint32 GetPlayerCount() const { return PlayerCount; } + public: + GroupsQueueType SelectedGroups; private: + uint32 PlayerCount; + }; - BattlegroundTypeId m_bgTypeId; - ArenaType m_arenaType; - uint32 m_WaitTimes[BG_TEAMS_COUNT][MAX_BATTLEGROUND_BRACKETS][COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME]; - uint32 m_WaitTimeLastIndex[BG_TEAMS_COUNT][MAX_BATTLEGROUND_BRACKETS]; + //one selection pool for horde, other one for alliance + SelectionPool m_SelectionPools[BG_TEAMS_COUNT]; +private: - // Event handler - EventProcessor m_events; + BattlegroundTypeId m_bgTypeId; + ArenaType m_arenaType; + uint32 m_WaitTimes[BG_TEAMS_COUNT][MAX_BATTLEGROUND_BRACKETS][COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME]; + uint32 m_WaitTimeLastIndex[BG_TEAMS_COUNT][MAX_BATTLEGROUND_BRACKETS]; + + // Event handler + EventProcessor m_events; }; /* @@ -128,20 +128,20 @@ class BattlegroundQueue */ class BGQueueInviteEvent : public BasicEvent { - public: - BGQueueInviteEvent(uint64 pl_guid, uint32 BgInstanceGUID, BattlegroundTypeId BgTypeId, uint8 arenaType, uint32 removeTime) : - m_PlayerGuid(pl_guid), m_BgInstanceGUID(BgInstanceGUID), m_BgTypeId(BgTypeId), m_ArenaType(arenaType), m_RemoveTime(removeTime) - { } - ~BGQueueInviteEvent() override = default; +public: + BGQueueInviteEvent(uint64 pl_guid, uint32 BgInstanceGUID, BattlegroundTypeId BgTypeId, uint8 arenaType, uint32 removeTime) : + m_PlayerGuid(pl_guid), m_BgInstanceGUID(BgInstanceGUID), m_BgTypeId(BgTypeId), m_ArenaType(arenaType), m_RemoveTime(removeTime) + { } + ~BGQueueInviteEvent() override = default; - bool Execute(uint64 e_time, uint32 p_time) override; - void Abort(uint64 e_time) override; - private: - uint64 m_PlayerGuid; - uint32 m_BgInstanceGUID; - BattlegroundTypeId m_BgTypeId; - uint8 m_ArenaType; - uint32 m_RemoveTime; + bool Execute(uint64 e_time, uint32 p_time) override; + void Abort(uint64 e_time) override; +private: + uint64 m_PlayerGuid; + uint32 m_BgInstanceGUID; + BattlegroundTypeId m_BgTypeId; + uint8 m_ArenaType; + uint32 m_RemoveTime; }; /* @@ -151,20 +151,20 @@ class BGQueueInviteEvent : public BasicEvent */ class BGQueueRemoveEvent : public BasicEvent { - public: - BGQueueRemoveEvent(uint64 pl_guid, uint32 bgInstanceGUID, BattlegroundQueueTypeId bgQueueTypeId, uint32 removeTime) - : m_PlayerGuid(pl_guid), m_BgInstanceGUID(bgInstanceGUID), m_RemoveTime(removeTime), m_BgQueueTypeId(bgQueueTypeId) - {} +public: + BGQueueRemoveEvent(uint64 pl_guid, uint32 bgInstanceGUID, BattlegroundQueueTypeId bgQueueTypeId, uint32 removeTime) + : m_PlayerGuid(pl_guid), m_BgInstanceGUID(bgInstanceGUID), m_RemoveTime(removeTime), m_BgQueueTypeId(bgQueueTypeId) + {} - ~BGQueueRemoveEvent() override = default; + ~BGQueueRemoveEvent() override = default; - bool Execute(uint64 e_time, uint32 p_time) override; - void Abort(uint64 e_time) override; - private: - uint64 m_PlayerGuid; - uint32 m_BgInstanceGUID; - uint32 m_RemoveTime; - BattlegroundQueueTypeId m_BgQueueTypeId; + bool Execute(uint64 e_time, uint32 p_time) override; + void Abort(uint64 e_time) override; +private: + uint64 m_PlayerGuid; + uint32 m_BgInstanceGUID; + uint32 m_RemoveTime; + BattlegroundQueueTypeId m_BgQueueTypeId; }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp index dbd7800df..9aaf0241f 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp @@ -41,7 +41,7 @@ void BattlegroundAB::PostUpdateImpl(uint32 diff) if (GetStatus() == STATUS_IN_PROGRESS) { _bgEvents.Update(diff); - while (uint32 eventId =_bgEvents.ExecuteEvent()) + while (uint32 eventId = _bgEvents.ExecuteEvent()) switch (eventId) { case BG_AB_EVENT_UPDATE_BANNER_STABLE: @@ -56,59 +56,59 @@ void BattlegroundAB::PostUpdateImpl(uint32 diff) case BG_AB_EVENT_CAPTURE_BLACKSMITH: case BG_AB_EVENT_CAPTURE_LUMBERMILL: case BG_AB_EVENT_CAPTURE_GOLDMINE: - { - uint8 node = eventId - BG_AB_EVENT_CAPTURE_STABLE; - TeamId teamId = _capturePointInfo[node]._state == BG_AB_NODE_STATE_ALLY_CONTESTED ? TEAM_ALLIANCE : TEAM_HORDE; - DeleteBanner(node); - _capturePointInfo[node]._ownerTeamId = teamId; - _capturePointInfo[node]._state = teamId == TEAM_ALLIANCE ? BG_AB_NODE_STATE_ALLY_OCCUPIED : BG_AB_NODE_STATE_HORDE_OCCUPIED; - _capturePointInfo[node]._captured = true; - - CreateBanner(node, false); - NodeOccupied(node); - SendNodeUpdate(node); - - SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, teamId == TEAM_ALLIANCE ? CHAT_MSG_BG_SYSTEM_ALLIANCE : CHAT_MSG_BG_SYSTEM_HORDE, nullptr, teamId == TEAM_ALLIANCE ? LANG_BG_AB_ALLY : LANG_BG_AB_HORDE, LANG_BG_AB_NODE_STABLES + node); - PlaySoundToAll(teamId == TEAM_ALLIANCE ? BG_AB_SOUND_NODE_CAPTURED_ALLIANCE : BG_AB_SOUND_NODE_CAPTURED_HORDE); - break; - } - case BG_AB_EVENT_ALLIANCE_TICK: - case BG_AB_EVENT_HORDE_TICK: - { - auto teamId = TeamId(eventId - BG_AB_EVENT_ALLIANCE_TICK); - uint8 controlledPoints = _controlledPoints[teamId]; - if (controlledPoints == 0) { - _bgEvents.ScheduleEvent(eventId, 3000); + uint8 node = eventId - BG_AB_EVENT_CAPTURE_STABLE; + TeamId teamId = _capturePointInfo[node]._state == BG_AB_NODE_STATE_ALLY_CONTESTED ? TEAM_ALLIANCE : TEAM_HORDE; + DeleteBanner(node); + _capturePointInfo[node]._ownerTeamId = teamId; + _capturePointInfo[node]._state = teamId == TEAM_ALLIANCE ? BG_AB_NODE_STATE_ALLY_OCCUPIED : BG_AB_NODE_STATE_HORDE_OCCUPIED; + _capturePointInfo[node]._captured = true; + + CreateBanner(node, false); + NodeOccupied(node); + SendNodeUpdate(node); + + SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, teamId == TEAM_ALLIANCE ? CHAT_MSG_BG_SYSTEM_ALLIANCE : CHAT_MSG_BG_SYSTEM_HORDE, nullptr, teamId == TEAM_ALLIANCE ? LANG_BG_AB_ALLY : LANG_BG_AB_HORDE, LANG_BG_AB_NODE_STABLES + node); + PlaySoundToAll(teamId == TEAM_ALLIANCE ? BG_AB_SOUND_NODE_CAPTURED_ALLIANCE : BG_AB_SOUND_NODE_CAPTURED_HORDE); break; } - - auto honorRewards = uint8(m_TeamScores[teamId] / _honorTics); - auto reputationRewards = uint8(m_TeamScores[teamId] / _reputationTics); - auto information = uint8(m_TeamScores[teamId] / BG_AB_WARNING_NEAR_VICTORY_SCORE); - m_TeamScores[teamId] += BG_AB_TickPoints[controlledPoints]; - if (m_TeamScores[teamId] > BG_AB_MAX_TEAM_SCORE) - m_TeamScores[teamId] = BG_AB_MAX_TEAM_SCORE; - - if (honorRewards < uint8(m_TeamScores[teamId] / _honorTics)) - RewardHonorToTeam(GetBonusHonorFromKill(1), teamId); - if (reputationRewards < uint8(m_TeamScores[teamId] / _reputationTics)) - RewardReputationToTeam(teamId == TEAM_ALLIANCE ? 509 : 510, 10, teamId); - if (information < uint8(m_TeamScores[teamId] / BG_AB_WARNING_NEAR_VICTORY_SCORE)) + case BG_AB_EVENT_ALLIANCE_TICK: + case BG_AB_EVENT_HORDE_TICK: { - SendMessageToAll(teamId == TEAM_ALLIANCE ? LANG_BG_AB_A_NEAR_VICTORY : LANG_BG_AB_H_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL); - PlaySoundToAll(BG_AB_SOUND_NEAR_VICTORY); + auto teamId = TeamId(eventId - BG_AB_EVENT_ALLIANCE_TICK); + uint8 controlledPoints = _controlledPoints[teamId]; + if (controlledPoints == 0) + { + _bgEvents.ScheduleEvent(eventId, 3000); + break; + } + + auto honorRewards = uint8(m_TeamScores[teamId] / _honorTics); + auto reputationRewards = uint8(m_TeamScores[teamId] / _reputationTics); + auto information = uint8(m_TeamScores[teamId] / BG_AB_WARNING_NEAR_VICTORY_SCORE); + m_TeamScores[teamId] += BG_AB_TickPoints[controlledPoints]; + if (m_TeamScores[teamId] > BG_AB_MAX_TEAM_SCORE) + m_TeamScores[teamId] = BG_AB_MAX_TEAM_SCORE; + + if (honorRewards < uint8(m_TeamScores[teamId] / _honorTics)) + RewardHonorToTeam(GetBonusHonorFromKill(1), teamId); + if (reputationRewards < uint8(m_TeamScores[teamId] / _reputationTics)) + RewardReputationToTeam(teamId == TEAM_ALLIANCE ? 509 : 510, 10, teamId); + if (information < uint8(m_TeamScores[teamId] / BG_AB_WARNING_NEAR_VICTORY_SCORE)) + { + SendMessageToAll(teamId == TEAM_ALLIANCE ? LANG_BG_AB_A_NEAR_VICTORY : LANG_BG_AB_H_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL); + PlaySoundToAll(BG_AB_SOUND_NEAR_VICTORY); + } + + UpdateWorldState(teamId == TEAM_ALLIANCE ? BG_AB_OP_RESOURCES_ALLY : BG_AB_OP_RESOURCES_HORDE, m_TeamScores[teamId]); + if (m_TeamScores[teamId] > m_TeamScores[GetOtherTeamId(teamId)] + 500) + _teamScores500Disadvantage[GetOtherTeamId(teamId)] = true; + if (m_TeamScores[teamId] >= BG_AB_MAX_TEAM_SCORE) + EndBattleground(teamId); + + _bgEvents.ScheduleEvent(eventId, BG_AB_TickIntervals[controlledPoints]); + break; } - - UpdateWorldState(teamId == TEAM_ALLIANCE ? BG_AB_OP_RESOURCES_ALLY : BG_AB_OP_RESOURCES_HORDE, m_TeamScores[teamId]); - if (m_TeamScores[teamId] > m_TeamScores[GetOtherTeamId(teamId)] + 500) - _teamScores500Disadvantage[GetOtherTeamId(teamId)] = true; - if (m_TeamScores[teamId] >= BG_AB_MAX_TEAM_SCORE) - EndBattleground(teamId); - - _bgEvents.ScheduleEvent(eventId, BG_AB_TickIntervals[controlledPoints]); - break; - } default: break; } @@ -193,29 +193,29 @@ void BattlegroundAB::CreateBanner(uint8 node, bool delay) // Just put it into the queue if (delay) { - _bgEvents.RescheduleEvent(BG_AB_EVENT_UPDATE_BANNER_STABLE+node, BG_AB_BANNER_UPDATE_TIME); + _bgEvents.RescheduleEvent(BG_AB_EVENT_UPDATE_BANNER_STABLE + node, BG_AB_BANNER_UPDATE_TIME); return; } - SpawnBGObject(node*BG_AB_OBJECTS_PER_NODE + _capturePointInfo[node]._state, RESPAWN_IMMEDIATELY); - SpawnBGObject(node*BG_AB_OBJECTS_PER_NODE + BG_AB_OBJECT_AURA_ALLY + _capturePointInfo[node]._ownerTeamId, RESPAWN_IMMEDIATELY); + SpawnBGObject(node * BG_AB_OBJECTS_PER_NODE + _capturePointInfo[node]._state, RESPAWN_IMMEDIATELY); + SpawnBGObject(node * BG_AB_OBJECTS_PER_NODE + BG_AB_OBJECT_AURA_ALLY + _capturePointInfo[node]._ownerTeamId, RESPAWN_IMMEDIATELY); } void BattlegroundAB::DeleteBanner(uint8 node) { - SpawnBGObject(node*BG_AB_OBJECTS_PER_NODE + _capturePointInfo[node]._state, RESPAWN_ONE_DAY); - SpawnBGObject(node*BG_AB_OBJECTS_PER_NODE + BG_AB_OBJECT_AURA_ALLY + _capturePointInfo[node]._ownerTeamId, RESPAWN_ONE_DAY); + SpawnBGObject(node * BG_AB_OBJECTS_PER_NODE + _capturePointInfo[node]._state, RESPAWN_ONE_DAY); + SpawnBGObject(node * BG_AB_OBJECTS_PER_NODE + BG_AB_OBJECT_AURA_ALLY + _capturePointInfo[node]._ownerTeamId, RESPAWN_ONE_DAY); } void BattlegroundAB::FillInitialWorldStates(WorldPacket& data) { - for (auto & node : _capturePointInfo) + for (auto& node : _capturePointInfo) { if (node._state == BG_AB_NODE_STATE_NEUTRAL) data << uint32(node._iconNone) << uint32(1); for (uint8 i = BG_AB_NODE_STATE_ALLY_OCCUPIED; i <= BG_AB_NODE_STATE_HORDE_CONTESTED; ++i) - data << uint32(node._iconCapture + i-1) << uint32(node._state == i); + data << uint32(node._iconCapture + i - 1) << uint32(node._state == i); } data << uint32(BG_AB_OP_OCCUPIED_BASES_ALLY) << uint32(_controlledPoints[TEAM_ALLIANCE]); @@ -231,7 +231,7 @@ void BattlegroundAB::SendNodeUpdate(uint8 node) { UpdateWorldState(_capturePointInfo[node]._iconNone, 0); for (uint8 i = BG_AB_NODE_STATE_ALLY_OCCUPIED; i <= BG_AB_NODE_STATE_HORDE_CONTESTED; ++i) - UpdateWorldState(_capturePointInfo[node]._iconCapture + i-1, _capturePointInfo[node]._state == i); + UpdateWorldState(_capturePointInfo[node]._iconCapture + i - 1, _capturePointInfo[node]._state == i); UpdateWorldState(BG_AB_OP_OCCUPIED_BASES_ALLY, _controlledPoints[TEAM_ALLIANCE]); UpdateWorldState(BG_AB_OP_OCCUPIED_BASES_HORDE, _controlledPoints[TEAM_HORDE]); @@ -280,9 +280,9 @@ void BattlegroundAB::EventPlayerClickedOnFlag(Player* player, GameObject* gameOb if (player->GetDistance2d(BG_AB_NodePositions[node][0], BG_AB_NodePositions[node][1]) < 10.0f) break; - if (node == BG_AB_DYNAMIC_NODES_COUNT || _capturePointInfo[node]._ownerTeamId == player->GetTeamId() || - (_capturePointInfo[node]._state == BG_AB_NODE_STATE_ALLY_CONTESTED && player->GetTeamId() == TEAM_ALLIANCE) || - (_capturePointInfo[node]._state == BG_AB_NODE_STATE_HORDE_CONTESTED && player->GetTeamId() == TEAM_HORDE)) + if (node == BG_AB_DYNAMIC_NODES_COUNT || _capturePointInfo[node]._ownerTeamId == player->GetTeamId() || + (_capturePointInfo[node]._state == BG_AB_NODE_STATE_ALLY_CONTESTED && player->GetTeamId() == TEAM_ALLIANCE) || + (_capturePointInfo[node]._state == BG_AB_NODE_STATE_HORDE_CONTESTED && player->GetTeamId() == TEAM_HORDE)) return; player->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); @@ -356,14 +356,14 @@ bool BattlegroundAB::SetupBattleground() { for (uint32 i = 0; i < BG_AB_DYNAMIC_NODES_COUNT; ++i) { - AddObject(BG_AB_OBJECT_BANNER_NEUTRAL + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_NODE_BANNER_0 + i, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_BANNER_ALLY + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_BANNER_A, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_BANNER_HORDE + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_BANNER_H, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_BANNER_CONT_A + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_BANNER_CONT_A, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_BANNER_CONT_H + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_BANNER_CONT_H, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_AURA_ALLY + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_AURA_A, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_AURA_HORDE + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_AURA_H, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_AURA_CONTESTED + BG_AB_OBJECTS_PER_NODE*i, BG_AB_OBJECTID_AURA_C, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3]/2), cos(BG_AB_NodePositions[i][3]/2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_BANNER_NEUTRAL + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_NODE_BANNER_0 + i, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_BANNER_ALLY + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_BANNER_A, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_BANNER_HORDE + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_BANNER_H, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_BANNER_CONT_A + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_BANNER_CONT_A, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_BANNER_CONT_H + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_BANNER_CONT_H, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_AURA_ALLY + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_AURA_A, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_AURA_HORDE + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_AURA_H, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_AURA_CONTESTED + BG_AB_OBJECTS_PER_NODE * i, BG_AB_OBJECTID_AURA_C, BG_AB_NodePositions[i][0], BG_AB_NodePositions[i][1], BG_AB_NodePositions[i][2], BG_AB_NodePositions[i][3], 0, 0, sin(BG_AB_NodePositions[i][3] / 2), cos(BG_AB_NodePositions[i][3] / 2), RESPAWN_ONE_DAY); } AddObject(BG_AB_OBJECT_GATE_A, BG_AB_OBJECTID_GATE_A, BG_AB_DoorPositions[0][0], BG_AB_DoorPositions[0][1], BG_AB_DoorPositions[0][2], BG_AB_DoorPositions[0][3], BG_AB_DoorPositions[0][4], BG_AB_DoorPositions[0][5], BG_AB_DoorPositions[0][6], BG_AB_DoorPositions[0][7], RESPAWN_IMMEDIATELY); @@ -371,9 +371,9 @@ bool BattlegroundAB::SetupBattleground() for (uint32 i = 0; i < BG_AB_DYNAMIC_NODES_COUNT; ++i) { - AddObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + 3 * i, Buff_Entries[0], BG_AB_BuffPositions[i][0], BG_AB_BuffPositions[i][1], BG_AB_BuffPositions[i][2], BG_AB_BuffPositions[i][3], 0, 0, sin(BG_AB_BuffPositions[i][3]/2), cos(BG_AB_BuffPositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + 3 * i + 1, Buff_Entries[1], BG_AB_BuffPositions[i][0], BG_AB_BuffPositions[i][1], BG_AB_BuffPositions[i][2], BG_AB_BuffPositions[i][3], 0, 0, sin(BG_AB_BuffPositions[i][3]/2), cos(BG_AB_BuffPositions[i][3]/2), RESPAWN_ONE_DAY); - AddObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + 3 * i + 2, Buff_Entries[2], BG_AB_BuffPositions[i][0], BG_AB_BuffPositions[i][1], BG_AB_BuffPositions[i][2], BG_AB_BuffPositions[i][3], 0, 0, sin(BG_AB_BuffPositions[i][3]/2), cos(BG_AB_BuffPositions[i][3]/2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + 3 * i, Buff_Entries[0], BG_AB_BuffPositions[i][0], BG_AB_BuffPositions[i][1], BG_AB_BuffPositions[i][2], BG_AB_BuffPositions[i][3], 0, 0, sin(BG_AB_BuffPositions[i][3] / 2), cos(BG_AB_BuffPositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + 3 * i + 1, Buff_Entries[1], BG_AB_BuffPositions[i][0], BG_AB_BuffPositions[i][1], BG_AB_BuffPositions[i][2], BG_AB_BuffPositions[i][3], 0, 0, sin(BG_AB_BuffPositions[i][3] / 2), cos(BG_AB_BuffPositions[i][3] / 2), RESPAWN_ONE_DAY); + AddObject(BG_AB_OBJECT_SPEEDBUFF_STABLES + 3 * i + 2, Buff_Entries[2], BG_AB_BuffPositions[i][0], BG_AB_BuffPositions[i][1], BG_AB_BuffPositions[i][2], BG_AB_BuffPositions[i][3], 0, 0, sin(BG_AB_BuffPositions[i][3] / 2), cos(BG_AB_BuffPositions[i][3] / 2), RESPAWN_ONE_DAY); } AddSpiritGuide(BG_AB_SPIRIT_ALIANCE, BG_AB_SpiritGuidePos[BG_AB_SPIRIT_ALIANCE][0], BG_AB_SpiritGuidePos[BG_AB_SPIRIT_ALIANCE][1], BG_AB_SpiritGuidePos[BG_AB_SPIRIT_ALIANCE][2], BG_AB_SpiritGuidePos[BG_AB_SPIRIT_ALIANCE][3], TEAM_ALLIANCE); @@ -434,14 +434,14 @@ GraveyardStruct const* BattlegroundAB::GetClosestGraveyard(Player* player) float pX = player->GetPositionX(); float pY = player->GetPositionY(); - float dist = (entry->x - pX)*(entry->x - pX)+(entry->y - pY)*(entry->y - pY); + float dist = (entry->x - pX) * (entry->x - pX) + (entry->y - pY) * (entry->y - pY); float minDist = dist; for (uint8 i = BG_AB_NODE_STABLES; i < BG_AB_DYNAMIC_NODES_COUNT; ++i) if (_capturePointInfo[i]._ownerTeamId == player->GetTeamId()) { entry = sGraveyard->GetGraveyard(BG_AB_GraveyardIds[i]); - dist = (entry->x - pX)*(entry->x - pX) + (entry->y - pY)*(entry->y - pY); + dist = (entry->x - pX) * (entry->x - pX) + (entry->y - pY) * (entry->y - pY); if (dist < minDist) { minDist = dist; @@ -484,7 +484,7 @@ void BattlegroundAB::ApplyPhaseMask() uint32 phaseMask = 1; for (uint32 i = BG_AB_NODE_STABLES; i < BG_AB_DYNAMIC_NODES_COUNT; ++i) if (_capturePointInfo[i]._ownerTeamId != TEAM_NEUTRAL) - phaseMask |= 1 << (i*2+1 + _capturePointInfo[i]._ownerTeamId); + phaseMask |= 1 << (i * 2 + 1 + _capturePointInfo[i]._ownerTeamId); const BattlegroundPlayerMap& bgPlayerMap = GetPlayers(); for (auto itr : bgPlayerMap) diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.h b/src/server/game/Battlegrounds/Zones/BattlegroundAB.h index 6d2603142..7b49ff0f7 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.h @@ -171,8 +171,8 @@ enum BG_AB_Misc BG_AB_BANNER_UPDATE_TIME = 2000 }; -const uint32 BG_AB_TickIntervals[BG_AB_DYNAMIC_NODES_COUNT+1] = {0, 12000, 9000, 6000, 3000, 1000}; -const uint32 BG_AB_TickPoints[BG_AB_DYNAMIC_NODES_COUNT+1] = {0, 10, 10, 10, 10, 30}; +const uint32 BG_AB_TickIntervals[BG_AB_DYNAMIC_NODES_COUNT + 1] = {0, 12000, 9000, 6000, 3000, 1000}; +const uint32 BG_AB_TickPoints[BG_AB_DYNAMIC_NODES_COUNT + 1] = {0, 10, 10, 10, 10, 30}; const uint32 BG_AB_GraveyardIds[BG_AB_ALL_NODES_COUNT] = {895, 894, 893, 897, 896, 898, 899}; const float BG_AB_BuffPositions[BG_AB_DYNAMIC_NODES_COUNT][4] = @@ -223,58 +223,58 @@ struct BattlegroundABScore : public BattlegroundScore class BattlegroundAB : public Battleground { - public: - BattlegroundAB(); - ~BattlegroundAB() override; +public: + BattlegroundAB(); + ~BattlegroundAB() override; - void AddPlayer(Player* player) override; - void StartingEventCloseDoors() override; - void StartingEventOpenDoors() override; - void RemovePlayer(Player* player) override; - void HandleAreaTrigger(Player* player, uint32 trigger) override; - bool SetupBattleground() override; - void Init() override; - void EndBattleground(TeamId winnerTeamId) override; - GraveyardStruct const* GetClosestGraveyard(Player* player) override; + void AddPlayer(Player* player) override; + void StartingEventCloseDoors() override; + void StartingEventOpenDoors() override; + void RemovePlayer(Player* player) override; + void HandleAreaTrigger(Player* player, uint32 trigger) override; + bool SetupBattleground() override; + void Init() override; + void EndBattleground(TeamId winnerTeamId) override; + GraveyardStruct const* GetClosestGraveyard(Player* player) override; - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true) override; - void FillInitialWorldStates(WorldPacket& data) override; - void EventPlayerClickedOnFlag(Player* source, GameObject* gameObject) override; + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true) override; + void FillInitialWorldStates(WorldPacket& data) override; + void EventPlayerClickedOnFlag(Player* source, GameObject* gameObject) override; - bool AllNodesConrolledByTeam(TeamId teamId) const override; - bool IsTeamScores500Disadvantage(TeamId teamId) const { return _teamScores500Disadvantage[teamId]; } - - TeamId GetPrematureWinner() override; - private: - void PostUpdateImpl(uint32 diff) override; + bool AllNodesConrolledByTeam(TeamId teamId) const override; + bool IsTeamScores500Disadvantage(TeamId teamId) const { return _teamScores500Disadvantage[teamId]; } - void DeleteBanner(uint8 node); - void CreateBanner(uint8 node, bool delay); - void SendNodeUpdate(uint8 node); - void NodeOccupied(uint8 node); - void NodeDeoccupied(uint8 node); - void ApplyPhaseMask(); + TeamId GetPrematureWinner() override; +private: + void PostUpdateImpl(uint32 diff) override; - struct CapturePointInfo + void DeleteBanner(uint8 node); + void CreateBanner(uint8 node, bool delay); + void SendNodeUpdate(uint8 node); + void NodeOccupied(uint8 node); + void NodeDeoccupied(uint8 node); + void ApplyPhaseMask(); + + struct CapturePointInfo + { + CapturePointInfo() : _ownerTeamId(TEAM_NEUTRAL), _iconNone(0), _iconCapture(0), _state(BG_AB_NODE_STATE_NEUTRAL), _captured(false) { - CapturePointInfo() : _ownerTeamId(TEAM_NEUTRAL), _iconNone(0), _iconCapture(0), _state(BG_AB_NODE_STATE_NEUTRAL), _captured(false) - { - } + } - TeamId _ownerTeamId; - uint32 _iconNone; - uint32 _iconCapture; - uint8 _state; + TeamId _ownerTeamId; + uint32 _iconNone; + uint32 _iconCapture; + uint8 _state; - bool _captured; - }; + bool _captured; + }; - CapturePointInfo _capturePointInfo[BG_AB_DYNAMIC_NODES_COUNT]; - EventMap _bgEvents; - uint32 _honorTics; - uint32 _reputationTics; - uint8 _controlledPoints[BG_TEAMS_COUNT]{}; - bool _teamScores500Disadvantage[BG_TEAMS_COUNT]{}; + CapturePointInfo _capturePointInfo[BG_AB_DYNAMIC_NODES_COUNT]; + EventMap _bgEvents; + uint32 _honorTics; + uint32 _reputationTics; + uint8 _controlledPoints[BG_TEAMS_COUNT] {}; + bool _teamScores500Disadvantage[BG_TEAMS_COUNT] {}; }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp index 9d3fedcd4..b3c28aefa 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp @@ -20,7 +20,7 @@ BattlegroundAV::BattlegroundAV() { BgObjects.resize(BG_AV_OBJECT_MAX); - BgCreatures.resize(AV_CPLACE_MAX+AV_STATICCPLACE_MAX); + BgCreatures.resize(AV_CPLACE_MAX + AV_STATICCPLACE_MAX); for (uint8 i = 0; i < 2; i++) { @@ -100,13 +100,13 @@ void BattlegroundAV::HandleKillUnit(Creature* unit, Player* killer) sLog->outError("Killed a Captain twice, please report this bug, if you haven't done \".respawn\""); return; } - m_CaptainAlive[0]=false; + m_CaptainAlive[0] = false; RewardReputationToTeam(729, BG_AV_REP_CAPTAIN, TEAM_HORDE); RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_CAPTAIN), TEAM_HORDE); UpdateScore(TEAM_ALLIANCE, (-1)*BG_AV_RES_CAPTAIN); //spawn destroyed aura - for (uint8 i=0; i <= 9; i++) - SpawnBGObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE+i, RESPAWN_IMMEDIATELY); + for (uint8 i = 0; i <= 9; i++) + SpawnBGObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE + i, RESPAWN_IMMEDIATELY); Creature* creature = GetBGCreature(AV_CPLACE_HERALD); if (creature) YellToAll(creature, GetAcoreString(LANG_BG_AV_A_CAPTAIN_DEAD), LANG_UNIVERSAL); @@ -119,13 +119,13 @@ void BattlegroundAV::HandleKillUnit(Creature* unit, Player* killer) sLog->outError("Killed a Captain twice, please report this bug, if you haven't done \".respawn\""); return; } - m_CaptainAlive[1]=false; + m_CaptainAlive[1] = false; RewardReputationToTeam(730, BG_AV_REP_CAPTAIN, TEAM_ALLIANCE); RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_CAPTAIN), TEAM_ALLIANCE); UpdateScore(TEAM_HORDE, (-1)*BG_AV_RES_CAPTAIN); //spawn destroyed aura - for (uint8 i=0; i <= 9; i++) - SpawnBGObject(BG_AV_OBJECT_BURN_BUILDING_HORDE+i, RESPAWN_IMMEDIATELY); + for (uint8 i = 0; i <= 9; i++) + SpawnBGObject(BG_AV_OBJECT_BURN_BUILDING_HORDE + i, RESPAWN_IMMEDIATELY); Creature* creature = GetBGCreature(AV_CPLACE_HERALD); if (creature) YellToAll(creature, GetAcoreString(LANG_BG_AV_H_CAPTAIN_DEAD), LANG_UNIVERSAL); @@ -152,7 +152,7 @@ void BattlegroundAV::HandleQuestComplete(uint32 questid, Player* player) case AV_QUEST_A_SCRAPS2: case AV_QUEST_H_SCRAPS1: case AV_QUEST_H_SCRAPS2: - m_Team_QuestStatus[teamId][0]+=20; + m_Team_QuestStatus[teamId][0] += 20; if (m_Team_QuestStatus[teamId][0] == 500 || m_Team_QuestStatus[teamId][0] == 1000 || m_Team_QuestStatus[teamId][0] == 1500) //25, 50, 75 turn ins { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) @@ -163,8 +163,8 @@ void BattlegroundAV::HandleQuestComplete(uint32 questid, Player* player) { DePopulateNode(i); PopulateNode(i); - //maybe this is bad, because it will instantly respawn all creatures on every grave.. - } + //maybe this is bad, because it will instantly respawn all creatures on every grave.. + } } break; case AV_QUEST_A_COMMANDER1: @@ -268,20 +268,21 @@ void BattlegroundAV::HandleQuestComplete(uint32 questid, Player* player) } void BattlegroundAV::UpdateScore(TeamId teamId, int16 points) -{ //note: to remove reinforcementpoints points must be negative, for adding reinforcements points must be positive +{ + //note: to remove reinforcementpoints points must be negative, for adding reinforcements points must be positive m_Team_Scores[teamId] += points; - UpdateWorldState(((teamId == TEAM_HORDE)?AV_Horde_Score:AV_Alliance_Score), m_Team_Scores[teamId]); + UpdateWorldState(((teamId == TEAM_HORDE) ? AV_Horde_Score : AV_Alliance_Score), m_Team_Scores[teamId]); if (points < 0) { if (m_Team_Scores[teamId] < 1) { - m_Team_Scores[teamId]=0; + m_Team_Scores[teamId] = 0; EndBattleground(GetOtherTeamId(teamId)); } else if (!m_IsInformedNearVictory[teamId] && m_Team_Scores[teamId] < SEND_MSG_NEAR_LOSE) { - SendMessageToAll(teamId == TEAM_HORDE?LANG_BG_AV_H_NEAR_LOSE:LANG_BG_AV_A_NEAR_LOSE, teamId == TEAM_HORDE ? CHAT_MSG_BG_SYSTEM_HORDE : CHAT_MSG_BG_SYSTEM_ALLIANCE); + SendMessageToAll(teamId == TEAM_HORDE ? LANG_BG_AV_H_NEAR_LOSE : LANG_BG_AV_A_NEAR_LOSE, teamId == TEAM_HORDE ? CHAT_MSG_BG_SYSTEM_HORDE : CHAT_MSG_BG_SYSTEM_ALLIANCE); PlaySoundToAll(AV_SOUND_NEAR_VICTORY); m_IsInformedNearVictory[teamId] = true; } @@ -296,7 +297,7 @@ Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type) if (type >= AV_CPLACE_MAX) //static { type -= AV_CPLACE_MAX; - cinfoid=uint16(BG_AV_StaticCreaturePos[type][4]); + cinfoid = uint16(BG_AV_StaticCreaturePos[type][4]); creature = AddCreature(BG_AV_StaticCreatureInfo[cinfoid], type + AV_CPLACE_MAX, BG_AV_StaticCreaturePos[type][0], @@ -320,12 +321,12 @@ Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type) creature->SetRespawnDelay(RESPAWN_ONE_DAY); // TODO: look if this can be done by database + also add this for the wingcommanders if ((isStatic && cinfoid >= 10 && cinfoid <= 14) || (!isStatic && ((cinfoid >= AV_NPC_A_GRAVEDEFENSE0 && cinfoid <= AV_NPC_A_GRAVEDEFENSE3) || - (cinfoid >= AV_NPC_H_GRAVEDEFENSE0 && cinfoid <= AV_NPC_H_GRAVEDEFENSE3)))) + (cinfoid >= AV_NPC_H_GRAVEDEFENSE0 && cinfoid <= AV_NPC_H_GRAVEDEFENSE3)))) { if (!isStatic && ((cinfoid >= AV_NPC_A_GRAVEDEFENSE0 && cinfoid <= AV_NPC_A_GRAVEDEFENSE3) - || (cinfoid >= AV_NPC_H_GRAVEDEFENSE0 && cinfoid <= AV_NPC_H_GRAVEDEFENSE3))) + || (cinfoid >= AV_NPC_H_GRAVEDEFENSE0 && cinfoid <= AV_NPC_H_GRAVEDEFENSE3))) { - CreatureData &data = sObjectMgr->NewOrExistCreatureData(creature->GetDBTableGUIDLow()); + CreatureData& data = sObjectMgr->NewOrExistCreatureData(creature->GetDBTableGUIDLow()); data.wander_distance = 5; } //else wander_distance will be 15, so creatures move maximum=10 @@ -380,7 +381,7 @@ void BattlegroundAV::PostUpdateImpl(uint32 diff) { if (GetStatus() == STATUS_IN_PROGRESS) { - for (uint8 i=0; i <= 1; i++)//0=alliance, 1=horde + for (uint8 i = 0; i <= 1; i++) //0=alliance, 1=horde { if (!m_CaptainAlive[i]) continue; @@ -402,12 +403,12 @@ void BattlegroundAV::PostUpdateImpl(uint32 diff) if (creature) YellToAll(creature, LANG_BG_AV_H_CAPTAIN_BUFF, LANG_ORCISH); } - m_CaptainBuffTimer[i] = 120000 + urand(0, 4)* 60000; //as far as i could see, the buff is randomly so i make 2minutes (thats the duration of the buff itself) + 0-4minutes TODO get the right times + m_CaptainBuffTimer[i] = 120000 + urand(0, 4) * 60000; //as far as i could see, the buff is randomly so i make 2minutes (thats the duration of the buff itself) + 0-4minutes TODO get the right times } } //add points from mine owning, and look if he neutral team wanrts to reclaim the mine - m_Mine_Timer -=diff; - for (uint8 mine=0; mine <2; mine++) + m_Mine_Timer -= diff; + for (uint8 mine = 0; mine < 2; mine++) { if (m_Mine_Owner[mine] == TEAM_ALLIANCE || m_Mine_Owner[mine] == TEAM_HORDE) { @@ -416,13 +417,14 @@ void BattlegroundAV::PostUpdateImpl(uint32 diff) if (m_Mine_Reclaim_Timer[mine] > diff) m_Mine_Reclaim_Timer[mine] -= diff; - else{ //we don't need to set this timer to 0 cause this codepart wont get called when this thing is 0 + else //we don't need to set this timer to 0 cause this codepart wont get called when this thing is 0 + { ChangeMineOwner(mine, TEAM_NEUTRAL); } } } if (m_Mine_Timer <= 0) - m_Mine_Timer=AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines + m_Mine_Timer = AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines //looks for all timers of the nodes and destroy the building (for graveyards the building wont get destroyed, it goes just to the other team for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i < BG_AV_NODES_MAX; ++i) @@ -431,7 +433,7 @@ void BattlegroundAV::PostUpdateImpl(uint32 diff) if (m_Nodes[i].Timer > diff) m_Nodes[i].Timer -= diff; else - EventPlayerDestroyedPoint(i); + EventPlayerDestroyedPoint(i); } } } @@ -450,9 +452,9 @@ void BattlegroundAV::StartingEventOpenDoors() #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_BATTLEGROUND, "BG_AV: start spawning mine stuff"); #endif - for (uint16 i= BG_AV_OBJECT_MINE_SUPPLY_N_MIN; i <= BG_AV_OBJECT_MINE_SUPPLY_N_MAX; i++) + for (uint16 i = BG_AV_OBJECT_MINE_SUPPLY_N_MIN; i <= BG_AV_OBJECT_MINE_SUPPLY_N_MAX; i++) SpawnBGObject(i, RESPAWN_IMMEDIATELY); - for (uint16 i= BG_AV_OBJECT_MINE_SUPPLY_S_MIN; i <= BG_AV_OBJECT_MINE_SUPPLY_S_MAX; i++) + for (uint16 i = BG_AV_OBJECT_MINE_SUPPLY_S_MIN; i <= BG_AV_OBJECT_MINE_SUPPLY_S_MAX; i++) SpawnBGObject(i, RESPAWN_IMMEDIATELY); for (uint8 mine = AV_NORTH_MINE; mine <= AV_SOUTH_MINE; mine++) //mine population ChangeMineOwner(mine, TEAM_NEUTRAL, true); @@ -482,22 +484,22 @@ void BattlegroundAV::EndBattleground(TeamId winnerTeamId) uint8 rep[2] = {0, 0}; // 0 = Alliance 1 = Horde for (BG_AV_Nodes i = BG_AV_NODES_DUNBALDAR_SOUTH; i <= BG_AV_NODES_FROSTWOLF_WTOWER; ++i) { - if (m_Nodes[i].State == POINT_CONTROLED) + if (m_Nodes[i].State == POINT_CONTROLED) + { + if (m_Nodes[i].OwnerId == TEAM_ALLIANCE) { - if (m_Nodes[i].OwnerId == TEAM_ALLIANCE) - { - rep[0] += BG_AV_REP_SURVIVING_TOWER; - kills[0] += BG_AV_KILL_SURVIVING_TOWER; - } - else - { - rep[0] += BG_AV_KILL_SURVIVING_TOWER; - kills[1] += BG_AV_KILL_SURVIVING_TOWER; - } + rep[0] += BG_AV_REP_SURVIVING_TOWER; + kills[0] += BG_AV_KILL_SURVIVING_TOWER; } + else + { + rep[0] += BG_AV_KILL_SURVIVING_TOWER; + kills[1] += BG_AV_KILL_SURVIVING_TOWER; + } + } } - for (TeamId iTeamId = TEAM_ALLIANCE; iTeamId <= TEAM_HORDE; iTeamId = TeamId(iTeamId+1)) + for (TeamId iTeamId = TEAM_ALLIANCE; iTeamId <= TEAM_HORDE; iTeamId = TeamId(iTeamId + 1)) { if (m_CaptainAlive[iTeamId]) { @@ -610,38 +612,38 @@ void BattlegroundAV::EventPlayerDestroyedPoint(BG_AV_Nodes node) TeamId ownerId = m_Nodes[node].OwnerId; if (IsTower(node)) { - uint8 tmp = node-BG_AV_NODES_DUNBALDAR_SOUTH; + uint8 tmp = node - BG_AV_NODES_DUNBALDAR_SOUTH; //despawn marshal if (BgCreatures[AV_CPLACE_A_MARSHAL_SOUTH + tmp]) DelCreature(AV_CPLACE_A_MARSHAL_SOUTH + tmp); else sLog->outError("BG_AV: playerdestroyedpoint: marshal %i doesn't exist", AV_CPLACE_A_MARSHAL_SOUTH + tmp); //spawn destroyed aura - for (uint8 i=0; i <= 9; i++) + for (uint8 i = 0; i <= 9; i++) SpawnBGObject(BG_AV_OBJECT_BURN_DUNBALDAR_SOUTH + i + (tmp * 10), RESPAWN_IMMEDIATELY); UpdateScore((ownerId == TEAM_ALLIANCE) ? TEAM_HORDE : TEAM_ALLIANCE, -1 * BG_AV_RES_TOWER); RewardReputationToTeam(ownerId == TEAM_ALLIANCE ? 730 : 729, BG_AV_REP_TOWER, ownerId); RewardHonorToTeam(GetBonusHonorFromKill(BG_AV_KILL_TOWER), ownerId); - SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+ownerId+(2*tmp), RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+ownerId+(2*tmp), RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH + ownerId + (2 * tmp), RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH + ownerId + (2 * tmp), RESPAWN_ONE_DAY); } else { if (ownerId == TEAM_ALLIANCE) - SpawnBGObject(object-11, RESPAWN_IMMEDIATELY); + SpawnBGObject(object - 11, RESPAWN_IMMEDIATELY); else - SpawnBGObject(object+11, RESPAWN_IMMEDIATELY); - SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+3*node, RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+ownerId+3*node, RESPAWN_IMMEDIATELY); + SpawnBGObject(object + 11, RESPAWN_IMMEDIATELY); + SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + ownerId + 3 * node, RESPAWN_IMMEDIATELY); PopulateNode(node); if (node == BG_AV_NODES_SNOWFALL_GRAVE) //snowfall eyecandy { for (uint8 i = 0; i < 4; i++) { - SpawnBGObject(((ownerId == TEAM_ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_PH)+i, RESPAWN_ONE_DAY); - SpawnBGObject(((ownerId == TEAM_ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_A : BG_AV_OBJECT_SNOW_EYECANDY_H)+i, RESPAWN_IMMEDIATELY); + SpawnBGObject(((ownerId == TEAM_ALLIANCE) ? BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_PH) + i, RESPAWN_ONE_DAY); + SpawnBGObject(((ownerId == TEAM_ALLIANCE) ? BG_AV_OBJECT_SNOW_EYECANDY_A : BG_AV_OBJECT_SNOW_EYECANDY_H) + i, RESPAWN_IMMEDIATELY); } } } @@ -650,7 +652,7 @@ void BattlegroundAV::EventPlayerDestroyedPoint(BG_AV_Nodes node) if (IsTower(node)) sprintf(buf, GetAcoreString(LANG_BG_AV_TOWER_TAKEN), GetNodeName(node), (ownerId == TEAM_ALLIANCE) ? GetAcoreString(LANG_BG_AV_ALLY) : GetAcoreString(LANG_BG_AV_HORDE)); else - sprintf(buf, GetAcoreString(LANG_BG_AV_GRAVE_TAKEN), GetNodeName(node), (ownerId == TEAM_ALLIANCE) ? GetAcoreString(LANG_BG_AV_ALLY) :GetAcoreString(LANG_BG_AV_HORDE)); + sprintf(buf, GetAcoreString(LANG_BG_AV_GRAVE_TAKEN), GetNodeName(node), (ownerId == TEAM_ALLIANCE) ? GetAcoreString(LANG_BG_AV_ALLY) : GetAcoreString(LANG_BG_AV_HORDE)); Creature* creature = GetBGCreature(AV_CPLACE_HERALD); if (creature) @@ -665,7 +667,7 @@ void BattlegroundAV::ChangeMineOwner(uint8 mine, TeamId teamId, bool initial) ASSERT(mine == AV_NORTH_MINE || mine == AV_SOUTH_MINE); if (teamId == TEAM_ALLIANCE || teamId == TEAM_HORDE) - PlaySoundToAll((teamId == TEAM_ALLIANCE)?AV_SOUND_ALLIANCE_GOOD:AV_SOUND_HORDE_GOOD); + PlaySoundToAll((teamId == TEAM_ALLIANCE) ? AV_SOUND_ALLIANCE_GOOD : AV_SOUND_HORDE_GOOD); if (m_Mine_Owner[mine] == teamId && !initial) return; @@ -677,10 +679,10 @@ void BattlegroundAV::ChangeMineOwner(uint8 mine, TeamId teamId, bool initial) sLog->outDebug(LOG_FILTER_BATTLEGROUND, "bg_av depopulating mine %i (0=north, 1=south)", mine); #endif if (mine == AV_SOUTH_MINE) - for (uint16 i=AV_CPLACE_MINE_S_S_MIN; i <= AV_CPLACE_MINE_S_S_MAX; i++) + for (uint16 i = AV_CPLACE_MINE_S_S_MIN; i <= AV_CPLACE_MINE_S_S_MAX; i++) if (BgCreatures[i]) DelCreature(i); //TODO just set the respawntime to 999999 - for (uint16 i=((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_1_MIN:AV_CPLACE_MINE_S_1_MIN); i <= ((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_3:AV_CPLACE_MINE_S_3); i++) + for (uint16 i = ((mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_1_MIN : AV_CPLACE_MINE_S_1_MIN); i <= ((mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_3 : AV_CPLACE_MINE_S_3); i++) if (BgCreatures[i]) DelCreature(i); //TODO here also } @@ -709,7 +711,7 @@ void BattlegroundAV::ChangeMineOwner(uint8 mine, TeamId teamId, bool initial) miner = AV_NPC_S_MINE_H_1; else miner = AV_NPC_S_MINE_N_1; - //vermin + //vermin #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_BATTLEGROUND, "spawning vermin"); #endif @@ -719,19 +721,19 @@ void BattlegroundAV::ChangeMineOwner(uint8 mine, TeamId teamId, bool initial) cinfo = AV_NPC_S_MINE_H_3; else cinfo = AV_NPC_S_MINE_N_S; - for (uint16 i=AV_CPLACE_MINE_S_S_MIN; i <= AV_CPLACE_MINE_S_S_MAX; i++) + for (uint16 i = AV_CPLACE_MINE_S_S_MIN; i <= AV_CPLACE_MINE_S_S_MAX; i++) AddAVCreature(cinfo, i); } - for (uint16 i=((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_1_MIN:AV_CPLACE_MINE_S_1_MIN); i <= ((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_1_MAX:AV_CPLACE_MINE_S_1_MAX); i++) + for (uint16 i = ((mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_1_MIN : AV_CPLACE_MINE_S_1_MIN); i <= ((mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_1_MAX : AV_CPLACE_MINE_S_1_MAX); i++) AddAVCreature(miner, i); //the next chooses randomly between 2 cretures - for (uint16 i=((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_2_MIN:AV_CPLACE_MINE_S_2_MIN); i <= ((mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_2_MAX:AV_CPLACE_MINE_S_2_MAX); i++) - AddAVCreature(miner+(urand(1, 2)), i); - AddAVCreature(miner+3, (mine == AV_NORTH_MINE)?AV_CPLACE_MINE_N_3:AV_CPLACE_MINE_S_3); + for (uint16 i = ((mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_2_MIN : AV_CPLACE_MINE_S_2_MIN); i <= ((mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_2_MAX : AV_CPLACE_MINE_S_2_MAX); i++) + AddAVCreature(miner + (urand(1, 2)), i); + AddAVCreature(miner + 3, (mine == AV_NORTH_MINE) ? AV_CPLACE_MINE_N_3 : AV_CPLACE_MINE_S_3); if (teamId == TEAM_ALLIANCE || teamId == TEAM_HORDE) { - m_Mine_Reclaim_Timer[mine]=AV_MINE_RECLAIM_TIMER; + m_Mine_Reclaim_Timer[mine] = AV_MINE_RECLAIM_TIMER; char buf[256]; sprintf(buf, GetAcoreString(LANG_BG_AV_MINE_TAKEN), GetAcoreString((mine == AV_NORTH_MINE) ? LANG_BG_AV_MINE_NORTH : LANG_BG_AV_MINE_SOUTH), (teamId == TEAM_ALLIANCE) ? GetAcoreString(LANG_BG_AV_ALLY) : GetAcoreString(LANG_BG_AV_HORDE)); @@ -752,9 +754,9 @@ void BattlegroundAV::ChangeMineOwner(uint8 mine, TeamId teamId, bool initial) bool BattlegroundAV::PlayerCanDoMineQuest(int32 GOId, TeamId teamId) { if (GOId == BG_AV_OBJECTID_MINE_N) - return (m_Mine_Owner[AV_NORTH_MINE] == teamId); + return (m_Mine_Owner[AV_NORTH_MINE] == teamId); if (GOId == BG_AV_OBJECTID_MINE_S) - return (m_Mine_Owner[AV_SOUTH_MINE] == teamId); + return (m_Mine_Owner[AV_SOUTH_MINE] == teamId); return true; //cause it's no mine'object it is ok if this is true } @@ -765,37 +767,37 @@ void BattlegroundAV::PopulateNode(BG_AV_Nodes node) uint32 c_place = AV_CPLACE_DEFENSE_STORM_AID + (4 * node); uint32 creatureid; if (IsTower(node)) - creatureid=(ownerId == TEAM_ALLIANCE)?AV_NPC_A_TOWERDEFENSE:AV_NPC_H_TOWERDEFENSE; + creatureid = (ownerId == TEAM_ALLIANCE) ? AV_NPC_A_TOWERDEFENSE : AV_NPC_H_TOWERDEFENSE; else { if (m_Team_QuestStatus[ownerId][0] < 500) - creatureid = (ownerId == TEAM_ALLIANCE)? AV_NPC_A_GRAVEDEFENSE0 : AV_NPC_H_GRAVEDEFENSE0; + creatureid = (ownerId == TEAM_ALLIANCE) ? AV_NPC_A_GRAVEDEFENSE0 : AV_NPC_H_GRAVEDEFENSE0; else if (m_Team_QuestStatus[ownerId][0] < 1000) - creatureid = (ownerId == TEAM_ALLIANCE)? AV_NPC_A_GRAVEDEFENSE1 : AV_NPC_H_GRAVEDEFENSE1; + creatureid = (ownerId == TEAM_ALLIANCE) ? AV_NPC_A_GRAVEDEFENSE1 : AV_NPC_H_GRAVEDEFENSE1; else if (m_Team_QuestStatus[ownerId][0] < 1500) - creatureid = (ownerId == TEAM_ALLIANCE)? AV_NPC_A_GRAVEDEFENSE2 : AV_NPC_H_GRAVEDEFENSE2; + creatureid = (ownerId == TEAM_ALLIANCE) ? AV_NPC_A_GRAVEDEFENSE2 : AV_NPC_H_GRAVEDEFENSE2; else - creatureid = (ownerId == TEAM_ALLIANCE)? AV_NPC_A_GRAVEDEFENSE3 : AV_NPC_H_GRAVEDEFENSE3; + creatureid = (ownerId == TEAM_ALLIANCE) ? AV_NPC_A_GRAVEDEFENSE3 : AV_NPC_H_GRAVEDEFENSE3; //spiritguide if (BgCreatures[node]) DelCreature(node); if (!AddSpiritGuide(node, BG_AV_CreaturePos[node][0], BG_AV_CreaturePos[node][1], BG_AV_CreaturePos[node][2], BG_AV_CreaturePos[node][3], ownerId)) sLog->outError("AV: couldn't spawn spiritguide at node %i", node); } - for (uint8 i=0; i<4; i++) - AddAVCreature(creatureid, c_place+i); + for (uint8 i = 0; i < 4; i++) + AddAVCreature(creatureid, c_place + i); if (node >= BG_AV_NODES_MAX)//fail safe return; Creature* trigger = GetBgMap()->GetCreature(BgCreatures[node + 302]);//0-302 other creatures if (!trigger) { - trigger = AddCreature(WORLD_TRIGGER, - node + 302, - BG_AV_CreaturePos[node + 302][0], - BG_AV_CreaturePos[node + 302][1], - BG_AV_CreaturePos[node + 302][2], - BG_AV_CreaturePos[node + 302][3]); + trigger = AddCreature(WORLD_TRIGGER, + node + 302, + BG_AV_CreaturePos[node + 302][0], + BG_AV_CreaturePos[node + 302][1], + BG_AV_CreaturePos[node + 302][2], + BG_AV_CreaturePos[node + 302][3]); } //add bonus honor aura trigger creature when node is accupied @@ -815,9 +817,9 @@ void BattlegroundAV::PopulateNode(BG_AV_Nodes node) void BattlegroundAV::DePopulateNode(BG_AV_Nodes node) { uint32 c_place = AV_CPLACE_DEFENSE_STORM_AID + (4 * node); - for (uint8 i=0; i<4; i++) - if (BgCreatures[c_place+i]) - DelCreature(c_place+i); + for (uint8 i = 0; i < 4; i++) + if (BgCreatures[c_place + i]) + DelCreature(c_place + i); //spiritguide if (!IsTower(node) && BgCreatures[node]) DelCreature(node); @@ -839,7 +841,7 @@ BG_AV_Nodes BattlegroundAV::GetNodeThroughObject(uint32 object) if (object <= BG_AV_OBJECT_FLAG_C_A_FROSTWOLF_WTOWER) return BG_AV_Nodes(object - 7); if (object <= BG_AV_OBJECT_FLAG_C_H_STONEHEART_BUNKER) - return BG_AV_Nodes(object -22); + return BG_AV_Nodes(object - 22); if (object <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_HUT) return BG_AV_Nodes(object - 33); if (object <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_WTOWER) @@ -852,7 +854,8 @@ BG_AV_Nodes BattlegroundAV::GetNodeThroughObject(uint32 object) } uint32 BattlegroundAV::GetObjectThroughNode(BG_AV_Nodes node) -{ //this function is the counterpart to GetNodeThroughObject() +{ + //this function is the counterpart to GetNodeThroughObject() #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_BATTLEGROUND, "bg_AV GetObjectThroughNode %i", node); #endif @@ -861,9 +864,9 @@ uint32 BattlegroundAV::GetObjectThroughNode(BG_AV_Nodes node) if (m_Nodes[node].State == POINT_ASSAULTED) { if (node <= BG_AV_NODES_FROSTWOLF_HUT) - return node+11; + return node + 11; if (node >= BG_AV_NODES_ICEBLOOD_TOWER && node <= BG_AV_NODES_FROSTWOLF_WTOWER) - return node+7; + return node + 7; } else if (m_Nodes[node].State == POINT_CONTROLED) if (node <= BG_AV_NODES_STONEHEART_BUNKER) @@ -874,14 +877,14 @@ uint32 BattlegroundAV::GetObjectThroughNode(BG_AV_Nodes node) if (m_Nodes[node].State == POINT_ASSAULTED) { if (node <= BG_AV_NODES_STONEHEART_BUNKER) - return node+22; + return node + 22; } else if (m_Nodes[node].State == POINT_CONTROLED) { if (node <= BG_AV_NODES_FROSTWOLF_HUT) - return node+33; + return node + 33; if (node >= BG_AV_NODES_ICEBLOOD_TOWER && node <= BG_AV_NODES_FROSTWOLF_WTOWER) - return node+29; + return node + 29; } } else if (m_Nodes[node].OwnerId == TEAM_NEUTRAL) @@ -931,7 +934,8 @@ void BattlegroundAV::EventPlayerDefendsPoint(Player* player, uint32 object) if (ownerId == player->GetTeamId() || m_Nodes[node].State != POINT_ASSAULTED) return; if (m_Nodes[node].TotalOwnerId == TEAM_NEUTRAL) - { //until snowfall doesn't belong to anyone it is better handled in assault-code + { + //until snowfall doesn't belong to anyone it is better handled in assault-code ASSERT(node == BG_AV_NODES_SNOWFALL_GRAVE); //currently the only neutral grave EventPlayerAssaultsPoint(player, object); return; @@ -945,18 +949,18 @@ void BattlegroundAV::EventPlayerDefendsPoint(Player* player, uint32 object) return; } - //spawn new go :) + //spawn new go :) if (m_Nodes[node].OwnerId == TEAM_ALLIANCE) - SpawnBGObject(object+22, RESPAWN_IMMEDIATELY); //spawn horde banner + SpawnBGObject(object + 22, RESPAWN_IMMEDIATELY); //spawn horde banner else - SpawnBGObject(object-22, RESPAWN_IMMEDIATELY); //spawn alliance banner + SpawnBGObject(object - 22, RESPAWN_IMMEDIATELY); //spawn alliance banner if (!IsTower(node)) { - SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+3*node, RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+teamId+3*node, RESPAWN_IMMEDIATELY); + SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + teamId + 3 * node, RESPAWN_IMMEDIATELY); } - // despawn old go + // despawn old go SpawnBGObject(object, RESPAWN_ONE_DAY); DefendNode(node, teamId); @@ -966,17 +970,17 @@ void BattlegroundAV::EventPlayerDefendsPoint(Player* player, uint32 object) if (IsTower(node)) { //spawn big flag+aura on top of tower - SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); } else if (node == BG_AV_NODES_SNOWFALL_GRAVE) //snowfall eyecandy { for (uint8 i = 0; i < 4; i++) { - SpawnBGObject(((ownerId == TEAM_ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_PH)+i, RESPAWN_ONE_DAY); - SpawnBGObject(((teamId == TEAM_ALLIANCE)?BG_AV_OBJECT_SNOW_EYECANDY_A : BG_AV_OBJECT_SNOW_EYECANDY_H)+i, RESPAWN_IMMEDIATELY); + SpawnBGObject(((ownerId == TEAM_ALLIANCE) ? BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_PH) + i, RESPAWN_ONE_DAY); + SpawnBGObject(((teamId == TEAM_ALLIANCE) ? BG_AV_OBJECT_SNOW_EYECANDY_A : BG_AV_OBJECT_SNOW_EYECANDY_H) + i, RESPAWN_IMMEDIATELY); } } //send a nice message to all :) @@ -990,7 +994,7 @@ void BattlegroundAV::EventPlayerDefendsPoint(Player* player, uint32 object) if (IsTower(node)) PlaySoundToAll(AV_SOUND_BOTH_TOWER_DEFEND); else - PlaySoundToAll((teamId == TEAM_ALLIANCE)?AV_SOUND_ALLIANCE_GOOD:AV_SOUND_HORDE_GOOD); + PlaySoundToAll((teamId == TEAM_ALLIANCE) ? AV_SOUND_ALLIANCE_GOOD : AV_SOUND_HORDE_GOOD); } void BattlegroundAV::EventPlayerAssaultsPoint(Player* player, uint32 object) @@ -1017,7 +1021,7 @@ void BattlegroundAV::EventPlayerAssaultsPoint(Player* player, uint32 object) SpawnBGObject(BG_AV_OBJECT_FLAG_C_A_SNOWFALL_GRAVE, RESPAWN_IMMEDIATELY); else SpawnBGObject(BG_AV_OBJECT_FLAG_C_H_SNOWFALL_GRAVE, RESPAWN_IMMEDIATELY); - SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+3*node, RESPAWN_IMMEDIATELY); //neutral aura spawn + SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_IMMEDIATELY); //neutral aura spawn } else if (m_Nodes[node].TotalOwnerId == TEAM_NEUTRAL) //recapping, when no team owns this node realy { @@ -1025,26 +1029,26 @@ void BattlegroundAV::EventPlayerAssaultsPoint(Player* player, uint32 object) return; if (teamId == TEAM_ALLIANCE) - SpawnBGObject(object-11, RESPAWN_IMMEDIATELY); + SpawnBGObject(object - 11, RESPAWN_IMMEDIATELY); else - SpawnBGObject(object+11, RESPAWN_IMMEDIATELY); + SpawnBGObject(object + 11, RESPAWN_IMMEDIATELY); } //eyecandy uint32 spawn, despawn; if (teamId == TEAM_ALLIANCE) { - despawn = (m_Nodes[node].State == POINT_ASSAULTED)?BG_AV_OBJECT_SNOW_EYECANDY_PH : BG_AV_OBJECT_SNOW_EYECANDY_H; + despawn = (m_Nodes[node].State == POINT_ASSAULTED) ? BG_AV_OBJECT_SNOW_EYECANDY_PH : BG_AV_OBJECT_SNOW_EYECANDY_H; spawn = BG_AV_OBJECT_SNOW_EYECANDY_PA; } else { - despawn = (m_Nodes[node].State == POINT_ASSAULTED)?BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_A; + despawn = (m_Nodes[node].State == POINT_ASSAULTED) ? BG_AV_OBJECT_SNOW_EYECANDY_PA : BG_AV_OBJECT_SNOW_EYECANDY_A; spawn = BG_AV_OBJECT_SNOW_EYECANDY_PH; } for (uint8 i = 0; i < 4; i++) { - SpawnBGObject(despawn+i, RESPAWN_ONE_DAY); - SpawnBGObject(spawn+i, RESPAWN_IMMEDIATELY); + SpawnBGObject(despawn + i, RESPAWN_ONE_DAY); + SpawnBGObject(spawn + i, RESPAWN_IMMEDIATELY); } } @@ -1056,21 +1060,22 @@ void BattlegroundAV::EventPlayerAssaultsPoint(Player* player, uint32 object) { ASSERT(prevOwnerId != TEAM_NEUTRAL); if (teamId == TEAM_ALLIANCE) - SpawnBGObject(object-22, RESPAWN_IMMEDIATELY); + SpawnBGObject(object - 22, RESPAWN_IMMEDIATELY); else - SpawnBGObject(object+22, RESPAWN_IMMEDIATELY); + SpawnBGObject(object + 22, RESPAWN_IMMEDIATELY); if (IsTower(node)) - { //spawning/despawning of bigflag+aura - SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); - SpawnBGObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(node-BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE)? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + { + //spawning/despawning of bigflag+aura + SpawnBGObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_ALLIANCE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); + SpawnBGObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH + (2 * (node - BG_AV_NODES_DUNBALDAR_SOUTH)), (teamId == TEAM_HORDE) ? RESPAWN_IMMEDIATELY : RESPAWN_ONE_DAY); } else { //spawning/despawning of aura - SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+3*node, RESPAWN_IMMEDIATELY); //neutral aura spawn - SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+prevOwnerId+3*node, RESPAWN_ONE_DAY); //teeamaura despawn + SpawnBGObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + 3 * node, RESPAWN_IMMEDIATELY); //neutral aura spawn + SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + prevOwnerId + 3 * node, RESPAWN_ONE_DAY); //teeamaura despawn RelocateDeadPlayers(BgCreatures[node]); } @@ -1089,7 +1094,7 @@ void BattlegroundAV::EventPlayerAssaultsPoint(Player* player, uint32 object) YellToAll(creature, buf, LANG_UNIVERSAL); //update the statistic for the assaulting player UpdatePlayerScore(player, (IsTower(node)) ? SCORE_TOWERS_ASSAULTED : SCORE_GRAVEYARDS_ASSAULTED, 1); - PlaySoundToAll((teamId == TEAM_ALLIANCE)?AV_SOUND_ALLIANCE_ASSAULTS:AV_SOUND_HORDE_ASSAULTS); + PlaySoundToAll((teamId == TEAM_ALLIANCE) ? AV_SOUND_ALLIANCE_ASSAULTS : AV_SOUND_HORDE_ASSAULTS); } void BattlegroundAV::FillInitialWorldStates(WorldPacket& data) @@ -1098,27 +1103,30 @@ void BattlegroundAV::FillInitialWorldStates(WorldPacket& data) //graveyards for (uint8 i = BG_AV_NODES_FIRSTAID_STATION; i <= BG_AV_NODES_FROSTWOLF_HUT; i++) { - for (uint8 j =1; j <= 3; j+=2) - {//j=1=assaulted j=3=controled + for (uint8 j = 1; j <= 3; j += 2) + { + //j=1=assaulted j=3=controled stateok = (m_Nodes[i].State == j); - data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_ALLIANCE)]) << uint32((m_Nodes[i].OwnerId == TEAM_ALLIANCE && stateok)?1:0); - data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_HORDE)]) << uint32((m_Nodes[i].OwnerId == TEAM_HORDE && stateok)?1:0); + data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_ALLIANCE)]) << uint32((m_Nodes[i].OwnerId == TEAM_ALLIANCE && stateok) ? 1 : 0); + data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_HORDE)]) << uint32((m_Nodes[i].OwnerId == TEAM_HORDE && stateok) ? 1 : 0); } } //towers for (uint8 i = BG_AV_NODES_DUNBALDAR_SOUTH; i < BG_AV_NODES_MAX; ++i) - for (uint8 j =1; j <= 3; j+=2) - {//j=1=assaulted j=3=controled //i dont have j=2=destroyed cause destroyed is the same like enemy-team controll + for (uint8 j = 1; j <= 3; j += 2) + { + //j=1=assaulted j=3=controled //i dont have j=2=destroyed cause destroyed is the same like enemy-team controll stateok = (m_Nodes[i].State == j || (m_Nodes[i].State == POINT_DESTROYED && j == 3)); - data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_ALLIANCE)]) << uint32((m_Nodes[i].OwnerId == TEAM_ALLIANCE && stateok)?1:0); - data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_HORDE)]) << uint32((m_Nodes[i].OwnerId == TEAM_HORDE && stateok)?1:0); + data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_ALLIANCE)]) << uint32((m_Nodes[i].OwnerId == TEAM_ALLIANCE && stateok) ? 1 : 0); + data << uint32(BG_AV_NodeWorldStates[i][GetWorldStateType(j, TEAM_HORDE)]) << uint32((m_Nodes[i].OwnerId == TEAM_HORDE && stateok) ? 1 : 0); } if (m_Nodes[BG_AV_NODES_SNOWFALL_GRAVE].OwnerId == TEAM_NEUTRAL) //cause neutral teams aren't handled generic data << uint32(AV_SNOWFALL_N) << uint32(1); data << uint32(AV_Alliance_Score) << uint32(m_Team_Scores[0]); data << uint32(AV_Horde_Score) << uint32(m_Team_Scores[1]); - if (GetStatus() == STATUS_IN_PROGRESS){ //only if game started the teamscores are displayed + if (GetStatus() == STATUS_IN_PROGRESS) //only if game started the teamscores are displayed + { data << uint32(AV_SHOW_A_SCORE) << uint32(1); data << uint32(AV_SHOW_H_SCORE) << uint32(1); } @@ -1189,8 +1197,8 @@ GraveyardStruct const* BattlegroundAV::GetClosestGraveyard(Player* player) player->GetPosition(x, y); - GraveyardStruct const* pGraveyard = sGraveyard->GetGraveyard(BG_AV_GraveyardIds[player->GetTeamId()+7]); - minDist = (pGraveyard->x - x)*(pGraveyard->x - x)+(pGraveyard->y - y)*(pGraveyard->y - y); + GraveyardStruct const* pGraveyard = sGraveyard->GetGraveyard(BG_AV_GraveyardIds[player->GetTeamId() + 7]); + minDist = (pGraveyard->x - x) * (pGraveyard->x - x) + (pGraveyard->y - y) * (pGraveyard->y - y); for (uint8 i = BG_AV_NODES_FIRSTAID_STATION; i <= BG_AV_NODES_FROSTWOLF_HUT; ++i) if (m_Nodes[i].OwnerId == player->GetTeamId() && m_Nodes[i].State == POINT_CONTROLED) @@ -1198,7 +1206,7 @@ GraveyardStruct const* BattlegroundAV::GetClosestGraveyard(Player* player) entry = sGraveyard->GetGraveyard(BG_AV_GraveyardIds[i]); if (entry) { - dist = (entry->x - x)*(entry->x - x)+(entry->y - y)*(entry->y - y); + dist = (entry->x - x) * (entry->x - x) + (entry->y - y) * (entry->y - y); if (dist < minDist) { minDist = dist; @@ -1218,14 +1226,14 @@ bool BattlegroundAV::SetupBattleground() { if (i <= BG_AV_NODES_FROSTWOLF_HUT) { - if (!AddObject(i, BG_AV_OBJECTID_BANNER_A_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(i+11, BG_AV_OBJECTID_BANNER_CONT_A_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(i+33, BG_AV_OBJECTID_BANNER_H_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(i+22, BG_AV_OBJECTID_BANNER_CONT_H_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - //aura - || !AddObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION+i*3, BG_AV_OBJECTID_AURA_N, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+i*3, BG_AV_OBJECTID_AURA_A, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_AURA_H_FIRSTAID_STATION+i*3, BG_AV_OBJECTID_AURA_H, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(i, BG_AV_OBJECTID_BANNER_A_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(i + 11, BG_AV_OBJECTID_BANNER_CONT_A_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(i + 33, BG_AV_OBJECTID_BANNER_H_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(i + 22, BG_AV_OBJECTID_BANNER_CONT_H_B, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + //aura + || !AddObject(BG_AV_OBJECT_AURA_N_FIRSTAID_STATION + i * 3, BG_AV_OBJECTID_AURA_N, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + i * 3, BG_AV_OBJECTID_AURA_A, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_AURA_H_FIRSTAID_STATION + i * 3, BG_AV_OBJECTID_AURA_H, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!2"); return false; @@ -1235,12 +1243,12 @@ bool BattlegroundAV::SetupBattleground() { if (i <= BG_AV_NODES_STONEHEART_BUNKER) //alliance towers { - if (!AddObject(i, BG_AV_OBJECTID_BANNER_A, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(i+22, BG_AV_OBJECTID_BANNER_CONT_H, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_A, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_N, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_A, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_PH, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(i, BG_AV_OBJECTID_BANNER_A, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(i + 22, BG_AV_OBJECTID_BANNER_CONT_H, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_A, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_N, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_A, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_PH, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!3"); return false; @@ -1248,20 +1256,20 @@ bool BattlegroundAV::SetupBattleground() } else //horde towers { - if (!AddObject(i+7, BG_AV_OBJECTID_BANNER_CONT_A, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(i+29, BG_AV_OBJECTID_BANNER_H, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3]/2), cos(BG_AV_ObjectPos[i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_N, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_H, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_PA, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH+(2*(i-BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_H, BG_AV_ObjectPos[i+8][0], BG_AV_ObjectPos[i+8][1], BG_AV_ObjectPos[i+8][2], BG_AV_ObjectPos[i+8][3], 0, 0, sin(BG_AV_ObjectPos[i+8][3]/2), cos(BG_AV_ObjectPos[i+8][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(i + 7, BG_AV_OBJECTID_BANNER_CONT_A, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(i + 29, BG_AV_OBJECTID_BANNER_H, BG_AV_ObjectPos[i][0], BG_AV_ObjectPos[i][1], BG_AV_ObjectPos[i][2], BG_AV_ObjectPos[i][3], 0, 0, sin(BG_AV_ObjectPos[i][3] / 2), cos(BG_AV_ObjectPos[i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TAURA_A_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_N, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TAURA_H_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_AURA_H, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_PA, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_TFLAG_H_DUNBALDAR_SOUTH + (2 * (i - BG_AV_NODES_DUNBALDAR_SOUTH)), BG_AV_OBJECTID_TOWER_BANNER_H, BG_AV_ObjectPos[i + 8][0], BG_AV_ObjectPos[i + 8][1], BG_AV_ObjectPos[i + 8][2], BG_AV_ObjectPos[i + 8][3], 0, 0, sin(BG_AV_ObjectPos[i + 8][3] / 2), cos(BG_AV_ObjectPos[i + 8][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!4"); return false; } } - for (uint8 j=0; j <= 9; j++) //burning aura + for (uint8 j = 0; j <= 9; j++) //burning aura { - if (!AddObject(BG_AV_OBJECT_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j, BG_AV_OBJECTID_FIRE, BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j][0], BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j][1], BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j][2], BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH+((i-BG_AV_NODES_DUNBALDAR_SOUTH)*10)+j][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j, BG_AV_OBJECTID_FIRE, BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j][0], BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j][1], BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j][2], BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_BURN_DUNBALDAR_SOUTH + ((i - BG_AV_NODES_DUNBALDAR_SOUTH) * 10) + j][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!5.%i", i); return false; @@ -1269,13 +1277,13 @@ bool BattlegroundAV::SetupBattleground() } } } - for (uint8 i=0; i<2; i++) //burning aura for buildings + for (uint8 i = 0; i < 2; i++) //burning aura for buildings { - for (uint8 j=0; j <= 9; j++) + for (uint8 j = 0; j <= 9; j++) { - if (j<5) + if (j < 5) { - if (!AddObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE+(i*10)+j, BG_AV_OBJECTID_SMOKE, BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][0], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][1], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][2], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE + (i * 10) + j, BG_AV_OBJECTID_SMOKE, BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][0], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][1], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][2], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!6.%i", i); return false; @@ -1283,7 +1291,7 @@ bool BattlegroundAV::SetupBattleground() } else { - if (!AddObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE+(i*10)+j, BG_AV_OBJECTID_FIRE, BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][0], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][1], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][2], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A+(i*10)+j][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_BURN_BUILDING_ALLIANCE + (i * 10) + j, BG_AV_OBJECTID_FIRE, BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][0], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][1], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][2], BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_BURN_BUILDING_A + (i * 10) + j][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!7.%i", i); return false; @@ -1291,34 +1299,34 @@ bool BattlegroundAV::SetupBattleground() } } } - for (uint16 i= 0; i <= (BG_AV_OBJECT_MINE_SUPPLY_N_MAX-BG_AV_OBJECT_MINE_SUPPLY_N_MIN); i++) + for (uint16 i = 0; i <= (BG_AV_OBJECT_MINE_SUPPLY_N_MAX - BG_AV_OBJECT_MINE_SUPPLY_N_MIN); i++) { - if (!AddObject(BG_AV_OBJECT_MINE_SUPPLY_N_MIN+i, BG_AV_OBJECTID_MINE_N, BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i][0], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i][1], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i][2], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN+i][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_MINE_SUPPLY_N_MIN + i, BG_AV_OBJECTID_MINE_N, BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN + i][0], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN + i][1], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN + i][2], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_N_MIN + i][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some mine supplies Battleground not created!7.5.%i", i); return false; } } - for (uint16 i= 0; i <= (BG_AV_OBJECT_MINE_SUPPLY_S_MAX-BG_AV_OBJECT_MINE_SUPPLY_S_MIN); i++) + for (uint16 i = 0; i <= (BG_AV_OBJECT_MINE_SUPPLY_S_MAX - BG_AV_OBJECT_MINE_SUPPLY_S_MIN); i++) { - if (!AddObject(BG_AV_OBJECT_MINE_SUPPLY_S_MIN+i, BG_AV_OBJECTID_MINE_S, BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i][0], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i][1], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i][2], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN+i][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_MINE_SUPPLY_S_MIN + i, BG_AV_OBJECTID_MINE_S, BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN + i][0], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN + i][1], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN + i][2], BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_MINE_SUPPLY_S_MIN + i][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some mine supplies Battleground not created!7.6.%i", i); return false; } } - if (!AddObject(BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE, BG_AV_OBJECTID_BANNER_SNOWFALL_N, BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][0], BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][1], BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][2], BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][3], 0, 0, sin(BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][3]/2), cos(BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_FLAG_N_SNOWFALL_GRAVE, BG_AV_OBJECTID_BANNER_SNOWFALL_N, BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][0], BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][1], BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][2], BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][3], 0, 0, sin(BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][3] / 2), cos(BG_AV_ObjectPos[BG_AV_NODES_SNOWFALL_GRAVE][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!8"); return false; } for (uint8 i = 0; i < 4; i++) { - if (!AddObject(BG_AV_OBJECT_SNOW_EYECANDY_A+i, BG_AV_OBJECTID_SNOWFALL_CANDY_A, BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_PA+i, BG_AV_OBJECTID_SNOWFALL_CANDY_PA, BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_H+i, BG_AV_OBJECTID_SNOWFALL_CANDY_H, BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), RESPAWN_ONE_DAY) - || !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_PH+i, BG_AV_OBJECTID_SNOWFALL_CANDY_PH, BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1+i][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_SNOW_EYECANDY_A + i, BG_AV_OBJECTID_SNOWFALL_CANDY_A, BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_PA + i, BG_AV_OBJECTID_SNOWFALL_CANDY_PA, BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_H + i, BG_AV_OBJECTID_SNOWFALL_CANDY_H, BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), RESPAWN_ONE_DAY) + || !AddObject(BG_AV_OBJECT_SNOW_EYECANDY_PH + i, BG_AV_OBJECTID_SNOWFALL_CANDY_PH, BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][0], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][1], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][2], BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_SNOW_1 + i][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!9.%i", i); return false; @@ -1327,19 +1335,19 @@ bool BattlegroundAV::SetupBattleground() // Handpacked snowdrift, only during holiday if (IsHolidayActive(HOLIDAY_FEAST_OF_WINTER_VEIL)) - for (uint16 i= 0 ; i <= (BG_AV_OBJECT_HANDPACKED_SNOWDRIFT_MAX-BG_AV_OBJECT_HANDPACKED_SNOWDRIFT_MIN); i++) + for (uint16 i = 0 ; i <= (BG_AV_OBJECT_HANDPACKED_SNOWDRIFT_MAX - BG_AV_OBJECT_HANDPACKED_SNOWDRIFT_MIN); i++) { - if (!AddObject(BG_AV_OBJECT_HANDPACKED_SNOWDRIFT_MIN+i, BG_AV_OBJECTID_HARDPACKED_SNOWDRIFT, BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN+i][0], BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN+i][1], BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN+i][2], BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN+i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN+i][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN+i][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_HANDPACKED_SNOWDRIFT_MIN + i, BG_AV_OBJECTID_HARDPACKED_SNOWDRIFT, BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN + i][0], BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN + i][1], BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN + i][2], BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN + i][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN + i][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_HANDPACKED_SNOWDRIFT_MIN + i][3] / 2), RESPAWN_ONE_DAY)) return false; } // Quest banners - if (!AddObject(BG_AV_OBJECT_FROSTWOLF_BANNER, BG_AV_OBJECTID_FROSTWOLF_BANNER, BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][0], BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][1], BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][2], BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_FROSTWOLF_BANNER, BG_AV_OBJECTID_FROSTWOLF_BANNER, BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][0], BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][1], BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][2], BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_FROSTWOLF_BANNER][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!8"); return false; } - if (!AddObject(BG_AV_OBJECT_STORMPIKE_BANNER, BG_AV_OBJECTID_STORMPIKE_BANNER, BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][0], BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][1], BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][2], BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][3]/2), cos(BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][3]/2), RESPAWN_ONE_DAY)) + if (!AddObject(BG_AV_OBJECT_STORMPIKE_BANNER, BG_AV_OBJECTID_STORMPIKE_BANNER, BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][0], BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][1], BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][2], BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][3], 0, 0, sin(BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][3] / 2), cos(BG_AV_ObjectPos[AV_OPLACE_STORMPIKE_BANNER][3] / 2), RESPAWN_ONE_DAY)) { sLog->outError("BatteGroundAV: Failed to spawn some object Battleground not created!8"); return false; @@ -1355,7 +1363,7 @@ bool BattlegroundAV::SetupBattleground() for (i = BG_AV_OBJECT_FLAG_A_FIRSTAID_STATION; i <= BG_AV_OBJECT_FLAG_A_STONEHEART_GRAVE; i++) { - SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION+3*i, RESPAWN_IMMEDIATELY); + SpawnBGObject(BG_AV_OBJECT_AURA_A_FIRSTAID_STATION + 3 * i, RESPAWN_IMMEDIATELY); SpawnBGObject(i, RESPAWN_IMMEDIATELY); } @@ -1366,19 +1374,19 @@ bool BattlegroundAV::SetupBattleground() { SpawnBGObject(i, RESPAWN_IMMEDIATELY); if (i <= BG_AV_OBJECT_FLAG_H_FROSTWOLF_HUT) - SpawnBGObject(BG_AV_OBJECT_AURA_H_FIRSTAID_STATION+3*GetNodeThroughObject(i), RESPAWN_IMMEDIATELY); + SpawnBGObject(BG_AV_OBJECT_AURA_H_FIRSTAID_STATION + 3 * GetNodeThroughObject(i), RESPAWN_IMMEDIATELY); } - for (i = BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH; i <= BG_AV_OBJECT_TFLAG_A_STONEHEART_BUNKER; i+=2) + for (i = BG_AV_OBJECT_TFLAG_A_DUNBALDAR_SOUTH; i <= BG_AV_OBJECT_TFLAG_A_STONEHEART_BUNKER; i += 2) { SpawnBGObject(i, RESPAWN_IMMEDIATELY); //flag - SpawnBGObject(i+16, RESPAWN_IMMEDIATELY); //aura + SpawnBGObject(i + 16, RESPAWN_IMMEDIATELY); //aura } - for (i = BG_AV_OBJECT_TFLAG_H_ICEBLOOD_TOWER; i <= BG_AV_OBJECT_TFLAG_H_FROSTWOLF_WTOWER; i+=2) + for (i = BG_AV_OBJECT_TFLAG_H_ICEBLOOD_TOWER; i <= BG_AV_OBJECT_TFLAG_H_FROSTWOLF_WTOWER; i += 2) { SpawnBGObject(i, RESPAWN_IMMEDIATELY); //flag - SpawnBGObject(i+16, RESPAWN_IMMEDIATELY); //aura + SpawnBGObject(i + 16, RESPAWN_IMMEDIATELY); //aura } //snowfall and the doors @@ -1425,9 +1433,9 @@ bool BattlegroundAV::SetupBattleground() if ( // alliance gates - !AddObject(BG_AV_OBJECT_DOOR_A, BG_AV_OBJECTID_GATE_A, BG_AV_DoorPositons[0][0], BG_AV_DoorPositons[0][1], BG_AV_DoorPositons[0][2], BG_AV_DoorPositons[0][3], 0, 0, sin(BG_AV_DoorPositons[0][3]/2), cos(BG_AV_DoorPositons[0][3]/2), RESPAWN_IMMEDIATELY) + !AddObject(BG_AV_OBJECT_DOOR_A, BG_AV_OBJECTID_GATE_A, BG_AV_DoorPositons[0][0], BG_AV_DoorPositons[0][1], BG_AV_DoorPositons[0][2], BG_AV_DoorPositons[0][3], 0, 0, sin(BG_AV_DoorPositons[0][3] / 2), cos(BG_AV_DoorPositons[0][3] / 2), RESPAWN_IMMEDIATELY) // horde gates - || !AddObject(BG_AV_OBJECT_DOOR_H, BG_AV_OBJECTID_GATE_H, BG_AV_DoorPositons[1][0], BG_AV_DoorPositons[1][1], BG_AV_DoorPositons[1][2], BG_AV_DoorPositons[1][3], 0, 0, sin(BG_AV_DoorPositons[1][3]/2), cos(BG_AV_DoorPositons[1][3]/2), RESPAWN_IMMEDIATELY)) + || !AddObject(BG_AV_OBJECT_DOOR_H, BG_AV_OBJECTID_GATE_H, BG_AV_DoorPositons[1][0], BG_AV_DoorPositons[1][1], BG_AV_DoorPositons[1][2], BG_AV_DoorPositons[1][3], 0, 0, sin(BG_AV_DoorPositons[1][3] / 2), cos(BG_AV_DoorPositons[1][3] / 2), RESPAWN_IMMEDIATELY)) { sLog->outErrorDb("BatteGroundAV: Failed to spawn some object Battleground not created!1"); return false; @@ -1440,21 +1448,36 @@ char const* BattlegroundAV::GetNodeName(BG_AV_Nodes node) { switch (node) { - case BG_AV_NODES_FIRSTAID_STATION: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_STORM_AID); - case BG_AV_NODES_DUNBALDAR_SOUTH: return GetAcoreString(LANG_BG_AV_NODE_TOWER_DUN_S); - case BG_AV_NODES_DUNBALDAR_NORTH: return GetAcoreString(LANG_BG_AV_NODE_TOWER_DUN_N); - case BG_AV_NODES_STORMPIKE_GRAVE: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_STORMPIKE); - case BG_AV_NODES_ICEWING_BUNKER: return GetAcoreString(LANG_BG_AV_NODE_TOWER_ICEWING); - case BG_AV_NODES_STONEHEART_GRAVE: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_STONE); - case BG_AV_NODES_STONEHEART_BUNKER: return GetAcoreString(LANG_BG_AV_NODE_TOWER_STONE); - case BG_AV_NODES_SNOWFALL_GRAVE: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_SNOW); - case BG_AV_NODES_ICEBLOOD_TOWER: return GetAcoreString(LANG_BG_AV_NODE_TOWER_ICE); - case BG_AV_NODES_ICEBLOOD_GRAVE: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_ICE); - case BG_AV_NODES_TOWER_POINT: return GetAcoreString(LANG_BG_AV_NODE_TOWER_POINT); - case BG_AV_NODES_FROSTWOLF_GRAVE: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_FROST); - case BG_AV_NODES_FROSTWOLF_ETOWER: return GetAcoreString(LANG_BG_AV_NODE_TOWER_FROST_E); - case BG_AV_NODES_FROSTWOLF_WTOWER: return GetAcoreString(LANG_BG_AV_NODE_TOWER_FROST_W); - case BG_AV_NODES_FROSTWOLF_HUT: return GetAcoreString(LANG_BG_AV_NODE_GRAVE_FROST_HUT); + case BG_AV_NODES_FIRSTAID_STATION: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_STORM_AID); + case BG_AV_NODES_DUNBALDAR_SOUTH: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_DUN_S); + case BG_AV_NODES_DUNBALDAR_NORTH: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_DUN_N); + case BG_AV_NODES_STORMPIKE_GRAVE: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_STORMPIKE); + case BG_AV_NODES_ICEWING_BUNKER: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_ICEWING); + case BG_AV_NODES_STONEHEART_GRAVE: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_STONE); + case BG_AV_NODES_STONEHEART_BUNKER: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_STONE); + case BG_AV_NODES_SNOWFALL_GRAVE: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_SNOW); + case BG_AV_NODES_ICEBLOOD_TOWER: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_ICE); + case BG_AV_NODES_ICEBLOOD_GRAVE: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_ICE); + case BG_AV_NODES_TOWER_POINT: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_POINT); + case BG_AV_NODES_FROSTWOLF_GRAVE: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_FROST); + case BG_AV_NODES_FROSTWOLF_ETOWER: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_FROST_E); + case BG_AV_NODES_FROSTWOLF_WTOWER: + return GetAcoreString(LANG_BG_AV_NODE_TOWER_FROST_W); + case BG_AV_NODES_FROSTWOLF_HUT: + return GetAcoreString(LANG_BG_AV_NODE_GRAVE_FROST_HUT); default: sLog->outError("tried to get name for node %u", node); break; @@ -1486,8 +1509,8 @@ void BattlegroundAV::AssaultNode(BG_AV_Nodes node, TeamId teamId) ABORT(); } //the timer gets another time, if the previous owner was 0 == Neutral - m_Nodes[node].Timer = (m_Nodes[node].PrevOwnerId != TEAM_NEUTRAL)? BG_AV_CAPTIME : BG_AV_SNOWFALL_FIRSTCAP; - m_Nodes[node].PrevOwnerId= m_Nodes[node].OwnerId; + m_Nodes[node].Timer = (m_Nodes[node].PrevOwnerId != TEAM_NEUTRAL) ? BG_AV_CAPTIME : BG_AV_SNOWFALL_FIRSTCAP; + m_Nodes[node].PrevOwnerId = m_Nodes[node].OwnerId; m_Nodes[node].OwnerId = teamId; m_Nodes[node].PrevState = m_Nodes[node].State; m_Nodes[node].State = POINT_ASSAULTED; @@ -1500,7 +1523,7 @@ void BattlegroundAV::DestroyNode(BG_AV_Nodes node) m_Nodes[node].TotalOwnerId = m_Nodes[node].OwnerId; m_Nodes[node].PrevOwnerId = m_Nodes[node].OwnerId; m_Nodes[node].PrevState = m_Nodes[node].State; - m_Nodes[node].State = (m_Nodes[node].Tower)? POINT_DESTROYED : POINT_CONTROLED; + m_Nodes[node].State = (m_Nodes[node].Tower) ? POINT_DESTROYED : POINT_CONTROLED; m_Nodes[node].Timer = 0; } @@ -1520,7 +1543,7 @@ void BattlegroundAV::DefendNode(BG_AV_Nodes node, TeamId teamId) ASSERT(m_Nodes[node].TotalOwnerId == teamId); ASSERT(m_Nodes[node].OwnerId != teamId); ASSERT(m_Nodes[node].State != POINT_CONTROLED && m_Nodes[node].State != POINT_DESTROYED); - m_Nodes[node].PrevOwnerId= m_Nodes[node].OwnerId; + m_Nodes[node].PrevOwnerId = m_Nodes[node].OwnerId; m_Nodes[node].OwnerId = teamId; m_Nodes[node].PrevState = m_Nodes[node].State; m_Nodes[node].State = POINT_CONTROLED; @@ -1529,14 +1552,14 @@ void BattlegroundAV::DefendNode(BG_AV_Nodes node, TeamId teamId) void BattlegroundAV::ResetBGSubclass() { - for (uint8 i=0; i<2; i++) //forloop for both teams (it just make 0 == alliance and 1 == horde also for both mines 0=north 1=south + for (uint8 i = 0; i < 2; i++) //forloop for both teams (it just make 0 == alliance and 1 == horde also for both mines 0=north 1=south { - for (uint8 j=0; j<9; j++) - m_Team_QuestStatus[i][j]=0; - m_Team_Scores[i]=BG_AV_SCORE_INITIAL_POINTS; - m_IsInformedNearVictory[i]=false; + for (uint8 j = 0; j < 9; j++) + m_Team_QuestStatus[i][j] = 0; + m_Team_Scores[i] = BG_AV_SCORE_INITIAL_POINTS; + m_IsInformedNearVictory[i] = false; m_CaptainAlive[i] = true; - m_CaptainBuffTimer[i] = 120000 + urand(0, 4)* 60; //as far as i could see, the buff is randomly so i make 2minutes (thats the duration of the buff itself) + 0-4minutes TODO get the right times + m_CaptainBuffTimer[i] = 120000 + urand(0, 4) * 60; //as far as i could see, the buff is randomly so i make 2minutes (thats the duration of the buff itself) + 0-4minutes TODO get the right times m_Mine_Owner[i] = TEAM_NEUTRAL; } for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i <= BG_AV_NODES_STONEHEART_GRAVE; ++i) //alliance graves @@ -1549,8 +1572,8 @@ void BattlegroundAV::ResetBGSubclass() InitNode(i, TEAM_HORDE, true); InitNode(BG_AV_NODES_SNOWFALL_GRAVE, TEAM_NEUTRAL, false); //give snowfall neutral owner - m_Mine_Timer=AV_MINE_TICK_TIMER; - for (uint16 i = 0; i < AV_CPLACE_MAX+AV_STATICCPLACE_MAX; i++) + m_Mine_Timer = AV_MINE_TICK_TIMER; + for (uint16 i = 0; i < AV_CPLACE_MAX + AV_STATICCPLACE_MAX; i++) if (BgCreatures[i]) DelCreature(i); } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.h b/src/server/game/Battlegrounds/Zones/BattlegroundAV.h index 75d9eeb13..caa484357 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.h @@ -41,38 +41,39 @@ #define AV_EVENT_START_BATTLE 9166 // Achievement: The Alterac Blitz enum BG_AV_Sounds -{ //TODO: get out if there comes a sound when neutral team captures mine +{ + //TODO: get out if there comes a sound when neutral team captures mine -/* -8212: - alliance grave assault - alliance tower assault - drek "mlanzenabschaum! In meiner Burg?! Toetet sie all" - nicht immer der sound -8333: - galv "sterbt fuer euch ist kein platz hier" + /* + 8212: + alliance grave assault + alliance tower assault + drek "mlanzenabschaum! In meiner Burg?! Toetet sie all" - nicht immer der sound + 8333: + galv "sterbt fuer euch ist kein platz hier" -8332: - bal "Verschwinde, dreckiger Abschaum! Die Allianz wird im Alteractal " -8174: - horde tower assault - horde grave assault - van "es Sturmlanzenklans, euer General wird angegriffen! Ich fordere Unterst" -8173: - ally grave capture/defend - tower destroy - mine capture - ally wins -8192: - ally tower destroy(only iceblood - found a bug^^) - ally tower defend - horde tower defend -8213 -horde: - grave defend/capture - tower destroy - mine capture - horde wins - */ + 8332: + bal "Verschwinde, dreckiger Abschaum! Die Allianz wird im Alteractal " + 8174: + horde tower assault + horde grave assault + van "es Sturmlanzenklans, euer General wird angegriffen! Ich fordere Unterst" + 8173: + ally grave capture/defend + tower destroy + mine capture + ally wins + 8192: + ally tower destroy(only iceblood - found a bug^^) + ally tower defend + horde tower defend + 8213 + horde: + grave defend/capture + tower destroy + mine capture + horde wins + */ AV_SOUND_NEAR_VICTORY = 8456, //not confirmed yet @@ -223,7 +224,7 @@ enum BG_AV_ObjectTypes BG_AV_OBJECT_DOOR_H = 45, BG_AV_OBJECT_DOOR_A = 46, -//auras for graveyards (3auras per graveyard neutral, alliance, horde) + //auras for graveyards (3auras per graveyard neutral, alliance, horde) BG_AV_OBJECT_AURA_N_FIRSTAID_STATION = 47, BG_AV_OBJECT_AURA_A_FIRSTAID_STATION = 48, BG_AV_OBJECT_AURA_H_FIRSTAID_STATION = 49, @@ -486,7 +487,7 @@ const float BG_AV_ObjectPos[AV_OPLACE_MAX][4] = {-62.9474f, -286.212f, 66.7288f, 0}, {-5.05132f, -325.323f, 38.8536f, 0}, {-64.2677f, -289.412f, 33.469f, 0}, -//horde + //horde {-524.276f, -199.6f, 82.8733f, -1.46608f}, {-518.196f, -173.085f, 102.43f, 0}, {-500.732f, -145.358f, 88.5337f, 2.44346f}, @@ -498,7 +499,7 @@ const float BG_AV_ObjectPos[AV_OPLACE_MAX][4] = {-501.775f, -151.581f, 81.2027f, 0}, {-509.975f, -191.652f, 83.2978f, 0}, -//snowfall eyecandy + //snowfall eyecandy {-191.153f, -129.868f, 78.5595f, -1.25664f }, {-201.282f, -134.319f, 78.6753f, -0.942478f }, {-215.981f, -91.4101f, 80.8702f, -1.74533f }, @@ -562,7 +563,7 @@ enum BG_AV_CreaturePlace AV_CPLACE_SPIRIT_FROST_HUT = 6, AV_CPLACE_SPIRIT_MAIN_ALLIANCE = 7, AV_CPLACE_SPIRIT_MAIN_HORDE = 8, -//i don't will add for all 4 positions a variable.. i think one is enough to compute the rest + //i don't will add for all 4 positions a variable.. i think one is enough to compute the rest AV_CPLACE_DEFENSE_STORM_AID = 9, AV_CPLACE_DEFEMSE_STORM_GRAVE = 13, AV_CPLACE_DEFENSE_STONE_GRAVE = 17, @@ -652,44 +653,44 @@ const float BG_AV_CreaturePos[AV_CPLACE_MAX][4] = {-1496.065063f, -333.338409f, 101.134804f, -0.001854f}, {873.001770f, -491.283630f, 96.541931f, -0.001854f}, {-1437.670044f, -610.088989f, 51.161900f, -0.001854f}, - //grave - //firstaid + //grave + //firstaid {635.17f, -29.5594f, 46.5056f, 4.81711f}, {642.488f, -32.9437f, 46.365f, 4.67748f}, {642.326f, -27.9442f, 46.9211f, 4.59022f}, {635.945f, -33.6171f, 45.7164f, 4.97419f}, - //stormpike + //stormpike {669.272f, -297.304f, 30.291f, 4.66604f}, {674.08f, -292.328f, 30.4817f, 0.0918785f}, {667.01f, -288.532f, 29.8809f, 1.81583f}, {664.153f, -294.042f, 30.2851f, 3.28531f}, - //stone + //stone {81.7027f, -406.135f, 47.7843f, 0.598464f}, {78.1431f, -409.215f, 48.0401f, 5.05953f}, {73.4135f, -407.035f, 46.7527f, 3.34736f}, {78.2258f, -401.859f, 46.4202f, 2.05852f}, - //snowfall + //snowfall {-207.412f, -110.616f, 78.7959f, 2.43251f}, {-197.95f, -112.205f, 78.5686f, 6.22441f}, {-202.709f, -116.829f, 78.4358f, 5.13742f}, {-202.059f, -108.314f, 78.5783f, 5.91968f}, - //ice + //ice {-615.501f, -393.802f, 60.4299f, 3.06147f}, {-608.513f, -392.717f, 62.5724f, 2.06323f}, {-609.769f, -400.072f, 60.7174f, 5.22367f}, {-616.093f, -398.293f, 60.5628f, 3.73613f}, - //frost + //frost {-1077.7f, -340.21f, 55.4682f, 6.25569f}, {-1082.74f, -333.821f, 54.7962f, 2.05459f}, {-1090.66f, -341.267f, 54.6768f, 3.27746f}, {-1081.58f, -344.63f, 55.256f, 4.75636f}, - //frost hut + //frost hut {-1408.95f, -311.69f, 89.2536f, 4.49954f}, {-1407.15f, -305.323f, 89.1993f, 2.86827f}, {-1400.64f, -304.3f, 89.7008f, 1.0595f}, {-1400.4f, -311.35f, 89.3028f, 4.99434f}, - //towers - //dun south - OK + //towers + //dun south - OK {569.395f, -101.064f, 52.8296f, 2.34974f}, {574.85f, -92.9842f, 52.5869f, 3.09325f}, {575.411f, -83.597f, 52.3626f, 6.26573f}, @@ -735,14 +736,14 @@ const float BG_AV_CreaturePos[AV_CPLACE_MAX][4] = {723.058f, -14.1548f, 50.7046f, 3.40339f}, // north {715.691f, -4.72233f, 50.2187f, 3.47321f}, // icewing {720.046f, -19.9413f, 50.2187f, 3.36849f}, // stone -//horde (coords not 100% ok) + //horde (coords not 100% ok) {-1363.99f, -221.99f, 98.4053f, 4.93012f}, {-1370.96f, -223.532f, 98.4266f, 4.93012f}, {-1378.37f, -228.614f, 99.3546f, 5.38565f}, {-1358.02f, -228.998f, 98.868f, 3.87768f}, - //irondeep mine - //Irondeep Trogg + //irondeep mine + //Irondeep Trogg {971.671f, -442.657f, 57.6951f, 3.1765f}, {969.979f, -457.148f, 58.1119f, 4.5204f}, {958.692f, -333.477f, 63.2276f, 5.77704f}, @@ -1024,7 +1025,7 @@ enum BG_AV_CreatureIds AV_NPC_H_MARSHAL_ICE = 18, AV_NPC_H_MARSHAL_TOWER = 19, AV_NPC_MARSHAL_ETOWER = 20, - AV_NPC_H_MARSHAL_WTOWER= 21, + AV_NPC_H_MARSHAL_WTOWER = 21, AV_NPC_N_MINE_N_1 = 22, AV_NPC_N_MINE_N_2 = 23, AV_NPC_N_MINE_N_3 = 24, @@ -1312,7 +1313,7 @@ enum BG_AV_Graveyards AV_GRAVE_MAIN_HORDE = 610 }; -const uint32 BG_AV_GraveyardIds[9]= +const uint32 BG_AV_GraveyardIds[9] = { AV_GRAVE_STORM_AID, AV_GRAVE_STORM_GRAVE, @@ -1326,7 +1327,8 @@ const uint32 BG_AV_GraveyardIds[9]= }; enum BG_AV_BUFF -{ //TODO add all other buffs here +{ + //TODO add all other buffs here AV_BUFF_ARMOR = 21163, AV_BUFF_A_CAPTAIN = 23693, //the buff which the alliance captain does AV_BUFF_H_CAPTAIN = 22751 //the buff which the horde captain does @@ -1346,110 +1348,110 @@ enum BG_AV_WorldStates AV_SHOW_H_SCORE = 3133, AV_SHOW_A_SCORE = 3134, -/* - //the comments behind the state shows which icon overlaps the other.. but is, until now, unused and maybe not a good solution (but give few performance (:) + /* + //the comments behind the state shows which icon overlaps the other.. but is, until now, unused and maybe not a good solution (but give few performance (:) -// Graves + // Graves - // Alliance - //Stormpike first aid station - AV_AID_A_C = 1325, - AV_AID_A_A = 1326, - AV_AID_H_C = 1327, - AV_AID_H_A = 1328, - //Stormpike Graveyard - AV_PIKEGRAVE_A_C = 1333, - AV_PIKEGRAVE_A_A = 1335, - AV_PIKEGRAVE_H_C = 1334, - AV_PIKEGRAVE_H_A = 1336, - //Stoneheart Grave - AV_STONEHEART_A_C = 1302, - AV_STONEHEART_A_A = 1304, //over hc - AV_STONEHEART_H_C = 1301, //over ac - AV_STONEHEART_H_A = 1303, //over aa - //Neutral - //Snowfall Grave -*/ + // Alliance + //Stormpike first aid station + AV_AID_A_C = 1325, + AV_AID_A_A = 1326, + AV_AID_H_C = 1327, + AV_AID_H_A = 1328, + //Stormpike Graveyard + AV_PIKEGRAVE_A_C = 1333, + AV_PIKEGRAVE_A_A = 1335, + AV_PIKEGRAVE_H_C = 1334, + AV_PIKEGRAVE_H_A = 1336, + //Stoneheart Grave + AV_STONEHEART_A_C = 1302, + AV_STONEHEART_A_A = 1304, //over hc + AV_STONEHEART_H_C = 1301, //over ac + AV_STONEHEART_H_A = 1303, //over aa + //Neutral + //Snowfall Grave + */ AV_SNOWFALL_N = 1966, //over aa -/* - AV_SNOWFALL_A_C = 1341, //over hc - AV_SNOWFALL_A_A = 1343, //over ha - AV_SNOWFALL_H_C = 1342, - AV_SNOWFALL_H_A = 1344, //over ac - //Horde - //Iceblood grave - AV_ICEBLOOD_A_C = 1346, //over hc - AV_ICEBLOOD_A_A = 1348, //over ac - AV_ICEBLOOD_H_C = 1347, - AV_ICEBLOOD_H_A = 1349, //over aa - //Frostwolf Grave - AV_FROSTWOLF_A_C = 1337, //over hc - AV_FROSTWOLF_A_A = 1339, //over ac - AV_FROSTWOLF_H_C = 1338, - AV_FROSTWOLF_H_A = 1340, //over aa - //Frostwolf Hut - AV_FROSTWOLFHUT_A_C = 1329, //over hc - AV_FROSTWOLFHUT_A_A = 1331, //over ha - AV_FROSTWOLFHUT_H_C = 1330, - AV_FROSTWOLFHUT_H_A = 1332, //over ac + /* + AV_SNOWFALL_A_C = 1341, //over hc + AV_SNOWFALL_A_A = 1343, //over ha + AV_SNOWFALL_H_C = 1342, + AV_SNOWFALL_H_A = 1344, //over ac + //Horde + //Iceblood grave + AV_ICEBLOOD_A_C = 1346, //over hc + AV_ICEBLOOD_A_A = 1348, //over ac + AV_ICEBLOOD_H_C = 1347, + AV_ICEBLOOD_H_A = 1349, //over aa + //Frostwolf Grave + AV_FROSTWOLF_A_C = 1337, //over hc + AV_FROSTWOLF_A_A = 1339, //over ac + AV_FROSTWOLF_H_C = 1338, + AV_FROSTWOLF_H_A = 1340, //over aa + //Frostwolf Hut + AV_FROSTWOLFHUT_A_C = 1329, //over hc + AV_FROSTWOLFHUT_A_A = 1331, //over ha + AV_FROSTWOLFHUT_H_C = 1330, + AV_FROSTWOLFHUT_H_A = 1332, //over ac -//Towers - //Alliance - //Dunbaldar South Bunker - AV_DUNS_CONTROLLED = 1361, - AV_DUNS_DESTROYED = 1370, - AV_DUNS_ASSAULTED = 1378, - //Dunbaldar North Bunker - AV_DUNN_CONTROLLED = 1362, - AV_DUNN_DESTROYED = 1371, - AV_DUNN_ASSAULTED = 1379, - //Icewing Bunker - AV_ICEWING_CONTROLLED = 1363, - AV_ICEWING_DESTROYED = 1372, - AV_ICEWING_ASSAULTED = 1380, - //Stoneheart Bunker - AV_STONEH_CONTROLLED = 1364, - AV_STONEH_DESTROYED = 1373, - AV_STONEH_ASSAULTED = 1381, - //Horde - //Iceblood Tower - AV_ICEBLOOD_CONTROLLED = 1385, - AV_ICEBLOOD_DESTROYED = 1368, - AV_ICEBLOOD_ASSAULTED = 1390, - //Tower Point - AV_TOWERPOINT_CONTROLLED = 1384, - AV_TOWERPOINT_DESTROYED = 1367, //goes over controlled - AV_TOWERPOINT_ASSAULTED = 1389, //goes over destroyed - //Frostwolf West - AV_FROSTWOLFW_CONTROLLED = 1382, - AV_FROSTWOLFW_DESTROYED = 1365, //over controlled - AV_FROSTWOLFW_ASSAULTED = 1387, //over destroyed - //Frostwolf East - AV_FROSTWOLFE_CONTROLLED = 1383, - AV_FROSTWOLFE_DESTROYED = 1366, - AV_FROSTWOLFE_ASSAULTED = 1388, + //Towers + //Alliance + //Dunbaldar South Bunker + AV_DUNS_CONTROLLED = 1361, + AV_DUNS_DESTROYED = 1370, + AV_DUNS_ASSAULTED = 1378, + //Dunbaldar North Bunker + AV_DUNN_CONTROLLED = 1362, + AV_DUNN_DESTROYED = 1371, + AV_DUNN_ASSAULTED = 1379, + //Icewing Bunker + AV_ICEWING_CONTROLLED = 1363, + AV_ICEWING_DESTROYED = 1372, + AV_ICEWING_ASSAULTED = 1380, + //Stoneheart Bunker + AV_STONEH_CONTROLLED = 1364, + AV_STONEH_DESTROYED = 1373, + AV_STONEH_ASSAULTED = 1381, + //Horde + //Iceblood Tower + AV_ICEBLOOD_CONTROLLED = 1385, + AV_ICEBLOOD_DESTROYED = 1368, + AV_ICEBLOOD_ASSAULTED = 1390, + //Tower Point + AV_TOWERPOINT_CONTROLLED = 1384, + AV_TOWERPOINT_DESTROYED = 1367, //goes over controlled + AV_TOWERPOINT_ASSAULTED = 1389, //goes over destroyed + //Frostwolf West + AV_FROSTWOLFW_CONTROLLED = 1382, + AV_FROSTWOLFW_DESTROYED = 1365, //over controlled + AV_FROSTWOLFW_ASSAULTED = 1387, //over destroyed + //Frostwolf East + AV_FROSTWOLFE_CONTROLLED = 1383, + AV_FROSTWOLFE_DESTROYED = 1366, + AV_FROSTWOLFE_ASSAULTED = 1388, -//mines + //mines - AV_N_MINE_N = 1360, - AV_N_MINE_A = 1358, - AV_N_MINE_H = 1359, + AV_N_MINE_N = 1360, + AV_N_MINE_A = 1358, + AV_N_MINE_H = 1359, - AV_S_MINE_N = 1357, - AV_S_MINE_A = 1355, - AV_S_MINE_H = 1356, + AV_S_MINE_N = 1357, + AV_S_MINE_A = 1355, + AV_S_MINE_H = 1356, -//towers assaulted by own team (unused) - AV_STONEH_UNUSED = 1377, - AV_ICEWING_UNUSED = 1376, - AV_DUNS_UNUSED = 1375, - AV_DUNN_UNUSED = 1374, + //towers assaulted by own team (unused) + AV_STONEH_UNUSED = 1377, + AV_ICEWING_UNUSED = 1376, + AV_DUNS_UNUSED = 1375, + AV_DUNN_UNUSED = 1374, - AV_ICEBLOOD_UNUSED = 1395, - AV_TOWERPOINT_UNUSED = 1394, - AV_FROSTWOLFE_UNUSED = 1393, - AV_FROSTWOLFW_UNUSED = 1392 -*/ + AV_ICEBLOOD_UNUSED = 1395, + AV_TOWERPOINT_UNUSED = 1394, + AV_FROSTWOLFE_UNUSED = 1393, + AV_FROSTWOLFW_UNUSED = 1392 + */ }; @@ -1540,7 +1542,7 @@ struct BG_AV_NodeInfo bool Tower; }; -inline BG_AV_Nodes &operator++(BG_AV_Nodes &i){ return i = BG_AV_Nodes(i + 1); } +inline BG_AV_Nodes& operator++(BG_AV_Nodes& i) { return i = BG_AV_Nodes(i + 1); } struct BattlegroundAVScore : public BattlegroundScore { @@ -1563,87 +1565,87 @@ struct BattlegroundAVScore : public BattlegroundScore class BattlegroundAV : public Battleground { - public: - BattlegroundAV(); - ~BattlegroundAV() override; +public: + BattlegroundAV(); + ~BattlegroundAV() override; - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player) override; - void StartingEventCloseDoors() override; - void StartingEventOpenDoors() override; + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player) override; + void StartingEventCloseDoors() override; + void StartingEventOpenDoors() override; - void RemovePlayer(Player* player) override; - void HandleAreaTrigger(Player* player, uint32 trigger) override; - bool SetupBattleground() override; - void ResetBGSubclass() override; + void RemovePlayer(Player* player) override; + void HandleAreaTrigger(Player* player, uint32 trigger) override; + bool SetupBattleground() override; + void ResetBGSubclass() override; - /*general stuff*/ - void UpdateScore(TeamId teamId, int16 points); - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true) override; + /*general stuff*/ + void UpdateScore(TeamId teamId, int16 points); + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true) override; - /*handlestuff*/ //these are functions which get called from extern - void EventPlayerClickedOnFlag(Player* source, GameObject* gameObject) override; - void HandleKillPlayer(Player* player, Player* killer) override; - void HandleKillUnit(Creature* unit, Player* killer) override; - void HandleQuestComplete(uint32 questid, Player* player); - bool PlayerCanDoMineQuest(int32 GOId, TeamId teamId); + /*handlestuff*/ //these are functions which get called from extern + void EventPlayerClickedOnFlag(Player* source, GameObject* gameObject) override; + void HandleKillPlayer(Player* player, Player* killer) override; + void HandleKillUnit(Creature* unit, Player* killer) override; + void HandleQuestComplete(uint32 questid, Player* player); + bool PlayerCanDoMineQuest(int32 GOId, TeamId teamId); - void EndBattleground(TeamId winnerTeamId) override; + void EndBattleground(TeamId winnerTeamId) override; - GraveyardStruct const* GetClosestGraveyard(Player* player) override; + GraveyardStruct const* GetClosestGraveyard(Player* player) override; - /* achievement req. */ - bool IsBothMinesControlledByTeam(TeamId teamId) const; - bool IsAllTowersControlledAndCaptainAlive(TeamId teamId) const; - - TeamId GetPrematureWinner() override; + /* achievement req. */ + bool IsBothMinesControlledByTeam(TeamId teamId) const; + bool IsAllTowersControlledAndCaptainAlive(TeamId teamId) const; - private: - void PostUpdateImpl(uint32 diff) override; + TeamId GetPrematureWinner() override; - /* Nodes occupying */ - void EventPlayerAssaultsPoint(Player* player, uint32 object); - void EventPlayerDefendsPoint(Player* player, uint32 object); - void EventPlayerDestroyedPoint(BG_AV_Nodes node); +private: + void PostUpdateImpl(uint32 diff) override; - void AssaultNode(BG_AV_Nodes node, TeamId teamId); - void DestroyNode(BG_AV_Nodes node); - void InitNode(BG_AV_Nodes node, TeamId teamId, bool tower); - void DefendNode(BG_AV_Nodes node, TeamId teamId); + /* Nodes occupying */ + void EventPlayerAssaultsPoint(Player* player, uint32 object); + void EventPlayerDefendsPoint(Player* player, uint32 object); + void EventPlayerDestroyedPoint(BG_AV_Nodes node); - void PopulateNode(BG_AV_Nodes node); - void DePopulateNode(BG_AV_Nodes node); + void AssaultNode(BG_AV_Nodes node, TeamId teamId); + void DestroyNode(BG_AV_Nodes node); + void InitNode(BG_AV_Nodes node, TeamId teamId, bool tower); + void DefendNode(BG_AV_Nodes node, TeamId teamId); - BG_AV_Nodes GetNodeThroughObject(uint32 object); - uint32 GetObjectThroughNode(BG_AV_Nodes node); - char const* GetNodeName(BG_AV_Nodes node); - bool IsTower(BG_AV_Nodes node) { return m_Nodes[node].Tower; } + void PopulateNode(BG_AV_Nodes node); + void DePopulateNode(BG_AV_Nodes node); - /*mine*/ - void ChangeMineOwner(uint8 mine, TeamId teamId, bool initial=false); + BG_AV_Nodes GetNodeThroughObject(uint32 object); + uint32 GetObjectThroughNode(BG_AV_Nodes node); + char const* GetNodeName(BG_AV_Nodes node); + bool IsTower(BG_AV_Nodes node) { return m_Nodes[node].Tower; } - /*worldstates*/ - void FillInitialWorldStates(WorldPacket& data) override; - uint8 GetWorldStateType(uint8 state, TeamId teamId); - void SendMineWorldStates(uint32 mine); - void UpdateNodeWorldState(BG_AV_Nodes node); + /*mine*/ + void ChangeMineOwner(uint8 mine, TeamId teamId, bool initial = false); - /*general */ - Creature* AddAVCreature(uint16 cinfoid, uint16 type); + /*worldstates*/ + void FillInitialWorldStates(WorldPacket& data) override; + uint8 GetWorldStateType(uint8 state, TeamId teamId); + void SendMineWorldStates(uint32 mine); + void UpdateNodeWorldState(BG_AV_Nodes node); - /*variables */ - int32 m_Team_Scores[2]{}; - uint32 m_Team_QuestStatus[2][9]{}; //[x][y] x=team y=questcounter + /*general */ + Creature* AddAVCreature(uint16 cinfoid, uint16 type); - BG_AV_NodeInfo m_Nodes[BG_AV_NODES_MAX]{}; + /*variables */ + int32 m_Team_Scores[2] {}; + uint32 m_Team_QuestStatus[2][9] {}; //[x][y] x=team y=questcounter - TeamId m_Mine_Owner[2]{}; - int32 m_Mine_Timer; //ticks for both teams - uint32 m_Mine_Reclaim_Timer[2]{}; - uint32 m_CaptainBuffTimer[2]{}; - bool m_CaptainAlive[2]{}; + BG_AV_NodeInfo m_Nodes[BG_AV_NODES_MAX] {}; - bool m_IsInformedNearVictory[2]{}; + TeamId m_Mine_Owner[2] {}; + int32 m_Mine_Timer; //ticks for both teams + uint32 m_Mine_Reclaim_Timer[2] {}; + uint32 m_CaptainBuffTimer[2] {}; + bool m_CaptainAlive[2] {}; + + bool m_IsInformedNearVictory[2] {}; }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp index 99e302868..f209e851d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp @@ -127,7 +127,7 @@ void BattlegroundBE::HandleAreaTrigger(Player* player, uint32 trigger) } } -void BattlegroundBE::FillInitialWorldStates(WorldPacket &data) +void BattlegroundBE::FillInitialWorldStates(WorldPacket& data) { data << uint32(0x9f3) << uint32(1); // 9 Battleground::UpdateArenaWorldState(); @@ -143,15 +143,15 @@ bool BattlegroundBE::SetupBattleground() { // gates if (!AddObject(BG_BE_OBJECT_DOOR_1, BG_BE_OBJECT_TYPE_DOOR_1, 6287.277f, 282.1877f, 3.810925f, -2.260201f, 0, 0, 0.9044551f, -0.4265689f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_BE_OBJECT_DOOR_2, BG_BE_OBJECT_TYPE_DOOR_2, 6189.546f, 241.7099f, 3.101481f, 0.8813917f, 0, 0, 0.4265689f, 0.9044551f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_BE_OBJECT_DOOR_3, BG_BE_OBJECT_TYPE_DOOR_3, 6299.116f, 296.5494f, 3.308032f, 0.8813917f, 0, 0, 0.4265689f, 0.9044551f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_BE_OBJECT_DOOR_4, BG_BE_OBJECT_TYPE_DOOR_4, 6177.708f, 227.3481f, 3.604374f, -2.260201f, 0, 0, 0.9044551f, -0.4265689f, RESPAWN_IMMEDIATELY) - // buffs - || !AddObject(BG_BE_OBJECT_BUFF_1, BG_BE_OBJECT_TYPE_BUFF_1, 6249.042f, 275.3239f, 11.22033f, -1.448624f, 0, 0, 0.6626201f, -0.7489557f, 120) - || !AddObject(BG_BE_OBJECT_BUFF_2, BG_BE_OBJECT_TYPE_BUFF_2, 6228.26f, 249.566f, 11.21812f, -0.06981307f, 0, 0, 0.03489945f, -0.9993908f, 120) - // Arena Ready Marker - || !AddObject(BG_BE_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 6189.47f, 235.54f, 5.52f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) - || !AddObject(BG_BE_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 6287.19f, 288.25f, 5.33f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) + || !AddObject(BG_BE_OBJECT_DOOR_2, BG_BE_OBJECT_TYPE_DOOR_2, 6189.546f, 241.7099f, 3.101481f, 0.8813917f, 0, 0, 0.4265689f, 0.9044551f, RESPAWN_IMMEDIATELY) + || !AddObject(BG_BE_OBJECT_DOOR_3, BG_BE_OBJECT_TYPE_DOOR_3, 6299.116f, 296.5494f, 3.308032f, 0.8813917f, 0, 0, 0.4265689f, 0.9044551f, RESPAWN_IMMEDIATELY) + || !AddObject(BG_BE_OBJECT_DOOR_4, BG_BE_OBJECT_TYPE_DOOR_4, 6177.708f, 227.3481f, 3.604374f, -2.260201f, 0, 0, 0.9044551f, -0.4265689f, RESPAWN_IMMEDIATELY) + // buffs + || !AddObject(BG_BE_OBJECT_BUFF_1, BG_BE_OBJECT_TYPE_BUFF_1, 6249.042f, 275.3239f, 11.22033f, -1.448624f, 0, 0, 0.6626201f, -0.7489557f, 120) + || !AddObject(BG_BE_OBJECT_BUFF_2, BG_BE_OBJECT_TYPE_BUFF_2, 6228.26f, 249.566f, 11.21812f, -0.06981307f, 0, 0, 0.03489945f, -0.9993908f, 120) + // Arena Ready Marker + || !AddObject(BG_BE_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 6189.47f, 235.54f, 5.52f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) + || !AddObject(BG_BE_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 6287.19f, 288.25f, 5.33f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { sLog->outErrorDb("BatteGroundBE: Failed to spawn some object!"); return false; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBE.h b/src/server/game/Battlegrounds/Zones/BattlegroundBE.h index 27bd28945..c74be91c7 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBE.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBE.h @@ -34,24 +34,24 @@ enum BattlegroundBEObjects class BattlegroundBE : public Battleground { - public: - BattlegroundBE(); - ~BattlegroundBE(); +public: + BattlegroundBE(); + ~BattlegroundBE(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); - bool SetupBattleground(); - void Init(); - void FillInitialWorldStates(WorldPacket &d); - void HandleKillPlayer(Player* player, Player* killer); - bool HandlePlayerUnderMap(Player* player); + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); + bool SetupBattleground(); + void Init(); + void FillInitialWorldStates(WorldPacket& d); + void HandleKillPlayer(Player* player, Player* killer); + bool HandlePlayerUnderMap(Player* player); - /* Scorekeeping */ - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); + /* Scorekeeping */ + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp index 30f30f646..4ee2b1438 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp @@ -216,7 +216,7 @@ bool BattlegroundDS::HandlePlayerUnderMap(Player* player) return true; } -void BattlegroundDS::FillInitialWorldStates(WorldPacket &data) +void BattlegroundDS::FillInitialWorldStates(WorldPacket& data) { data << uint32(3610) << uint32(1); // 9 show Battleground::UpdateArenaWorldState(); @@ -232,20 +232,20 @@ bool BattlegroundDS::SetupBattleground() { // gates if (!AddObject(BG_DS_OBJECT_DOOR_1, BG_DS_OBJECT_TYPE_DOOR_1, 1350.95f, 817.2f, 20.8096f, 3.15f, 0, 0, 0.99627f, 0.0862864f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_DS_OBJECT_DOOR_2, BG_DS_OBJECT_TYPE_DOOR_2, 1232.65f, 764.913f, 20.0729f, 6.3f, 0, 0, 0.0310211f, -0.999519f, RESPAWN_IMMEDIATELY) - // water - || !AddObject(BG_DS_OBJECT_WATER_1, BG_DS_OBJECT_TYPE_WATER_1, 1291.56f, 790.837f, 7.1f, 3.14238f, 0, 0, 0.694215f, -0.719768f, 120) - || !AddObject(BG_DS_OBJECT_WATER_2, BG_DS_OBJECT_TYPE_WATER_2, 1291.56f, 790.837f, 7.1f, 3.14238f, 0, 0, 0.694215f, -0.719768f, 120) - // buffs - || !AddObject(BG_DS_OBJECT_BUFF_1, BG_DS_OBJECT_TYPE_BUFF_1, 1291.7f, 813.424f, 7.11472f, 4.64562f, 0, 0, 0.730314f, -0.683111f, 120) - || !AddObject(BG_DS_OBJECT_BUFF_2, BG_DS_OBJECT_TYPE_BUFF_2, 1291.7f, 768.911f, 7.11472f, 1.55194f, 0, 0, 0.700409f, 0.713742f, 120) - // knockback creatures - || !AddCreature(BG_DS_NPC_TYPE_WATER_SPOUT, BG_DS_NPC_WATERFALL_KNOCKBACK, 1291.76f, 791.02f, 7.115f, 3.054326f, RESPAWN_IMMEDIATELY) - || !AddCreature(BG_DS_NPC_TYPE_WATER_SPOUT, BG_DS_NPC_PIPE_KNOCKBACK_1, 1369.977f, 817.2882f, 16.08718f, 3.106686f, RESPAWN_IMMEDIATELY) - || !AddCreature(BG_DS_NPC_TYPE_WATER_SPOUT, BG_DS_NPC_PIPE_KNOCKBACK_2, 1212.833f, 765.3871f, 16.09484f, 0.0f, RESPAWN_IMMEDIATELY) - // Arena Ready Marker - || !AddObject(BG_DS_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 1229.44f, 759.35f, 17.89f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) - || !AddObject(BG_DS_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 1352.90f, 822.77f, 17.96f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) + || !AddObject(BG_DS_OBJECT_DOOR_2, BG_DS_OBJECT_TYPE_DOOR_2, 1232.65f, 764.913f, 20.0729f, 6.3f, 0, 0, 0.0310211f, -0.999519f, RESPAWN_IMMEDIATELY) + // water + || !AddObject(BG_DS_OBJECT_WATER_1, BG_DS_OBJECT_TYPE_WATER_1, 1291.56f, 790.837f, 7.1f, 3.14238f, 0, 0, 0.694215f, -0.719768f, 120) + || !AddObject(BG_DS_OBJECT_WATER_2, BG_DS_OBJECT_TYPE_WATER_2, 1291.56f, 790.837f, 7.1f, 3.14238f, 0, 0, 0.694215f, -0.719768f, 120) + // buffs + || !AddObject(BG_DS_OBJECT_BUFF_1, BG_DS_OBJECT_TYPE_BUFF_1, 1291.7f, 813.424f, 7.11472f, 4.64562f, 0, 0, 0.730314f, -0.683111f, 120) + || !AddObject(BG_DS_OBJECT_BUFF_2, BG_DS_OBJECT_TYPE_BUFF_2, 1291.7f, 768.911f, 7.11472f, 1.55194f, 0, 0, 0.700409f, 0.713742f, 120) + // knockback creatures + || !AddCreature(BG_DS_NPC_TYPE_WATER_SPOUT, BG_DS_NPC_WATERFALL_KNOCKBACK, 1291.76f, 791.02f, 7.115f, 3.054326f, RESPAWN_IMMEDIATELY) + || !AddCreature(BG_DS_NPC_TYPE_WATER_SPOUT, BG_DS_NPC_PIPE_KNOCKBACK_1, 1369.977f, 817.2882f, 16.08718f, 3.106686f, RESPAWN_IMMEDIATELY) + || !AddCreature(BG_DS_NPC_TYPE_WATER_SPOUT, BG_DS_NPC_PIPE_KNOCKBACK_2, 1212.833f, 765.3871f, 16.09484f, 0.0f, RESPAWN_IMMEDIATELY) + // Arena Ready Marker + || !AddObject(BG_DS_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 1229.44f, 759.35f, 17.89f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) + || !AddObject(BG_DS_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 1352.90f, 822.77f, 17.96f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { sLog->outErrorDb("BatteGroundDS: Failed to spawn some object!"); return false; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.h b/src/server/game/Battlegrounds/Zones/BattlegroundDS.h index d75c7c9e3..1d6fb4934 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.h @@ -53,7 +53,8 @@ enum BattlegroundDSSpells }; enum BattlegroundDSData -{ // These values are NOT blizzlike... need the correct data! +{ + // These values are NOT blizzlike... need the correct data! BG_DS_WATERFALL_TIMER_MIN = 30000, BG_DS_WATERFALL_TIMER_MAX = 60000, BG_DS_WATERFALL_WARNING_DURATION = 5000, @@ -71,40 +72,40 @@ enum BattlegroundDSData class BattlegroundDS : public Battleground { - public: - BattlegroundDS(); - ~BattlegroundDS(); +public: + BattlegroundDS(); + ~BattlegroundDS(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); - bool SetupBattleground(); - void Init(); - void FillInitialWorldStates(WorldPacket &d); - void HandleKillPlayer(Player* player, Player* killer); - bool HandlePlayerUnderMap(Player* player); - private: - uint32 _waterfallTimer; - uint8 _waterfallStatus; - uint32 _waterfallKnockbackTimer; - uint32 _pipeKnockBackTimer; - uint8 _pipeKnockBackCount; + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); + bool SetupBattleground(); + void Init(); + void FillInitialWorldStates(WorldPacket& d); + void HandleKillPlayer(Player* player, Player* killer); + bool HandlePlayerUnderMap(Player* player); +private: + uint32 _waterfallTimer; + uint8 _waterfallStatus; + uint32 _waterfallKnockbackTimer; + uint32 _pipeKnockBackTimer; + uint8 _pipeKnockBackCount; - void PostUpdateImpl(uint32 diff); - protected: - uint32 getWaterFallStatus() { return _waterfallStatus; }; - void setWaterFallStatus(uint8 status) { _waterfallStatus = status; }; - uint32 getWaterFallTimer() { return _waterfallTimer; }; - void setWaterFallTimer(uint32 timer) { _waterfallTimer = timer; }; - uint32 getWaterFallKnockbackTimer() { return _waterfallKnockbackTimer; }; - void setWaterFallKnockbackTimer(uint32 timer) { _waterfallKnockbackTimer = timer; }; - uint8 getPipeKnockBackCount() { return _pipeKnockBackCount; }; - void setPipeKnockBackCount(uint8 count) { _pipeKnockBackCount = count; }; - uint32 getPipeKnockBackTimer() { return _pipeKnockBackTimer; }; - void setPipeKnockBackTimer(uint32 timer) { _pipeKnockBackTimer = timer; }; + void PostUpdateImpl(uint32 diff); +protected: + uint32 getWaterFallStatus() { return _waterfallStatus; }; + void setWaterFallStatus(uint8 status) { _waterfallStatus = status; }; + uint32 getWaterFallTimer() { return _waterfallTimer; }; + void setWaterFallTimer(uint32 timer) { _waterfallTimer = timer; }; + uint32 getWaterFallKnockbackTimer() { return _waterfallKnockbackTimer; }; + void setWaterFallKnockbackTimer(uint32 timer) { _waterfallKnockbackTimer = timer; }; + uint8 getPipeKnockBackCount() { return _pipeKnockBackCount; }; + void setPipeKnockBackCount(uint8 count) { _pipeKnockBackCount = count; }; + uint32 getPipeKnockBackTimer() { return _pipeKnockBackTimer; }; + void setPipeKnockBackTimer(uint32 timer) { _pipeKnockBackTimer = timer; }; }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp index 11b0ddaba..03054227f 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp @@ -90,7 +90,7 @@ void BattlegroundEY::StartingEventOpenDoors() SpawnBGObject(i, RESPAWN_IMMEDIATELY); for (uint32 i = 0; i < EY_POINTS_MAX; ++i) - SpawnBGObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i*3 + urand(0, 2), RESPAWN_IMMEDIATELY); + SpawnBGObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + urand(0, 2), RESPAWN_IMMEDIATELY); // Achievement: Flurry StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, BG_EY_EVENT_START_BATTLE); @@ -150,7 +150,7 @@ void BattlegroundEY::UpdatePointsState() pointOwnerTeamId = TEAM_HORDE; else if (_capturePointInfo[point]._barStatus >= BG_EY_PROGRESS_BAR_NEUTRAL_HIGH) pointOwnerTeamId = TEAM_ALLIANCE; - + if (pointOwnerTeamId != _capturePointInfo[point]._ownerTeamId) { if (_capturePointInfo[point].IsUncontrolled()) @@ -248,10 +248,10 @@ void BattlegroundEY::HandleAreaTrigger(Player* player, uint32 trigger) bool BattlegroundEY::SetupBattleground() { - // doors + // doors AddObject(BG_EY_OBJECT_DOOR_A, BG_OBJECT_A_DOOR_EY_ENTRY, 2527.6f, 1596.91f, 1262.13f, -3.12414f, -0.173642f, -0.001515f, 0.98477f, -0.008594f, RESPAWN_IMMEDIATELY); AddObject(BG_EY_OBJECT_DOOR_H, BG_OBJECT_H_DOOR_EY_ENTRY, 1803.21f, 1539.49f, 1261.09f, 3.14159f, 0.173648f, 0, 0.984808f, 0, RESPAWN_IMMEDIATELY); - // banners (alliance) + // banners (alliance) AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY); @@ -264,7 +264,7 @@ bool BattlegroundEY::SetupBattleground() AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY); - // banners (horde) + // banners (horde) AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY); @@ -277,7 +277,7 @@ bool BattlegroundEY::SetupBattleground() AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY); - // banners (natural) + // banners (natural) AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY); @@ -290,13 +290,13 @@ bool BattlegroundEY::SetupBattleground() AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY); - // flags + // flags AddObject(BG_EY_OBJECT_FLAG_NETHERSTORM, BG_OBJECT_FLAG2_EY_ENTRY, 2174.782227f, 1569.054688f, 1160.361938f, -1.448624f, 0, 0, 0.662620f, -0.748956f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_FLAG_FEL_REAVER, BG_OBJECT_FLAG1_EY_ENTRY, 2044.28f, 1729.68f, 1189.96f, -0.017453f, 0, 0, 0.008727f, -0.999962f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_FLAG_BLOOD_ELF, BG_OBJECT_FLAG1_EY_ENTRY, 2048.83f, 1393.65f, 1194.49f, 0.20944f, 0, 0, 0.104528f, 0.994522f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_FLAG_DRAENEI_RUINS, BG_OBJECT_FLAG1_EY_ENTRY, 2286.56f, 1402.36f, 1197.11f, 3.72381f, 0, 0, 0.957926f, -0.287016f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_FLAG_MAGE_TOWER, BG_OBJECT_FLAG1_EY_ENTRY, 2284.48f, 1731.23f, 1189.99f, 2.89725f, 0, 0, 0.992546f, 0.121869f, RESPAWN_ONE_DAY); - // tower cap + // tower cap AddObject(BG_EY_OBJECT_TOWER_CAP_FEL_REAVER, BG_OBJECT_FR_TOWER_CAP_EY_ENTRY, 2024.600708f, 1742.819580f, 1195.157715f, 2.443461f, 0, 0, 0.939693f, 0.342020f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_TOWER_CAP_BLOOD_ELF, BG_OBJECT_BE_TOWER_CAP_EY_ENTRY, 2050.493164f, 1372.235962f, 1194.563477f, 1.710423f, 0, 0, 0.754710f, 0.656059f, RESPAWN_ONE_DAY); AddObject(BG_EY_OBJECT_TOWER_CAP_DRAENEI_RUINS, BG_OBJECT_DR_TOWER_CAP_EY_ENTRY, 2301.010498f, 1386.931641f, 1197.183472f, 1.570796f, 0, 0, 0.707107f, 0.707107f, RESPAWN_ONE_DAY); @@ -490,7 +490,7 @@ void BattlegroundEY::EventTeamCapturedPoint(TeamId teamId, uint32 point) // Xinef: done this way to avoid errors in console Creature* trigger = GetBgMap()->GetCreature(BgCreatures[BG_EY_TRIGGER_FEL_REAVER + point]); if (!trigger) - trigger = AddCreature(WORLD_TRIGGER, BG_EY_TRIGGER_FEL_REAVER + point, BG_EY_TriggerPositions[point][0], BG_EY_TriggerPositions[point][1], BG_EY_TriggerPositions[point][2], BG_EY_TriggerPositions[point][3]); + trigger = AddCreature(WORLD_TRIGGER, BG_EY_TRIGGER_FEL_REAVER + point, BG_EY_TriggerPositions[point][0], BG_EY_TriggerPositions[point][1], BG_EY_TriggerPositions[point][2], BG_EY_TriggerPositions[point][3]); if (trigger) { @@ -574,14 +574,14 @@ GraveyardStruct const* BattlegroundEY::GetClosestGraveyard(Player* player) float pX = player->GetPositionX(); float pY = player->GetPositionY(); float pZ = player->GetPositionZ(); - float dist = (entry->x - pX)*(entry->x - pX) + (entry->y - pY)*(entry->y - pY) + (entry->z - pZ)*(entry->z - pZ); + float dist = (entry->x - pX) * (entry->x - pX) + (entry->y - pY) * (entry->y - pY) + (entry->z - pZ) * (entry->z - pZ); float minDist = dist; for (uint8 i = 0; i < EY_POINTS_MAX; ++i) if (_capturePointInfo[i].IsUnderControl(player->GetTeamId())) { entry = sGraveyard->GetGraveyard(m_CapturingPointTypes[i].GraveYardId); - dist = (entry->x - pX)*(entry->x - pX) + (entry->y - pY)*(entry->y - pY) + (entry->z - pZ)*(entry->z - pZ); + dist = (entry->x - pX) * (entry->x - pX) + (entry->y - pY) * (entry->y - pY) + (entry->z - pZ) * (entry->z - pZ); if (dist < minDist) { minDist = dist; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.h b/src/server/game/Battlegrounds/Zones/BattlegroundEY.h index 3740147b3..f9836cf36 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.h @@ -18,10 +18,10 @@ enum BG_EY_Events enum BG_EY_Timers { - BG_EY_FLAG_RESPAWN_TIME = 20*IN_MILLISECONDS, - BG_EY_FLAG_ON_GROUND_TIME = 10*IN_MILLISECONDS, - BG_EY_FPOINTS_CHECK_TIME = 2*IN_MILLISECONDS, - BG_EY_FPOINTS_TICK_TIME = 1*IN_MILLISECONDS + BG_EY_FLAG_RESPAWN_TIME = 20 * IN_MILLISECONDS, + BG_EY_FLAG_ON_GROUND_TIME = 10 * IN_MILLISECONDS, + BG_EY_FPOINTS_CHECK_TIME = 2 * IN_MILLISECONDS, + BG_EY_FPOINTS_TICK_TIME = 1 * IN_MILLISECONDS }; enum BG_EY_WorldStates @@ -249,8 +249,8 @@ struct BattlegroundEYLosingPointStruct { BattlegroundEYLosingPointStruct(uint32 _SpawnNeutralObjectType, uint32 _DespawnObjectTypeAlliance, uint32 _MessageIdAlliance, uint32 _DespawnObjectTypeHorde, uint32 _MessageIdHorde) : SpawnNeutralObjectType(_SpawnNeutralObjectType), - DespawnObjectTypeAlliance(_DespawnObjectTypeAlliance), MessageIdAlliance(_MessageIdAlliance), - DespawnObjectTypeHorde(_DespawnObjectTypeHorde), MessageIdHorde(_MessageIdHorde) + DespawnObjectTypeAlliance(_DespawnObjectTypeAlliance), MessageIdAlliance(_MessageIdAlliance), + DespawnObjectTypeHorde(_DespawnObjectTypeHorde), MessageIdHorde(_MessageIdHorde) {} uint32 SpawnNeutralObjectType; @@ -264,9 +264,9 @@ struct BattlegroundEYCapturingPointStruct { BattlegroundEYCapturingPointStruct(uint32 _DespawnNeutralObjectType, uint32 _SpawnObjectTypeAlliance, uint32 _MessageIdAlliance, uint32 _SpawnObjectTypeHorde, uint32 _MessageIdHorde, uint32 _GraveYardId) : DespawnNeutralObjectType(_DespawnNeutralObjectType), - SpawnObjectTypeAlliance(_SpawnObjectTypeAlliance), MessageIdAlliance(_MessageIdAlliance), - SpawnObjectTypeHorde(_SpawnObjectTypeHorde), MessageIdHorde(_MessageIdHorde), - GraveYardId(_GraveYardId) + SpawnObjectTypeAlliance(_SpawnObjectTypeAlliance), MessageIdAlliance(_MessageIdAlliance), + SpawnObjectTypeHorde(_SpawnObjectTypeHorde), MessageIdHorde(_MessageIdHorde), + GraveYardId(_GraveYardId) {} uint32 DespawnNeutralObjectType; @@ -316,84 +316,84 @@ struct BattlegroundEYScore : public BattlegroundScore class BattlegroundEY : public Battleground { - public: - BattlegroundEY(); - ~BattlegroundEY(); +public: + BattlegroundEY(); + ~BattlegroundEY(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); - /* BG Flags */ - uint64 GetFlagPickerGUID(TeamId /*teamId*/ = TEAM_NEUTRAL) const { return _flagKeeperGUID; } - void SetFlagPicker(uint64 guid) { _flagKeeperGUID = guid; } - uint8 GetFlagState() const { return _flagState; } - void RespawnFlag(); - void RespawnFlagAfterDrop(); + /* BG Flags */ + uint64 GetFlagPickerGUID(TeamId /*teamId*/ = TEAM_NEUTRAL) const { return _flagKeeperGUID; } + void SetFlagPicker(uint64 guid) { _flagKeeperGUID = guid; } + uint8 GetFlagState() const { return _flagState; } + void RespawnFlag(); + void RespawnFlagAfterDrop(); - void RemovePlayer(Player* player); - void HandleBuffUse(uint64 buff_guid); - void HandleAreaTrigger(Player* player, uint32 trigger); - void HandleKillPlayer(Player* player, Player* killer); - GraveyardStruct const* GetClosestGraveyard(Player* player); - bool SetupBattleground(); - void Init(); - void EndBattleground(TeamId winnerTeamId); - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); - void FillInitialWorldStates(WorldPacket& data); - void SetDroppedFlagGUID(uint64 guid, TeamId /*teamId*/ = TEAM_NEUTRAL) { _droppedFlagGUID = guid; } - uint64 GetDroppedFlagGUID() const { return _droppedFlagGUID; } + void RemovePlayer(Player* player); + void HandleBuffUse(uint64 buff_guid); + void HandleAreaTrigger(Player* player, uint32 trigger); + void HandleKillPlayer(Player* player, Player* killer); + GraveyardStruct const* GetClosestGraveyard(Player* player); + bool SetupBattleground(); + void Init(); + void EndBattleground(TeamId winnerTeamId); + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); + void FillInitialWorldStates(WorldPacket& data); + void SetDroppedFlagGUID(uint64 guid, TeamId /*teamId*/ = TEAM_NEUTRAL) { _droppedFlagGUID = guid; } + uint64 GetDroppedFlagGUID() const { return _droppedFlagGUID; } - /* Battleground Events */ - void EventPlayerClickedOnFlag(Player* player, GameObject* gameObject); - void EventPlayerDroppedFlag(Player* player); + /* Battleground Events */ + void EventPlayerClickedOnFlag(Player* player, GameObject* gameObject); + void EventPlayerDroppedFlag(Player* player); - /* achievement req. */ - bool AllNodesConrolledByTeam(TeamId teamId) const; - TeamId GetPrematureWinner(); + /* achievement req. */ + bool AllNodesConrolledByTeam(TeamId teamId) const; + TeamId GetPrematureWinner(); - private: - void PostUpdateImpl(uint32 diff); +private: + void PostUpdateImpl(uint32 diff); - void EventPlayerCapturedFlag(Player* Source, uint32 BgObjectType); - void EventTeamLostPoint(TeamId teamId, uint32 point); - void EventTeamCapturedPoint(TeamId teamId, uint32 point); - void UpdatePointsCount(); - void UpdatePointsIcons(uint32 point); + void EventPlayerCapturedFlag(Player* Source, uint32 BgObjectType); + void EventTeamLostPoint(TeamId teamId, uint32 point); + void EventTeamCapturedPoint(TeamId teamId, uint32 point); + void UpdatePointsCount(); + void UpdatePointsIcons(uint32 point); - /* Point status updating procedures */ - void UpdatePointsState(); + /* Point status updating procedures */ + void UpdatePointsState(); - /* Scorekeeping */ - void AddPoints(TeamId teamId, uint32 points); + /* Scorekeeping */ + void AddPoints(TeamId teamId, uint32 points); - struct CapturePointInfo + struct CapturePointInfo + { + CapturePointInfo() : _ownerTeamId(TEAM_NEUTRAL), _barStatus(BG_EY_PROGRESS_BAR_STATE_MIDDLE), _areaTrigger(0) { - CapturePointInfo() : _ownerTeamId(TEAM_NEUTRAL), _barStatus(BG_EY_PROGRESS_BAR_STATE_MIDDLE), _areaTrigger(0) - { - _playersCount[TEAM_ALLIANCE] = 0; - _playersCount[TEAM_HORDE] = 0; - } + _playersCount[TEAM_ALLIANCE] = 0; + _playersCount[TEAM_HORDE] = 0; + } - TeamId _ownerTeamId; - int8 _barStatus; - uint32 _areaTrigger; - int8 _playersCount[BG_TEAMS_COUNT]; + TeamId _ownerTeamId; + int8 _barStatus; + uint32 _areaTrigger; + int8 _playersCount[BG_TEAMS_COUNT]; - bool IsUnderControl(TeamId teamId) const { return _ownerTeamId == teamId; } - bool IsUnderControl() const { return _ownerTeamId != TEAM_NEUTRAL; } - bool IsUncontrolled() const { return _ownerTeamId == TEAM_NEUTRAL; } - }; + bool IsUnderControl(TeamId teamId) const { return _ownerTeamId == teamId; } + bool IsUnderControl() const { return _ownerTeamId != TEAM_NEUTRAL; } + bool IsUncontrolled() const { return _ownerTeamId == TEAM_NEUTRAL; } + }; - CapturePointInfo _capturePointInfo[EY_POINTS_MAX]; - EventMap _bgEvents; - uint32 _honorTics; - uint8 _ownedPointsCount[BG_TEAMS_COUNT]; - uint64 _flagKeeperGUID; - uint64 _droppedFlagGUID; - uint8 _flagState; - uint32 _flagCapturedObject; + CapturePointInfo _capturePointInfo[EY_POINTS_MAX]; + EventMap _bgEvents; + uint32 _honorTics; + uint8 _ownedPointsCount[BG_TEAMS_COUNT]; + uint64 _flagKeeperGUID; + uint64 _droppedFlagGUID; + uint8 _flagState; + uint32 _flagCapturedObject; }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp index 47ae2c6e9..916fc58e2 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp @@ -106,7 +106,8 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) GetBGObject(BG_IC_GO_HORDE_GATE_3)->SetDestructibleState(GO_DESTRUCTIBLE_DAMAGED); doorsClosed = true; - } else closeFortressDoorsTimer -= diff; + } + else closeFortressDoorsTimer -= diff; } for (uint8 i = NODE_TYPE_REFINERY; i < MAX_NODE_TYPES; ++i) @@ -114,14 +115,14 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) if (nodePoint[i].nodeType == NODE_TYPE_DOCKS) { if (nodePoint[i].nodeState == NODE_STATE_CONTROLLED_A || - nodePoint[i].nodeState == NODE_STATE_CONTROLLED_H) + nodePoint[i].nodeState == NODE_STATE_CONTROLLED_H) { if (nodePoint[i].timer <= diff) { // we need to confirm this, i am not sure if this every 3 minutes for (uint8 j = 0; j < MAX_CATAPULTS_SPAWNS_PER_FACTION; ++j) { - uint8 type = (nodePoint[i].faction == TEAM_ALLIANCE ? BG_IC_NPC_CATAPULT_1_A : BG_IC_NPC_CATAPULT_1_H)+j; + uint8 type = (nodePoint[i].faction == TEAM_ALLIANCE ? BG_IC_NPC_CATAPULT_1_A : BG_IC_NPC_CATAPULT_1_H) + j; if (Creature* catapult = GetBgMap()->GetCreature(BgCreatures[type])) if (!catapult->IsAlive()) { @@ -139,7 +140,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) // we need to confirm this is blizzlike, not sure if it is every 3 minutes for (uint8 j = 0; j < MAX_GLAIVE_THROWERS_SPAWNS_PER_FACTION; ++j) { - uint8 type = (nodePoint[i].faction == TEAM_ALLIANCE ? BG_IC_NPC_GLAIVE_THROWER_1_A : BG_IC_NPC_GLAIVE_THROWER_1_H)+j; + uint8 type = (nodePoint[i].faction == TEAM_ALLIANCE ? BG_IC_NPC_GLAIVE_THROWER_1_A : BG_IC_NPC_GLAIVE_THROWER_1_H) + j; if (Creature* glaiveThrower = GetBgMap()->GetCreature(BgCreatures[type])) if (!glaiveThrower->IsAlive()) { @@ -164,7 +165,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) if (nodePoint[i].nodeType == NODE_TYPE_WORKSHOP) { if (nodePoint[i].nodeState == NODE_STATE_CONTROLLED_A || - nodePoint[i].nodeState == NODE_STATE_CONTROLLED_H) + nodePoint[i].nodeState == NODE_STATE_CONTROLLED_H) { if (siegeEngineWorkshopTimer <= diff) { @@ -185,7 +186,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) // we need to confirm this, i am not sure if this every 3 minutes for (uint8 u = 0; u < MAX_DEMOLISHERS_SPAWNS_PER_FACTION; ++u) { - uint8 type = (nodePoint[i].faction == TEAM_ALLIANCE ? BG_IC_NPC_DEMOLISHER_1_A : BG_IC_NPC_DEMOLISHER_1_H)+u; + uint8 type = (nodePoint[i].faction == TEAM_ALLIANCE ? BG_IC_NPC_DEMOLISHER_1_A : BG_IC_NPC_DEMOLISHER_1_H) + u; if (Creature* demolisher = GetBgMap()->GetCreature(BgCreatures[type])) if (!demolisher->IsAlive()) { @@ -237,7 +238,8 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) nodePoint[i].needChange = false; nodePoint[i].timer = BANNER_STATE_CHANGE_TIME; - } else nodePoint[i].timer -= diff; + } + else nodePoint[i].timer -= diff; } } @@ -246,7 +248,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) for (uint8 i = 0; i < NODE_TYPE_DOCKS; ++i) { if (nodePoint[i].nodeState == NODE_STATE_CONTROLLED_A || - nodePoint[i].nodeState == NODE_STATE_CONTROLLED_H) + nodePoint[i].nodeState == NODE_STATE_CONTROLLED_H) { factionReinforcements[nodePoint[i].faction] += 1; RewardHonorToTeam(RESOURCE_HONOR_AMOUNT, nodePoint[i].faction); @@ -254,7 +256,8 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) } } resourceTimer = IC_RESOURCE_TIME; - } else resourceTimer -= diff; + } + else resourceTimer -= diff; } void BattlegroundIC::StartingEventCloseDoors() @@ -431,10 +434,10 @@ bool BattlegroundIC::SetupBattleground() } } - if (!AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1+3, BG_IC_SpiritGuidePos[5][0], BG_IC_SpiritGuidePos[5][1], BG_IC_SpiritGuidePos[5][2], BG_IC_SpiritGuidePos[5][3], TEAM_ALLIANCE) - || !AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1+4, BG_IC_SpiritGuidePos[6][0], BG_IC_SpiritGuidePos[6][1], BG_IC_SpiritGuidePos[6][2], BG_IC_SpiritGuidePos[6][3], TEAM_HORDE) - || !AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1+5, BG_IC_SpiritGuidePos[7][0], BG_IC_SpiritGuidePos[7][1], BG_IC_SpiritGuidePos[7][2], BG_IC_SpiritGuidePos[7][3], TEAM_ALLIANCE) - || !AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1+6, BG_IC_SpiritGuidePos[8][0], BG_IC_SpiritGuidePos[8][1], BG_IC_SpiritGuidePos[8][2], BG_IC_SpiritGuidePos[8][3], TEAM_HORDE)) + if (!AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1 + 3, BG_IC_SpiritGuidePos[5][0], BG_IC_SpiritGuidePos[5][1], BG_IC_SpiritGuidePos[5][2], BG_IC_SpiritGuidePos[5][3], TEAM_ALLIANCE) + || !AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1 + 4, BG_IC_SpiritGuidePos[6][0], BG_IC_SpiritGuidePos[6][1], BG_IC_SpiritGuidePos[6][2], BG_IC_SpiritGuidePos[6][3], TEAM_HORDE) + || !AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1 + 5, BG_IC_SpiritGuidePos[7][0], BG_IC_SpiritGuidePos[7][1], BG_IC_SpiritGuidePos[7][2], BG_IC_SpiritGuidePos[7][3], TEAM_ALLIANCE) + || !AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1 + 6, BG_IC_SpiritGuidePos[8][0], BG_IC_SpiritGuidePos[8][1], BG_IC_SpiritGuidePos[8][2], BG_IC_SpiritGuidePos[8][3], TEAM_HORDE)) { sLog->outError("Isle of Conquest: Failed to spawn initial spirit guide!"); return false; @@ -496,7 +499,7 @@ void BattlegroundIC::TurnBosses(bool on) void BattlegroundIC::HandleKillUnit(Creature* unit, Player* killer) { if (GetStatus() != STATUS_IN_PROGRESS) - return; + return; uint32 entry = unit->GetEntry(); if (entry == NPC_HIGH_COMMANDER_HALFORD_WYRMBANE) @@ -518,7 +521,7 @@ void BattlegroundIC::HandleKillUnit(Creature* unit, Player* killer) // Xinef: Add to respawn list if (entry == NPC_DEMOLISHER || entry == NPC_SIEGE_ENGINE_H || entry == NPC_SIEGE_ENGINE_A || - entry == NPC_GLAIVE_THROWER_A || entry == NPC_GLAIVE_THROWER_H || entry == NPC_CATAPULT) + entry == NPC_GLAIVE_THROWER_A || entry == NPC_GLAIVE_THROWER_H || entry == NPC_CATAPULT) respawnMap[unit->GetGUIDLow()] = time(nullptr) + VEHICLE_RESPAWN_TIME; } } @@ -563,15 +566,15 @@ void BattlegroundIC::EventPlayerClickedOnFlag(Player* player, GameObject* gameOb if (nodePoint[i].gameobject_entry == GO_ALLIANCE_BANNER) { if (GateStatus[BG_IC_A_FRONT] != BG_IC_GATE_DESTROYED && - GateStatus[BG_IC_A_WEST] != BG_IC_GATE_DESTROYED && - GateStatus[BG_IC_A_EAST] != BG_IC_GATE_DESTROYED) + GateStatus[BG_IC_A_WEST] != BG_IC_GATE_DESTROYED && + GateStatus[BG_IC_A_EAST] != BG_IC_GATE_DESTROYED) return; } else if (nodePoint[i].gameobject_entry == GO_HORDE_BANNER) { if (GateStatus[BG_IC_H_FRONT] != BG_IC_GATE_DESTROYED && - GateStatus[BG_IC_H_WEST] != BG_IC_GATE_DESTROYED && - GateStatus[BG_IC_H_EAST] != BG_IC_GATE_DESTROYED) + GateStatus[BG_IC_H_WEST] != BG_IC_GATE_DESTROYED && + GateStatus[BG_IC_H_EAST] != BG_IC_GATE_DESTROYED) return; } @@ -593,8 +596,8 @@ void BattlegroundIC::EventPlayerClickedOnFlag(Player* player, GameObject* gameOb // if we are here means that the point has been lost, or it is the first capture if (nodePoint[i].nodeType != NODE_TYPE_REFINERY && nodePoint[i].nodeType != NODE_TYPE_QUARRY) - if (BgCreatures[BG_IC_NPC_SPIRIT_GUIDE_1+(nodePoint[i].nodeType)-2]) - DelCreature(BG_IC_NPC_SPIRIT_GUIDE_1+(nodePoint[i].nodeType)-2); + if (BgCreatures[BG_IC_NPC_SPIRIT_GUIDE_1 + (nodePoint[i].nodeType) - 2]) + DelCreature(BG_IC_NPC_SPIRIT_GUIDE_1 + (nodePoint[i].nodeType) - 2); UpdatePlayerScore(player, SCORE_BASES_ASSAULTED, 1); @@ -603,7 +606,7 @@ void BattlegroundIC::EventPlayerClickedOnFlag(Player* player, GameObject* gameOb HandleContestedNodes(&nodePoint[i]); } else if (nextBanner == nodePoint[i].banners[BANNER_A_CONTROLLED] || nextBanner == nodePoint[i].banners[BANNER_H_CONTROLLED]) - // if we are going to spawn the definitve faction banner, we dont need the timer anymore + // if we are going to spawn the definitve faction banner, we dont need the timer anymore { nodePoint[i].timer = BANNER_STATE_CHANGE_TIME; nodePoint[i].needChange = false; @@ -722,65 +725,65 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture) { if (nodePoint->nodeType != NODE_TYPE_REFINERY && nodePoint->nodeType != NODE_TYPE_QUARRY) { - if (!AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1+nodePoint->nodeType-2, - BG_IC_SpiritGuidePos[nodePoint->nodeType][0], BG_IC_SpiritGuidePos[nodePoint->nodeType][1], - BG_IC_SpiritGuidePos[nodePoint->nodeType][2], BG_IC_SpiritGuidePos[nodePoint->nodeType][3], - nodePoint->faction)) + if (!AddSpiritGuide(BG_IC_NPC_SPIRIT_GUIDE_1 + nodePoint->nodeType - 2, + BG_IC_SpiritGuidePos[nodePoint->nodeType][0], BG_IC_SpiritGuidePos[nodePoint->nodeType][1], + BG_IC_SpiritGuidePos[nodePoint->nodeType][2], BG_IC_SpiritGuidePos[nodePoint->nodeType][3], + nodePoint->faction)) sLog->outError("Isle of Conquest: Failed to spawn spirit guide! point: %u, team: %u, ", nodePoint->nodeType, nodePoint->faction); } switch (nodePoint->gameobject_type) { case BG_IC_GO_HANGAR_BANNER: - { - if (!gunshipAlliance || !gunshipHorde) + { + if (!gunshipAlliance || !gunshipHorde) + break; + + std::list cannons; + if (nodePoint->faction == TEAM_ALLIANCE) + gunshipAlliance->GetCreatureListWithEntryInGrid(cannons, NPC_ALLIANCE_GUNSHIP_CANNON, 150.0f); + else + gunshipHorde->GetCreatureListWithEntryInGrid(cannons, NPC_HORDE_GUNSHIP_CANNON, 150.0f); + + for (std::list::const_iterator itr = cannons.begin(); itr != cannons.end(); ++itr) + (*itr)->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + + for (uint8 u = 0; u < MAX_HANGAR_TELEPORTERS_SPAWNS; ++u) + { + uint8 type = BG_IC_GO_HANGAR_TELEPORTER_1 + u; + if (!AddObject(type, (nodePoint->faction == TEAM_ALLIANCE ? GO_ALLIANCE_GUNSHIP_PORTAL : GO_HORDE_GUNSHIP_PORTAL), BG_IC_HangarTeleporters[u].GetPositionX(), BG_IC_HangarTeleporters[u].GetPositionY(), BG_IC_HangarTeleporters[u].GetPositionZ(), BG_IC_HangarTeleporters[u].GetOrientation(), 0, 0, 0, 0, RESPAWN_ONE_DAY)) + sLog->outError("Isle of Conquest: There was an error spawning a gunship portal. Type: %u", BG_IC_GO_HANGAR_TELEPORTER_1 + u); + } + + for (uint8 u = 0; u < MAX_HANGAR_TELEPORTER_EFFECTS_SPAWNS; ++u) + { + uint8 type = BG_IC_GO_HANGAR_TELEPORTER_EFFECT_1 + u; + if (!AddObject(type, (nodePoint->faction == TEAM_ALLIANCE ? GO_ALLIANCE_GUNSHIP_PORTAL_EFFECTS : GO_HORDE_GUNSHIP_PORTAL_EFFECTS), BG_IC_HangarTeleporterEffects[u].GetPositionX(), BG_IC_HangarTeleporterEffects[u].GetPositionY(), BG_IC_HangarTeleporterEffects[u].GetPositionZ(), BG_IC_HangarTeleporterEffects[u].GetOrientation(), 0, 0, 0, 0, RESPAWN_ONE_DAY, GO_STATE_ACTIVE)) + sLog->outError("Isle of Conquest: There was an error spawning a gunship portal effects. Type: %u", BG_IC_GO_HANGAR_TELEPORTER_1 + u); + } + + for (uint8 u = 0; u < MAX_TRIGGER_SPAWNS_PER_FACTION; ++u) + { + if (!AddCreature(NPC_WORLD_TRIGGER_NOT_FLOATING, BG_IC_NPC_WORLD_TRIGGER_NOT_FLOATING, BG_IC_HangarTrigger[nodePoint->faction].GetPositionX(), BG_IC_HangarTrigger[nodePoint->faction].GetPositionY(), BG_IC_HangarTrigger[nodePoint->faction].GetPositionZ(), BG_IC_HangarTrigger[nodePoint->faction].GetOrientation(), RESPAWN_ONE_DAY, nodePoint->faction == TEAM_ALLIANCE ? gunshipAlliance : gunshipHorde)) + sLog->outError("Isle of Conquest: There was an error spawning a world trigger. Type: %u", BG_IC_NPC_WORLD_TRIGGER_NOT_FLOATING); + } + + for (uint8 u = 0; u < MAX_CAPTAIN_SPAWNS_PER_FACTION; ++u) + { + uint8 type = BG_IC_NPC_GUNSHIP_CAPTAIN_1 + u; + + if (type == BG_IC_NPC_GUNSHIP_CAPTAIN_1) + if (AddCreature(nodePoint->faction == TEAM_ALLIANCE ? NPC_ALLIANCE_GUNSHIP_CAPTAIN : NPC_HORDE_GUNSHIP_CAPTAIN, type, BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetPositionX(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetPositionY(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetPositionZ(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetOrientation(), RESPAWN_ONE_DAY)) + GetBGCreature(BG_IC_NPC_GUNSHIP_CAPTAIN_1)->GetAI()->DoAction(ACTION_GUNSHIP_READY); + + if (type == BG_IC_NPC_GUNSHIP_CAPTAIN_2) + if (!AddCreature(nodePoint->faction == TEAM_ALLIANCE ? NPC_ALLIANCE_GUNSHIP_CAPTAIN : NPC_HORDE_GUNSHIP_CAPTAIN, type, BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetPositionX(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetPositionY(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetPositionZ(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetOrientation(), RESPAWN_ONE_DAY, nodePoint->faction == TEAM_ALLIANCE ? gunshipAlliance : gunshipHorde)) + sLog->outError("Isle of Conquest: There was an error spawning a world trigger. Type: %u", BG_IC_NPC_GUNSHIP_CAPTAIN_2); + } + + (nodePoint->faction == TEAM_ALLIANCE ? gunshipAlliance : gunshipHorde)->EnableMovement(true); break; - - std::list cannons; - if (nodePoint->faction == TEAM_ALLIANCE) - gunshipAlliance->GetCreatureListWithEntryInGrid(cannons, NPC_ALLIANCE_GUNSHIP_CANNON, 150.0f); - else - gunshipHorde->GetCreatureListWithEntryInGrid(cannons, NPC_HORDE_GUNSHIP_CANNON, 150.0f); - - for (std::list::const_iterator itr = cannons.begin(); itr != cannons.end(); ++itr) - (*itr)->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - - for (uint8 u = 0; u < MAX_HANGAR_TELEPORTERS_SPAWNS; ++u) - { - uint8 type = BG_IC_GO_HANGAR_TELEPORTER_1 + u; - if (!AddObject(type, (nodePoint->faction == TEAM_ALLIANCE ? GO_ALLIANCE_GUNSHIP_PORTAL : GO_HORDE_GUNSHIP_PORTAL), BG_IC_HangarTeleporters[u].GetPositionX(), BG_IC_HangarTeleporters[u].GetPositionY(), BG_IC_HangarTeleporters[u].GetPositionZ(), BG_IC_HangarTeleporters[u].GetOrientation(), 0, 0, 0, 0, RESPAWN_ONE_DAY)) - sLog->outError("Isle of Conquest: There was an error spawning a gunship portal. Type: %u", BG_IC_GO_HANGAR_TELEPORTER_1 + u); } - - for (uint8 u = 0; u < MAX_HANGAR_TELEPORTER_EFFECTS_SPAWNS; ++u) - { - uint8 type = BG_IC_GO_HANGAR_TELEPORTER_EFFECT_1 + u; - if (!AddObject(type, (nodePoint->faction == TEAM_ALLIANCE ? GO_ALLIANCE_GUNSHIP_PORTAL_EFFECTS : GO_HORDE_GUNSHIP_PORTAL_EFFECTS), BG_IC_HangarTeleporterEffects[u].GetPositionX(), BG_IC_HangarTeleporterEffects[u].GetPositionY(), BG_IC_HangarTeleporterEffects[u].GetPositionZ(), BG_IC_HangarTeleporterEffects[u].GetOrientation(), 0, 0, 0, 0, RESPAWN_ONE_DAY, GO_STATE_ACTIVE)) - sLog->outError("Isle of Conquest: There was an error spawning a gunship portal effects. Type: %u", BG_IC_GO_HANGAR_TELEPORTER_1 + u); - } - - for (uint8 u = 0; u < MAX_TRIGGER_SPAWNS_PER_FACTION; ++u) - { - if (!AddCreature(NPC_WORLD_TRIGGER_NOT_FLOATING, BG_IC_NPC_WORLD_TRIGGER_NOT_FLOATING, BG_IC_HangarTrigger[nodePoint->faction].GetPositionX(), BG_IC_HangarTrigger[nodePoint->faction].GetPositionY(), BG_IC_HangarTrigger[nodePoint->faction].GetPositionZ(), BG_IC_HangarTrigger[nodePoint->faction].GetOrientation(), RESPAWN_ONE_DAY, nodePoint->faction == TEAM_ALLIANCE ? gunshipAlliance : gunshipHorde)) - sLog->outError("Isle of Conquest: There was an error spawning a world trigger. Type: %u", BG_IC_NPC_WORLD_TRIGGER_NOT_FLOATING); - } - - for (uint8 u = 0; u < MAX_CAPTAIN_SPAWNS_PER_FACTION; ++u) - { - uint8 type = BG_IC_NPC_GUNSHIP_CAPTAIN_1 + u; - - if (type == BG_IC_NPC_GUNSHIP_CAPTAIN_1) - if (AddCreature(nodePoint->faction == TEAM_ALLIANCE ? NPC_ALLIANCE_GUNSHIP_CAPTAIN : NPC_HORDE_GUNSHIP_CAPTAIN, type, BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetPositionX(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetPositionY(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetPositionZ(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 2 : 0].GetOrientation(), RESPAWN_ONE_DAY)) - GetBGCreature(BG_IC_NPC_GUNSHIP_CAPTAIN_1)->GetAI()->DoAction(ACTION_GUNSHIP_READY); - - if (type == BG_IC_NPC_GUNSHIP_CAPTAIN_2) - if (!AddCreature(nodePoint->faction == TEAM_ALLIANCE ? NPC_ALLIANCE_GUNSHIP_CAPTAIN : NPC_HORDE_GUNSHIP_CAPTAIN, type, BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetPositionX(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetPositionY(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetPositionZ(), BG_IC_HangarCaptains[nodePoint->faction == TEAM_ALLIANCE ? 3 : 1].GetOrientation(), RESPAWN_ONE_DAY, nodePoint->faction == TEAM_ALLIANCE ? gunshipAlliance : gunshipHorde)) - sLog->outError("Isle of Conquest: There was an error spawning a world trigger. Type: %u", BG_IC_NPC_GUNSHIP_CAPTAIN_2); - } - - (nodePoint->faction == TEAM_ALLIANCE ? gunshipAlliance : gunshipHorde)->EnableMovement(true); - break; - } case BG_IC_GO_QUARRY_BANNER: RemoveAuraOnTeam(SPELL_QUARRY, GetOtherTeamId(nodePoint->faction)); CastSpellOnTeam(SPELL_QUARRY, nodePoint->faction); @@ -799,31 +802,31 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture) // spawning glaive throwers for (uint8 i = 0; i < MAX_GLAIVE_THROWERS_SPAWNS_PER_FACTION; ++i) { - uint8 type = (nodePoint->faction == TEAM_ALLIANCE ? BG_IC_NPC_GLAIVE_THROWER_1_A : BG_IC_NPC_GLAIVE_THROWER_1_H)+i; + uint8 type = (nodePoint->faction == TEAM_ALLIANCE ? BG_IC_NPC_GLAIVE_THROWER_1_A : BG_IC_NPC_GLAIVE_THROWER_1_H) + i; if (GetBgMap()->GetCreature(BgCreatures[type])) continue; if (AddCreature(nodePoint->faction == TEAM_ALLIANCE ? NPC_GLAIVE_THROWER_A : NPC_GLAIVE_THROWER_H, type, - BG_IC_DocksVehiclesGlaives[i].GetPositionX(), BG_IC_DocksVehiclesGlaives[i].GetPositionY(), - BG_IC_DocksVehiclesGlaives[i].GetPositionZ(), BG_IC_DocksVehiclesGlaives[i].GetOrientation(), - RESPAWN_ONE_DAY)) - GetBGCreature(type)->setFaction(BG_IC_Factions[nodePoint->faction]); + BG_IC_DocksVehiclesGlaives[i].GetPositionX(), BG_IC_DocksVehiclesGlaives[i].GetPositionY(), + BG_IC_DocksVehiclesGlaives[i].GetPositionZ(), BG_IC_DocksVehiclesGlaives[i].GetOrientation(), + RESPAWN_ONE_DAY)) + GetBGCreature(type)->setFaction(BG_IC_Factions[nodePoint->faction]); } // spawning catapults for (uint8 i = 0; i < MAX_CATAPULTS_SPAWNS_PER_FACTION; ++i) { - uint8 type = (nodePoint->faction == TEAM_ALLIANCE ? BG_IC_NPC_CATAPULT_1_A : BG_IC_NPC_CATAPULT_1_H)+i; + uint8 type = (nodePoint->faction == TEAM_ALLIANCE ? BG_IC_NPC_CATAPULT_1_A : BG_IC_NPC_CATAPULT_1_H) + i; if (GetBgMap()->GetCreature(BgCreatures[type])) continue; if (AddCreature(NPC_CATAPULT, type, - BG_IC_DocksVehiclesCatapults[i].GetPositionX(), BG_IC_DocksVehiclesCatapults[i].GetPositionY(), - BG_IC_DocksVehiclesCatapults[i].GetPositionZ(), BG_IC_DocksVehiclesCatapults[i].GetOrientation(), - RESPAWN_ONE_DAY)) - GetBGCreature(type)->setFaction(BG_IC_Factions[(nodePoint->faction == TEAM_ALLIANCE ? 0 : 1)]); + BG_IC_DocksVehiclesCatapults[i].GetPositionX(), BG_IC_DocksVehiclesCatapults[i].GetPositionY(), + BG_IC_DocksVehiclesCatapults[i].GetPositionZ(), BG_IC_DocksVehiclesCatapults[i].GetOrientation(), + RESPAWN_ONE_DAY)) + GetBGCreature(type)->setFaction(BG_IC_Factions[(nodePoint->faction == TEAM_ALLIANCE ? 0 : 1)]); } break; case BG_IC_GO_WORKSHOP_BANNER: @@ -835,15 +838,15 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture) { for (uint8 i = 0; i < MAX_DEMOLISHERS_SPAWNS_PER_FACTION; ++i) { - uint8 type = (nodePoint->faction == TEAM_ALLIANCE ? BG_IC_NPC_DEMOLISHER_1_A : BG_IC_NPC_DEMOLISHER_1_H)+i; + uint8 type = (nodePoint->faction == TEAM_ALLIANCE ? BG_IC_NPC_DEMOLISHER_1_A : BG_IC_NPC_DEMOLISHER_1_H) + i; if (GetBgMap()->GetCreature(BgCreatures[type])) continue; if (AddCreature(NPC_DEMOLISHER, type, - BG_IC_WorkshopVehicles[i].GetPositionX(), BG_IC_WorkshopVehicles[i].GetPositionY(), - BG_IC_WorkshopVehicles[i].GetPositionZ(), BG_IC_WorkshopVehicles[i].GetOrientation(), - RESPAWN_ONE_DAY)) + BG_IC_WorkshopVehicles[i].GetPositionX(), BG_IC_WorkshopVehicles[i].GetPositionY(), + BG_IC_WorkshopVehicles[i].GetPositionZ(), BG_IC_WorkshopVehicles[i].GetOrientation(), + RESPAWN_ONE_DAY)) GetBGCreature(type)->setFaction(BG_IC_Factions[(nodePoint->faction == TEAM_ALLIANCE ? 0 : 1)]); } @@ -851,15 +854,15 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture) if (!GetBgMap()->GetCreature(BgCreatures[siegeType])) { AddCreature((nodePoint->faction == TEAM_ALLIANCE ? NPC_SIEGE_ENGINE_A : NPC_SIEGE_ENGINE_H), siegeType, - BG_IC_WorkshopVehicles[4].GetPositionX(), BG_IC_WorkshopVehicles[4].GetPositionY(), - BG_IC_WorkshopVehicles[4].GetPositionZ(), BG_IC_WorkshopVehicles[4].GetOrientation(), - RESPAWN_ONE_DAY); + BG_IC_WorkshopVehicles[4].GetPositionX(), BG_IC_WorkshopVehicles[4].GetPositionY(), + BG_IC_WorkshopVehicles[4].GetPositionZ(), BG_IC_WorkshopVehicles[4].GetOrientation(), + RESPAWN_ONE_DAY); } if (Creature* siegeEngine = GetBgMap()->GetCreature(BgCreatures[siegeType])) { siegeEngine->setFaction(BG_IC_Factions[(nodePoint->faction == TEAM_ALLIANCE ? 0 : 1)]); - siegeEngine->SetCorpseDelay(5*MINUTE); + siegeEngine->SetCorpseDelay(5 * MINUTE); if (siegeEngine->IsAlive()) if (Vehicle* siegeVehicle = siegeEngine->GetVehicleKit()) @@ -872,12 +875,12 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture) for (uint8 i = 0; i < MAX_WORKSHOP_BOMBS_SPAWNS_PER_FACTION; ++i) { - AddObject(BG_IC_GO_SEAFORIUM_BOMBS_1+i, GO_SEAFORIUM_BOMBS, - workshopBombs[i].GetPositionX(), workshopBombs[i].GetPositionY(), - workshopBombs[i].GetPositionZ(), workshopBombs[i].GetOrientation(), - 0, 0, 0, 0, 10); + AddObject(BG_IC_GO_SEAFORIUM_BOMBS_1 + i, GO_SEAFORIUM_BOMBS, + workshopBombs[i].GetPositionX(), workshopBombs[i].GetPositionY(), + workshopBombs[i].GetPositionZ(), workshopBombs[i].GetOrientation(), + 0, 0, 0, 0, 10); - if (GameObject* seaforiumBombs = GetBGObject(BG_IC_GO_SEAFORIUM_BOMBS_1+i)) + if (GameObject* seaforiumBombs = GetBGObject(BG_IC_GO_SEAFORIUM_BOMBS_1 + i)) { seaforiumBombs->SetRespawnTime(10); seaforiumBombs->SetUInt32Value(GAMEOBJECT_FACTION, BG_IC_Factions[(nodePoint->faction == TEAM_ALLIANCE ? 0 : 1)]); @@ -968,10 +971,10 @@ GraveyardStruct const* BattlegroundIC::GetClosestGraveyard(Player* player) float mindist = 999999.0f; for (uint8 i = 0; i < nodes.size(); ++i) { - GraveyardStruct const*entry = sGraveyard->GetGraveyard(BG_IC_GraveyardIds[nodes[i]]); + GraveyardStruct const* entry = sGraveyard->GetGraveyard(BG_IC_GraveyardIds[nodes[i]]); if (!entry) continue; - float dist = (entry->x - plr_x)*(entry->x - plr_x)+(entry->y - plr_y)*(entry->y - plr_y); + float dist = (entry->x - plr_x) * (entry->x - plr_x) + (entry->y - plr_y) * (entry->y - plr_y); if (mindist > dist) { mindist = dist; @@ -982,7 +985,7 @@ GraveyardStruct const* BattlegroundIC::GetClosestGraveyard(Player* player) } // If not, place ghost on starting location if (!good_entry) - good_entry = sGraveyard->GetGraveyard(BG_IC_GraveyardIds[player->GetTeamId()+MAX_NODE_TYPES]); + good_entry = sGraveyard->GetGraveyard(BG_IC_GraveyardIds[player->GetTeamId() + MAX_NODE_TYPES]); return good_entry; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.h b/src/server/game/Battlegrounds/Zones/BattlegroundIC.h index c54eca52c..f712a2da2 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.h @@ -434,8 +434,8 @@ enum BannersTypes enum BG_IC_MaxSpawns { - MAX_NORMAL_GAMEOBJECTS_SPAWNS = BG_IC_GO_DOODAD_ND_WINTERORC_WALL_GATEFX_DOOR03+1, - MAX_NORMAL_NPCS_SPAWNS = BG_IC_NPC_KEEP_CANNON_25+1, + MAX_NORMAL_GAMEOBJECTS_SPAWNS = BG_IC_GO_DOODAD_ND_WINTERORC_WALL_GATEFX_DOOR03 + 1, + MAX_NORMAL_NPCS_SPAWNS = BG_IC_NPC_KEEP_CANNON_25 + 1, MAX_WORKSHOP_SPAWNS = 10, MAX_DOCKS_SPAWNS = 12, MAX_SPIRIT_GUIDES_SPAWNS = 7, @@ -828,9 +828,9 @@ enum ICNodeState NODE_STATE_CONTROLLED_H }; -const uint32 BG_IC_GraveyardIds[MAX_NODE_TYPES+2] = {0, 0, 1480, 1481, 1482, 1485, 1486, 1483, 1484}; +const uint32 BG_IC_GraveyardIds[MAX_NODE_TYPES + 2] = {0, 0, 1480, 1481, 1482, 1485, 1486, 1483, 1484}; -const float BG_IC_SpiritGuidePos[MAX_NODE_TYPES+2][4] = +const float BG_IC_SpiritGuidePos[MAX_NODE_TYPES + 2][4] = { {0.0f, 0.0f, 0.0f, 0.0f}, // no grave {0.0f, 0.0f, 0.0f, 0.0f}, // no grave @@ -889,107 +889,119 @@ struct BattlegroundICScore : public BattlegroundScore class BattlegroundIC : public Battleground { - public: - BattlegroundIC(); - ~BattlegroundIC(); +public: + BattlegroundIC(); + ~BattlegroundIC(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); - void PostUpdateImpl(uint32 diff); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); + void PostUpdateImpl(uint32 diff); - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); - bool SetupBattleground(); - void SpawnLeader(uint32 teamid); - void HandleKillUnit(Creature* unit, Player* killer); - void HandleKillPlayer(Player* player, Player* killer); - void EndBattleground(TeamId winnerTeamId); - void EventPlayerClickedOnFlag(Player* source, GameObject* /*gameObject*/); + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); + bool SetupBattleground(); + void SpawnLeader(uint32 teamid); + void HandleKillUnit(Creature* unit, Player* killer); + void HandleKillPlayer(Player* player, Player* killer); + void EndBattleground(TeamId winnerTeamId); + void EventPlayerClickedOnFlag(Player* source, GameObject* /*gameObject*/); - void EventPlayerDamagedGO(Player* /*player*/, GameObject* go, uint32 eventType); - void DestroyGate(Player* player, GameObject* go); + void EventPlayerDamagedGO(Player* /*player*/, GameObject* go, uint32 eventType); + void DestroyGate(Player* player, GameObject* go); - GraveyardStruct const* GetClosestGraveyard(Player* player); + GraveyardStruct const* GetClosestGraveyard(Player* player); - /* Scorekeeping */ - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); + /* Scorekeeping */ + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); - void FillInitialWorldStates(WorldPacket& data); + void FillInitialWorldStates(WorldPacket& data); - void HandlePlayerResurrect(Player* player); + void HandlePlayerResurrect(Player* player); - uint32 GetNodeState(uint8 nodeType) const { return (uint8)nodePoint[nodeType].nodeState; } + uint32 GetNodeState(uint8 nodeType) const { return (uint8)nodePoint[nodeType].nodeState; } - bool AllNodesConrolledByTeam(TeamId teamId) const; // overwrited - bool IsResourceGlutAllowed(TeamId teamId) const; - void DoAction(uint32 action, uint64 guid); - private: - uint32 closeFortressDoorsTimer; - bool doorsClosed; - uint32 docksTimer; - uint32 resourceTimer; - uint32 siegeEngineWorkshopTimer; - uint16 factionReinforcements[2]; - BG_IC_GateState GateStatus[6]; - ICNodePoint nodePoint[7]; + bool AllNodesConrolledByTeam(TeamId teamId) const; // overwrited + bool IsResourceGlutAllowed(TeamId teamId) const; + void DoAction(uint32 action, uint64 guid); +private: + uint32 closeFortressDoorsTimer; + bool doorsClosed; + uint32 docksTimer; + uint32 resourceTimer; + uint32 siegeEngineWorkshopTimer; + uint16 factionReinforcements[2]; + BG_IC_GateState GateStatus[6]; + ICNodePoint nodePoint[7]; - typedef std::map RespawnMap; - RespawnMap respawnMap; + typedef std::map RespawnMap; + RespawnMap respawnMap; - MotionTransport* gunshipAlliance; - MotionTransport* gunshipHorde; + MotionTransport* gunshipAlliance; + MotionTransport* gunshipHorde; - uint32 GetNextBanner(ICNodePoint* nodePoint, uint32 team, bool returnDefinitve); + uint32 GetNextBanner(ICNodePoint* nodePoint, uint32 team, bool returnDefinitve); - uint32 GetGateIDFromEntry(uint32 id) + uint32 GetGateIDFromEntry(uint32 id) + { + uint32 i = 0; + switch (id) { - uint32 i = 0; - switch (id) - { - case GO_HORDE_GATE_1: i = BG_IC_H_FRONT; break; - case GO_HORDE_GATE_2: i = BG_IC_H_EAST; break; - case GO_HORDE_GATE_3: i = BG_IC_H_WEST; break; - case GO_ALLIANCE_GATE_3: i = BG_IC_A_FRONT; break; - case GO_ALLIANCE_GATE_1: i = BG_IC_A_WEST; break; - case GO_ALLIANCE_GATE_2: i = BG_IC_A_EAST; break; - } - return i; + case GO_HORDE_GATE_1: + i = BG_IC_H_FRONT; + break; + case GO_HORDE_GATE_2: + i = BG_IC_H_EAST; + break; + case GO_HORDE_GATE_3: + i = BG_IC_H_WEST; + break; + case GO_ALLIANCE_GATE_3: + i = BG_IC_A_FRONT; + break; + case GO_ALLIANCE_GATE_1: + i = BG_IC_A_WEST; + break; + case GO_ALLIANCE_GATE_2: + i = BG_IC_A_EAST; + break; } + return i; + } - uint32 GetWorldStateFromGateEntry(uint32 id, bool open) + uint32 GetWorldStateFromGateEntry(uint32 id, bool open) + { + uint32 uws = 0; + + switch (id) { - uint32 uws = 0; - - switch (id) - { - case GO_HORDE_GATE_1: - uws = (open ? BG_IC_GATE_FRONT_H_WS_OPEN : BG_IC_GATE_FRONT_H_WS_CLOSED); - break; - case GO_HORDE_GATE_2: - uws = (open ? BG_IC_GATE_EAST_H_WS_OPEN : BG_IC_GATE_EAST_H_WS_CLOSED); - break; - case GO_HORDE_GATE_3: - uws = (open ? BG_IC_GATE_WEST_H_WS_OPEN : BG_IC_GATE_WEST_H_WS_CLOSED); - break; - case GO_ALLIANCE_GATE_3: - uws = (open ? BG_IC_GATE_FRONT_A_WS_OPEN : BG_IC_GATE_FRONT_A_WS_CLOSED); - break; - case GO_ALLIANCE_GATE_1: - uws = (open ? BG_IC_GATE_WEST_A_WS_OPEN : BG_IC_GATE_WEST_A_WS_CLOSED); - break; - case GO_ALLIANCE_GATE_2: - uws = (open ? BG_IC_GATE_EAST_A_WS_OPEN : BG_IC_GATE_EAST_A_WS_CLOSED); - break; - } - return uws; + case GO_HORDE_GATE_1: + uws = (open ? BG_IC_GATE_FRONT_H_WS_OPEN : BG_IC_GATE_FRONT_H_WS_CLOSED); + break; + case GO_HORDE_GATE_2: + uws = (open ? BG_IC_GATE_EAST_H_WS_OPEN : BG_IC_GATE_EAST_H_WS_CLOSED); + break; + case GO_HORDE_GATE_3: + uws = (open ? BG_IC_GATE_WEST_H_WS_OPEN : BG_IC_GATE_WEST_H_WS_CLOSED); + break; + case GO_ALLIANCE_GATE_3: + uws = (open ? BG_IC_GATE_FRONT_A_WS_OPEN : BG_IC_GATE_FRONT_A_WS_CLOSED); + break; + case GO_ALLIANCE_GATE_1: + uws = (open ? BG_IC_GATE_WEST_A_WS_OPEN : BG_IC_GATE_WEST_A_WS_CLOSED); + break; + case GO_ALLIANCE_GATE_2: + uws = (open ? BG_IC_GATE_EAST_A_WS_OPEN : BG_IC_GATE_EAST_A_WS_CLOSED); + break; } + return uws; + } - void UpdateNodeWorldState(ICNodePoint* nodePoint); - void HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture); - void HandleContestedNodes(ICNodePoint* nodePoint); - void TurnBosses(bool on); + void UpdateNodeWorldState(ICNodePoint* nodePoint); + void HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture); + void HandleContestedNodes(ICNodePoint* nodePoint); + void TurnBosses(bool on); }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp index a3d69f9b5..e562d0209 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp @@ -105,7 +105,7 @@ void BattlegroundNA::HandleAreaTrigger(Player* player, uint32 trigger) } } -void BattlegroundNA::FillInitialWorldStates(WorldPacket &data) +void BattlegroundNA::FillInitialWorldStates(WorldPacket& data) { data << uint32(0xa11) << uint32(1); // 9 Battleground::UpdateArenaWorldState(); @@ -121,15 +121,15 @@ bool BattlegroundNA::SetupBattleground() { // gates if ( !AddObject(BG_NA_OBJECT_DOOR_1, BG_NA_OBJECT_TYPE_DOOR_1, 4031.854f, 2966.833f, 12.0462f, -2.648788f, 0, 0, 0.9697962f, -0.2439165f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_NA_OBJECT_DOOR_2, BG_NA_OBJECT_TYPE_DOOR_2, 4081.179f, 2874.97f, 12.00171f, 0.4928045f, 0, 0, 0.2439165f, 0.9697962f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_NA_OBJECT_DOOR_3, BG_NA_OBJECT_TYPE_DOOR_3, 4023.709f, 2981.777f, 10.70117f, -2.648788f, 0, 0, 0.9697962f, -0.2439165f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_NA_OBJECT_DOOR_4, BG_NA_OBJECT_TYPE_DOOR_4, 4090.064f, 2858.438f, 10.23631f, 0.4928045f, 0, 0, 0.2439165f, 0.9697962f, RESPAWN_IMMEDIATELY) - // buffs - || !AddObject(BG_NA_OBJECT_BUFF_1, BG_NA_OBJECT_TYPE_BUFF_1, 4009.189941f, 2895.250000f, 13.052700f, -1.448624f, 0, 0, 0.6626201f, -0.7489557f, 120) - || !AddObject(BG_NA_OBJECT_BUFF_2, BG_NA_OBJECT_TYPE_BUFF_2, 4103.330078f, 2946.350098f, 13.051300f, -0.06981307f, 0, 0, 0.03489945f, -0.9993908f, 120) - // Arena Ready Marker - || !AddObject(BG_NA_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 4090.46f, 2875.43f, 12.16f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) - || !AddObject(BG_NA_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 4022.82f, 2966.61f, 12.17f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) + || !AddObject(BG_NA_OBJECT_DOOR_2, BG_NA_OBJECT_TYPE_DOOR_2, 4081.179f, 2874.97f, 12.00171f, 0.4928045f, 0, 0, 0.2439165f, 0.9697962f, RESPAWN_IMMEDIATELY) + || !AddObject(BG_NA_OBJECT_DOOR_3, BG_NA_OBJECT_TYPE_DOOR_3, 4023.709f, 2981.777f, 10.70117f, -2.648788f, 0, 0, 0.9697962f, -0.2439165f, RESPAWN_IMMEDIATELY) + || !AddObject(BG_NA_OBJECT_DOOR_4, BG_NA_OBJECT_TYPE_DOOR_4, 4090.064f, 2858.438f, 10.23631f, 0.4928045f, 0, 0, 0.2439165f, 0.9697962f, RESPAWN_IMMEDIATELY) + // buffs + || !AddObject(BG_NA_OBJECT_BUFF_1, BG_NA_OBJECT_TYPE_BUFF_1, 4009.189941f, 2895.250000f, 13.052700f, -1.448624f, 0, 0, 0.6626201f, -0.7489557f, 120) + || !AddObject(BG_NA_OBJECT_BUFF_2, BG_NA_OBJECT_TYPE_BUFF_2, 4103.330078f, 2946.350098f, 13.051300f, -0.06981307f, 0, 0, 0.03489945f, -0.9993908f, 120) + // Arena Ready Marker + || !AddObject(BG_NA_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 4090.46f, 2875.43f, 12.16f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) + || !AddObject(BG_NA_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 4022.82f, 2966.61f, 12.17f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { sLog->outErrorDb("BatteGroundNA: Failed to spawn some object!"); return false; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundNA.h b/src/server/game/Battlegrounds/Zones/BattlegroundNA.h index d3e7a0af8..7a300df50 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundNA.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundNA.h @@ -33,21 +33,21 @@ enum BattlegroundNAObjects class BattlegroundNA : public Battleground { - public: - BattlegroundNA(); - ~BattlegroundNA(); +public: + BattlegroundNA(); + ~BattlegroundNA(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); - bool SetupBattleground(); - void Init(); - void FillInitialWorldStates(WorldPacket &d); - void HandleKillPlayer(Player* player, Player* killer); - bool HandlePlayerUnderMap(Player* player); + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); + bool SetupBattleground(); + void Init(); + void FillInitialWorldStates(WorldPacket& d); + void HandleKillPlayer(Player* player, Player* killer); + bool HandlePlayerUnderMap(Player* player); }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp index 10c822978..6da969cdb 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp @@ -131,7 +131,7 @@ void BattlegroundRL::HandleAreaTrigger(Player* player, uint32 trigger) } } -void BattlegroundRL::FillInitialWorldStates(WorldPacket &data) +void BattlegroundRL::FillInitialWorldStates(WorldPacket& data) { data << uint32(0xbba) << uint32(1); // 9 Battleground::UpdateArenaWorldState(); @@ -147,13 +147,13 @@ bool BattlegroundRL::SetupBattleground() { // gates if (!AddObject(BG_RL_OBJECT_DOOR_1, BG_RL_OBJECT_TYPE_DOOR_1, 1293.561f, 1601.938f, 31.60557f, -1.457349f, 0, 0, -0.6658813f, 0.7460576f, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RL_OBJECT_DOOR_2, BG_RL_OBJECT_TYPE_DOOR_2, 1278.648f, 1730.557f, 31.60557f, 1.684245f, 0, 0, 0.7460582f, 0.6658807f, RESPAWN_IMMEDIATELY) - // buffs - || !AddObject(BG_RL_OBJECT_BUFF_1, BG_RL_OBJECT_TYPE_BUFF_1, 1328.719971f, 1632.719971f, 36.730400f, -1.448624f, 0, 0, 0.6626201f, -0.7489557f, 120) - || !AddObject(BG_RL_OBJECT_BUFF_2, BG_RL_OBJECT_TYPE_BUFF_2, 1243.300049f, 1699.170044f, 34.872601f, -0.06981307f, 0, 0, 0.03489945f, -0.9993908f, 120) - // Arena Ready Marker - || !AddObject(BG_RL_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 1298.61f, 1598.59f, 31.62f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) - || !AddObject(BG_RL_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 1273.71f, 1734.05f, 31.61f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) + || !AddObject(BG_RL_OBJECT_DOOR_2, BG_RL_OBJECT_TYPE_DOOR_2, 1278.648f, 1730.557f, 31.60557f, 1.684245f, 0, 0, 0.7460582f, 0.6658807f, RESPAWN_IMMEDIATELY) + // buffs + || !AddObject(BG_RL_OBJECT_BUFF_1, BG_RL_OBJECT_TYPE_BUFF_1, 1328.719971f, 1632.719971f, 36.730400f, -1.448624f, 0, 0, 0.6626201f, -0.7489557f, 120) + || !AddObject(BG_RL_OBJECT_BUFF_2, BG_RL_OBJECT_TYPE_BUFF_2, 1243.300049f, 1699.170044f, 34.872601f, -0.06981307f, 0, 0, 0.03489945f, -0.9993908f, 120) + // Arena Ready Marker + || !AddObject(BG_RL_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 1298.61f, 1598.59f, 31.62f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) + || !AddObject(BG_RL_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 1273.71f, 1734.05f, 31.61f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { sLog->outErrorDb("BatteGroundRL: Failed to spawn some object!"); return false; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRL.h b/src/server/game/Battlegrounds/Zones/BattlegroundRL.h index 21f847f06..0bf56bf29 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRL.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRL.h @@ -29,21 +29,21 @@ enum BattlegroundRLObjects class BattlegroundRL : public Battleground { - public: - BattlegroundRL(); - ~BattlegroundRL(); +public: + BattlegroundRL(); + ~BattlegroundRL(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void Init(); - void FillInitialWorldStates(WorldPacket &d); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void Init(); + void FillInitialWorldStates(WorldPacket& d); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); - bool SetupBattleground(); - void HandleKillPlayer(Player* player, Player* killer); - bool HandlePlayerUnderMap(Player* player); + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); + bool SetupBattleground(); + void HandleKillPlayer(Player* player, Player* killer); + bool HandlePlayerUnderMap(Player* player); }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp index 82e5abc68..6430d0574 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp @@ -51,7 +51,7 @@ void BattlegroundRV::CheckPositionForUnit(Unit* unit) { float groundZ = std::max(groundZ_vmap, groundZ_dyntree); if (unit->GetPositionZ() < groundZ - 0.2f || unit->GetPositionZ() > groundZ + 3.5f) - TeleportUnitToNewZ(unit, groundZ+1.0f, true); + TeleportUnitToNewZ(unit, groundZ + 1.0f, true); } } } @@ -108,7 +108,7 @@ void BattlegroundRV::PostUpdateImpl(uint32 diff) // fix ground on elevators (so aoe spells can be casted there) { uint32 objects[2] = {BG_RV_OBJECT_ELEVATOR_1, BG_RV_OBJECT_ELEVATOR_2}; - for (uint8 i=0; i<2; ++i) + for (uint8 i = 0; i < 2; ++i) if (GameObject* go = GetBGObject(objects[i])) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_TRANSPORT); } @@ -231,7 +231,7 @@ void BattlegroundRV::HandleAreaTrigger(Player* player, uint32 trigger) } } -void BattlegroundRV::FillInitialWorldStates(WorldPacket &data) +void BattlegroundRV::FillInitialWorldStates(WorldPacket& data) { data << uint32(BG_RV_WORLD_STATE) << uint32(1); BattlegroundRV::UpdateArenaWorldState(); @@ -253,37 +253,37 @@ bool BattlegroundRV::SetupBattleground() { // elevators if (!AddObject(BG_RV_OBJECT_ELEVATOR_1, BG_RV_OBJECT_TYPE_ELEVATOR_1, 763.536377f, -294.535767f, 0.505383f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_ELEVATOR_2, BG_RV_OBJECT_TYPE_ELEVATOR_2, 763.506348f, -273.873352f, 0.505383f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) - // buffs - || !AddObject(BG_RV_OBJECT_BUFF_1, BG_RV_OBJECT_TYPE_BUFF_1, 735.551819f, -284.794678f, 28.276682f, 0.034906f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_BUFF_2, BG_RV_OBJECT_TYPE_BUFF_2, 791.224487f, -284.794464f, 28.276682f, 2.600535f, 0, 0, 0, RESPAWN_IMMEDIATELY) - // fire - || !AddObject(BG_RV_OBJECT_FIRE_1, BG_RV_OBJECT_TYPE_FIRE_1, 743.543457f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_FIRE_2, BG_RV_OBJECT_TYPE_FIRE_2, 782.971802f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_FIREDOOR_1, BG_RV_OBJECT_TYPE_FIREDOOR_1, 743.711060f, -284.099609f, 27.542587f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_FIREDOOR_2, BG_RV_OBJECT_TYPE_FIREDOOR_2, 783.221252f, -284.133362f, 27.535686f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) - // Gear - || !AddObject(BG_RV_OBJECT_GEAR_1, BG_RV_OBJECT_TYPE_GEAR_1, 763.664551f, -261.872986f, 26.686588f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_GEAR_2, BG_RV_OBJECT_TYPE_GEAR_2, 763.578979f, -306.146149f, 26.665222f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - // Pulley - || !AddObject(BG_RV_OBJECT_PULLEY_1, BG_RV_OBJECT_TYPE_PULLEY_1, 700.722290f, -283.990662f, 39.517582f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_PULLEY_2, BG_RV_OBJECT_TYPE_PULLEY_2, 826.303833f, -283.996429f, 39.517582f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) - // Pilars - || !AddObject(BG_RV_OBJECT_PILAR_1, BG_RV_OBJECT_TYPE_PILAR_1, 763.632385f, -306.162384f, 25.909504f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_PILAR_2, BG_RV_OBJECT_TYPE_PILAR_2, 723.644287f, -284.493256f, 24.648525f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_PILAR_3, BG_RV_OBJECT_TYPE_PILAR_3, 763.611145f, -261.856750f, 25.909504f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) - || !AddObject(BG_RV_OBJECT_PILAR_4, BG_RV_OBJECT_TYPE_PILAR_4, 802.211609f, -284.493256f, 24.648525f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_ELEVATOR_2, BG_RV_OBJECT_TYPE_ELEVATOR_2, 763.506348f, -273.873352f, 0.505383f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // buffs + || !AddObject(BG_RV_OBJECT_BUFF_1, BG_RV_OBJECT_TYPE_BUFF_1, 735.551819f, -284.794678f, 28.276682f, 0.034906f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_BUFF_2, BG_RV_OBJECT_TYPE_BUFF_2, 791.224487f, -284.794464f, 28.276682f, 2.600535f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // fire + || !AddObject(BG_RV_OBJECT_FIRE_1, BG_RV_OBJECT_TYPE_FIRE_1, 743.543457f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FIRE_2, BG_RV_OBJECT_TYPE_FIRE_2, 782.971802f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FIREDOOR_1, BG_RV_OBJECT_TYPE_FIREDOOR_1, 743.711060f, -284.099609f, 27.542587f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FIREDOOR_2, BG_RV_OBJECT_TYPE_FIREDOOR_2, 783.221252f, -284.133362f, 27.535686f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // Gear + || !AddObject(BG_RV_OBJECT_GEAR_1, BG_RV_OBJECT_TYPE_GEAR_1, 763.664551f, -261.872986f, 26.686588f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_GEAR_2, BG_RV_OBJECT_TYPE_GEAR_2, 763.578979f, -306.146149f, 26.665222f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // Pulley + || !AddObject(BG_RV_OBJECT_PULLEY_1, BG_RV_OBJECT_TYPE_PULLEY_1, 700.722290f, -283.990662f, 39.517582f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PULLEY_2, BG_RV_OBJECT_TYPE_PULLEY_2, 826.303833f, -283.996429f, 39.517582f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // Pilars + || !AddObject(BG_RV_OBJECT_PILAR_1, BG_RV_OBJECT_TYPE_PILAR_1, 763.632385f, -306.162384f, 25.909504f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_2, BG_RV_OBJECT_TYPE_PILAR_2, 723.644287f, -284.493256f, 24.648525f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_3, BG_RV_OBJECT_TYPE_PILAR_3, 763.611145f, -261.856750f, 25.909504f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_4, BG_RV_OBJECT_TYPE_PILAR_4, 802.211609f, -284.493256f, 24.648525f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) - // Arena Ready Marker - || !AddObject(BG_RV_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 769.93f, -301.04f, 2.80f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) - || !AddObject(BG_RV_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 757.02f, -267.30f, 2.80f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) - ) + // Arena Ready Marker + || !AddObject(BG_RV_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 769.93f, -301.04f, 2.80f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) + || !AddObject(BG_RV_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 757.02f, -267.30f, 2.80f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) + ) { sLog->outErrorDb("BatteGroundRV: Failed to spawn some object!"); return false; } - for (uint8 i=0; iSetPhaseMask(3, true); @@ -321,11 +321,11 @@ uint32 BattlegroundRV::GetPillarIdForPos(Position* p) float range = 1.75f; if (p->GetExactDist2d(763.632385f, -306.162384f) < range) return BG_RV_OBJECT_PILAR_1; - if (p->GetExactDist2d(723.644287f, -284.493256f) < 2.0f*range) + if (p->GetExactDist2d(723.644287f, -284.493256f) < 2.0f * range) return BG_RV_OBJECT_PILAR_2; if (p->GetExactDist2d(763.611145f, -261.856750f) < range) return BG_RV_OBJECT_PILAR_3; - if (p->GetExactDist2d(802.211609f, -284.493256f) < 2.0f*range) + if (p->GetExactDist2d(802.211609f, -284.493256f) < 2.0f * range) return BG_RV_OBJECT_PILAR_4; return 0; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRV.h b/src/server/game/Battlegrounds/Zones/BattlegroundRV.h index 066e04c91..a6f4f8622 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRV.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRV.h @@ -76,41 +76,41 @@ enum BattlegroundRVData class BattlegroundRV : public Battleground { - public: - BattlegroundRV(); - ~BattlegroundRV(); +public: + BattlegroundRV(); + ~BattlegroundRV(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void RemovePlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); - void Init(); - void FillInitialWorldStates(WorldPacket &d); - void UpdateArenaWorldState(); - void HandleAreaTrigger(Player* player, uint32 trigger); - bool SetupBattleground(); - void HandleKillPlayer(Player* player, Player* killer); - bool HandlePlayerUnderMap(Player* player); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void RemovePlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); + void Init(); + void FillInitialWorldStates(WorldPacket& d); + void UpdateArenaWorldState(); + void HandleAreaTrigger(Player* player, uint32 trigger); + bool SetupBattleground(); + void HandleKillPlayer(Player* player, Player* killer); + bool HandlePlayerUnderMap(Player* player); - GameObject* GetPillarAtPosition(Position* p); + GameObject* GetPillarAtPosition(Position* p); - private: - uint32 Timer; - uint32 State; - uint16 CheckPlayersTimer; +private: + uint32 Timer; + uint32 State; + uint16 CheckPlayersTimer; - void PostUpdateImpl(uint32 diff); + void PostUpdateImpl(uint32 diff); - protected: - uint32 getTimer() { return Timer; } - void setTimer(uint32 timer) { Timer = timer; } - uint32 getState() { return State; }; - void setState(uint32 state) { State = state; } +protected: + uint32 getTimer() { return Timer; } + void setTimer(uint32 timer) { Timer = timer; } + uint32 getState() { return State; }; + void setState(uint32 state) { State = state; } - void TeleportUnitToNewZ(Unit* unit, float newZ, bool casting); - void CheckPositionForUnit(Unit* unit); - void UpdatePillars(); - uint32 GetPillarIdForPos(Position* p); + void TeleportUnitToNewZ(Unit* unit, float newZ, bool casting); + void CheckPositionForUnit(Unit* unit); + void UpdatePillars(); + uint32 GetPillarIdForPos(Position* p); }; #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp index 989f20f03..aaa3caf4d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp @@ -79,7 +79,7 @@ bool BattlegroundSA::ResetObjs() uint32 atF = BG_SA_Factions[Attackers]; uint32 defF = BG_SA_Factions[Attackers ? TEAM_ALLIANCE : TEAM_HORDE]; - for (uint8 i = 0; i GetGraveyard(BG_SA_GYEntries[i]); @@ -189,19 +189,19 @@ bool BattlegroundSA::ResetObjs() //GY capture points for (uint8 i = BG_SA_CENTRAL_FLAG; i < BG_SA_PORTAL_DEFFENDER_BLUE; i++) { - AddObject(i, (BG_SA_ObjEntries[i] - (Attackers == TEAM_ALLIANCE ? 1:0)), - BG_SA_ObjSpawnlocs[i][0], BG_SA_ObjSpawnlocs[i][1], - BG_SA_ObjSpawnlocs[i][2], BG_SA_ObjSpawnlocs[i][3], - 0, 0, 0, 0, RESPAWN_ONE_DAY); + AddObject(i, (BG_SA_ObjEntries[i] - (Attackers == TEAM_ALLIANCE ? 1 : 0)), + BG_SA_ObjSpawnlocs[i][0], BG_SA_ObjSpawnlocs[i][1], + BG_SA_ObjSpawnlocs[i][2], BG_SA_ObjSpawnlocs[i][3], + 0, 0, 0, 0, RESPAWN_ONE_DAY); GetBGObject(i)->SetUInt32Value(GAMEOBJECT_FACTION, atF); } for (uint8 i = BG_SA_PORTAL_DEFFENDER_BLUE; i < BG_SA_BOMB; i++) { AddObject(i, BG_SA_ObjEntries[i], - BG_SA_ObjSpawnlocs[i][0], BG_SA_ObjSpawnlocs[i][1], - BG_SA_ObjSpawnlocs[i][2], BG_SA_ObjSpawnlocs[i][3], - 0, 0, 0, 0, RESPAWN_ONE_DAY); + BG_SA_ObjSpawnlocs[i][0], BG_SA_ObjSpawnlocs[i][1], + BG_SA_ObjSpawnlocs[i][2], BG_SA_ObjSpawnlocs[i][3], + 0, 0, 0, 0, RESPAWN_ONE_DAY); GetBGObject(i)->SetUInt32Value(GAMEOBJECT_FACTION, defF); } @@ -210,20 +210,20 @@ bool BattlegroundSA::ResetObjs() for (uint8 i = BG_SA_BOMB; i < BG_SA_MAXOBJ; i++) { AddObject(i, BG_SA_ObjEntries[BG_SA_BOMB], - BG_SA_ObjSpawnlocs[i][0], BG_SA_ObjSpawnlocs[i][1], - BG_SA_ObjSpawnlocs[i][2], BG_SA_ObjSpawnlocs[i][3], - 0, 0, 0, 0, RESPAWN_ONE_DAY); + BG_SA_ObjSpawnlocs[i][0], BG_SA_ObjSpawnlocs[i][1], + BG_SA_ObjSpawnlocs[i][2], BG_SA_ObjSpawnlocs[i][3], + 0, 0, 0, 0, RESPAWN_ONE_DAY); GetBGObject(i)->SetUInt32Value(GAMEOBJECT_FACTION, atF); } //Player may enter BEFORE we set up bG - lets update his worldstates anyway... - UpdateWorldState(BG_SA_RIGHT_GY_HORDE, GraveyardStatus[BG_SA_RIGHT_CAPTURABLE_GY] == TEAM_HORDE?1:0); - UpdateWorldState(BG_SA_LEFT_GY_HORDE, GraveyardStatus[BG_SA_LEFT_CAPTURABLE_GY] == TEAM_HORDE?1:0); - UpdateWorldState(BG_SA_CENTER_GY_HORDE, GraveyardStatus[BG_SA_CENTRAL_CAPTURABLE_GY] == TEAM_HORDE?1:0); + UpdateWorldState(BG_SA_RIGHT_GY_HORDE, GraveyardStatus[BG_SA_RIGHT_CAPTURABLE_GY] == TEAM_HORDE ? 1 : 0); + UpdateWorldState(BG_SA_LEFT_GY_HORDE, GraveyardStatus[BG_SA_LEFT_CAPTURABLE_GY] == TEAM_HORDE ? 1 : 0); + UpdateWorldState(BG_SA_CENTER_GY_HORDE, GraveyardStatus[BG_SA_CENTRAL_CAPTURABLE_GY] == TEAM_HORDE ? 1 : 0); - UpdateWorldState(BG_SA_RIGHT_GY_ALLIANCE, GraveyardStatus[BG_SA_RIGHT_CAPTURABLE_GY] == TEAM_ALLIANCE?1:0); - UpdateWorldState(BG_SA_LEFT_GY_ALLIANCE, GraveyardStatus[BG_SA_LEFT_CAPTURABLE_GY] == TEAM_ALLIANCE?1:0); - UpdateWorldState(BG_SA_CENTER_GY_ALLIANCE, GraveyardStatus[BG_SA_CENTRAL_CAPTURABLE_GY] == TEAM_ALLIANCE?1:0); + UpdateWorldState(BG_SA_RIGHT_GY_ALLIANCE, GraveyardStatus[BG_SA_RIGHT_CAPTURABLE_GY] == TEAM_ALLIANCE ? 1 : 0); + UpdateWorldState(BG_SA_LEFT_GY_ALLIANCE, GraveyardStatus[BG_SA_LEFT_CAPTURABLE_GY] == TEAM_ALLIANCE ? 1 : 0); + UpdateWorldState(BG_SA_CENTER_GY_ALLIANCE, GraveyardStatus[BG_SA_CENTRAL_CAPTURABLE_GY] == TEAM_ALLIANCE ? 1 : 0); if (Attackers == TEAM_ALLIANCE) { @@ -322,7 +322,7 @@ void BattlegroundSA::PostUpdateImpl(uint32 diff) ToggleTimer(); DemolisherStartState(false); Status = BG_SA_ROUND_ONE; - StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, (Attackers == TEAM_ALLIANCE)?23748:21702); + StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, (Attackers == TEAM_ALLIANCE) ? 23748 : 21702); } if (TotalTime >= BG_SA_BOAT_START) StartShips(); @@ -330,7 +330,7 @@ void BattlegroundSA::PostUpdateImpl(uint32 diff) } else if (Status == BG_SA_SECOND_WARMUP) { - if (RoundScores[0].timeGetTeamId() == Attackers) + if (plr->GetTeamId() == Attackers) return; uint32 portal_num = 0; //get it via X switch( (uint32)portal->GetPositionX() ) { - case 1394: - portal_num = 0; - break; - case 1065: - portal_num = 1; - break; - case 1468: - portal_num = 2; - break; - case 1255: - portal_num = 3; - break; - case 1216: - portal_num = 4; - break; + case 1394: + portal_num = 0; + break; + case 1065: + portal_num = 1; + break; + case 1468: + portal_num = 2; + break; + case 1255: + portal_num = 3; + break; + case 1216: + portal_num = 4; + break; } plr->TeleportTo( plr->GetMapId(), SOTADefPortalDest[portal_num][0], SOTADefPortalDest[portal_num][1], SOTADefPortalDest[portal_num][2], SOTADefPortalDest[portal_num][3], TELE_TO_SPELL ); @@ -623,14 +623,14 @@ void BattlegroundSA::EventPlayerDamagedGO(Player* /*player*/, GameObject* go, ui { case BG_SA_BLUE_GATE: case BG_SA_GREEN_GATE: - { - GameObject* go = nullptr; - if ((go = GetBGObject(BG_SA_RED_GATE))) - go->SetDestructibleBuildingModifyState(true); - if ((go = GetBGObject(BG_SA_PURPLE_GATE))) - go->SetDestructibleBuildingModifyState(true); - break; - } + { + GameObject* go = nullptr; + if ((go = GetBGObject(BG_SA_RED_GATE))) + go->SetDestructibleBuildingModifyState(true); + if ((go = GetBGObject(BG_SA_PURPLE_GATE))) + go->SetDestructibleBuildingModifyState(true); + break; + } case BG_SA_RED_GATE: case BG_SA_PURPLE_GATE: if (GameObject* go = GetBGObject(BG_SA_YELLOW_GATE)) @@ -666,13 +666,13 @@ void BattlegroundSA::OverrideGunFaction() if (!BgCreatures[0]) return; - for (uint8 i = BG_SA_GUN_1; i <= BG_SA_GUN_10;i++) + for (uint8 i = BG_SA_GUN_1; i <= BG_SA_GUN_10; i++) { if (Creature* gun = GetBGCreature(i)) - gun->setFaction(BG_SA_Factions[Attackers? TEAM_ALLIANCE : TEAM_HORDE]); + gun->setFaction(BG_SA_Factions[Attackers ? TEAM_ALLIANCE : TEAM_HORDE]); } - for (uint8 i = BG_SA_DEMOLISHER_1; i <= BG_SA_DEMOLISHER_4;i++) + for (uint8 i = BG_SA_DEMOLISHER_1; i <= BG_SA_DEMOLISHER_4; i++) { if (Creature* dem = GetBGCreature(i)) dem->setFaction(BG_SA_Factions[Attackers]); @@ -693,7 +693,7 @@ void BattlegroundSA::DemolisherStartState(bool start) dem->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); } - for (uint8 i = BG_SA_GUN_1; i <= BG_SA_GUN_10;i++) + for (uint8 i = BG_SA_GUN_1; i <= BG_SA_GUN_10; i++) if (Creature* gun = GetBGCreature(i)) { if (start) @@ -704,7 +704,7 @@ void BattlegroundSA::DemolisherStartState(bool start) // xinef: enable first gates damaging at start if (!start) - { + { if (GameObject* go = GetBGObject(BG_SA_GREEN_GATE)) go->SetDestructibleBuildingModifyState(true); if (GameObject* go = GetBGObject(BG_SA_BLUE_GATE)) @@ -750,7 +750,7 @@ void BattlegroundSA::DestroyGate(Player* player, GameObject* go) UpdateObjectInteractionFlags(); if (i < 5) - DelObject(i+9); + DelObject(i + 9); if (player) { @@ -776,7 +776,7 @@ GraveyardStruct const* BattlegroundSA::GetClosestGraveyard(Player* player) continue; GraveyardStruct const* ret = sGraveyard->GetGraveyard(BG_SA_GYEntries[i]); - + // if on beach if (i == BG_SA_BEACH_GY) { @@ -802,9 +802,9 @@ GraveyardStruct const* BattlegroundSA::GetClosestGraveyard(Player* player) void BattlegroundSA::SendTime() { uint32 end_of_round = (EndRoundTimer - TotalTime); - UpdateWorldState(BG_SA_TIMER_MINS, end_of_round/60000); - UpdateWorldState(BG_SA_TIMER_SEC_TENS, (end_of_round%60000)/10000); - UpdateWorldState(BG_SA_TIMER_SEC_DECS, ((end_of_round%60000)%10000)/1000); + UpdateWorldState(BG_SA_TIMER_MINS, end_of_round / 60000); + UpdateWorldState(BG_SA_TIMER_SEC_TENS, (end_of_round % 60000) / 10000); + UpdateWorldState(BG_SA_TIMER_SEC_DECS, ((end_of_round % 60000) % 10000) / 1000); } bool BattlegroundSA::CanInteractWithObject(uint32 objectId) @@ -843,7 +843,7 @@ void BattlegroundSA::UpdateObjectInteractionFlags(uint32 objectId) if (GameObject* go = GetBGObject(objectId)) { if (CanInteractWithObject(objectId)) - go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE|GO_FLAG_INTERACT_COND|GO_FLAG_IN_USE); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE | GO_FLAG_INTERACT_COND | GO_FLAG_IN_USE); else go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); } @@ -880,7 +880,7 @@ void BattlegroundSA::EventPlayerClickedOnFlag(Player* Source, GameObject* gameOb }; } -void BattlegroundSA::CaptureGraveyard(BG_SA_Graveyards i, Player *Source) +void BattlegroundSA::CaptureGraveyard(BG_SA_Graveyards i, Player* Source) { if (GraveyardStatus[i] == Attackers || Source->GetTeamId() != Attackers) return; @@ -908,7 +908,7 @@ void BattlegroundSA::CaptureGraveyard(BG_SA_Graveyards i, Player *Source) } DelCreature(BG_SA_MAXNPC + i); - + GraveyardStruct const* sg = sGraveyard->GetGraveyard(BG_SA_GYEntries[i]); if (!sg) { @@ -925,20 +925,20 @@ void BattlegroundSA::CaptureGraveyard(BG_SA_Graveyards i, Player *Source) case BG_SA_LEFT_CAPTURABLE_GY: flag = BG_SA_LEFT_FLAG; DelObject(flag); - AddObject(flag, (BG_SA_ObjEntries[flag] - (Source->GetTeamId() == TEAM_ALLIANCE ? 0:1)), - BG_SA_ObjSpawnlocs[flag][0], BG_SA_ObjSpawnlocs[flag][1], - BG_SA_ObjSpawnlocs[flag][2], BG_SA_ObjSpawnlocs[flag][3], 0, 0, 0, 0, RESPAWN_ONE_DAY); + AddObject(flag, (BG_SA_ObjEntries[flag] - (Source->GetTeamId() == TEAM_ALLIANCE ? 0 : 1)), + BG_SA_ObjSpawnlocs[flag][0], BG_SA_ObjSpawnlocs[flag][1], + BG_SA_ObjSpawnlocs[flag][2], BG_SA_ObjSpawnlocs[flag][3], 0, 0, 0, 0, RESPAWN_ONE_DAY); npc = BG_SA_NPC_RIGSPARK; AddCreature(BG_SA_NpcEntries[npc], npc, Attackers, - BG_SA_NpcSpawnlocs[npc][0], BG_SA_NpcSpawnlocs[npc][1], - BG_SA_NpcSpawnlocs[npc][2], BG_SA_NpcSpawnlocs[npc][3]); + BG_SA_NpcSpawnlocs[npc][0], BG_SA_NpcSpawnlocs[npc][1], + BG_SA_NpcSpawnlocs[npc][2], BG_SA_NpcSpawnlocs[npc][3]); for (uint8 j = BG_SA_DEMOLISHER_7; j <= BG_SA_DEMOLISHER_8; j++) { AddCreature(BG_SA_NpcEntries[j], j, - BG_SA_NpcSpawnlocs[j][0], BG_SA_NpcSpawnlocs[j][1], - BG_SA_NpcSpawnlocs[j][2], BG_SA_NpcSpawnlocs[j][3], 600); + BG_SA_NpcSpawnlocs[j][0], BG_SA_NpcSpawnlocs[j][1], + BG_SA_NpcSpawnlocs[j][2], BG_SA_NpcSpawnlocs[j][3], 600); if (Creature* dem = GetBGCreature(j)) dem->setFaction(BG_SA_Factions[Attackers]); @@ -954,19 +954,19 @@ void BattlegroundSA::CaptureGraveyard(BG_SA_Graveyards i, Player *Source) case BG_SA_RIGHT_CAPTURABLE_GY: flag = BG_SA_RIGHT_FLAG; DelObject(flag); - AddObject(flag, (BG_SA_ObjEntries[flag] - (Source->GetTeamId() == TEAM_ALLIANCE ? 0:1)), - BG_SA_ObjSpawnlocs[flag][0], BG_SA_ObjSpawnlocs[flag][1], - BG_SA_ObjSpawnlocs[flag][2], BG_SA_ObjSpawnlocs[flag][3], 0, 0, 0, 0, RESPAWN_ONE_DAY); + AddObject(flag, (BG_SA_ObjEntries[flag] - (Source->GetTeamId() == TEAM_ALLIANCE ? 0 : 1)), + BG_SA_ObjSpawnlocs[flag][0], BG_SA_ObjSpawnlocs[flag][1], + BG_SA_ObjSpawnlocs[flag][2], BG_SA_ObjSpawnlocs[flag][3], 0, 0, 0, 0, RESPAWN_ONE_DAY); npc = BG_SA_NPC_SPARKLIGHT; AddCreature(BG_SA_NpcEntries[npc], npc, - BG_SA_NpcSpawnlocs[npc][0], BG_SA_NpcSpawnlocs[npc][1], - BG_SA_NpcSpawnlocs[npc][2], BG_SA_NpcSpawnlocs[npc][3]); + BG_SA_NpcSpawnlocs[npc][0], BG_SA_NpcSpawnlocs[npc][1], + BG_SA_NpcSpawnlocs[npc][2], BG_SA_NpcSpawnlocs[npc][3]); for (uint8 j = BG_SA_DEMOLISHER_5; j <= BG_SA_DEMOLISHER_6; j++) { AddCreature(BG_SA_NpcEntries[j], j, BG_SA_NpcSpawnlocs[j][0], BG_SA_NpcSpawnlocs[j][1], - BG_SA_NpcSpawnlocs[j][2], BG_SA_NpcSpawnlocs[j][3], 600); + BG_SA_NpcSpawnlocs[j][2], BG_SA_NpcSpawnlocs[j][3], 600); if (Creature* dem = GetBGCreature(j)) dem->setFaction(BG_SA_Factions[Attackers]); @@ -982,12 +982,12 @@ void BattlegroundSA::CaptureGraveyard(BG_SA_Graveyards i, Player *Source) case BG_SA_CENTRAL_CAPTURABLE_GY: flag = BG_SA_CENTRAL_FLAG; DelObject(flag); - AddObject(flag, (BG_SA_ObjEntries[flag] - (Source->GetTeamId() == TEAM_ALLIANCE ? 0:1)), - BG_SA_ObjSpawnlocs[flag][0], BG_SA_ObjSpawnlocs[flag][1], - BG_SA_ObjSpawnlocs[flag][2], BG_SA_ObjSpawnlocs[flag][3], 0, 0, 0, 0, RESPAWN_ONE_DAY); + AddObject(flag, (BG_SA_ObjEntries[flag] - (Source->GetTeamId() == TEAM_ALLIANCE ? 0 : 1)), + BG_SA_ObjSpawnlocs[flag][0], BG_SA_ObjSpawnlocs[flag][1], + BG_SA_ObjSpawnlocs[flag][2], BG_SA_ObjSpawnlocs[flag][3], 0, 0, 0, 0, RESPAWN_ONE_DAY); - UpdateWorldState(BG_SA_CENTER_GY_ALLIANCE, (GraveyardStatus[i] == TEAM_ALLIANCE? 1:0)); - UpdateWorldState(BG_SA_CENTER_GY_HORDE, (GraveyardStatus[i] == TEAM_ALLIANCE? 0:1)); + UpdateWorldState(BG_SA_CENTER_GY_ALLIANCE, (GraveyardStatus[i] == TEAM_ALLIANCE ? 1 : 0)); + UpdateWorldState(BG_SA_CENTER_GY_HORDE, (GraveyardStatus[i] == TEAM_ALLIANCE ? 0 : 1)); if (Source->GetTeamId() == TEAM_ALLIANCE) SendWarningToAll(LANG_BG_SA_A_GY_SOUTH); else @@ -1065,14 +1065,14 @@ void BattlegroundSA::UpdateDemolisherSpawns() // Demolisher is not in list if (DemoliserRespawnList.find(i) == DemoliserRespawnList.end()) { - DemoliserRespawnList[i] = World::GetGameTimeMS()+30000; + DemoliserRespawnList[i] = World::GetGameTimeMS() + 30000; } else { if (DemoliserRespawnList[i] < World::GetGameTimeMS()) { Demolisher->Relocate(BG_SA_NpcSpawnlocs[i][0], BG_SA_NpcSpawnlocs[i][1], - BG_SA_NpcSpawnlocs[i][2], BG_SA_NpcSpawnlocs[i][3]); + BG_SA_NpcSpawnlocs[i][2], BG_SA_NpcSpawnlocs[i][3]); Demolisher->SetVisible(true); Demolisher->Respawn(); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.h b/src/server/game/Battlegrounds/Zones/BattlegroundSA.h index 8802d8095..834e13954 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.h @@ -218,7 +218,7 @@ enum BG_SA_Objects BG_SA_PORTAL_DEFFENDER_PURPLE, BG_SA_PORTAL_DEFFENDER_RED, BG_SA_BOMB, - BG_SA_MAXOBJ = BG_SA_BOMB+68 + BG_SA_MAXOBJ = BG_SA_BOMB + 68 }; float const BG_SA_ObjSpawnlocs[BG_SA_MAXOBJ][4] = @@ -407,7 +407,8 @@ struct BG_SA_RoundScore uint32 time; }; -const float SOTADefPortalDest[5][4] = { +const float SOTADefPortalDest[5][4] = +{ { 1388.94f, 103.067f, 34.49f, 5.4571f }, { 1043.69f, -87.95f, 87.12f, 0.003f }, { 1441.0411f, -240.974f, 35.264f, 0.949f }, @@ -418,180 +419,204 @@ const float SOTADefPortalDest[5][4] = { /// Class for manage Strand of Ancient battleground class BattlegroundSA : public Battleground { - public: - BattlegroundSA(); - ~BattlegroundSA(); +public: + BattlegroundSA(); + ~BattlegroundSA(); - /** - * \brief Called every time for update battle data - * -Update timer - * -Round switch - */ - void PostUpdateImpl(uint32 diff); + /** + * \brief Called every time for update battle data + * -Update timer + * -Round switch + */ + void PostUpdateImpl(uint32 diff); - /* inherited from BattlegroundClass */ - /// Called when a player join battle - void AddPlayer(Player* player); - /// Called when battle start - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); - /// Called for ini battleground, after that the first player be entered - bool SetupBattleground(); - void Init(); - /// Called for generate packet contain worldstate data - void FillInitialWorldStates(WorldPacket& data); - /// Called when a player deal damage to building (door) - void EventPlayerDamagedGO(Player* player, GameObject* go, uint32 eventType); - /// Called when a player kill a unit in bg - void HandleKillUnit(Creature* creature, Player* killer); - /// Return the nearest graveyard where player can respawn - GraveyardStruct const* GetClosestGraveyard(Player* player); - /// Called when a player click on flag (graveyard flag) - void EventPlayerClickedOnFlag(Player* Source, GameObject* gameObject); - /// Called when a player use a gamobject (relic) - void EventPlayerUsedGO(Player* Source, GameObject* object); - - /// Return worldstate id, according to door id - uint32 GetWorldStateFromGateID(uint32 id) + /* inherited from BattlegroundClass */ + /// Called when a player join battle + void AddPlayer(Player* player); + /// Called when battle start + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); + /// Called for ini battleground, after that the first player be entered + bool SetupBattleground(); + void Init(); + /// Called for generate packet contain worldstate data + void FillInitialWorldStates(WorldPacket& data); + /// Called when a player deal damage to building (door) + void EventPlayerDamagedGO(Player* player, GameObject* go, uint32 eventType); + /// Called when a player kill a unit in bg + void HandleKillUnit(Creature* creature, Player* killer); + /// Return the nearest graveyard where player can respawn + GraveyardStruct const* GetClosestGraveyard(Player* player); + /// Called when a player click on flag (graveyard flag) + void EventPlayerClickedOnFlag(Player* Source, GameObject* gameObject); + /// Called when a player use a gamobject (relic) + void EventPlayerUsedGO(Player* Source, GameObject* object); + + /// Return worldstate id, according to door id + uint32 GetWorldStateFromGateID(uint32 id) + { + uint32 uws = 0; + switch (id) { - uint32 uws = 0; - switch (id) - { - case BG_SA_GREEN_GATE: uws = BG_SA_GREEN_GATEWS; break; - case BG_SA_YELLOW_GATE: uws = BG_SA_YELLOW_GATEWS; break; - case BG_SA_BLUE_GATE: uws = BG_SA_BLUE_GATEWS; break; - case BG_SA_RED_GATE: uws = BG_SA_RED_GATEWS; break; - case BG_SA_PURPLE_GATE: uws = BG_SA_PURPLE_GATEWS; break; - case BG_SA_ANCIENT_GATE: uws = BG_SA_ANCIENT_GATEWS; break; - } - return uws; + case BG_SA_GREEN_GATE: + uws = BG_SA_GREEN_GATEWS; + break; + case BG_SA_YELLOW_GATE: + uws = BG_SA_YELLOW_GATEWS; + break; + case BG_SA_BLUE_GATE: + uws = BG_SA_BLUE_GATEWS; + break; + case BG_SA_RED_GATE: + uws = BG_SA_RED_GATEWS; + break; + case BG_SA_PURPLE_GATE: + uws = BG_SA_PURPLE_GATEWS; + break; + case BG_SA_ANCIENT_GATE: + uws = BG_SA_ANCIENT_GATEWS; + break; } + return uws; + } - /// Called on battleground ending - void EndBattleground(TeamId winnerTeamId); + /// Called on battleground ending + void EndBattleground(TeamId winnerTeamId); - /// CAlled when a player leave battleground - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); + /// CAlled when a player leave battleground + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); - /* Scorekeeping */ - /// Update score board - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); + /* Scorekeeping */ + /// Update score board + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); - // Teleporters - void DefendersPortalTeleport(GameObject* portal, Player* plr); + // Teleporters + void DefendersPortalTeleport(GameObject* portal, Player* plr); - // Achievements - bool AllowDefenseOfTheAncients(Player* source); + // Achievements + bool AllowDefenseOfTheAncients(Player* source); - // Achievement: Not Even a Scratch - bool notEvenAScratch(TeamId teamId) const { return _notEvenAScratch[teamId]; } + // Achievement: Not Even a Scratch + bool notEvenAScratch(TeamId teamId) const { return _notEvenAScratch[teamId]; } - private: +private: - /// Return gate id, relative to bg data, according to gameobject id - uint32 GetGateIDFromEntry(uint32 id) + /// Return gate id, relative to bg data, according to gameobject id + uint32 GetGateIDFromEntry(uint32 id) + { + uint32 i = 0; + switch(id) { - uint32 i = 0; - switch(id) - { - case 190722: i = BG_SA_GREEN_GATE; break; //Green gate destroyed - case 190724: i = BG_SA_BLUE_GATE; break; //blue gate - case 190726: i = BG_SA_RED_GATE; break; //red gate - case 190723: i = BG_SA_PURPLE_GATE; break; //purple gate - case 190727: i = BG_SA_YELLOW_GATE; break; //yellow gate - case 192549: i = BG_SA_ANCIENT_GATE; break; //ancient gate - } - return i; + case 190722: + i = BG_SA_GREEN_GATE; + break; //Green gate destroyed + case 190724: + i = BG_SA_BLUE_GATE; + break; //blue gate + case 190726: + i = BG_SA_RED_GATE; + break; //red gate + case 190723: + i = BG_SA_PURPLE_GATE; + break; //purple gate + case 190727: + i = BG_SA_YELLOW_GATE; + break; //yellow gate + case 192549: + i = BG_SA_ANCIENT_GATE; + break; //ancient gate } - /** - * \brief Called on setup and between the two round - * -Delete all gameobject / creature - * -Respawn all gameobject / creature to have good faction - */ - bool ResetObjs(); - /// Called for start ship movement - void StartShips(); - /** - * \brief Called between the two round - * -Teleport all players to good location - */ - void TeleportPlayers(); - void TeleportToEntrancePosition(Player* player); - /** - * \brief Called on start and between the two round - * -Update faction of all vehicle - */ - void OverrideGunFaction(); - /// Set selectable or not demolisher, called on battle start, when boats arrive to dock - void DemolisherStartState(bool start); - /// Checks if a player can interact with the given object - bool CanInteractWithObject(uint32 objectId); - /// Updates interaction flags of specific objects - void UpdateObjectInteractionFlags(uint32 objectId); - void UpdateObjectInteractionFlags(); - /** - * \brief Called when a gate is destroy - * -Give honor to player witch destroy it - * -Update worldstate - * -Delete gameobject in front of door (lighting object, with different colours for each door) - */ - void DestroyGate(Player* player, GameObject* go); - /// Update timer worldstate - void SendTime(); - /** - * \brief Called when a graveyard is capture - * -Update spiritguide - * -Update gameobject (flag) - * -Update Worldstate - * -Send warning for announce this - * \param i : id of graveyard - * \param Source : Player who capture gy - */ - void CaptureGraveyard(BG_SA_Graveyards i, Player* Source); - /// Switch on/off timer worldstate - void ToggleTimer(); + return i; + } + /** + * \brief Called on setup and between the two round + * -Delete all gameobject / creature + * -Respawn all gameobject / creature to have good faction + */ + bool ResetObjs(); + /// Called for start ship movement + void StartShips(); + /** + * \brief Called between the two round + * -Teleport all players to good location + */ + void TeleportPlayers(); + void TeleportToEntrancePosition(Player* player); + /** + * \brief Called on start and between the two round + * -Update faction of all vehicle + */ + void OverrideGunFaction(); + /// Set selectable or not demolisher, called on battle start, when boats arrive to dock + void DemolisherStartState(bool start); + /// Checks if a player can interact with the given object + bool CanInteractWithObject(uint32 objectId); + /// Updates interaction flags of specific objects + void UpdateObjectInteractionFlags(uint32 objectId); + void UpdateObjectInteractionFlags(); + /** + * \brief Called when a gate is destroy + * -Give honor to player witch destroy it + * -Update worldstate + * -Delete gameobject in front of door (lighting object, with different colours for each door) + */ + void DestroyGate(Player* player, GameObject* go); + /// Update timer worldstate + void SendTime(); + /** + * \brief Called when a graveyard is capture + * -Update spiritguide + * -Update gameobject (flag) + * -Update Worldstate + * -Send warning for announce this + * \param i : id of graveyard + * \param Source : Player who capture gy + */ + void CaptureGraveyard(BG_SA_Graveyards i, Player* Source); + /// Switch on/off timer worldstate + void ToggleTimer(); - /// Respawn dead demolisher - void UpdateDemolisherSpawns(); + /// Respawn dead demolisher + void UpdateDemolisherSpawns(); - /// Send packet to player for create boats (client part) - void SendTransportInit(Player* player); - /// Send packet to player for destroy boats (client part) - void SendTransportsRemove(Player* player); + /// Send packet to player for create boats (client part) + void SendTransportInit(Player* player); + /// Send packet to player for destroy boats (client part) + void SendTransportsRemove(Player* player); - /// Id of attacker team - TeamId Attackers; - /// Totale elapsed time of current round - uint32 TotalTime; - /// Max time of round - uint32 EndRoundTimer; - /// For know if boats has start moving or not yet - bool ShipsStarted; - /// Status of each gate (Destroy/Damage/Intact) - BG_SA_GateState GateStatus[6]; - /// Statu of battle (Start or not, and what round) - BG_SA_Status Status; - /// Team witch conntrol each graveyard - TeamId GraveyardStatus[BG_SA_MAX_GY]; - /// Score of each round - BG_SA_RoundScore RoundScores[2]; - /// used for know we are in timer phase or not (used for worldstate update) - bool TimerEnabled; - /// 5secs before starting the 1min countdown for second round - uint32 UpdateWaitTimer; - /// for know if warning about second round start has been sent - bool SignaledRoundTwo; - /// for know if warning about second round start has been sent - bool SignaledRoundTwoHalfMin; - /// for know if second round has been init - bool InitSecondRound; - std::map DemoliserRespawnList; + /// Id of attacker team + TeamId Attackers; + /// Totale elapsed time of current round + uint32 TotalTime; + /// Max time of round + uint32 EndRoundTimer; + /// For know if boats has start moving or not yet + bool ShipsStarted; + /// Status of each gate (Destroy/Damage/Intact) + BG_SA_GateState GateStatus[6]; + /// Statu of battle (Start or not, and what round) + BG_SA_Status Status; + /// Team witch conntrol each graveyard + TeamId GraveyardStatus[BG_SA_MAX_GY]; + /// Score of each round + BG_SA_RoundScore RoundScores[2]; + /// used for know we are in timer phase or not (used for worldstate update) + bool TimerEnabled; + /// 5secs before starting the 1min countdown for second round + uint32 UpdateWaitTimer; + /// for know if warning about second round start has been sent + bool SignaledRoundTwo; + /// for know if warning about second round start has been sent + bool SignaledRoundTwoHalfMin; + /// for know if second round has been init + bool InitSecondRound; + std::map DemoliserRespawnList; - // xinef: - bool _relicClicked; + // xinef: + bool _relicClicked; - // Achievement: Not Even a Scratch - bool _notEvenAScratch[BG_TEAMS_COUNT]; + // Achievement: Not Even a Scratch + bool _notEvenAScratch[BG_TEAMS_COUNT]; }; #endif \ No newline at end of file diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp index 3408b5122..ff335f5b4 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp @@ -49,7 +49,7 @@ void BattlegroundWS::PostUpdateImpl(uint32 diff) { case BG_WS_EVENT_UPDATE_GAME_TIME: UpdateWorldState(BG_WS_STATE_TIMER, GetMatchTime()); - _bgEvents.ScheduleEvent(BG_WS_EVENT_UPDATE_GAME_TIME, ((BG_WS_TOTAL_GAME_TIME - GetStartTime()) % (MINUTE*IN_MILLISECONDS)) + 1); + _bgEvents.ScheduleEvent(BG_WS_EVENT_UPDATE_GAME_TIME, ((BG_WS_TOTAL_GAME_TIME - GetStartTime()) % (MINUTE * IN_MILLISECONDS)) + 1); break; case BG_WS_EVENT_NO_TIME_LEFT: if (GetTeamScore(TEAM_ALLIANCE) == GetTeamScore(TEAM_HORDE)) @@ -120,7 +120,7 @@ void BattlegroundWS::StartingEventOpenDoors() StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, WS_EVENT_START_BATTLE); UpdateWorldState(BG_WS_STATE_TIMER_ACTIVE, 1); _bgEvents.ScheduleEvent(BG_WS_EVENT_UPDATE_GAME_TIME, 0); - _bgEvents.ScheduleEvent(BG_WS_EVENT_NO_TIME_LEFT, BG_WS_TOTAL_GAME_TIME - 2*MINUTE*IN_MILLISECONDS); // 27 - 2 = 25 minutes + _bgEvents.ScheduleEvent(BG_WS_EVENT_NO_TIME_LEFT, BG_WS_TOTAL_GAME_TIME - 2 * MINUTE * IN_MILLISECONDS); // 27 - 2 = 25 minutes } void BattlegroundWS::AddPlayer(Player* player) @@ -299,7 +299,7 @@ void BattlegroundWS::EventPlayerClickedOnFlag(Player* player, GameObject* gameOb UpdateFlagState(TEAM_ALLIANCE, BG_WS_FLAG_STATE_ON_PLAYER); player->CastSpell(player, BG_WS_SPELL_SILVERWING_FLAG, true); if (uint32 assaultSpellId = GetAssaultSpellId()) - player->CastSpell(player, assaultSpellId, true); + player->CastSpell(player, assaultSpellId, true); PlaySoundToAll(BG_WS_SOUND_ALLIANCE_FLAG_PICKED_UP); SendMessageToAll(LANG_BG_WS_PICKEDUP_AF, CHAT_MSG_BG_SYSTEM_HORDE, player); @@ -330,7 +330,7 @@ void BattlegroundWS::EventPlayerClickedOnFlag(Player* player, GameObject* gameOb UpdateFlagState(TEAM_HORDE, BG_WS_FLAG_STATE_ON_PLAYER); player->CastSpell(player, BG_WS_SPELL_WARSONG_FLAG, true); if (uint32 assaultSpellId = GetAssaultSpellId()) - player->CastSpell(player, assaultSpellId, true); + player->CastSpell(player, assaultSpellId, true); PlaySoundToAll(BG_WS_SOUND_HORDE_FLAG_PICKED_UP); SendMessageToAll(LANG_BG_WS_PICKEDUP_HF, CHAT_MSG_BG_SYSTEM_ALLIANCE, player); @@ -385,26 +385,26 @@ bool BattlegroundWS::SetupBattleground() // flags AddObject(BG_WS_OBJECT_A_FLAG, BG_OBJECT_A_FLAG_WS_ENTRY, 1540.423f, 1481.325f, 351.8284f, 3.089233f, 0, 0, 0.9996573f, 0.02617699f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_H_FLAG, BG_OBJECT_H_FLAG_WS_ENTRY, 916.0226f, 1434.405f, 345.413f, 0.01745329f, 0, 0, 0.008726535f, 0.9999619f, RESPAWN_IMMEDIATELY); - // buffs + // buffs AddObject(BG_WS_OBJECT_SPEEDBUFF_1, BG_OBJECTID_SPEEDBUFF_ENTRY, 1449.93f, 1470.71f, 342.6346f, -1.64061f, 0, 0, 0.7313537f, -0.6819983f, BUFF_RESPAWN_TIME); AddObject(BG_WS_OBJECT_SPEEDBUFF_2, BG_OBJECTID_SPEEDBUFF_ENTRY, 1005.171f, 1447.946f, 335.9032f, 1.64061f, 0, 0, 0.7313537f, 0.6819984f, BUFF_RESPAWN_TIME); AddObject(BG_WS_OBJECT_REGENBUFF_1, BG_OBJECTID_REGENBUFF_ENTRY, 1317.506f, 1550.851f, 313.2344f, -0.2617996f, 0, 0, 0.1305263f, -0.9914448f, BUFF_RESPAWN_TIME); AddObject(BG_WS_OBJECT_REGENBUFF_2, BG_OBJECTID_REGENBUFF_ENTRY, 1110.451f, 1353.656f, 316.5181f, -0.6806787f, 0, 0, 0.333807f, -0.9426414f, BUFF_RESPAWN_TIME); AddObject(BG_WS_OBJECT_BERSERKBUFF_1, BG_OBJECTID_BERSERKERBUFF_ENTRY, 1320.09f, 1378.79f, 314.7532f, 1.186824f, 0, 0, 0.5591929f, 0.8290376f, BUFF_RESPAWN_TIME); AddObject(BG_WS_OBJECT_BERSERKBUFF_2, BG_OBJECTID_BERSERKERBUFF_ENTRY, 1139.688f, 1560.288f, 306.8432f, -2.443461f, 0, 0, 0.9396926f, -0.3420201f, BUFF_RESPAWN_TIME); - // alliance gates + // alliance gates AddObject(BG_WS_OBJECT_DOOR_A_1, BG_OBJECT_DOOR_A_1_WS_ENTRY, 1503.335f, 1493.466f, 352.1888f, 3.115414f, 0, 0, 0.9999143f, 0.01308903f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_A_2, BG_OBJECT_DOOR_A_2_WS_ENTRY, 1492.478f, 1457.912f, 342.9689f, 3.115414f, 0, 0, 0.9999143f, 0.01308903f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_A_3, BG_OBJECT_DOOR_A_3_WS_ENTRY, 1468.503f, 1494.357f, 351.8618f, 3.115414f, 0, 0, 0.9999143f, 0.01308903f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_A_4, BG_OBJECT_DOOR_A_4_WS_ENTRY, 1471.555f, 1458.778f, 362.6332f, 3.115414f, 0, 0, 0.9999143f, 0.01308903f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_A_5, BG_OBJECT_DOOR_A_5_WS_ENTRY, 1492.347f, 1458.34f, 342.3712f, -0.03490669f, 0, 0, 0.01745246f, -0.9998477f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_A_6, BG_OBJECT_DOOR_A_6_WS_ENTRY, 1503.466f, 1493.367f, 351.7352f, -0.03490669f, 0, 0, 0.01745246f, -0.9998477f, RESPAWN_IMMEDIATELY); - // horde gates + // horde gates AddObject(BG_WS_OBJECT_DOOR_H_1, BG_OBJECT_DOOR_H_1_WS_ENTRY, 949.1663f, 1423.772f, 345.6241f, -0.5756807f, -0.01673368f, -0.004956111f, -0.2839723f, 0.9586737f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_H_2, BG_OBJECT_DOOR_H_2_WS_ENTRY, 953.0507f, 1459.842f, 340.6526f, -1.99662f, -0.1971825f, 0.1575096f, -0.8239487f, 0.5073641f, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_H_3, BG_OBJECT_DOOR_H_3_WS_ENTRY, 949.9523f, 1422.751f, 344.9273f, 0.0f, 0, 0, 0, 1, RESPAWN_IMMEDIATELY); AddObject(BG_WS_OBJECT_DOOR_H_4, BG_OBJECT_DOOR_H_4_WS_ENTRY, 950.7952f, 1459.583f, 342.1523f, 0.05235988f, 0, 0, 0.02617695f, 0.9996573f, RESPAWN_IMMEDIATELY); - + GraveyardStruct const* sg = sGraveyard->GetGraveyard(WS_GRAVEYARD_MAIN_ALLIANCE); AddSpiritGuide(WS_SPIRIT_MAIN_ALLIANCE, sg->x, sg->y, sg->z, 3.124139f, TEAM_ALLIANCE); @@ -531,9 +531,9 @@ TeamId BattlegroundWS::GetPrematureWinner() uint32 BattlegroundWS::GetAssaultSpellId() const { - if ((GetFlagPickerGUID(TEAM_ALLIANCE) == 0 && GetFlagState(TEAM_ALLIANCE) != BG_WS_FLAG_STATE_ON_GROUND) || - (GetFlagPickerGUID(TEAM_HORDE) == 0 && GetFlagState(TEAM_HORDE) != BG_WS_FLAG_STATE_ON_GROUND) || - _bgEvents.GetNextEventTime(BG_WS_EVENT_BOTH_FLAGS_KEPT10) > 0) + if ((GetFlagPickerGUID(TEAM_ALLIANCE) == 0 && GetFlagState(TEAM_ALLIANCE) != BG_WS_FLAG_STATE_ON_GROUND) || + (GetFlagPickerGUID(TEAM_HORDE) == 0 && GetFlagState(TEAM_HORDE) != BG_WS_FLAG_STATE_ON_GROUND) || + _bgEvents.GetNextEventTime(BG_WS_EVENT_BOTH_FLAGS_KEPT10) > 0) return 0; return _bgEvents.GetNextEventTime(BG_WS_EVENT_BOTH_FLAGS_KEPT15) > 0 ? BG_WS_SPELL_FOCUSED_ASSAULT : BG_WS_SPELL_BRUTAL_ASSAULT; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.h b/src/server/game/Battlegrounds/Zones/BattlegroundWS.h index ee564162a..8ac7791c3 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.h @@ -22,11 +22,11 @@ enum BG_WS_TimerOrScore { BG_WS_MAX_TEAM_SCORE = 3, - BG_WS_TOTAL_GAME_TIME = 27*MINUTE*IN_MILLISECONDS, - BG_WS_FLAG_RESPAWN_TIME = 23*IN_MILLISECONDS, - BG_WS_FLAG_DROP_TIME = 10*IN_MILLISECONDS, - BG_WS_SPELL_FORCE_TIME = 10*MINUTE*IN_MILLISECONDS, - BG_WS_SPELL_BRUTAL_TIME = 15*MINUTE*IN_MILLISECONDS + BG_WS_TOTAL_GAME_TIME = 27 * MINUTE * IN_MILLISECONDS, + BG_WS_FLAG_RESPAWN_TIME = 23 * IN_MILLISECONDS, + BG_WS_FLAG_DROP_TIME = 10 * IN_MILLISECONDS, + BG_WS_SPELL_FORCE_TIME = 10 * MINUTE * IN_MILLISECONDS, + BG_WS_SPELL_BRUTAL_TIME = 15 * MINUTE * IN_MILLISECONDS }; enum BG_WS_Sound @@ -149,60 +149,60 @@ struct BattlegroundWGScore : public BattlegroundScore class BattlegroundWS : public Battleground { - public: - /* Construction */ - BattlegroundWS(); - ~BattlegroundWS(); +public: + /* Construction */ + BattlegroundWS(); + ~BattlegroundWS(); - /* inherited from BattlegroundClass */ - void AddPlayer(Player* player); - void StartingEventCloseDoors(); - void StartingEventOpenDoors(); + /* inherited from BattlegroundClass */ + void AddPlayer(Player* player); + void StartingEventCloseDoors(); + void StartingEventOpenDoors(); - /* BG Flags */ - uint64 GetFlagPickerGUID(TeamId teamId) const { return _flagKeepers[teamId]; } - void SetFlagPicker(uint64 guid, TeamId teamId) { _flagKeepers[teamId] = guid; } - void RespawnFlagAfterDrop(TeamId teamId); - uint8 GetFlagState(TeamId teamId) const { return _flagState[teamId]; } + /* BG Flags */ + uint64 GetFlagPickerGUID(TeamId teamId) const { return _flagKeepers[teamId]; } + void SetFlagPicker(uint64 guid, TeamId teamId) { _flagKeepers[teamId] = guid; } + void RespawnFlagAfterDrop(TeamId teamId); + uint8 GetFlagState(TeamId teamId) const { return _flagState[teamId]; } - /* Battleground Events */ - void EventPlayerDroppedFlag(Player* player); - void EventPlayerClickedOnFlag(Player* player, GameObject* gameObject); - void EventPlayerCapturedFlag(Player* player); + /* Battleground Events */ + void EventPlayerDroppedFlag(Player* player); + void EventPlayerClickedOnFlag(Player* player, GameObject* gameObject); + void EventPlayerCapturedFlag(Player* player); - void RemovePlayer(Player* player); - void HandleAreaTrigger(Player* player, uint32 trigger); - void HandleKillPlayer(Player* player, Player* killer); - bool SetupBattleground(); - void Init(); - void EndBattleground(TeamId winnerTeamId); - GraveyardStruct const* GetClosestGraveyard(Player* player); + void RemovePlayer(Player* player); + void HandleAreaTrigger(Player* player, uint32 trigger); + void HandleKillPlayer(Player* player, Player* killer); + bool SetupBattleground(); + void Init(); + void EndBattleground(TeamId winnerTeamId); + GraveyardStruct const* GetClosestGraveyard(Player* player); - void UpdateFlagState(TeamId teamId, uint32 value); - void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); - void SetDroppedFlagGUID(uint64 guid, TeamId teamId) { _droppedFlagGUID[teamId] = guid; } - uint64 GetDroppedFlagGUID(TeamId teamId) const { return _droppedFlagGUID[teamId];} - void FillInitialWorldStates(WorldPacket& data); + void UpdateFlagState(TeamId teamId, uint32 value); + void UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true); + void SetDroppedFlagGUID(uint64 guid, TeamId teamId) { _droppedFlagGUID[teamId] = guid; } + uint64 GetDroppedFlagGUID(TeamId teamId) const { return _droppedFlagGUID[teamId];} + void FillInitialWorldStates(WorldPacket& data); - /* Scorekeeping */ - void AddPoints(TeamId teamId, uint32 points) { m_TeamScores[teamId] += points; } - - TeamId GetPrematureWinner(); - uint32 GetMatchTime() const { return 1 + (BG_WS_TOTAL_GAME_TIME - GetStartTime()) / (MINUTE*IN_MILLISECONDS); } - uint32 GetAssaultSpellId() const; - void RemoveAssaultAuras(); + /* Scorekeeping */ + void AddPoints(TeamId teamId, uint32 points) { m_TeamScores[teamId] += points; } - private: - EventMap _bgEvents; + TeamId GetPrematureWinner(); + uint32 GetMatchTime() const { return 1 + (BG_WS_TOTAL_GAME_TIME - GetStartTime()) / (MINUTE * IN_MILLISECONDS); } + uint32 GetAssaultSpellId() const; + void RemoveAssaultAuras(); - uint64 _flagKeepers[2]; - uint64 _droppedFlagGUID[2]; - uint8 _flagState[2]; - TeamId _lastFlagCaptureTeam; - uint32 _reputationCapture; - uint32 _honorWinKills; - uint32 _honorEndKills; +private: + EventMap _bgEvents; - void PostUpdateImpl(uint32 diff); + uint64 _flagKeepers[2]; + uint64 _droppedFlagGUID[2]; + uint8 _flagState[2]; + TeamId _lastFlagCaptureTeam; + uint32 _reputationCapture; + uint32 _honorWinKills; + uint32 _honorEndKills; + + void PostUpdateImpl(uint32 diff); }; #endif diff --git a/src/server/game/Calendar/CalendarMgr.cpp b/src/server/game/Calendar/CalendarMgr.cpp index 161878c77..3e3f48d19 100644 --- a/src/server/game/Calendar/CalendarMgr.cpp +++ b/src/server/game/Calendar/CalendarMgr.cpp @@ -74,8 +74,7 @@ void CalendarMgr::LoadFromDB() _maxEventId = std::max(_maxEventId, eventId); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u calendar events", count); count = 0; @@ -101,8 +100,7 @@ void CalendarMgr::LoadFromDB() _maxInviteId = std::max(_maxInviteId, inviteId); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u calendar invites", count); @@ -510,7 +508,7 @@ void CalendarMgr::SendCalendarEventInvite(CalendarInvite const& invite) void CalendarMgr::SendCalendarEventUpdateAlert(CalendarEvent const& calendarEvent, time_t oldEventTime) { WorldPacket data(SMSG_CALENDAR_EVENT_UPDATED_ALERT, 1 + 8 + 4 + 4 + 4 + 1 + 4 + - calendarEvent.GetTitle().size() + calendarEvent.GetDescription().size() + 1 + 4 + 4); + calendarEvent.GetTitle().size() + calendarEvent.GetDescription().size() + 1 + 4 + 4); data << uint8(1); // unk data << uint64(calendarEvent.GetEventId()); data.AppendPackedTime(oldEventTime); @@ -593,9 +591,8 @@ void CalendarMgr::SendCalendarEventInviteAlert(CalendarEvent const& calendarEven if (Guild* guild = sGuildMgr->GetGuildById(calendarEvent.GetGuildId())) guild->BroadcastPacket(&data); } - else - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(invite.GetInviteeGUID())) - player->SendDirectMessage(&data); + else if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(invite.GetInviteeGUID())) + player->SendDirectMessage(&data); } void CalendarMgr::SendCalendarEvent(uint64 guid, CalendarEvent const& calendarEvent, CalendarSendEventType sendType) diff --git a/src/server/game/Calendar/CalendarMgr.h b/src/server/game/Calendar/CalendarMgr.h index 48653ad90..30379a7e4 100644 --- a/src/server/game/Calendar/CalendarMgr.h +++ b/src/server/game/Calendar/CalendarMgr.h @@ -121,142 +121,142 @@ enum CalendarLimits struct CalendarInvite { - public: - CalendarInvite(CalendarInvite const& calendarInvite, uint64 inviteId, uint64 eventId) - { - _inviteId = inviteId; - _eventId = eventId; - _invitee = calendarInvite.GetInviteeGUID(); - _senderGUID = calendarInvite.GetSenderGUID(); - _statusTime = calendarInvite.GetStatusTime(); - _status = calendarInvite.GetStatus(); - _rank = calendarInvite.GetRank(); - _text = calendarInvite.GetText(); - } +public: + CalendarInvite(CalendarInvite const& calendarInvite, uint64 inviteId, uint64 eventId) + { + _inviteId = inviteId; + _eventId = eventId; + _invitee = calendarInvite.GetInviteeGUID(); + _senderGUID = calendarInvite.GetSenderGUID(); + _statusTime = calendarInvite.GetStatusTime(); + _status = calendarInvite.GetStatus(); + _rank = calendarInvite.GetRank(); + _text = calendarInvite.GetText(); + } - CalendarInvite() : _inviteId(1), _eventId(0), _invitee(0), _senderGUID(0), _statusTime(time(nullptr)), - _status(CALENDAR_STATUS_INVITED), _rank(CALENDAR_RANK_PLAYER), _text("") { } + CalendarInvite() : _inviteId(1), _eventId(0), _invitee(0), _senderGUID(0), _statusTime(time(nullptr)), + _status(CALENDAR_STATUS_INVITED), _rank(CALENDAR_RANK_PLAYER), _text("") { } - CalendarInvite(uint64 inviteId, uint64 eventId, uint64 invitee, uint64 senderGUID, time_t statusTime, - CalendarInviteStatus status, CalendarModerationRank rank, std::string text) : - _inviteId(inviteId), _eventId(eventId), _invitee(invitee), _senderGUID(senderGUID), _statusTime(statusTime), - _status(status), _rank(rank), _text(text) { } + CalendarInvite(uint64 inviteId, uint64 eventId, uint64 invitee, uint64 senderGUID, time_t statusTime, + CalendarInviteStatus status, CalendarModerationRank rank, std::string text) : + _inviteId(inviteId), _eventId(eventId), _invitee(invitee), _senderGUID(senderGUID), _statusTime(statusTime), + _status(status), _rank(rank), _text(text) { } - ~CalendarInvite(); + ~CalendarInvite(); - void SetInviteId(uint64 inviteId) { _inviteId = inviteId; } - uint64 GetInviteId() const { return _inviteId; } + void SetInviteId(uint64 inviteId) { _inviteId = inviteId; } + uint64 GetInviteId() const { return _inviteId; } - void SetEventId(uint64 eventId) { _eventId = eventId; } - uint64 GetEventId() const { return _eventId; } + void SetEventId(uint64 eventId) { _eventId = eventId; } + uint64 GetEventId() const { return _eventId; } - void SetSenderGUID(uint64 guid) { _senderGUID = guid; } - uint64 GetSenderGUID() const { return _senderGUID; } + void SetSenderGUID(uint64 guid) { _senderGUID = guid; } + uint64 GetSenderGUID() const { return _senderGUID; } - void SetInvitee(uint64 guid) { _invitee = guid; } - uint64 GetInviteeGUID() const { return _invitee; } + void SetInvitee(uint64 guid) { _invitee = guid; } + uint64 GetInviteeGUID() const { return _invitee; } - void SetStatusTime(time_t statusTime) { _statusTime = statusTime; } - time_t GetStatusTime() const { return _statusTime; } + void SetStatusTime(time_t statusTime) { _statusTime = statusTime; } + time_t GetStatusTime() const { return _statusTime; } - void SetText(const std::string& text) { _text = text; } - std::string GetText() const { return _text; } + void SetText(const std::string& text) { _text = text; } + std::string GetText() const { return _text; } - void SetStatus(CalendarInviteStatus status) { _status = status; } - CalendarInviteStatus GetStatus() const { return _status; } + void SetStatus(CalendarInviteStatus status) { _status = status; } + CalendarInviteStatus GetStatus() const { return _status; } - void SetRank(CalendarModerationRank rank) { _rank = rank; } - CalendarModerationRank GetRank() const { return _rank; } + void SetRank(CalendarModerationRank rank) { _rank = rank; } + CalendarModerationRank GetRank() const { return _rank; } - private: - uint64 _inviteId; - uint64 _eventId; - uint64 _invitee; - uint64 _senderGUID; - time_t _statusTime; - CalendarInviteStatus _status; - CalendarModerationRank _rank; - std::string _text; +private: + uint64 _inviteId; + uint64 _eventId; + uint64 _invitee; + uint64 _senderGUID; + time_t _statusTime; + CalendarInviteStatus _status; + CalendarModerationRank _rank; + std::string _text; }; struct CalendarEvent { - public: - CalendarEvent(CalendarEvent const& calendarEvent, uint64 eventId) - { - _eventId = eventId; - _creatorGUID = calendarEvent.GetCreatorGUID(); - _guildId = calendarEvent.GetGuildId(); - _type = calendarEvent.GetType(); - _dungeonId = calendarEvent.GetDungeonId(); - _eventTime = calendarEvent.GetEventTime(); - _flags = calendarEvent.GetFlags(); - _timezoneTime = calendarEvent.GetTimeZoneTime(); - _title = calendarEvent.GetTitle(); - _description = calendarEvent.GetDescription(); - } +public: + CalendarEvent(CalendarEvent const& calendarEvent, uint64 eventId) + { + _eventId = eventId; + _creatorGUID = calendarEvent.GetCreatorGUID(); + _guildId = calendarEvent.GetGuildId(); + _type = calendarEvent.GetType(); + _dungeonId = calendarEvent.GetDungeonId(); + _eventTime = calendarEvent.GetEventTime(); + _flags = calendarEvent.GetFlags(); + _timezoneTime = calendarEvent.GetTimeZoneTime(); + _title = calendarEvent.GetTitle(); + _description = calendarEvent.GetDescription(); + } - CalendarEvent(uint64 eventId, uint64 creatorGUID, uint32 guildId, CalendarEventType type, int32 dungeonId, - time_t eventTime, uint32 flags, time_t timezoneTime, std::string title, std::string description) : - _eventId(eventId), _creatorGUID(creatorGUID), _guildId(guildId), _type(type), _dungeonId(dungeonId), - _eventTime(eventTime), _flags(flags), _timezoneTime(timezoneTime), _title(title), - _description(description) { } + CalendarEvent(uint64 eventId, uint64 creatorGUID, uint32 guildId, CalendarEventType type, int32 dungeonId, + time_t eventTime, uint32 flags, time_t timezoneTime, std::string title, std::string description) : + _eventId(eventId), _creatorGUID(creatorGUID), _guildId(guildId), _type(type), _dungeonId(dungeonId), + _eventTime(eventTime), _flags(flags), _timezoneTime(timezoneTime), _title(title), + _description(description) { } - CalendarEvent() : _eventId(1), _creatorGUID(0), _guildId(0), _type(CALENDAR_TYPE_OTHER), _dungeonId(-1), _eventTime(0), - _flags(0), _timezoneTime(0), _title(""), _description("") { } + CalendarEvent() : _eventId(1), _creatorGUID(0), _guildId(0), _type(CALENDAR_TYPE_OTHER), _dungeonId(-1), _eventTime(0), + _flags(0), _timezoneTime(0), _title(""), _description("") { } - ~CalendarEvent(); + ~CalendarEvent(); - void SetEventId(uint64 eventId) { _eventId = eventId; } - uint64 GetEventId() const { return _eventId; } + void SetEventId(uint64 eventId) { _eventId = eventId; } + uint64 GetEventId() const { return _eventId; } - void SetCreatorGUID(uint64 guid) { _creatorGUID = guid; } - uint64 GetCreatorGUID() const { return _creatorGUID; } + void SetCreatorGUID(uint64 guid) { _creatorGUID = guid; } + uint64 GetCreatorGUID() const { return _creatorGUID; } - void SetGuildId(uint32 guildId) { _guildId = guildId; } - uint32 GetGuildId() const { return _guildId; } + void SetGuildId(uint32 guildId) { _guildId = guildId; } + uint32 GetGuildId() const { return _guildId; } - void SetTitle(const std::string& title) { _title = title; } - std::string GetTitle() const { return _title; } + void SetTitle(const std::string& title) { _title = title; } + std::string GetTitle() const { return _title; } - void SetDescription(const std::string& description) { _description = description; } - std::string GetDescription() const { return _description; } + void SetDescription(const std::string& description) { _description = description; } + std::string GetDescription() const { return _description; } - void SetType(CalendarEventType type) { _type = type; } - CalendarEventType GetType() const { return _type; } + void SetType(CalendarEventType type) { _type = type; } + CalendarEventType GetType() const { return _type; } - void SetDungeonId(int32 dungeonId) { _dungeonId = dungeonId; } - int32 GetDungeonId() const { return _dungeonId; } + void SetDungeonId(int32 dungeonId) { _dungeonId = dungeonId; } + int32 GetDungeonId() const { return _dungeonId; } - void SetEventTime(time_t eventTime) { _eventTime = eventTime; } - time_t GetEventTime() const { return _eventTime; } + void SetEventTime(time_t eventTime) { _eventTime = eventTime; } + time_t GetEventTime() const { return _eventTime; } - void SetFlags(uint32 flags) { _flags = flags; } - uint32 GetFlags() const { return _flags; } + void SetFlags(uint32 flags) { _flags = flags; } + uint32 GetFlags() const { return _flags; } - void SetTimeZoneTime(time_t timezoneTime) { _timezoneTime = timezoneTime; } - time_t GetTimeZoneTime() const { return _timezoneTime; } + void SetTimeZoneTime(time_t timezoneTime) { _timezoneTime = timezoneTime; } + time_t GetTimeZoneTime() const { return _timezoneTime; } - bool IsGuildEvent() const { return _flags & CALENDAR_FLAG_GUILD_EVENT; } - bool IsGuildAnnouncement() const { return _flags & CALENDAR_FLAG_WITHOUT_INVITES; } + bool IsGuildEvent() const { return _flags & CALENDAR_FLAG_GUILD_EVENT; } + bool IsGuildAnnouncement() const { return _flags & CALENDAR_FLAG_WITHOUT_INVITES; } - static bool IsGuildEvent(uint32 flags) { return (flags & CALENDAR_FLAG_GUILD_EVENT) != 0; } - static bool IsGuildAnnouncement(uint32 flags) { return (flags & CALENDAR_FLAG_WITHOUT_INVITES) != 0; } + static bool IsGuildEvent(uint32 flags) { return (flags & CALENDAR_FLAG_GUILD_EVENT) != 0; } + static bool IsGuildAnnouncement(uint32 flags) { return (flags & CALENDAR_FLAG_WITHOUT_INVITES) != 0; } - std::string BuildCalendarMailSubject(uint64 remover) const; - std::string BuildCalendarMailBody() const; + std::string BuildCalendarMailSubject(uint64 remover) const; + std::string BuildCalendarMailBody() const; - private: - uint64 _eventId; - uint64 _creatorGUID; - uint32 _guildId; - CalendarEventType _type; - int32 _dungeonId; - time_t _eventTime; - uint32 _flags; - time_t _timezoneTime; - std::string _title; - std::string _description; +private: + uint64 _eventId; + uint64 _creatorGUID; + uint32 _guildId; + CalendarEventType _type; + int32 _dungeonId; + time_t _eventTime; + uint32 _flags; + time_t _timezoneTime; + std::string _title; + std::string _description; }; typedef std::vector CalendarInviteStore; typedef std::unordered_set CalendarEventStore; @@ -264,70 +264,70 @@ typedef std::unordered_map CalendarE class CalendarMgr { - private: - CalendarMgr(); - ~CalendarMgr(); +private: + CalendarMgr(); + ~CalendarMgr(); - CalendarEventStore _events; - CalendarEventInviteStore _invites; + CalendarEventStore _events; + CalendarEventInviteStore _invites; - std::deque _freeEventIds; - std::deque _freeInviteIds; - uint64 _maxEventId; - uint64 _maxInviteId; + std::deque _freeEventIds; + std::deque _freeInviteIds; + uint64 _maxEventId; + uint64 _maxInviteId; - public: - static CalendarMgr* instance(); - - void LoadFromDB(); +public: + static CalendarMgr* instance(); - CalendarEvent* GetEvent(uint64 eventId); - CalendarEventStore const& GetEvents() const { return _events; } - CalendarEventStore GetEventsCreatedBy(uint64 guid, bool includeGuildEvents = false); - CalendarEventStore GetPlayerEvents(uint64 guid); - CalendarEventStore GetGuildEvents(uint32 guildId); + void LoadFromDB(); - CalendarInvite* GetInvite(uint64 inviteId) const; - CalendarEventInviteStore const& GetInvites() const { return _invites; } - CalendarInviteStore const& GetEventInvites(uint64 eventId); - CalendarInviteStore GetPlayerInvites(uint64 guid); + CalendarEvent* GetEvent(uint64 eventId); + CalendarEventStore const& GetEvents() const { return _events; } + CalendarEventStore GetEventsCreatedBy(uint64 guid, bool includeGuildEvents = false); + CalendarEventStore GetPlayerEvents(uint64 guid); + CalendarEventStore GetGuildEvents(uint32 guildId); - void FreeEventId(uint64 id); - uint64 GetFreeEventId(); - void FreeInviteId(uint64 id); - uint64 GetFreeInviteId(); + CalendarInvite* GetInvite(uint64 inviteId) const; + CalendarEventInviteStore const& GetInvites() const { return _invites; } + CalendarInviteStore const& GetEventInvites(uint64 eventId); + CalendarInviteStore GetPlayerInvites(uint64 guid); - void DeleteOldEvents(); + void FreeEventId(uint64 id); + uint64 GetFreeEventId(); + void FreeInviteId(uint64 id); + uint64 GetFreeInviteId(); - uint32 GetPlayerNumPending(uint64 guid); + void DeleteOldEvents(); - void AddEvent(CalendarEvent* calendarEvent, CalendarSendEventType sendType); - void RemoveEvent(uint64 eventId, uint64 remover); - void RemoveEvent(CalendarEvent* calendarEvent, uint64 remover); - void UpdateEvent(CalendarEvent* calendarEvent); + uint32 GetPlayerNumPending(uint64 guid); - void AddInvite(CalendarEvent* calendarEvent, CalendarInvite* invite); - void AddInvite(CalendarEvent* calendarEvent, CalendarInvite* invite, SQLTransaction& trans); - void RemoveInvite(uint64 inviteId, uint64 eventId, uint64 remover); - void UpdateInvite(CalendarInvite* invite); - void UpdateInvite(CalendarInvite* invite, SQLTransaction& trans); + void AddEvent(CalendarEvent* calendarEvent, CalendarSendEventType sendType); + void RemoveEvent(uint64 eventId, uint64 remover); + void RemoveEvent(CalendarEvent* calendarEvent, uint64 remover); + void UpdateEvent(CalendarEvent* calendarEvent); - void RemoveAllPlayerEventsAndInvites(uint64 guid); - void RemovePlayerGuildEventsAndSignups(uint64 guid, uint32 guildId); + void AddInvite(CalendarEvent* calendarEvent, CalendarInvite* invite); + void AddInvite(CalendarEvent* calendarEvent, CalendarInvite* invite, SQLTransaction& trans); + void RemoveInvite(uint64 inviteId, uint64 eventId, uint64 remover); + void UpdateInvite(CalendarInvite* invite); + void UpdateInvite(CalendarInvite* invite, SQLTransaction& trans); - void SendCalendarEvent(uint64 guid, CalendarEvent const& calendarEvent, CalendarSendEventType sendType); - void SendCalendarEventInvite(CalendarInvite const& invite); - void SendCalendarEventInviteAlert(CalendarEvent const& calendarEvent, CalendarInvite const& invite); - void SendCalendarEventInviteRemove(CalendarEvent const& calendarEvent, CalendarInvite const& invite, uint32 flags); - void SendCalendarEventInviteRemoveAlert(uint64 guid, CalendarEvent const& calendarEvent, CalendarInviteStatus status); - void SendCalendarEventUpdateAlert(CalendarEvent const& calendarEvent, time_t oldEventTime); - void SendCalendarEventStatus(CalendarEvent const& calendarEvent, CalendarInvite const& invite); - void SendCalendarEventRemovedAlert(CalendarEvent const& calendarEvent); - void SendCalendarEventModeratorStatusAlert(CalendarEvent const& calendarEvent, CalendarInvite const& invite); - void SendCalendarClearPendingAction(uint64 guid); - void SendCalendarCommandResult(uint64 guid, CalendarError err, char const* param = nullptr); + void RemoveAllPlayerEventsAndInvites(uint64 guid); + void RemovePlayerGuildEventsAndSignups(uint64 guid, uint32 guildId); - void SendPacketToAllEventRelatives(WorldPacket packet, CalendarEvent const& calendarEvent); + void SendCalendarEvent(uint64 guid, CalendarEvent const& calendarEvent, CalendarSendEventType sendType); + void SendCalendarEventInvite(CalendarInvite const& invite); + void SendCalendarEventInviteAlert(CalendarEvent const& calendarEvent, CalendarInvite const& invite); + void SendCalendarEventInviteRemove(CalendarEvent const& calendarEvent, CalendarInvite const& invite, uint32 flags); + void SendCalendarEventInviteRemoveAlert(uint64 guid, CalendarEvent const& calendarEvent, CalendarInviteStatus status); + void SendCalendarEventUpdateAlert(CalendarEvent const& calendarEvent, time_t oldEventTime); + void SendCalendarEventStatus(CalendarEvent const& calendarEvent, CalendarInvite const& invite); + void SendCalendarEventRemovedAlert(CalendarEvent const& calendarEvent); + void SendCalendarEventModeratorStatusAlert(CalendarEvent const& calendarEvent, CalendarInvite const& invite); + void SendCalendarClearPendingAction(uint64 guid); + void SendCalendarCommandResult(uint64 guid, CalendarError err, char const* param = nullptr); + + void SendPacketToAllEventRelatives(WorldPacket packet, CalendarEvent const& calendarEvent); }; #define sCalendarMgr CalendarMgr::instance() diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index 3ebec9193..07c854f5d 100644 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -139,7 +139,7 @@ void Channel::CleanOldChannelsInDB() stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_OLD_CHANNELS_BANS); trans->Append(stmt); - + CharacterDatabase.CommitTransaction(trans); } } @@ -176,9 +176,9 @@ void Channel::JoinChannel(Player* player, std::string const& pass) } if (HasFlag(CHANNEL_FLAG_LFG) && - sWorld->getBoolConfig(CONFIG_RESTRICTED_LFG_CHANNEL) && - AccountMgr::IsPlayerAccount(player->GetSession()->GetSecurity()) && - player->GetGroup()) + sWorld->getBoolConfig(CONFIG_RESTRICTED_LFG_CHANNEL) && + AccountMgr::IsPlayerAccount(player->GetSession()->GetSecurity()) && + player->GetGroup()) { WorldPacket data; MakeNotInLfg(&data); @@ -189,7 +189,7 @@ void Channel::JoinChannel(Player* player, std::string const& pass) player->JoinedChannel(this); if (_announce && (!AccountMgr::IsGMAccount(player->GetSession()->GetSecurity()) || - !sWorld->getBoolConfig(CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL))) + !sWorld->getBoolConfig(CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL))) { WorldPacket data; MakeJoined(&data, guid); @@ -268,7 +268,7 @@ void Channel::LeaveChannel(Player* player, bool send) playersStore.erase(guid); if (_announce && (!AccountMgr::IsGMAccount(player->GetSession()->GetSecurity()) || - !sWorld->getBoolConfig(CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL))) + !sWorld->getBoolConfig(CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL))) { WorldPacket data; MakeLeft(&data, guid); @@ -593,10 +593,10 @@ void Channel::SetMode(Player const* player, std::string const& p2n, bool mod, bo uint64 victim = newp ? newp->GetGUID() : 0; if (!victim || !IsOn(victim) || - // allow make moderator from another team only if both is GMs - // at this moment this only way to show channel post for GM from another team - ((!AccountMgr::IsGMAccount(sec) || !AccountMgr::IsGMAccount(newp->GetSession()->GetSecurity())) && player->GetTeamId() != newp->GetTeamId() && - !sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL))) + // allow make moderator from another team only if both is GMs + // at this moment this only way to show channel post for GM from another team + ((!AccountMgr::IsGMAccount(sec) || !AccountMgr::IsGMAccount(newp->GetSession()->GetSecurity())) && player->GetTeamId() != newp->GetTeamId() && + !sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL))) { WorldPacket data; MakePlayerNotFound(&data, p2n); @@ -662,7 +662,7 @@ void Channel::SetOwner(Player const* player, std::string const& newname) uint64 victim = newp ? newp->GetGUID() : 0; if (!victim || !IsOn(victim) || (newp->GetTeamId() != player->GetTeamId() && - !sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL))) + !sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL))) { WorldPacket data; MakePlayerNotFound(&data, newname); @@ -698,7 +698,7 @@ void Channel::List(Player const* player) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "SMSG_CHANNEL_LIST %s Channel: %s", player->GetSession()->GetPlayerInfo().c_str(), GetName().c_str()); #endif - WorldPacket data(SMSG_CHANNEL_LIST, 1+(GetName().size()+1)+1+4+playersStore.size()*(8+1)); + WorldPacket data(SMSG_CHANNEL_LIST, 1 + (GetName().size() + 1) + 1 + 4 + playersStore.size() * (8 + 1)); data << uint8(1); // channel type? data << GetName(); // channel name data << uint8(GetFlags()); // channel flags? @@ -742,7 +742,7 @@ void Channel::Announce(Player const* player) return; } - if (_channelRights.flags & (CHANNEL_RIGHT_FORCE_NO_ANNOUNCEMENTS|CHANNEL_RIGHT_FORCE_ANNOUNCEMENTS)) + if (_channelRights.flags & (CHANNEL_RIGHT_FORCE_NO_ANNOUNCEMENTS | CHANNEL_RIGHT_FORCE_ANNOUNCEMENTS)) { WorldPacket data; MakeNotModerator(&data); @@ -817,14 +817,14 @@ void Channel::Say(uint64 guid, std::string const& what, uint32 lang) SendToAll(&data, pinfo.IsModerator() ? 0 : guid); } -void Channel::EveryoneSayToSelf(const char *what) +void Channel::EveryoneSayToSelf(const char* what) { if (!what) return; uint32 messageLength = strlen(what) + 1; - WorldPacket data(SMSG_MESSAGECHAT, 1+4+8+4+_name.size()+1+8+4+messageLength+1); + WorldPacket data(SMSG_MESSAGECHAT, 1 + 4 + 8 + 4 + _name.size() + 1 + 8 + 4 + messageLength + 1); data << (uint8)CHAT_MSG_CHANNEL; data << (uint32)LANG_UNIVERSAL; data << uint64(0); // put player guid here @@ -838,7 +838,7 @@ void Channel::EveryoneSayToSelf(const char *what) for (PlayerContainer::const_iterator i = playersStore.begin(); i != playersStore.end(); ++i) { data.put(5, i->first); - data.put(17+_name.size()+1, i->first); + data.put(17 + _name.size() + 1, i->first); i->second.plrPtr->GetSession()->SendPacket(&data); } } @@ -1120,7 +1120,7 @@ void Channel::MakePlayerUnbanned(WorldPacket* data, uint64 bad, uint64 good) *data << uint64(good); } -void Channel::MakePlayerNotBanned(WorldPacket* data, const std::string &name) +void Channel::MakePlayerNotBanned(WorldPacket* data, const std::string& name) { MakeNotifyPacket(data, CHAT_PLAYER_NOT_BANNED_NOTICE); *data << name; diff --git a/src/server/game/Chat/Channels/Channel.h b/src/server/game/Chat/Channels/Channel.h index e2eaa4c73..9312d9534 100644 --- a/src/server/game/Chat/Channels/Channel.h +++ b/src/server/game/Chat/Channels/Channel.h @@ -73,11 +73,11 @@ enum ChannelFlags CHANNEL_FLAG_CITY = 0x20, CHANNEL_FLAG_LFG = 0x40, CHANNEL_FLAG_VOICE = 0x80 - // General 0x18 = 0x10 | 0x08 - // Trade 0x3C = 0x20 | 0x10 | 0x08 | 0x04 - // LocalDefence 0x18 = 0x10 | 0x08 - // GuildRecruitment 0x38 = 0x20 | 0x10 | 0x08 - // LookingForGroup 0x50 = 0x40 | 0x10 + // General 0x18 = 0x10 | 0x08 + // Trade 0x3C = 0x20 | 0x10 | 0x08 | 0x04 + // LocalDefence 0x18 = 0x10 | 0x08 + // GuildRecruitment 0x38 = 0x20 | 0x10 | 0x08 + // LookingForGroup 0x50 = 0x40 | 0x10 }; enum ChannelDBCFlags @@ -104,8 +104,8 @@ enum ChannelMemberFlags MEMBER_FLAG_MUTED = 0x08, MEMBER_FLAG_CUSTOM = 0x10, MEMBER_FLAG_MIC_MUTED = 0x20 - // 0x40 - // 0x80 + // 0x40 + // 0x80 }; class ChannelRights @@ -166,7 +166,7 @@ class Channel } bool IsAllowedToSpeak(uint32 speakDelay) // pussywizard { - if (lastSpeakTime+speakDelay <= sWorld->GetGameTime()) + if (lastSpeakTime + speakDelay <= sWorld->GetGameTime()) { lastSpeakTime = sWorld->GetGameTime(); return true; @@ -178,159 +178,159 @@ class Channel bool _gmStatus = false; }; - public: - Channel(std::string const& name, uint32 channel_id, uint32 channelDBId, TeamId teamId = TEAM_NEUTRAL, bool announce = true, bool ownership = true); - std::string const& GetName() const { return _name; } - uint32 GetChannelId() const { return _channelId; } - bool IsConstant() const { return _channelId != 0; } - bool IsAnnounce() const { return _announce; } - bool IsLFG() const { return GetFlags() & CHANNEL_FLAG_LFG; } - std::string const& GetPassword() const { return _password; } - void SetPassword(std::string const& npassword) { _password = npassword; } - uint32 GetNumPlayers() const { return playersStore.size(); } - uint8 GetFlags() const { return _flags; } - bool HasFlag(uint8 flag) const { return _flags & flag; } +public: + Channel(std::string const& name, uint32 channel_id, uint32 channelDBId, TeamId teamId = TEAM_NEUTRAL, bool announce = true, bool ownership = true); + std::string const& GetName() const { return _name; } + uint32 GetChannelId() const { return _channelId; } + bool IsConstant() const { return _channelId != 0; } + bool IsAnnounce() const { return _announce; } + bool IsLFG() const { return GetFlags() & CHANNEL_FLAG_LFG; } + std::string const& GetPassword() const { return _password; } + void SetPassword(std::string const& npassword) { _password = npassword; } + uint32 GetNumPlayers() const { return playersStore.size(); } + uint8 GetFlags() const { return _flags; } + bool HasFlag(uint8 flag) const { return _flags & flag; } - void JoinChannel(Player* player, std::string const& pass); - void LeaveChannel(Player* player, bool send = true); - void KickOrBan(Player const* player, std::string const& badname, bool ban); - void Kick(Player const* player, std::string const& badname) { KickOrBan(player, badname, false); } - void Ban(Player const* player, std::string const& badname) { KickOrBan(player, badname, true); } - void AddBan(uint32 guid, uint32 time) { bannedStore[guid] = time; } - void UnBan(Player const* player, std::string const& badname); - void UnBan(uint64 guid); - void Password(Player const* player, std::string const& pass); - void SetMode(Player const* player, std::string const& p2n, bool mod, bool set); - void SetOwner(uint64 guid, bool exclaim = true); - void SetOwner(Player const* player, std::string const& name); - void SendWhoOwner(uint64 guid); - void SetModerator(Player const* player, std::string const& newname) { SetMode(player, newname, true, true); } - void UnsetModerator(Player const* player, std::string const& newname) { SetMode(player, newname, true, false); } - void SetMute(Player const* player, std::string const& newname) { SetMode(player, newname, false, true); } - void UnsetMute(Player const* player, std::string const& newname) { SetMode(player, newname, false, false); } - void List(Player const* player); - void Announce(Player const* player); - void Say(uint64 guid, std::string const& what, uint32 lang); - void EveryoneSayToSelf(const char *what); - void Invite(Player const* player, std::string const& newp); - void Voice(uint64 guid1, uint64 guid2); - void DeVoice(uint64 guid1, uint64 guid2); - void JoinNotify(Player* p); - void LeaveNotify(Player* p); - void FlagsNotify(Player* p); - static void CleanOldChannelsInDB(); + void JoinChannel(Player* player, std::string const& pass); + void LeaveChannel(Player* player, bool send = true); + void KickOrBan(Player const* player, std::string const& badname, bool ban); + void Kick(Player const* player, std::string const& badname) { KickOrBan(player, badname, false); } + void Ban(Player const* player, std::string const& badname) { KickOrBan(player, badname, true); } + void AddBan(uint32 guid, uint32 time) { bannedStore[guid] = time; } + void UnBan(Player const* player, std::string const& badname); + void UnBan(uint64 guid); + void Password(Player const* player, std::string const& pass); + void SetMode(Player const* player, std::string const& p2n, bool mod, bool set); + void SetOwner(uint64 guid, bool exclaim = true); + void SetOwner(Player const* player, std::string const& name); + void SendWhoOwner(uint64 guid); + void SetModerator(Player const* player, std::string const& newname) { SetMode(player, newname, true, true); } + void UnsetModerator(Player const* player, std::string const& newname) { SetMode(player, newname, true, false); } + void SetMute(Player const* player, std::string const& newname) { SetMode(player, newname, false, true); } + void UnsetMute(Player const* player, std::string const& newname) { SetMode(player, newname, false, false); } + void List(Player const* player); + void Announce(Player const* player); + void Say(uint64 guid, std::string const& what, uint32 lang); + void EveryoneSayToSelf(const char* what); + void Invite(Player const* player, std::string const& newp); + void Voice(uint64 guid1, uint64 guid2); + void DeVoice(uint64 guid1, uint64 guid2); + void JoinNotify(Player* p); + void LeaveNotify(Player* p); + void FlagsNotify(Player* p); + static void CleanOldChannelsInDB(); - // pussywizard: - void AddWatching(Player* p); - void RemoveWatching(Player* p); + // pussywizard: + void AddWatching(Player* p); + void RemoveWatching(Player* p); - private: - // initial packet data (notify type and channel name) - void MakeNotifyPacket(WorldPacket* data, uint8 notify_type); - // type specific packet data - void MakeJoined(WorldPacket* data, uint64 guid); //+ 0x00 - void MakeLeft(WorldPacket* data, uint64 guid); //+ 0x01 - void MakeYouJoined(WorldPacket* data); //+ 0x02 - void MakeYouLeft(WorldPacket* data); //+ 0x03 - void MakeWrongPassword(WorldPacket* data); //? 0x04 - void MakeNotMember(WorldPacket* data); //? 0x05 - void MakeNotModerator(WorldPacket* data); //? 0x06 - void MakePasswordChanged(WorldPacket* data, uint64 guid); //+ 0x07 - void MakeOwnerChanged(WorldPacket* data, uint64 guid); //? 0x08 - void MakePlayerNotFound(WorldPacket* data, std::string const& name); //+ 0x09 - void MakeNotOwner(WorldPacket* data); //? 0x0A - void MakeChannelOwner(WorldPacket* data); //? 0x0B - void MakeModeChange(WorldPacket* data, uint64 guid, uint8 oldflags); //+ 0x0C - void MakeAnnouncementsOn(WorldPacket* data, uint64 guid); //+ 0x0D - void MakeAnnouncementsOff(WorldPacket* data, uint64 guid); //+ 0x0E - void MakeMuted(WorldPacket* data); //? 0x11 - void MakePlayerKicked(WorldPacket* data, uint64 bad, uint64 good); //? 0x12 - void MakeBanned(WorldPacket* data); //? 0x13 - void MakePlayerBanned(WorldPacket* data, uint64 bad, uint64 good); //? 0x14 - void MakePlayerUnbanned(WorldPacket* data, uint64 bad, uint64 good); //? 0x15 - void MakePlayerNotBanned(WorldPacket* data, std::string const& name); //? 0x16 - void MakePlayerAlreadyMember(WorldPacket* data, uint64 guid); //+ 0x17 - void MakeInvite(WorldPacket* data, uint64 guid); //? 0x18 - void MakeInviteWrongFaction(WorldPacket* data); //? 0x19 - void MakeWrongFaction(WorldPacket* data); //? 0x1A - void MakeInvalidName(WorldPacket* data); //? 0x1B - void MakeNotModerated(WorldPacket* data); //? 0x1C - void MakePlayerInvited(WorldPacket* data, std::string const& name); //+ 0x1D - void MakePlayerInviteBanned(WorldPacket* data, std::string const& name);//? 0x1E - void MakeThrottled(WorldPacket* data); //? 0x1F - void MakeNotInArea(WorldPacket* data); //? 0x20 - void MakeNotInLfg(WorldPacket* data); //? 0x21 - void MakeVoiceOn(WorldPacket* data, uint64 guid); //+ 0x22 - void MakeVoiceOff(WorldPacket* data, uint64 guid); //+ 0x23 +private: + // initial packet data (notify type and channel name) + void MakeNotifyPacket(WorldPacket* data, uint8 notify_type); + // type specific packet data + void MakeJoined(WorldPacket* data, uint64 guid); //+ 0x00 + void MakeLeft(WorldPacket* data, uint64 guid); //+ 0x01 + void MakeYouJoined(WorldPacket* data); //+ 0x02 + void MakeYouLeft(WorldPacket* data); //+ 0x03 + void MakeWrongPassword(WorldPacket* data); //? 0x04 + void MakeNotMember(WorldPacket* data); //? 0x05 + void MakeNotModerator(WorldPacket* data); //? 0x06 + void MakePasswordChanged(WorldPacket* data, uint64 guid); //+ 0x07 + void MakeOwnerChanged(WorldPacket* data, uint64 guid); //? 0x08 + void MakePlayerNotFound(WorldPacket* data, std::string const& name); //+ 0x09 + void MakeNotOwner(WorldPacket* data); //? 0x0A + void MakeChannelOwner(WorldPacket* data); //? 0x0B + void MakeModeChange(WorldPacket* data, uint64 guid, uint8 oldflags); //+ 0x0C + void MakeAnnouncementsOn(WorldPacket* data, uint64 guid); //+ 0x0D + void MakeAnnouncementsOff(WorldPacket* data, uint64 guid); //+ 0x0E + void MakeMuted(WorldPacket* data); //? 0x11 + void MakePlayerKicked(WorldPacket* data, uint64 bad, uint64 good); //? 0x12 + void MakeBanned(WorldPacket* data); //? 0x13 + void MakePlayerBanned(WorldPacket* data, uint64 bad, uint64 good); //? 0x14 + void MakePlayerUnbanned(WorldPacket* data, uint64 bad, uint64 good); //? 0x15 + void MakePlayerNotBanned(WorldPacket* data, std::string const& name); //? 0x16 + void MakePlayerAlreadyMember(WorldPacket* data, uint64 guid); //+ 0x17 + void MakeInvite(WorldPacket* data, uint64 guid); //? 0x18 + void MakeInviteWrongFaction(WorldPacket* data); //? 0x19 + void MakeWrongFaction(WorldPacket* data); //? 0x1A + void MakeInvalidName(WorldPacket* data); //? 0x1B + void MakeNotModerated(WorldPacket* data); //? 0x1C + void MakePlayerInvited(WorldPacket* data, std::string const& name); //+ 0x1D + void MakePlayerInviteBanned(WorldPacket* data, std::string const& name);//? 0x1E + void MakeThrottled(WorldPacket* data); //? 0x1F + void MakeNotInArea(WorldPacket* data); //? 0x20 + void MakeNotInLfg(WorldPacket* data); //? 0x21 + void MakeVoiceOn(WorldPacket* data, uint64 guid); //+ 0x22 + void MakeVoiceOff(WorldPacket* data, uint64 guid); //+ 0x23 - void SendToAll(WorldPacket* data, uint64 guid = 0); - void SendToAllButOne(WorldPacket* data, uint64 who); - void SendToOne(WorldPacket* data, uint64 who); - void SendToAllWatching(WorldPacket* data); + void SendToAll(WorldPacket* data, uint64 guid = 0); + void SendToAllButOne(WorldPacket* data, uint64 who); + void SendToOne(WorldPacket* data, uint64 who); + void SendToAllWatching(WorldPacket* data); - bool IsOn(uint64 who) const { return playersStore.find(who) != playersStore.end(); } - bool IsBanned(uint64 guid) const; + bool IsOn(uint64 who) const { return playersStore.find(who) != playersStore.end(); } + bool IsBanned(uint64 guid) const; - void UpdateChannelInDB() const; - void UpdateChannelUseageInDB() const; - void AddChannelBanToDB(uint32 guid, uint32 time) const; - void RemoveChannelBanFromDB(uint32 guid) const; + void UpdateChannelInDB() const; + void UpdateChannelUseageInDB() const; + void AddChannelBanToDB(uint32 guid, uint32 time) const; + void RemoveChannelBanFromDB(uint32 guid) const; - uint8 GetPlayerFlags(uint64 guid) const + uint8 GetPlayerFlags(uint64 guid) const + { + PlayerContainer::const_iterator itr = playersStore.find(guid); + return itr != playersStore.end() ? itr->second.flags : 0; + } + + void SetModerator(uint64 guid, bool set) + { + PlayerInfo& pinfo = playersStore[guid]; + if (pinfo.IsModerator() != set) { - PlayerContainer::const_iterator itr = playersStore.find(guid); - return itr != playersStore.end() ? itr->second.flags : 0; - } + uint8 oldFlag = pinfo.flags; + pinfo.SetModerator(set); - void SetModerator(uint64 guid, bool set) + WorldPacket data; + MakeModeChange(&data, guid, oldFlag); + SendToAll(&data); + + FlagsNotify(pinfo.plrPtr); + } + } + + void SetMute(uint64 guid, bool set) + { + PlayerInfo& pinfo = playersStore[guid]; + if (pinfo.IsMuted() != set) { - PlayerInfo& pinfo = playersStore[guid]; - if (pinfo.IsModerator() != set) - { - uint8 oldFlag = pinfo.flags; - pinfo.SetModerator(set); + uint8 oldFlag = pinfo.flags; + pinfo.SetMuted(set); - WorldPacket data; - MakeModeChange(&data, guid, oldFlag); - SendToAll(&data); - - FlagsNotify(pinfo.plrPtr); - } + WorldPacket data; + MakeModeChange(&data, guid, oldFlag); + SendToAll(&data); } + } - void SetMute(uint64 guid, bool set) - { - PlayerInfo& pinfo = playersStore[guid]; - if (pinfo.IsMuted() != set) - { - uint8 oldFlag = pinfo.flags; - pinfo.SetMuted(set); + typedef std::unordered_map PlayerContainer; + typedef std::unordered_map BannedContainer; + typedef std::unordered_set PlayersWatchingContainer; - WorldPacket data; - MakeModeChange(&data, guid, oldFlag); - SendToAll(&data); - } - } - - typedef std::unordered_map PlayerContainer; - typedef std::unordered_map BannedContainer; - typedef std::unordered_set PlayersWatchingContainer; - - bool _announce; - bool _ownership; - bool _IsSaved; - bool _isOwnerGM; - uint8 _flags; - uint32 _channelId; - uint32 _channelDBId; - TeamId _teamId; - uint64 _ownerGUID; - std::string _name; - std::string _password; - ChannelRights _channelRights; - PlayerContainer playersStore; - BannedContainer bannedStore; - PlayersWatchingContainer playersWatchingStore; + bool _announce; + bool _ownership; + bool _IsSaved; + bool _isOwnerGM; + uint8 _flags; + uint32 _channelId; + uint32 _channelDBId; + TeamId _teamId; + uint64 _ownerGUID; + std::string _name; + std::string _password; + ChannelRights _channelRights; + PlayerContainer playersStore; + BannedContainer bannedStore; + PlayersWatchingContainer playersWatchingStore; }; #endif diff --git a/src/server/game/Chat/Channels/ChannelMgr.cpp b/src/server/game/Chat/Channels/ChannelMgr.cpp index 55d596022..4c8c847cf 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.cpp +++ b/src/server/game/Chat/Channels/ChannelMgr.cpp @@ -70,16 +70,14 @@ void ChannelMgr::LoadChannels() Field* banFields = banResult->Fetch(); if (!banFields) break; - newChannel->AddBan(banFields[0].GetUInt32(), banFields[1].GetUInt32()); - } - while (banResult->NextRow()); + newChannel->AddBan(banFields[0].GetUInt32(), banFields[1].GetUInt32()); + } while (banResult->NextRow()); } - if (channelDBId > ChannelMgr::_channelIdMax) + if (channelDBId > ChannelMgr::_channelIdMax) ChannelMgr::_channelIdMax = channelDBId; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u channels for %s in %ums", count, _teamId == TEAM_ALLIANCE ? "Alliance" : "Horde", GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/Chat/Channels/ChannelMgr.h b/src/server/game/Chat/Channels/ChannelMgr.h index bbe9c6b2f..c2e1f5174 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.h +++ b/src/server/game/Chat/Channels/ChannelMgr.h @@ -19,30 +19,30 @@ class ChannelMgr typedef std::unordered_map ChannelMap; typedef std::map ChannelRightsMap; - public: - ChannelMgr(TeamId teamId) : _teamId(teamId) - { } +public: + ChannelMgr(TeamId teamId) : _teamId(teamId) + { } - ~ChannelMgr(); + ~ChannelMgr(); - static ChannelMgr * forTeam(TeamId teamId); + static ChannelMgr* forTeam(TeamId teamId); - Channel* GetJoinChannel(std::string const& name, uint32 channel_id); - Channel* GetChannel(std::string const& name, Player* p, bool pkt = true); - void LoadChannels(); + Channel* GetJoinChannel(std::string const& name, uint32 channel_id); + Channel* GetChannel(std::string const& name, Player* p, bool pkt = true); + void LoadChannels(); - static void LoadChannelRights(); - static const ChannelRights& GetChannelRightsFor(const std::string& name); - static void SetChannelRightsFor(const std::string& name, const uint32& flags, const uint32& speakDelay, const std::string& joinmessage, const std::string& speakmessage, const std::set& moderators); - static uint32 _channelIdMax; + static void LoadChannelRights(); + static const ChannelRights& GetChannelRightsFor(const std::string& name); + static void SetChannelRightsFor(const std::string& name, const uint32& flags, const uint32& speakDelay, const std::string& joinmessage, const std::string& speakmessage, const std::set& moderators); + static uint32 _channelIdMax; - private: - ChannelMap channels; - TeamId _teamId; - static ChannelRightsMap channels_rights; - static ChannelRights channelRightsEmpty; // when not found in the map, reference to this is returned +private: + ChannelMap channels; + TeamId _teamId; + static ChannelRightsMap channels_rights; + static ChannelRights channelRightsEmpty; // when not found in the map, reference to this is returned - void MakeNotOnPacket(WorldPacket* data, std::string const& name); + void MakeNotOnPacket(WorldPacket* data, std::string const& name); }; class AllianceChannelMgr : public ChannelMgr { public: AllianceChannelMgr() : ChannelMgr(TEAM_ALLIANCE) {} }; diff --git a/src/server/game/Chat/Chat.cpp b/src/server/game/Chat/Chat.cpp index 9948351b2..786462e33 100644 --- a/src/server/game/Chat/Chat.cpp +++ b/src/server/game/Chat/Chat.cpp @@ -51,8 +51,7 @@ std::vector const& ChatHandler::getCommandTable() std::string name = fields[0].GetString(); SetDataForCommandInTable(commandTableCache, name.c_str(), fields[1].GetUInt8(), fields[2].GetString(), name); - } - while (result->NextRow()); + } while (result->NextRow()); } } @@ -61,7 +60,7 @@ std::vector const& ChatHandler::getCommandTable() std::string ChatHandler::PGetParseString(uint32 entry, ...) const { - const char *format = GetAcoreString(entry); + const char* format = GetAcoreString(entry); char str[1024]; va_list ap; va_start(ap, entry); @@ -148,7 +147,8 @@ bool ChatHandler::hasStringAbbr(const char* name, const char* part) return false; else if (tolower(*name) != tolower(*part)) return false; - ++name; ++part; + ++name; + ++part; } } // allow with any for "" @@ -156,7 +156,7 @@ bool ChatHandler::hasStringAbbr(const char* name, const char* part) return true; } -void ChatHandler::SendSysMessage(const char *str) +void ChatHandler::SendSysMessage(const char* str) { WorldPacket data; @@ -173,7 +173,7 @@ void ChatHandler::SendSysMessage(const char *str) free(buf); } -void ChatHandler::SendGlobalSysMessage(const char *str) +void ChatHandler::SendGlobalSysMessage(const char* str) { // Chat output WorldPacket data; @@ -191,7 +191,7 @@ void ChatHandler::SendGlobalSysMessage(const char *str) free(buf); } -void ChatHandler::SendGlobalGMSysMessage(const char *str) +void ChatHandler::SendGlobalGMSysMessage(const char* str) { // Chat output WorldPacket data; @@ -216,7 +216,7 @@ void ChatHandler::SendSysMessage(uint32 entry) void ChatHandler::PSendSysMessage(uint32 entry, ...) { - const char *format = GetAcoreString(entry); + const char* format = GetAcoreString(entry); va_list ap; char str [2048]; va_start(ap, entry); @@ -225,7 +225,7 @@ void ChatHandler::PSendSysMessage(uint32 entry, ...) SendSysMessage(str); } -void ChatHandler::PSendSysMessage(const char *format, ...) +void ChatHandler::PSendSysMessage(const char* format, ...) { va_list ap; char str [2048]; @@ -318,13 +318,13 @@ bool ChatHandler::ExecuteCommandInTable(std::vector const& table, c } sLog->outCommand(m_session->GetAccountId(), "Command: %s [Player: %s (%ul) (Account: %u) X: %f Y: %f Z: %f Map: %u (%s) Area: %u (%s) Zone: %s Selected: %s (%ul)]", - fullcmd.c_str(), player->GetName().c_str(), GUID_LOPART(player->GetGUID()), - m_session->GetAccountId(), player->GetPositionX(), player->GetPositionY(), - player->GetPositionZ(), player->GetMapId(), - player->GetMap()->GetMapName(), - areaId, areaName.c_str(), zoneName.c_str(), - (player->GetSelectedUnit()) ? player->GetSelectedUnit()->GetName().c_str() : "", - GUID_LOPART(guid)); + fullcmd.c_str(), player->GetName().c_str(), GUID_LOPART(player->GetGUID()), + m_session->GetAccountId(), player->GetPositionX(), player->GetPositionY(), + player->GetPositionZ(), player->GetMapId(), + player->GetMap()->GetMapName(), + areaId, areaName.c_str(), zoneName.c_str(), + (player->GetSelectedUnit()) ? player->GetSelectedUnit()->GetName().c_str() : "", + GUID_LOPART(guid)); } } // some commands have custom error messages. Don't send the default one in these cases. @@ -405,7 +405,7 @@ bool ChatHandler::ParseCommands(char const* text) std::string fullcmd = text; if (m_session && AccountMgr::IsPlayerAccount(m_session->GetSecurity()) && !sWorld->getBoolConfig(CONFIG_ALLOW_PLAYER_COMMANDS)) - return false; + return false; /// chat case (.command or !command format) if (m_session) @@ -443,19 +443,19 @@ bool ChatHandler::ParseCommands(char const* text) bool ChatHandler::isValidChatMessage(char const* message) { -/* -Valid examples: -|cffa335ee|Hitem:812:0:0:0:0:0:0:0:70|h[Glowing Brightwood Staff]|h|r -|cff808080|Hquest:2278:47|h[The Platinum Discs]|h|r -|cffffd000|Htrade:4037:1:150:1:6AAAAAAAAAAAAAAAAAAAAAAOAADAAAAAAAAAAAAAAAAIAAAAAAAAA|h[Engineering]|h|r -|cff4e96f7|Htalent:2232:-1|h[Taste for Blood]|h|r -|cff71d5ff|Hspell:21563|h[Command]|h|r -|cffffd000|Henchant:3919|h[Engineering: Rough Dynamite]|h|r -|cffffff00|Hachievement:546:0000000000000001:0:0:0:-1:0:0:0:0|h[Safe Deposit]|h|r -|cff66bbff|Hglyph:21:762|h[Glyph of Bladestorm]|h|r + /* + Valid examples: + |cffa335ee|Hitem:812:0:0:0:0:0:0:0:70|h[Glowing Brightwood Staff]|h|r + |cff808080|Hquest:2278:47|h[The Platinum Discs]|h|r + |cffffd000|Htrade:4037:1:150:1:6AAAAAAAAAAAAAAAAAAAAAAOAADAAAAAAAAAAAAAAAAIAAAAAAAAA|h[Engineering]|h|r + |cff4e96f7|Htalent:2232:-1|h[Taste for Blood]|h|r + |cff71d5ff|Hspell:21563|h[Command]|h|r + |cffffd000|Henchant:3919|h[Engineering: Rough Dynamite]|h|r + |cffffff00|Hachievement:546:0000000000000001:0:0:0:-1:0:0:0:0|h[Safe Deposit]|h|r + |cff66bbff|Hglyph:21:762|h[Glyph of Bladestorm]|h|r -| will be escaped to || -*/ + | will be escaped to || + */ if (strlen(message) > 255) return false; @@ -597,8 +597,8 @@ bool ChatHandler::ShowHelpForCommand(std::vector const& table, cons } size_t ChatHandler::BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, uint64 senderGUID, uint64 receiverGUID, std::string const& message, uint8 chatTag, - std::string const& senderName /*= ""*/, std::string const& receiverName /*= ""*/, - uint32 achievementId /*= 0*/, bool gmMessage /*= false*/, std::string const& channelName /*= ""*/) + std::string const& senderName /*= ""*/, std::string const& receiverName /*= ""*/, + uint32 achievementId /*= 0*/, bool gmMessage /*= false*/, std::string const& channelName /*= ""*/) { size_t receiverGUIDPos = 0; data.Initialize(!gmMessage ? SMSG_MESSAGECHAT : SMSG_GM_MESSAGECHAT); @@ -677,7 +677,7 @@ size_t ChatHandler::BuildChatPacket(WorldPacket& data, ChatMsg chatType, Languag } size_t ChatHandler::BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, WorldObject const* sender, WorldObject const* receiver, std::string const& message, - uint32 achievementId /*= 0*/, std::string const& channelName /*= ""*/, LocaleConstant locale /*= DEFAULT_LOCALE*/) + uint32 achievementId /*= 0*/, std::string const& channelName /*= ""*/, LocaleConstant locale /*= DEFAULT_LOCALE*/) { uint64 senderGUID = 0; std::string senderName = ""; @@ -774,7 +774,7 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* linkType, char** s return nullptr; // skip spaces - while (*text == ' '||*text == '\t'||*text == '\b') + while (*text == ' ' || *text == '\t' || *text == '\b') ++text; if (!*text) @@ -822,7 +822,7 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* const* linkTypes, return nullptr; // skip spaces - while (*text == ' '||*text == '\t'||*text == '\b') + while (*text == ' ' || *text == '\t' || *text == '\b') ++text; if (!*text) @@ -849,7 +849,7 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* const* linkTypes, tail = strtok(nullptr, ""); // tail } else - tail = text+1; // skip first | + tail = text + 1; // skip first | char* cLinkType = strtok(tail, ":"); // linktype if (!cLinkType) @@ -956,34 +956,34 @@ uint32 ChatHandler::extractSpellIdFromLink(char* text) case SPELL_LINK_SPELL: return id; case SPELL_LINK_TALENT: - { - // talent - TalentEntry const* talentEntry = sTalentStore.LookupEntry(id); - if (!talentEntry) - return 0; + { + // talent + TalentEntry const* talentEntry = sTalentStore.LookupEntry(id); + if (!talentEntry) + return 0; - int32 rank = param1_str ? (uint32)atol(param1_str) : 0; - if (rank >= MAX_TALENT_RANK) - return 0; + int32 rank = param1_str ? (uint32)atol(param1_str) : 0; + if (rank >= MAX_TALENT_RANK) + return 0; - if (rank < 0) - rank = 0; + if (rank < 0) + rank = 0; - return talentEntry->RankID[rank]; - } + return talentEntry->RankID[rank]; + } case SPELL_LINK_ENCHANT: case SPELL_LINK_TRADE: return id; case SPELL_LINK_GLYPH: - { - uint32 glyph_prop_id = param1_str ? (uint32)atol(param1_str) : 0; + { + uint32 glyph_prop_id = param1_str ? (uint32)atol(param1_str) : 0; - GlyphPropertiesEntry const* glyphPropEntry = sGlyphPropertiesStore.LookupEntry(glyph_prop_id); - if (!glyphPropEntry) - return 0; + GlyphPropertiesEntry const* glyphPropEntry = sGlyphPropertiesStore.LookupEntry(glyph_prop_id); + if (!glyphPropEntry) + return 0; - return glyphPropEntry->SpellId; - } + return glyphPropEntry->SpellId; + } } // unknown type? @@ -1034,37 +1034,37 @@ uint64 ChatHandler::extractGuidFromLink(char* text) switch (type) { case SPELL_LINK_PLAYER: - { - std::string name = idS; - if (!normalizePlayerName(name)) + { + std::string name = idS; + if (!normalizePlayerName(name)) + return 0; + + if (Player* player = ObjectAccessor::FindPlayerByName(name, false)) + return player->GetGUID(); + + if (uint64 guid = sObjectMgr->GetPlayerGUIDByName(name)) + return guid; + return 0; - - if (Player* player = ObjectAccessor::FindPlayerByName(name, false)) - return player->GetGUID(); - - if (uint64 guid = sObjectMgr->GetPlayerGUIDByName(name)) - return guid; - - return 0; - } + } case SPELL_LINK_CREATURE: - { - uint32 lowguid = (uint32)atol(idS); + { + uint32 lowguid = (uint32)atol(idS); - if (CreatureData const* data = sObjectMgr->GetCreatureData(lowguid)) - return MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT); - else - return 0; - } + if (CreatureData const* data = sObjectMgr->GetCreatureData(lowguid)) + return MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT); + else + return 0; + } case SPELL_LINK_GAMEOBJECT: - { - uint32 lowguid = (uint32)atol(idS); + { + uint32 lowguid = (uint32)atol(idS); - if (GameObjectData const* data = sObjectMgr->GetGOData(lowguid)) - return MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_GAMEOBJECT); - else - return 0; - } + if (GameObjectData const* data = sObjectMgr->GetGOData(lowguid)) + return MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_GAMEOBJECT); + else + return 0; + } } // unknown type? @@ -1162,7 +1162,7 @@ char* ChatHandler::extractQuotedArg(char* args) return nullptr; if (*args == '"') - return strtok(args+1, "\""); + return strtok(args + 1, "\""); else { // skip spaces @@ -1228,7 +1228,7 @@ bool CliHandler::isAvailable(ChatCommand const& cmd) const return cmd.AllowConsole; } -void CliHandler::SendSysMessage(const char *str) +void CliHandler::SendSysMessage(const char* str) { m_print(m_callbackArg, str); m_print(m_callbackArg, "\r\n"); @@ -1244,7 +1244,7 @@ bool CliHandler::needReportToTarget(Player* /*chr*/) const return true; } -bool ChatHandler::GetPlayerGroupAndGUIDByName(const char* cname, Player* &player, Group* &group, uint64 &guid, bool offline) +bool ChatHandler::GetPlayerGroupAndGUIDByName(const char* cname, Player*& player, Group*& group, uint64& guid, bool offline) { player = nullptr; guid = 0; diff --git a/src/server/game/Chat/Chat.h b/src/server/game/Chat/Chat.h index 8db66b3fb..46a98f550 100644 --- a/src/server/game/Chat/Chat.h +++ b/src/server/game/Chat/Chat.h @@ -26,130 +26,130 @@ class ChatCommand { typedef bool(*pHandler)(ChatHandler*, char const*); - public: - ChatCommand(char const* name, uint32 securityLevel, bool allowConsole, pHandler handler, std::string help, std::vector childCommands = std::vector()) - : Name(ASSERT_NOTNULL(name)), SecurityLevel(securityLevel), AllowConsole(allowConsole), Handler(handler), Help(std::move(help)), ChildCommands(std::move(childCommands)) { } +public: + ChatCommand(char const* name, uint32 securityLevel, bool allowConsole, pHandler handler, std::string help, std::vector childCommands = std::vector()) + : Name(ASSERT_NOTNULL(name)), SecurityLevel(securityLevel), AllowConsole(allowConsole), Handler(handler), Help(std::move(help)), ChildCommands(std::move(childCommands)) { } - char const* Name; - uint32 SecurityLevel; - bool AllowConsole; - pHandler Handler; - std::string Help; - std::vector ChildCommands; + char const* Name; + uint32 SecurityLevel; + bool AllowConsole; + pHandler Handler; + std::string Help; + std::vector ChildCommands; }; class ChatHandler { - public: - WorldSession* GetSession() { return m_session; } - explicit ChatHandler(WorldSession* session) : m_session(session), sentErrorMessage(false) {} - virtual ~ChatHandler() { } +public: + WorldSession* GetSession() { return m_session; } + explicit ChatHandler(WorldSession* session) : m_session(session), sentErrorMessage(false) {} + virtual ~ChatHandler() { } - // Builds chat packet and returns receiver guid position in the packet to substitute in whisper builders - static size_t BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, uint64 senderGUID, uint64 receiverGUID, std::string const& message, uint8 chatTag, - std::string const& senderName = "", std::string const& receiverName = "", - uint32 achievementId = 0, bool gmMessage = false, std::string const& channelName = ""); + // Builds chat packet and returns receiver guid position in the packet to substitute in whisper builders + static size_t BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, uint64 senderGUID, uint64 receiverGUID, std::string const& message, uint8 chatTag, + std::string const& senderName = "", std::string const& receiverName = "", + uint32 achievementId = 0, bool gmMessage = false, std::string const& channelName = ""); - // Builds chat packet and returns receiver guid position in the packet to substitute in whisper builders - static size_t BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, WorldObject const* sender, WorldObject const* receiver, std::string const& message, uint32 achievementId = 0, std::string const& channelName = "", LocaleConstant locale = DEFAULT_LOCALE); + // Builds chat packet and returns receiver guid position in the packet to substitute in whisper builders + static size_t BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, WorldObject const* sender, WorldObject const* receiver, std::string const& message, uint32 achievementId = 0, std::string const& channelName = "", LocaleConstant locale = DEFAULT_LOCALE); - static char* LineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } + static char* LineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } - // function with different implementation for chat/console - virtual char const* GetAcoreString(uint32 entry) const; - virtual void SendSysMessage(char const* str); + // function with different implementation for chat/console + virtual char const* GetAcoreString(uint32 entry) const; + virtual void SendSysMessage(char const* str); - void SendSysMessage(uint32 entry); - void PSendSysMessage(char const* format, ...) ATTR_PRINTF(2, 3); - void PSendSysMessage(uint32 entry, ...); - std::string PGetParseString(uint32 entry, ...) const; + void SendSysMessage(uint32 entry); + void PSendSysMessage(char const* format, ...) ATTR_PRINTF(2, 3); + void PSendSysMessage(uint32 entry, ...); + std::string PGetParseString(uint32 entry, ...) const; - bool ParseCommands(const char* text); + bool ParseCommands(const char* text); - static std::vector const& getCommandTable(); + static std::vector const& getCommandTable(); - bool isValidChatMessage(const char* msg); - void SendGlobalSysMessage(const char *str); + bool isValidChatMessage(const char* msg); + void SendGlobalSysMessage(const char* str); - bool hasStringAbbr(const char* name, const char* part); + bool hasStringAbbr(const char* name, const char* part); - // function with different implementation for chat/console - virtual bool isAvailable(ChatCommand const& cmd) const; - virtual std::string GetNameLink() const { return GetNameLink(m_session->GetPlayer()); } - virtual bool needReportToTarget(Player* chr) const; - virtual LocaleConstant GetSessionDbcLocale() const; - virtual int GetSessionDbLocaleIndex() const; + // function with different implementation for chat/console + virtual bool isAvailable(ChatCommand const& cmd) const; + virtual std::string GetNameLink() const { return GetNameLink(m_session->GetPlayer()); } + virtual bool needReportToTarget(Player* chr) const; + virtual LocaleConstant GetSessionDbcLocale() const; + virtual int GetSessionDbLocaleIndex() const; - bool HasLowerSecurity(Player* target, uint64 guid, bool strong = false); - bool HasLowerSecurityAccount(WorldSession* target, uint32 account, bool strong = false); + bool HasLowerSecurity(Player* target, uint64 guid, bool strong = false); + bool HasLowerSecurityAccount(WorldSession* target, uint32 account, bool strong = false); - void SendGlobalGMSysMessage(const char *str); - Player* getSelectedPlayer(); - Creature* getSelectedCreature(); - Unit* getSelectedUnit(); - WorldObject* getSelectedObject(); - // Returns either the selected player or self if there is no selected player - Player* getSelectedPlayerOrSelf(); + void SendGlobalGMSysMessage(const char* str); + Player* getSelectedPlayer(); + Creature* getSelectedCreature(); + Unit* getSelectedUnit(); + WorldObject* getSelectedObject(); + // Returns either the selected player or self if there is no selected player + Player* getSelectedPlayerOrSelf(); - char* extractKeyFromLink(char* text, char const* linkType, char** something1 = nullptr); - char* extractKeyFromLink(char* text, char const* const* linkTypes, int* found_idx, char** something1 = nullptr); + char* extractKeyFromLink(char* text, char const* linkType, char** something1 = nullptr); + char* extractKeyFromLink(char* text, char const* const* linkTypes, int* found_idx, char** something1 = nullptr); - // if args have single value then it return in arg2 and arg1 == NULL - void extractOptFirstArg(char* args, char** arg1, char** arg2); - char* extractQuotedArg(char* args); + // if args have single value then it return in arg2 and arg1 == NULL + void extractOptFirstArg(char* args, char** arg1, char** arg2); + char* extractQuotedArg(char* args); - uint32 extractSpellIdFromLink(char* text); - uint64 extractGuidFromLink(char* text); - GameTele const* extractGameTeleFromLink(char* text); - bool GetPlayerGroupAndGUIDByName(const char* cname, Player* &player, Group* &group, uint64 &guid, bool offline = false); - std::string extractPlayerNameFromLink(char* text); - // select by arg (name/link) or in-game selection online/offline player - bool extractPlayerTarget(char* args, Player** player, uint64* player_guid = NULL, std::string* player_name = nullptr); + uint32 extractSpellIdFromLink(char* text); + uint64 extractGuidFromLink(char* text); + GameTele const* extractGameTeleFromLink(char* text); + bool GetPlayerGroupAndGUIDByName(const char* cname, Player*& player, Group*& group, uint64& guid, bool offline = false); + std::string extractPlayerNameFromLink(char* text); + // select by arg (name/link) or in-game selection online/offline player + bool extractPlayerTarget(char* args, Player** player, uint64* player_guid = NULL, std::string* player_name = nullptr); - std::string playerLink(std::string const& name) const { return m_session ? "|cffffffff|Hplayer:"+name+"|h["+name+"]|h|r" : name; } - std::string GetNameLink(Player* chr) const; + std::string playerLink(std::string const& name) const { return m_session ? "|cffffffff|Hplayer:" + name + "|h[" + name + "]|h|r" : name; } + std::string GetNameLink(Player* chr) const; - GameObject* GetNearbyGameObject(); - GameObject* GetObjectGlobalyWithGuidOrNearWithDbGuid(uint32 lowguid, uint32 entry); - bool HasSentErrorMessage() const { return sentErrorMessage; } - void SetSentErrorMessage(bool val){ sentErrorMessage = val; } - static bool LoadCommandTable() { return load_command_table; } - static void SetLoadCommandTable(bool val) { load_command_table = val; } + GameObject* GetNearbyGameObject(); + GameObject* GetObjectGlobalyWithGuidOrNearWithDbGuid(uint32 lowguid, uint32 entry); + bool HasSentErrorMessage() const { return sentErrorMessage; } + void SetSentErrorMessage(bool val) { sentErrorMessage = val; } + static bool LoadCommandTable() { return load_command_table; } + static void SetLoadCommandTable(bool val) { load_command_table = val; } - bool ShowHelpForCommand(std::vector const& table, const char* cmd); - protected: - explicit ChatHandler() : m_session(nullptr), sentErrorMessage(false) {} // for CLI subclass - static bool SetDataForCommandInTable(std::vector& table, const char* text, uint32 securityLevel, std::string const& help, std::string const& fullcommand); - bool ExecuteCommandInTable(std::vector const& table, const char* text, std::string const& fullcmd); - bool ShowHelpForSubCommands(std::vector const& table, char const* cmd, char const* subcmd); + bool ShowHelpForCommand(std::vector const& table, const char* cmd); +protected: + explicit ChatHandler() : m_session(nullptr), sentErrorMessage(false) {} // for CLI subclass + static bool SetDataForCommandInTable(std::vector& table, const char* text, uint32 securityLevel, std::string const& help, std::string const& fullcommand); + bool ExecuteCommandInTable(std::vector const& table, const char* text, std::string const& fullcmd); + bool ShowHelpForSubCommands(std::vector const& table, char const* cmd, char const* subcmd); - private: +private: - WorldSession* m_session; // != NULL for chat command call and NULL for CLI command + WorldSession* m_session; // != NULL for chat command call and NULL for CLI command - // common global flag - static bool load_command_table; - bool sentErrorMessage; + // common global flag + static bool load_command_table; + bool sentErrorMessage; }; class CliHandler : public ChatHandler { - public: - typedef void Print(void*, char const*); - explicit CliHandler(void* callbackArg, Print* zprint) : m_callbackArg(callbackArg), m_print(zprint) {} +public: + typedef void Print(void*, char const*); + explicit CliHandler(void* callbackArg, Print* zprint) : m_callbackArg(callbackArg), m_print(zprint) {} - // overwrite functions - char const* GetAcoreString(uint32 entry) const override; - bool isAvailable(ChatCommand const& cmd) const override; - void SendSysMessage(const char *str) override; - std::string GetNameLink() const override; - bool needReportToTarget(Player* chr) const override; - LocaleConstant GetSessionDbcLocale() const override; - int GetSessionDbLocaleIndex() const override; + // overwrite functions + char const* GetAcoreString(uint32 entry) const override; + bool isAvailable(ChatCommand const& cmd) const override; + void SendSysMessage(const char* str) override; + std::string GetNameLink() const override; + bool needReportToTarget(Player* chr) const override; + LocaleConstant GetSessionDbcLocale() const override; + int GetSessionDbLocaleIndex() const override; - private: - void* m_callbackArg; - Print* m_print; +private: + void* m_callbackArg; + Print* m_print; }; #endif diff --git a/src/server/game/Chat/ChatLink.cpp b/src/server/game/Chat/ChatLink.cpp index 3a9233224..b64677ec0 100644 --- a/src/server/game/Chat/ChatLink.cpp +++ b/src/server/game/Chat/ChatLink.cpp @@ -676,7 +676,7 @@ bool LinkExtractor::IsValidMessage() { if (commandChar == *validSequenceIterator) { - if (validSequenceIterator == validSequence+4) + if (validSequenceIterator == validSequence + 4) validSequenceIterator = validSequence; else ++validSequenceIterator; diff --git a/src/server/game/Chat/ChatLink.h b/src/server/game/Chat/ChatLink.h index 71fb0410f..97cacbea1 100644 --- a/src/server/game/Chat/ChatLink.h +++ b/src/server/game/Chat/ChatLink.h @@ -46,7 +46,7 @@ class ItemChatLink : public ChatLink { public: ItemChatLink() : ChatLink(), _item(nullptr), _suffix(nullptr), _property(nullptr) - { + { memset(_data, 0, sizeof(_data)); } virtual bool Initialize(std::istringstream& iss); @@ -91,7 +91,7 @@ class AchievementChatLink : public ChatLink { public: AchievementChatLink() : ChatLink(), _guid(0), _achievement(nullptr) - { + { memset(_data, 0, sizeof(_data)); } virtual bool Initialize(std::istringstream& iss); diff --git a/src/server/game/Combat/HostileRefManager.cpp b/src/server/game/Combat/HostileRefManager.cpp index 568ae8678..e66775505 100644 --- a/src/server/game/Combat/HostileRefManager.cpp +++ b/src/server/game/Combat/HostileRefManager.cpp @@ -155,7 +155,7 @@ void HostileRefManager::deleteReference(Unit* creature) void HostileRefManager::deleteReferencesOutOfRange(float range) { HostileReference* ref = getFirst(); - range = range*range; + range = range * range; while (ref) { HostileReference* nextRef = ref->next(); @@ -195,8 +195,8 @@ void HostileRefManager::UpdateVisibility(bool checkThreat) while (ref) { HostileReference* nextRef = ref->next(); - if ((!checkThreat || ref->GetSource()->getThreatList().size() <= 1) && - !ref->GetSource()->GetOwner()->CanSeeOrDetect(GetOwner())) + if ((!checkThreat || ref->GetSource()->getThreatList().size() <= 1) && + !ref->GetSource()->GetOwner()->CanSeeOrDetect(GetOwner())) { nextRef = ref->next(); ref->removeReference(); diff --git a/src/server/game/Combat/HostileRefManager.h b/src/server/game/Combat/HostileRefManager.h index 8c703aa13..74f947f6c 100644 --- a/src/server/game/Combat/HostileRefManager.h +++ b/src/server/game/Combat/HostileRefManager.h @@ -19,46 +19,46 @@ class SpellInfo; class HostileRefManager : public RefManager { - private: - Unit* iOwner; - public: - explicit HostileRefManager(Unit* owner) { iOwner = owner; } - ~HostileRefManager(); +private: + Unit* iOwner; +public: + explicit HostileRefManager(Unit* owner) { iOwner = owner; } + ~HostileRefManager(); - Unit* GetOwner() { return iOwner; } + Unit* GetOwner() { return iOwner; } - // send threat to all my hateres for the victim - // The victim is hated than by them as well - // use for buffs and healing threat functionality - void threatAssist(Unit* victim, float baseThreat, SpellInfo const* threatSpell = nullptr); + // send threat to all my hateres for the victim + // The victim is hated than by them as well + // use for buffs and healing threat functionality + void threatAssist(Unit* victim, float baseThreat, SpellInfo const* threatSpell = nullptr); - void addTempThreat(float threat, bool apply); + void addTempThreat(float threat, bool apply); - void addThreatPercent(int32 percent); + void addThreatPercent(int32 percent); - // The references are not needed anymore - // tell the source to remove them from the list and free the mem - void deleteReferences(); + // The references are not needed anymore + // tell the source to remove them from the list and free the mem + void deleteReferences(); - // Remove specific faction references - void deleteReferencesForFaction(uint32 faction); + // Remove specific faction references + void deleteReferencesForFaction(uint32 faction); - // pussywizard: for combat bugs - void deleteReferencesOutOfRange(float range); + // pussywizard: for combat bugs + void deleteReferencesOutOfRange(float range); - HostileReference* getFirst() { return ((HostileReference*) RefManager::getFirst()); } + HostileReference* getFirst() { return ((HostileReference*) RefManager::getFirst()); } - void updateThreatTables(); + void updateThreatTables(); - void setOnlineOfflineState(bool isOnline); + void setOnlineOfflineState(bool isOnline); - // set state for one reference, defined by Unit - void setOnlineOfflineState(Unit* creature, bool isOnline); + // set state for one reference, defined by Unit + void setOnlineOfflineState(Unit* creature, bool isOnline); - // delete one reference, defined by Unit - void deleteReference(Unit* creature); + // delete one reference, defined by Unit + void deleteReference(Unit* creature); - void UpdateVisibility(bool checkThreat); + void UpdateVisibility(bool checkThreat); }; //================================================= #endif diff --git a/src/server/game/Combat/ThreatManager.cpp b/src/server/game/Combat/ThreatManager.cpp index 973eb8176..eb723e8c0 100644 --- a/src/server/game/Combat/ThreatManager.cpp +++ b/src/server/game/Combat/ThreatManager.cpp @@ -171,11 +171,11 @@ void HostileReference::updateOnlineStatus() // target is no player or not gamemaster // target is not in flight if (isValid() - && (getTarget()->GetTypeId() != TYPEID_PLAYER || !getTarget()->ToPlayer()->IsGameMaster()) - && !getTarget()->IsInFlight() - && getTarget()->IsInMap(GetSourceUnit()) - && getTarget()->InSamePhase(GetSourceUnit()) - ) + && (getTarget()->GetTypeId() != TYPEID_PLAYER || !getTarget()->ToPlayer()->IsGameMaster()) + && !getTarget()->IsInFlight() + && getTarget()->IsInMap(GetSourceUnit()) + && getTarget()->InSamePhase(GetSourceUnit()) + ) { Creature* creature = GetSourceUnit()->ToCreature(); online = getTarget()->isInAccessiblePlaceFor(creature); @@ -247,7 +247,7 @@ HostileReference* ThreatContainer::getReferenceByTarget(Unit* victim) const uint64 const guid = victim->GetGUID(); for (ThreatContainer::StorageType::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i) { - HostileReference *ref = (*i); + HostileReference* ref = (*i); if (ref && ref->getUnitGuid() == guid) return ref; } @@ -438,7 +438,7 @@ void ThreatManager::_addThreat(Unit* victim, float threat) if (!ref) // there was no ref => create a new one { - // threat has to be 0 here + // threat has to be 0 here HostileReference* hostileRef = new HostileReference(victim, this, 0); iThreatContainer.addReference(hostileRef); hostileRef->addThreat(threat); // now we add the real threat @@ -535,8 +535,8 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat switch (threatRefStatusChangeEvent->getType()) { case UEV_THREAT_REF_THREAT_CHANGE: - if ((getCurrentVictim() == hostilRef && threatRefStatusChangeEvent->getFValue()<0.0f) || - (getCurrentVictim() != hostilRef && threatRefStatusChangeEvent->getFValue()>0.0f)) + if ((getCurrentVictim() == hostilRef && threatRefStatusChangeEvent->getFValue() < 0.0f) || + (getCurrentVictim() != hostilRef && threatRefStatusChangeEvent->getFValue() > 0.0f)) setDirty(true); // the order in the threat list might have changed break; case UEV_THREAT_REF_ONLINE_STATUS: @@ -594,7 +594,7 @@ bool ThreatManager::isNeedUpdateToClient(uint32 time) // Reset all aggro without modifying the threatlist. void ThreatManager::resetAllAggro() { - ThreatContainer::StorageType &threatList = iThreatContainer.iThreatList; + ThreatContainer::StorageType& threatList = iThreatContainer.iThreatList; if (threatList.empty()) return; diff --git a/src/server/game/Combat/ThreatManager.h b/src/server/game/Combat/ThreatManager.h index eea330c57..6151c1af9 100644 --- a/src/server/game/Combat/ThreatManager.h +++ b/src/server/game/Combat/ThreatManager.h @@ -35,87 +35,87 @@ struct ThreatCalcHelper //============================================================== class HostileReference : public Reference { - public: - HostileReference(Unit* refUnit, ThreatManager* threatManager, float threat); +public: + HostileReference(Unit* refUnit, ThreatManager* threatManager, float threat); - //================================================= - void addThreat(float modThreat); + //================================================= + void addThreat(float modThreat); - void setThreat(float threat) { addThreat(threat - getThreat()); } + void setThreat(float threat) { addThreat(threat - getThreat()); } - void addThreatPercent(int32 percent); + void addThreatPercent(int32 percent); - float getThreat() const { return iThreat; } + float getThreat() const { return iThreat; } - bool isOnline() const { return iOnline; } + bool isOnline() const { return iOnline; } - // used for temporary setting a threat and reducting it later again. - // the threat modification is stored - void setTempThreat(float threat) + // used for temporary setting a threat and reducting it later again. + // the threat modification is stored + void setTempThreat(float threat) + { + addTempThreat(threat - getThreat()); + } + + void addTempThreat(float threat) + { + iTempThreatModifier = threat; + if (iTempThreatModifier != 0.0f) + addThreat(iTempThreatModifier); + } + + void resetTempThreat() + { + if (iTempThreatModifier != 0.0f) { - addTempThreat(threat - getThreat()); + addThreat(-iTempThreatModifier); + iTempThreatModifier = 0.0f; } + } - void addTempThreat(float threat) - { - iTempThreatModifier = threat; - if (iTempThreatModifier != 0.0f) - addThreat(iTempThreatModifier); - } + float getTempThreatModifier() { return iTempThreatModifier; } - void resetTempThreat() - { - if (iTempThreatModifier != 0.0f) - { - addThreat(-iTempThreatModifier); - iTempThreatModifier = 0.0f; - } - } + //================================================= + // check, if source can reach target and set the status + void updateOnlineStatus(); - float getTempThreatModifier() { return iTempThreatModifier; } + void setOnlineOfflineState(bool isOnline); + //================================================= - //================================================= - // check, if source can reach target and set the status - void updateOnlineStatus(); + bool operator == (const HostileReference& hostileRef) const { return hostileRef.getUnitGuid() == getUnitGuid(); } - void setOnlineOfflineState(bool isOnline); - //================================================= + //================================================= - bool operator == (const HostileReference& hostileRef) const { return hostileRef.getUnitGuid() == getUnitGuid(); } + uint64 getUnitGuid() const { return iUnitGuid; } - //================================================= + //================================================= + // reference is not needed anymore. realy delete it ! - uint64 getUnitGuid() const { return iUnitGuid; } + void removeReference(); - //================================================= - // reference is not needed anymore. realy delete it ! + //================================================= - void removeReference(); + HostileReference* next() { return ((HostileReference*) Reference::next()); } - //================================================= + //================================================= - HostileReference* next() { return ((HostileReference*) Reference::next()); } + // Tell our refTo (target) object that we have a link + void targetObjectBuildLink(); - //================================================= + // Tell our refTo (taget) object, that the link is cut + void targetObjectDestroyLink(); - // Tell our refTo (target) object that we have a link - void targetObjectBuildLink(); + // Tell our refFrom (source) object, that the link is cut (Target destroyed) + void sourceObjectDestroyLink(); +private: + // Inform the source, that the status of that reference was changed + void fireStatusChanged(ThreatRefStatusChangeEvent& threatRefStatusChangeEvent); - // Tell our refTo (taget) object, that the link is cut - void targetObjectDestroyLink(); - - // Tell our refFrom (source) object, that the link is cut (Target destroyed) - void sourceObjectDestroyLink(); - private: - // Inform the source, that the status of that reference was changed - void fireStatusChanged(ThreatRefStatusChangeEvent& threatRefStatusChangeEvent); - - Unit* GetSourceUnit(); - private: - float iThreat; - float iTempThreatModifier; // used for taunt - uint64 iUnitGuid; - bool iOnline; + Unit* GetSourceUnit(); +private: + float iThreat; + float iTempThreatModifier; // used for taunt + uint64 iUnitGuid; + bool iOnline; }; //============================================================== @@ -123,138 +123,138 @@ class ThreatManager; class ThreatContainer { - friend class ThreatManager; + friend class ThreatManager; - public: - typedef std::list StorageType; +public: + typedef std::list StorageType; - ThreatContainer(): iDirty(false) { } + ThreatContainer(): iDirty(false) { } - ~ThreatContainer() { clearReferences(); } + ~ThreatContainer() { clearReferences(); } - HostileReference* addThreat(Unit* victim, float threat); + HostileReference* addThreat(Unit* victim, float threat); - void modifyThreatPercent(Unit* victim, int32 percent); + void modifyThreatPercent(Unit* victim, int32 percent); - HostileReference* selectNextVictim(Creature* attacker, HostileReference* currentVictim) const; + HostileReference* selectNextVictim(Creature* attacker, HostileReference* currentVictim) const; - void setDirty(bool isDirty) { iDirty = isDirty; } + void setDirty(bool isDirty) { iDirty = isDirty; } - bool isDirty() const { return iDirty; } + bool isDirty() const { return iDirty; } - bool empty() const - { - return iThreatList.empty(); - } + bool empty() const + { + return iThreatList.empty(); + } - HostileReference* getMostHated() const - { - return iThreatList.empty() ? NULL : iThreatList.front(); - } + HostileReference* getMostHated() const + { + return iThreatList.empty() ? NULL : iThreatList.front(); + } - HostileReference* getReferenceByTarget(Unit* victim) const; + HostileReference* getReferenceByTarget(Unit* victim) const; - StorageType const & getThreatList() const { return iThreatList; } + StorageType const& getThreatList() const { return iThreatList; } - private: - void remove(HostileReference* hostileRef) - { - iThreatList.remove(hostileRef); - } +private: + void remove(HostileReference* hostileRef) + { + iThreatList.remove(hostileRef); + } - void addReference(HostileReference* hostileRef) - { - iThreatList.push_back(hostileRef); - } + void addReference(HostileReference* hostileRef) + { + iThreatList.push_back(hostileRef); + } - void clearReferences(); + void clearReferences(); - // Sort the list if necessary - void update(); + // Sort the list if necessary + void update(); - StorageType iThreatList; - bool iDirty; + StorageType iThreatList; + bool iDirty; }; //================================================= class ThreatManager { - public: - friend class HostileReference; +public: + friend class HostileReference; - explicit ThreatManager(Unit* owner); + explicit ThreatManager(Unit* owner); - ~ThreatManager() { clearReferences(); } + ~ThreatManager() { clearReferences(); } - void clearReferences(); + void clearReferences(); - void addThreat(Unit* victim, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); + void addThreat(Unit* victim, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); - void doAddThreat(Unit* victim, float threat); + void doAddThreat(Unit* victim, float threat); - void modifyThreatPercent(Unit* victim, int32 percent); + void modifyThreatPercent(Unit* victim, int32 percent); - float getThreat(Unit* victim, bool alsoSearchOfflineList = false); + float getThreat(Unit* victim, bool alsoSearchOfflineList = false); - float getThreatWithoutTemp(Unit* victim, bool alsoSearchOfflineList = false); + float getThreatWithoutTemp(Unit* victim, bool alsoSearchOfflineList = false); - bool isThreatListEmpty() const { return iThreatContainer.empty(); } - bool areThreatListsEmpty() const { return iThreatContainer.empty() && iThreatOfflineContainer.empty(); } + bool isThreatListEmpty() const { return iThreatContainer.empty(); } + bool areThreatListsEmpty() const { return iThreatContainer.empty() && iThreatOfflineContainer.empty(); } - void processThreatEvent(ThreatRefStatusChangeEvent* threatRefStatusChangeEvent); + void processThreatEvent(ThreatRefStatusChangeEvent* threatRefStatusChangeEvent); - bool isNeedUpdateToClient(uint32 time); + bool isNeedUpdateToClient(uint32 time); - HostileReference* getCurrentVictim() const { return iCurrentVictim; } + HostileReference* getCurrentVictim() const { return iCurrentVictim; } - Unit* GetOwner() const { return iOwner; } + Unit* GetOwner() const { return iOwner; } - Unit* getHostilTarget(); + Unit* getHostilTarget(); - void tauntApply(Unit* taunter); - void tauntFadeOut(Unit* taunter); + void tauntApply(Unit* taunter); + void tauntFadeOut(Unit* taunter); - void setCurrentVictim(HostileReference* hostileRef); + void setCurrentVictim(HostileReference* hostileRef); - void setDirty(bool isDirty) { iThreatContainer.setDirty(isDirty); } + void setDirty(bool isDirty) { iThreatContainer.setDirty(isDirty); } - // Reset all aggro without modifying the threadlist. - void resetAllAggro(); + // Reset all aggro without modifying the threadlist. + void resetAllAggro(); - // Reset all aggro of unit in threadlist satisfying the predicate. - template void resetAggro(PREDICATE predicate) + // Reset all aggro of unit in threadlist satisfying the predicate. + template void resetAggro(PREDICATE predicate) + { + ThreatContainer::StorageType& threatList = iThreatContainer.iThreatList; + if (threatList.empty()) + return; + + for (ThreatContainer::StorageType::iterator itr = threatList.begin(); itr != threatList.end(); ++itr) { - ThreatContainer::StorageType &threatList = iThreatContainer.iThreatList; - if (threatList.empty()) - return; + HostileReference* ref = (*itr); - for (ThreatContainer::StorageType::iterator itr = threatList.begin(); itr != threatList.end(); ++itr) + if (predicate(ref->getTarget())) { - HostileReference* ref = (*itr); - - if (predicate(ref->getTarget())) - { - ref->setThreat(0); - setDirty(true); - } + ref->setThreat(0); + setDirty(true); } } + } - // methods to access the lists from the outside to do some dirty manipulation (scriping and such) - // I hope they are used as little as possible. - ThreatContainer::StorageType const & getThreatList() const { return iThreatContainer.getThreatList(); } - ThreatContainer::StorageType const & getOfflineThreatList() const { return iThreatOfflineContainer.getThreatList(); } - ThreatContainer& getOnlineContainer() { return iThreatContainer; } - ThreatContainer& getOfflineContainer() { return iThreatOfflineContainer; } - private: - void _addThreat(Unit* victim, float threat); + // methods to access the lists from the outside to do some dirty manipulation (scriping and such) + // I hope they are used as little as possible. + ThreatContainer::StorageType const& getThreatList() const { return iThreatContainer.getThreatList(); } + ThreatContainer::StorageType const& getOfflineThreatList() const { return iThreatOfflineContainer.getThreatList(); } + ThreatContainer& getOnlineContainer() { return iThreatContainer; } + ThreatContainer& getOfflineContainer() { return iThreatOfflineContainer; } +private: + void _addThreat(Unit* victim, float threat); - HostileReference* iCurrentVictim; - Unit* iOwner; - uint32 iUpdateTimer; - ThreatContainer iThreatContainer; - ThreatContainer iThreatOfflineContainer; + HostileReference* iCurrentVictim; + Unit* iOwner; + uint32 iUpdateTimer; + ThreatContainer iThreatContainer; + ThreatContainer iThreatOfflineContainer; }; //================================================= @@ -264,14 +264,14 @@ namespace acore // Binary predicate for sorting HostileReferences based on threat value class ThreatOrderPred { - public: - ThreatOrderPred(bool ascending = false) : m_ascending(ascending) {} - bool operator() (HostileReference const* a, HostileReference const* b) const - { - return m_ascending ? a->getThreat() < b->getThreat() : a->getThreat() > b->getThreat(); - } - private: - const bool m_ascending; + public: + ThreatOrderPred(bool ascending = false) : m_ascending(ascending) {} + bool operator() (HostileReference const* a, HostileReference const* b) const + { + return m_ascending ? a->getThreat() < b->getThreat() : a->getThreat() > b->getThreat(); + } + private: + const bool m_ascending; }; } #endif diff --git a/src/server/game/Combat/UnitEvents.h b/src/server/game/Combat/UnitEvents.h index e6fa7190c..d9ed69400 100644 --- a/src/server/game/Combat/UnitEvents.h +++ b/src/server/game/Combat/UnitEvents.h @@ -19,25 +19,25 @@ class HostileReference; enum UNIT_EVENT_TYPE { // Player/Pet changed on/offline status - UEV_THREAT_REF_ONLINE_STATUS = 1<<0, + UEV_THREAT_REF_ONLINE_STATUS = 1 << 0, // Threat for Player/Pet changed - UEV_THREAT_REF_THREAT_CHANGE = 1<<1, + UEV_THREAT_REF_THREAT_CHANGE = 1 << 1, // Player/Pet will be removed from list (dead) [for internal use] - UEV_THREAT_REF_REMOVE_FROM_LIST = 1<<2, + UEV_THREAT_REF_REMOVE_FROM_LIST = 1 << 2, // Player/Pet entered/left water or some other place where it is/was not accessible for the creature - UEV_THREAT_REF_ASSECCIBLE_STATUS = 1<<3, + UEV_THREAT_REF_ASSECCIBLE_STATUS = 1 << 3, // Threat list is going to be sorted (if dirty flag is set) - UEV_THREAT_SORT_LIST = 1<<4, + UEV_THREAT_SORT_LIST = 1 << 4, // New target should be fetched, could tbe the current target as well - UEV_THREAT_SET_NEXT_TARGET = 1<<5, + UEV_THREAT_SET_NEXT_TARGET = 1 << 5, // A new victim (target) was set. Could be NULL - UEV_THREAT_VICTIM_CHANGED = 1<<6, + UEV_THREAT_VICTIM_CHANGED = 1 << 6, // Future use //UEV_UNIT_KILLED = 1<<7, @@ -57,14 +57,14 @@ enum UNIT_EVENT_TYPE class UnitBaseEvent { - private: - uint32 iType; - public: - UnitBaseEvent(uint32 pType) { iType = pType; } - uint32 getType() const { return iType; } - bool matchesTypeMask(uint32 pMask) const { return iType & pMask; } +private: + uint32 iType; +public: + UnitBaseEvent(uint32 pType) { iType = pType; } + uint32 getType() const { return iType; } + bool matchesTypeMask(uint32 pMask) const { return iType & pMask; } - void setType(uint32 pType) { iType = pType; } + void setType(uint32 pType) { iType = pType; } }; @@ -72,52 +72,52 @@ class UnitBaseEvent class ThreatRefStatusChangeEvent : public UnitBaseEvent { - private: - HostileReference* iHostileReference; - union - { - float iFValue; - int32 iIValue; - bool iBValue; - }; - ThreatManager* iThreatManager; - public: - ThreatRefStatusChangeEvent(uint32 pType) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = nullptr; } +private: + HostileReference* iHostileReference; + union + { + float iFValue; + int32 iIValue; + bool iBValue; + }; + ThreatManager* iThreatManager; +public: + ThreatRefStatusChangeEvent(uint32 pType) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = nullptr; } - ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = pHostileReference; } + ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = pHostileReference; } - ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference, float pValue) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = pHostileReference; iFValue = pValue; } + ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference, float pValue) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = pHostileReference; iFValue = pValue; } - ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference, bool pValue) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = pHostileReference; iBValue = pValue; } + ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference, bool pValue) : UnitBaseEvent(pType), iThreatManager(nullptr) { iHostileReference = pHostileReference; iBValue = pValue; } - int32 getIValue() const { return iIValue; } + int32 getIValue() const { return iIValue; } - float getFValue() const { return iFValue; } + float getFValue() const { return iFValue; } - bool getBValue() const { return iBValue; } + bool getBValue() const { return iBValue; } - void setBValue(bool pValue) { iBValue = pValue; } + void setBValue(bool pValue) { iBValue = pValue; } - HostileReference* getReference() const { return iHostileReference; } + HostileReference* getReference() const { return iHostileReference; } - void setThreatManager(ThreatManager* pThreatManager) { iThreatManager = pThreatManager; } + void setThreatManager(ThreatManager* pThreatManager) { iThreatManager = pThreatManager; } - ThreatManager* getThreatManager() const { return iThreatManager; } + ThreatManager* getThreatManager() const { return iThreatManager; } }; //============================================================== class ThreatManagerEvent : public ThreatRefStatusChangeEvent { - private: - ThreatContainer* iThreatContainer; - public: - ThreatManagerEvent(uint32 pType) : ThreatRefStatusChangeEvent(pType), iThreatContainer(nullptr) {} - ThreatManagerEvent(uint32 pType, HostileReference* pHostileReference) : ThreatRefStatusChangeEvent(pType, pHostileReference), iThreatContainer(nullptr) {} +private: + ThreatContainer* iThreatContainer; +public: + ThreatManagerEvent(uint32 pType) : ThreatRefStatusChangeEvent(pType), iThreatContainer(nullptr) {} + ThreatManagerEvent(uint32 pType, HostileReference* pHostileReference) : ThreatRefStatusChangeEvent(pType, pHostileReference), iThreatContainer(nullptr) {} - void setThreatContainer(ThreatContainer* pThreatContainer) { iThreatContainer = pThreatContainer; } + void setThreatContainer(ThreatContainer* pThreatContainer) { iThreatContainer = pThreatContainer; } - ThreatContainer* getThreatContainer() const { return iThreatContainer; } + ThreatContainer* getThreatContainer() const { return iThreatContainer; } }; //============================================================== diff --git a/src/server/game/Conditions/ConditionMgr.cpp b/src/server/game/Conditions/ConditionMgr.cpp index 35b3b5562..af2d72ad5 100644 --- a/src/server/game/Conditions/ConditionMgr.cpp +++ b/src/server/game/Conditions/ConditionMgr.cpp @@ -38,149 +38,149 @@ bool Condition::Meets(ConditionSourceInfo& sourceInfo) condMeets = true; // empty condition, always met break; case CONDITION_AURA: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->HasAuraEffect(ConditionValue1, ConditionValue2); - break; - } - case CONDITION_ITEM: - { - if (Player* player = object->ToPlayer()) { - // don't allow 0 items (it's checked during table load) - ASSERT(ConditionValue2); - bool checkBank = !!ConditionValue3; - condMeets = player->HasItemCount(ConditionValue1, ConditionValue2, checkBank); + if (Unit* unit = object->ToUnit()) + condMeets = unit->HasAuraEffect(ConditionValue1, ConditionValue2); + break; + } + case CONDITION_ITEM: + { + if (Player* player = object->ToPlayer()) + { + // don't allow 0 items (it's checked during table load) + ASSERT(ConditionValue2); + bool checkBank = !!ConditionValue3; + condMeets = player->HasItemCount(ConditionValue1, ConditionValue2, checkBank); + } + break; } - break; - } case CONDITION_ITEM_EQUIPPED: - { - if (Player* player = object->ToPlayer()) - condMeets = player->HasItemOrGemWithIdEquipped(ConditionValue1, 1); - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = player->HasItemOrGemWithIdEquipped(ConditionValue1, 1); + break; + } case CONDITION_ZONEID: condMeets = object->GetZoneId() == ConditionValue1; break; case CONDITION_REPUTATION_RANK: - { - if (Player* player = object->ToPlayer()) { - if (FactionEntry const* faction = sFactionStore.LookupEntry(ConditionValue1)) - condMeets = (ConditionValue2 & (1 << player->GetReputationMgr().GetRank(faction))); + if (Player* player = object->ToPlayer()) + { + if (FactionEntry const* faction = sFactionStore.LookupEntry(ConditionValue1)) + condMeets = (ConditionValue2 & (1 << player->GetReputationMgr().GetRank(faction))); + } + break; } - break; - } case CONDITION_ACHIEVEMENT: - { - if (Player* player = object->ToPlayer()) - condMeets = player->HasAchieved(ConditionValue1); - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = player->HasAchieved(ConditionValue1); + break; + } case CONDITION_TEAM: - { - if (Player* player = object->ToPlayer()) { - // Xinef: DB Data compatibility... - uint32 teamOld = player->GetTeamId() == TEAM_ALLIANCE ? ALLIANCE : HORDE; - condMeets = teamOld == ConditionValue1; + if (Player* player = object->ToPlayer()) + { + // Xinef: DB Data compatibility... + uint32 teamOld = player->GetTeamId() == TEAM_ALLIANCE ? ALLIANCE : HORDE; + condMeets = teamOld == ConditionValue1; + } + break; } - break; - } case CONDITION_CLASS: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->getClassMask() & ConditionValue1; - break; - } + { + if (Unit* unit = object->ToUnit()) + condMeets = unit->getClassMask() & ConditionValue1; + break; + } case CONDITION_RACE: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->getRaceMask() & ConditionValue1; - break; - } + { + if (Unit* unit = object->ToUnit()) + condMeets = unit->getRaceMask() & ConditionValue1; + break; + } case CONDITION_GENDER: - { - if (Player* player = object->ToPlayer()) - condMeets = player->getGender() == ConditionValue1; - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = player->getGender() == ConditionValue1; + break; + } case CONDITION_SKILL: - { - if (Player* player = object->ToPlayer()) - condMeets = player->HasSkill(ConditionValue1) && player->GetBaseSkillValue(ConditionValue1) >= ConditionValue2; - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = player->HasSkill(ConditionValue1) && player->GetBaseSkillValue(ConditionValue1) >= ConditionValue2; + break; + } case CONDITION_QUESTREWARDED: - { - if (Player* player = object->ToPlayer()) - condMeets = player->GetQuestRewardStatus(ConditionValue1); - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = player->GetQuestRewardStatus(ConditionValue1); + break; + } case CONDITION_QUESTTAKEN: - { - if (Player* player = object->ToPlayer()) { - QuestStatus status = player->GetQuestStatus(ConditionValue1); - condMeets = (status == QUEST_STATUS_INCOMPLETE); + if (Player* player = object->ToPlayer()) + { + QuestStatus status = player->GetQuestStatus(ConditionValue1); + condMeets = (status == QUEST_STATUS_INCOMPLETE); + } + break; } - break; - } case CONDITION_QUEST_COMPLETE: - { - if (Player* player = object->ToPlayer()) { - QuestStatus status = player->GetQuestStatus(ConditionValue1); - condMeets = (status == QUEST_STATUS_COMPLETE && !player->GetQuestRewardStatus(ConditionValue1)); + if (Player* player = object->ToPlayer()) + { + QuestStatus status = player->GetQuestStatus(ConditionValue1); + condMeets = (status == QUEST_STATUS_COMPLETE && !player->GetQuestRewardStatus(ConditionValue1)); + } + break; } - break; - } case CONDITION_QUEST_NONE: - { - if (Player* player = object->ToPlayer()) { - QuestStatus status = player->GetQuestStatus(ConditionValue1); - condMeets = (status == QUEST_STATUS_NONE); + if (Player* player = object->ToPlayer()) + { + QuestStatus status = player->GetQuestStatus(ConditionValue1); + condMeets = (status == QUEST_STATUS_NONE); + } + break; } - break; - } case CONDITION_QUEST_SATISFY_EXCLUSIVE: - { - if (Player* player = object->ToPlayer()) { - // Xinef: cannot be null, checked at loading - const Quest* quest = sObjectMgr->GetQuestTemplate(ConditionValue1); - condMeets = !player->IsQuestRewarded(ConditionValue1) && player->SatisfyQuestExclusiveGroup(quest, false); + if (Player* player = object->ToPlayer()) + { + // Xinef: cannot be null, checked at loading + const Quest* quest = sObjectMgr->GetQuestTemplate(ConditionValue1); + condMeets = !player->IsQuestRewarded(ConditionValue1) && player->SatisfyQuestExclusiveGroup(quest, false); + } + break; } - break; - } case CONDITION_ACTIVE_EVENT: condMeets = sGameEventMgr->IsActiveEvent(ConditionValue1); break; case CONDITION_INSTANCE_INFO: - { - Map* map = object->GetMap(); - if (map->IsDungeon()) { - if (InstanceScript const* instance = map->ToInstanceMap()->GetInstanceScript()) + Map* map = object->GetMap(); + if (map->IsDungeon()) { - switch (ConditionValue3) + if (InstanceScript const* instance = map->ToInstanceMap()->GetInstanceScript()) { - case INSTANCE_INFO_DATA: - condMeets = instance->GetData(ConditionValue1) == ConditionValue2; - break; - case INSTANCE_INFO_DATA64: - condMeets = instance->GetData64(ConditionValue1) == ConditionValue2; - break; - case INSTANCE_INFO_BOSS_STATE: - condMeets = instance->GetBossState(ConditionValue1) == EncounterState(ConditionValue2); - break; + switch (ConditionValue3) + { + case INSTANCE_INFO_DATA: + condMeets = instance->GetData(ConditionValue1) == ConditionValue2; + break; + case INSTANCE_INFO_DATA64: + condMeets = instance->GetData64(ConditionValue1) == ConditionValue2; + break; + case INSTANCE_INFO_BOSS_STATE: + condMeets = instance->GetBossState(ConditionValue1) == EncounterState(ConditionValue2); + break; + } } } + break; } - break; - } case CONDITION_MAPID: condMeets = object->GetMapId() == ConditionValue1; break; @@ -188,198 +188,198 @@ bool Condition::Meets(ConditionSourceInfo& sourceInfo) condMeets = object->GetAreaId() == ConditionValue1; break; case CONDITION_SPELL: - { - if (Player* player = object->ToPlayer()) - condMeets = player->HasSpell(ConditionValue1); - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = player->HasSpell(ConditionValue1); + break; + } case CONDITION_LEVEL: - { - if (Unit* unit = object->ToUnit()) - condMeets = CompareValues(static_cast(ConditionValue2), static_cast(unit->getLevel()), ConditionValue1); - break; - } + { + if (Unit* unit = object->ToUnit()) + condMeets = CompareValues(static_cast(ConditionValue2), static_cast(unit->getLevel()), ConditionValue1); + break; + } case CONDITION_DRUNKENSTATE: - { - if (Player* player = object->ToPlayer()) - condMeets = (uint32)Player::GetDrunkenstateByValue(player->GetDrunkValue()) >= ConditionValue1; - break; - } + { + if (Player* player = object->ToPlayer()) + condMeets = (uint32)Player::GetDrunkenstateByValue(player->GetDrunkValue()) >= ConditionValue1; + break; + } case CONDITION_NEAR_CREATURE: - { - condMeets = !!GetClosestCreatureWithEntry(object, ConditionValue1, (float)ConditionValue2, !ConditionValue3); - break; - } + { + condMeets = !!GetClosestCreatureWithEntry(object, ConditionValue1, (float)ConditionValue2, !ConditionValue3); + break; + } case CONDITION_NEAR_GAMEOBJECT: - { - condMeets = !!GetClosestGameObjectWithEntry(object, ConditionValue1, (float)ConditionValue2); - break; - } + { + condMeets = !!GetClosestGameObjectWithEntry(object, ConditionValue1, (float)ConditionValue2); + break; + } case CONDITION_OBJECT_ENTRY_GUID: - { - if (ConditionValue3 == 1 && object->ToUnit()) // pussywizard: if == 1, ignore not attackable/selectable targets - if (object->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE)) - break; - - if (uint32(object->GetTypeId()) == ConditionValue1) { - condMeets = !ConditionValue2 || (object->GetEntry() == ConditionValue2); + if (ConditionValue3 == 1 && object->ToUnit()) // pussywizard: if == 1, ignore not attackable/selectable targets + if (object->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE)) + break; - if (ConditionValue3 > 1) + if (uint32(object->GetTypeId()) == ConditionValue1) { - switch (object->GetTypeId()) + condMeets = !ConditionValue2 || (object->GetEntry() == ConditionValue2); + + if (ConditionValue3 > 1) { - case TYPEID_UNIT: - condMeets &= object->ToCreature()->GetDBTableGUIDLow() == ConditionValue3; - break; - case TYPEID_GAMEOBJECT: - condMeets &= object->ToGameObject()->GetDBTableGUIDLow() == ConditionValue3; - break; - default: - break; + switch (object->GetTypeId()) + { + case TYPEID_UNIT: + condMeets &= object->ToCreature()->GetDBTableGUIDLow() == ConditionValue3; + break; + case TYPEID_GAMEOBJECT: + condMeets &= object->ToGameObject()->GetDBTableGUIDLow() == ConditionValue3; + break; + default: + break; + } } } + break; } - break; - } case CONDITION_TYPE_MASK: - { - condMeets = object->isType(ConditionValue1); - break; - } - case CONDITION_RELATION_TO: - { - if (WorldObject* toObject = sourceInfo.mConditionTargets[ConditionValue1]) { - Unit* toUnit = toObject->ToUnit(); - Unit* unit = object->ToUnit(); - if (toUnit && unit) + condMeets = object->isType(ConditionValue1); + break; + } + case CONDITION_RELATION_TO: + { + if (WorldObject* toObject = sourceInfo.mConditionTargets[ConditionValue1]) { - switch (ConditionValue2) + Unit* toUnit = toObject->ToUnit(); + Unit* unit = object->ToUnit(); + if (toUnit && unit) { - case RELATION_SELF: - condMeets = unit == toUnit; - break; - case RELATION_IN_PARTY: - condMeets = unit->IsInPartyWith(toUnit); - break; - case RELATION_IN_RAID_OR_PARTY: - condMeets = unit->IsInRaidWith(toUnit); - break; - case RELATION_OWNED_BY: - condMeets = unit->GetOwnerGUID() == toUnit->GetGUID(); - break; - case RELATION_PASSENGER_OF: - condMeets = unit->IsOnVehicle(toUnit); - break; - case RELATION_CREATED_BY: - condMeets = unit->GetCreatorGUID() == toUnit->GetGUID(); - break; + switch (ConditionValue2) + { + case RELATION_SELF: + condMeets = unit == toUnit; + break; + case RELATION_IN_PARTY: + condMeets = unit->IsInPartyWith(toUnit); + break; + case RELATION_IN_RAID_OR_PARTY: + condMeets = unit->IsInRaidWith(toUnit); + break; + case RELATION_OWNED_BY: + condMeets = unit->GetOwnerGUID() == toUnit->GetGUID(); + break; + case RELATION_PASSENGER_OF: + condMeets = unit->IsOnVehicle(toUnit); + break; + case RELATION_CREATED_BY: + condMeets = unit->GetCreatorGUID() == toUnit->GetGUID(); + break; + } } } + break; } - break; - } case CONDITION_REACTION_TO: - { - if (WorldObject* toObject = sourceInfo.mConditionTargets[ConditionValue1]) { - Unit* toUnit = toObject->ToUnit(); - Unit* unit = object->ToUnit(); - if (toUnit && unit) - condMeets = (1 << unit->GetReactionTo(toUnit)) & ConditionValue2; + if (WorldObject* toObject = sourceInfo.mConditionTargets[ConditionValue1]) + { + Unit* toUnit = toObject->ToUnit(); + Unit* unit = object->ToUnit(); + if (toUnit && unit) + condMeets = (1 << unit->GetReactionTo(toUnit)) & ConditionValue2; + } + break; } - break; - } case CONDITION_DISTANCE_TO: - { - if (WorldObject* toObject = sourceInfo.mConditionTargets[ConditionValue1]) - condMeets = CompareValues(static_cast(ConditionValue3), object->GetDistance(toObject), static_cast(ConditionValue2)); - break; - } - case CONDITION_ALIVE: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->IsAlive(); - break; - } - case CONDITION_HP_VAL: - { - if (Unit* unit = object->ToUnit()) - condMeets = CompareValues(static_cast(ConditionValue2), unit->GetHealth(), static_cast(ConditionValue1)); - break; - } - case CONDITION_HP_PCT: - { - if (Unit* unit = object->ToUnit()) - condMeets = CompareValues(static_cast(ConditionValue2), unit->GetHealthPct(), static_cast(ConditionValue1)); - break; - } - case CONDITION_WORLD_STATE: - { - condMeets = ConditionValue2 == sWorld->getWorldState(ConditionValue1); - break; - } - case CONDITION_PHASEMASK: - { - condMeets = object->GetPhaseMask() & ConditionValue1; - break; - } - case CONDITION_TITLE: - { - if (Player* player = object->ToPlayer()) - condMeets = player->HasTitle(ConditionValue1); - break; - } - case CONDITION_SPAWNMASK: - { - condMeets = ((1 << object->GetMap()->GetSpawnMode()) & ConditionValue1); - break; - } - case CONDITION_UNIT_STATE: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->HasUnitState(ConditionValue1); - break; - } - case CONDITION_CREATURE_TYPE: - { - if (Creature* creature = object->ToCreature()) - condMeets = creature->GetCreatureTemplate()->type == ConditionValue1; - break; - } - case CONDITION_REALM_ACHIEVEMENT: - { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(ConditionValue1); - if (achievement && sAchievementMgr->IsRealmCompleted(achievement)) - condMeets = true; - break; - } - case CONDITION_IN_WATER: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->IsInWater(); - break; - } - case CONDITION_QUEST_OBJECTIVE_PROGRESS: - { - if (Player* player = object->ToPlayer()) { - const Quest* quest = ASSERT_NOTNULL(sObjectMgr->GetQuestTemplate(ConditionValue1)); - uint16 log_slot = player->FindQuestSlot(quest->GetQuestId()); - if (log_slot >= MAX_QUEST_LOG_SIZE) - break; - if (player->GetQuestSlotCounter(log_slot, ConditionValue2) == ConditionValue3) - condMeets = true; + if (WorldObject* toObject = sourceInfo.mConditionTargets[ConditionValue1]) + condMeets = CompareValues(static_cast(ConditionValue3), object->GetDistance(toObject), static_cast(ConditionValue2)); + break; + } + case CONDITION_ALIVE: + { + if (Unit* unit = object->ToUnit()) + condMeets = unit->IsAlive(); + break; + } + case CONDITION_HP_VAL: + { + if (Unit* unit = object->ToUnit()) + condMeets = CompareValues(static_cast(ConditionValue2), unit->GetHealth(), static_cast(ConditionValue1)); + break; + } + case CONDITION_HP_PCT: + { + if (Unit* unit = object->ToUnit()) + condMeets = CompareValues(static_cast(ConditionValue2), unit->GetHealthPct(), static_cast(ConditionValue1)); + break; + } + case CONDITION_WORLD_STATE: + { + condMeets = ConditionValue2 == sWorld->getWorldState(ConditionValue1); + break; + } + case CONDITION_PHASEMASK: + { + condMeets = object->GetPhaseMask() & ConditionValue1; + break; + } + case CONDITION_TITLE: + { + if (Player* player = object->ToPlayer()) + condMeets = player->HasTitle(ConditionValue1); + break; + } + case CONDITION_SPAWNMASK: + { + condMeets = ((1 << object->GetMap()->GetSpawnMode()) & ConditionValue1); + break; + } + case CONDITION_UNIT_STATE: + { + if (Unit* unit = object->ToUnit()) + condMeets = unit->HasUnitState(ConditionValue1); + break; + } + case CONDITION_CREATURE_TYPE: + { + if (Creature* creature = object->ToCreature()) + condMeets = creature->GetCreatureTemplate()->type == ConditionValue1; + break; + } + case CONDITION_REALM_ACHIEVEMENT: + { + AchievementEntry const* achievement = sAchievementStore.LookupEntry(ConditionValue1); + if (achievement && sAchievementMgr->IsRealmCompleted(achievement)) + condMeets = true; + break; + } + case CONDITION_IN_WATER: + { + if (Unit* unit = object->ToUnit()) + condMeets = unit->IsInWater(); + break; + } + case CONDITION_QUEST_OBJECTIVE_PROGRESS: + { + if (Player* player = object->ToPlayer()) + { + const Quest* quest = ASSERT_NOTNULL(sObjectMgr->GetQuestTemplate(ConditionValue1)); + uint16 log_slot = player->FindQuestSlot(quest->GetQuestId()); + if (log_slot >= MAX_QUEST_LOG_SIZE) + break; + if (player->GetQuestSlotCounter(log_slot, ConditionValue2) == ConditionValue3) + condMeets = true; + } + break; } - break; - } case CONDITION_HAS_AURA_TYPE: - { - if (Unit* unit = object->ToUnit()) - condMeets = unit->HasAuraType(AuraType(ConditionValue1)); - break; - } + { + if (Unit* unit = object->ToUnit()) + condMeets = unit->HasAuraType(AuraType(ConditionValue1)); + break; + } default: condMeets = false; break; @@ -797,7 +797,7 @@ ConditionList ConditionMgr::GetConditionsForVehicleSpell(uint32 creatureId, uint CreatureSpellConditionContainer::const_iterator itr = VehicleSpellConditionStore.find(creatureId); if (itr != VehicleSpellConditionStore.end()) { - ConditionTypeContainer::const_iterator i = (*itr).second.find(spellId); + ConditionTypeContainer::const_iterator i = (*itr).second.find(spellId); if (i != (*itr).second.end()) { cond = (*i).second; @@ -875,7 +875,7 @@ void ConditionMgr::LoadConditions(bool isReload) } QueryResult result = WorldDatabase.Query("SELECT SourceTypeOrReferenceId, SourceGroup, SourceEntry, SourceId, ElseGroup, ConditionTypeOrReference, ConditionTarget, " - " ConditionValue1, ConditionValue2, ConditionValue3, NegativeCondition, ErrorType, ErrorTextId, ScriptName FROM conditions"); + " ConditionValue1, ConditionValue2, ConditionValue3, NegativeCondition, ErrorType, ErrorTextId, ScriptName FROM conditions"); if (!result) { @@ -1042,38 +1042,38 @@ void ConditionMgr::LoadConditions(bool isReload) valid = addToGossipMenuItems(cond); break; case CONDITION_SOURCE_TYPE_SPELL_CLICK_EVENT: - { - SpellClickEventConditionStore[cond->SourceGroup][cond->SourceEntry].push_back(cond); - valid = true; - ++count; - continue; // do not add to m_AllocatedMemory to avoid double deleting - } + { + SpellClickEventConditionStore[cond->SourceGroup][cond->SourceEntry].push_back(cond); + valid = true; + ++count; + continue; // do not add to m_AllocatedMemory to avoid double deleting + } case CONDITION_SOURCE_TYPE_SPELL_IMPLICIT_TARGET: valid = addToSpellImplicitTargetConditions(cond); break; case CONDITION_SOURCE_TYPE_VEHICLE_SPELL: - { - VehicleSpellConditionStore[cond->SourceGroup][cond->SourceEntry].push_back(cond); - valid = true; - ++count; - continue; // do not add to m_AllocatedMemory to avoid double deleting - } + { + VehicleSpellConditionStore[cond->SourceGroup][cond->SourceEntry].push_back(cond); + valid = true; + ++count; + continue; // do not add to m_AllocatedMemory to avoid double deleting + } case CONDITION_SOURCE_TYPE_SMART_EVENT: - { - //! TODO: PAIR_32 ? - std::pair key = std::make_pair(cond->SourceEntry, cond->SourceId); - SmartEventConditionStore[key][cond->SourceGroup].push_back(cond); - valid = true; - ++count; - continue; - } + { + //! TODO: PAIR_32 ? + std::pair key = std::make_pair(cond->SourceEntry, cond->SourceId); + SmartEventConditionStore[key][cond->SourceGroup].push_back(cond); + valid = true; + ++count; + continue; + } case CONDITION_SOURCE_TYPE_NPC_VENDOR: - { - NpcVendorConditionContainerStore[cond->SourceGroup][cond->SourceEntry].push_back(cond); - valid = true; - ++count; - continue; - } + { + NpcVendorConditionContainerStore[cond->SourceGroup][cond->SourceEntry].push_back(cond); + valid = true; + ++count; + continue; + } default: break; } @@ -1109,8 +1109,7 @@ void ConditionMgr::LoadConditions(bool isReload) //add new Condition to storage based on Type/Entry ConditionStore[cond->SourceType][cond->SourceEntry].push_back(cond); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u conditions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1182,7 +1181,7 @@ bool ConditionMgr::addToSpellImplicitTargetConditions(Condition* cond) bool found = false; for (std::list::iterator itr = sharedMasks.begin(); itr != sharedMasks.end(); ++itr) { - if ((1<Effects[i].ImplicitTargetConditions; - for (uint8 effIndex = i+1; effIndex < MAX_SPELL_EFFECTS; ++effIndex) + for (uint8 effIndex = i + 1; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { if (spellInfo->Effects[effIndex].ImplicitTargetConditions == cmp) - sharedMask |= 1<= MAX_SPELL_EFFECTS) @@ -1225,7 +1224,7 @@ bool ConditionMgr::addToSpellImplicitTargetConditions(Condition* cond) if (conditionEffMask != *itr) { sLog->outErrorDb("SourceEntry %u in `condition` table, has incorrect SourceGroup %u (spell effectMask) set - " - "effect masks are overlapping (all SourceGroup values having given bit set must be equal) - ignoring.", cond->SourceEntry, cond->SourceGroup); + "effect masks are overlapping (all SourceGroup values having given bit set must be equal) - ignoring.", cond->SourceEntry, cond->SourceGroup); return false; } } @@ -1237,7 +1236,7 @@ bool ConditionMgr::addToSpellImplicitTargetConditions(Condition* cond) bool assigned = false; for (uint8 i = firstEffIndex; i < MAX_SPELL_EFFECTS; ++i) { - if ((1<Effects[i].ImplicitTargetConditions = sharedList; assigned = true; @@ -1268,290 +1267,290 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) case CONDITION_SOURCE_TYPE_TERRAIN_SWAP: case CONDITION_SOURCE_TYPE_PHASE: case CONDITION_SOURCE_TYPE_GRAVEYARD: - { - sLog->outErrorDb("ConditionSourceType %u in `condition` table is not supported on 3.3.5a, ignoring.", uint32(cond->SourceType)); - return false; - } + { + sLog->outErrorDb("ConditionSourceType %u in `condition` table is not supported on 3.3.5a, ignoring.", uint32(cond->SourceType)); + return false; + } case CONDITION_SOURCE_TYPE_CREATURE_LOOT_TEMPLATE: - { - if (!LootTemplates_Creature.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `creature_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Creature.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `creature_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Creature.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Creature.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_DISENCHANT_LOOT_TEMPLATE: - { - if (!LootTemplates_Disenchant.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `disenchant_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Disenchant.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `disenchant_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Disenchant.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Disenchant.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_FISHING_LOOT_TEMPLATE: - { - if (!LootTemplates_Fishing.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `fishing_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Fishing.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `fishing_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Fishing.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Fishing.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_GAMEOBJECT_LOOT_TEMPLATE: - { - if (!LootTemplates_Gameobject.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `gameobject_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Gameobject.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `gameobject_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Gameobject.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Gameobject.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_ITEM_LOOT_TEMPLATE: - { - if (!LootTemplates_Item.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `item_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Item.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `item_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Item.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Item.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_MAIL_LOOT_TEMPLATE: - { - if (!LootTemplates_Mail.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `mail_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Mail.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `mail_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Mail.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Mail.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_MILLING_LOOT_TEMPLATE: - { - if (!LootTemplates_Milling.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `milling_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Milling.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `milling_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Milling.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Milling.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_PICKPOCKETING_LOOT_TEMPLATE: - { - if (!LootTemplates_Pickpocketing.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `pickpocketing_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Pickpocketing.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `pickpocketing_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Pickpocketing.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Pickpocketing.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_PROSPECTING_LOOT_TEMPLATE: - { - if (!LootTemplates_Prospecting.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `prospecting_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Prospecting.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `prospecting_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Prospecting.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Prospecting.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_REFERENCE_LOOT_TEMPLATE: - { - if (!LootTemplates_Reference.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `reference_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Reference.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `reference_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Reference.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Reference.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_SKINNING_LOOT_TEMPLATE: - { - if (!LootTemplates_Skinning.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `skinning_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Skinning.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `skinning_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Skinning.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Skinning.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_SPELL_LOOT_TEMPLATE: - { - if (!LootTemplates_Spell.HaveLootFor(cond->SourceGroup)) { - sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `spell_loot_template`, ignoring.", cond->SourceGroup); - return false; - } + if (!LootTemplates_Spell.HaveLootFor(cond->SourceGroup)) + { + sLog->outErrorDb("SourceGroup %u in `condition` table, does not exist in `spell_loot_template`, ignoring.", cond->SourceGroup); + return false; + } - LootTemplate* loot = LootTemplates_Spell.GetLootForConditionFill(cond->SourceGroup); - ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!pItemProto && !loot->isReference(cond->SourceEntry)) - { - sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); - return false; + LootTemplate* loot = LootTemplates_Spell.GetLootForConditionFill(cond->SourceGroup); + ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!pItemProto && !loot->isReference(cond->SourceEntry)) + { + sLog->outErrorDb("SourceType %u, SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_SPELL_IMPLICIT_TARGET: - { - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(cond->SourceEntry); - if (!spellInfo) { - sLog->outErrorDb("SourceEntry %u in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); - return false; - } - - if ((cond->SourceGroup > MAX_EFFECT_MASK) || !cond->SourceGroup) - { - sLog->outErrorDb("SourceEntry %u in `condition` table, has incorrect SourceGroup %u (spell effectMask) set , ignoring.", cond->SourceEntry, cond->SourceGroup); - return false; - } - - uint32 origGroup = cond->SourceGroup; - - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - { - if (!((1<SourceGroup)) - continue; - - switch (spellInfo->Effects[i].TargetA.GetSelectionCategory()) + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(cond->SourceEntry); + if (!spellInfo) { - case TARGET_SELECT_CATEGORY_NEARBY: - case TARGET_SELECT_CATEGORY_CONE: - case TARGET_SELECT_CATEGORY_AREA: - case TARGET_SELECT_CATEGORY_TRAJ: - continue; - default: - break; + sLog->outErrorDb("SourceEntry %u in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); + return false; } - switch (spellInfo->Effects[i].TargetB.GetSelectionCategory()) + if ((cond->SourceGroup > MAX_EFFECT_MASK) || !cond->SourceGroup) { - case TARGET_SELECT_CATEGORY_NEARBY: - case TARGET_SELECT_CATEGORY_CONE: - case TARGET_SELECT_CATEGORY_AREA: - case TARGET_SELECT_CATEGORY_TRAJ: - continue; - default: - break; + sLog->outErrorDb("SourceEntry %u in `condition` table, has incorrect SourceGroup %u (spell effectMask) set , ignoring.", cond->SourceEntry, cond->SourceGroup); + return false; } - // Xinef: chain targets are treated as area targets! Apply conditions! - if (spellInfo->Effects[i].ChainTarget > 1) - continue; + uint32 origGroup = cond->SourceGroup; - sLog->outErrorDb("SourceEntry %u SourceGroup %u in `condition` table - spell %u does not have implicit targets of types: _AREA_, _CONE_, _NEARBY_ for effect %u, SourceGroup needs correction, ignoring.", cond->SourceEntry, origGroup, cond->SourceEntry, uint32(i)); - cond->SourceGroup &= ~(1<SourceGroup)) + continue; + + switch (spellInfo->Effects[i].TargetA.GetSelectionCategory()) + { + case TARGET_SELECT_CATEGORY_NEARBY: + case TARGET_SELECT_CATEGORY_CONE: + case TARGET_SELECT_CATEGORY_AREA: + case TARGET_SELECT_CATEGORY_TRAJ: + continue; + default: + break; + } + + switch (spellInfo->Effects[i].TargetB.GetSelectionCategory()) + { + case TARGET_SELECT_CATEGORY_NEARBY: + case TARGET_SELECT_CATEGORY_CONE: + case TARGET_SELECT_CATEGORY_AREA: + case TARGET_SELECT_CATEGORY_TRAJ: + continue; + default: + break; + } + + // Xinef: chain targets are treated as area targets! Apply conditions! + if (spellInfo->Effects[i].ChainTarget > 1) + continue; + + sLog->outErrorDb("SourceEntry %u SourceGroup %u in `condition` table - spell %u does not have implicit targets of types: _AREA_, _CONE_, _NEARBY_ for effect %u, SourceGroup needs correction, ignoring.", cond->SourceEntry, origGroup, cond->SourceEntry, uint32(i)); + cond->SourceGroup &= ~(1 << i); + } + // all effects were removed, no need to add the condition at all + if (!cond->SourceGroup) + return false; + break; } - // all effects were removed, no need to add the condition at all - if (!cond->SourceGroup) - return false; - break; - } case CONDITION_SOURCE_TYPE_CREATURE_TEMPLATE_VEHICLE: - { - if (!sObjectMgr->GetCreatureTemplate(cond->SourceEntry)) { - sLog->outErrorDb("SourceEntry %u in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceEntry); - return false; + if (!sObjectMgr->GetCreatureTemplate(cond->SourceEntry)) + { + sLog->outErrorDb("SourceEntry %u in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_SPELL: case CONDITION_SOURCE_TYPE_SPELL_PROC: - { - SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(cond->SourceEntry); - if (!spellProto) { - sLog->outErrorDb("SourceEntry %u in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); - return false; + SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(cond->SourceEntry); + if (!spellProto) + { + sLog->outErrorDb("SourceEntry %u in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); + return false; + } + break; } - break; - } case CONDITION_SOURCE_TYPE_QUEST_AVAILABLE: if (!sObjectMgr->GetQuestTemplate(cond->SourceEntry)) { @@ -1577,20 +1576,20 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) } break; case CONDITION_SOURCE_TYPE_NPC_VENDOR: - { - if (!sObjectMgr->GetCreatureTemplate(cond->SourceGroup)) { - sLog->outError("SourceEntry %u in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceGroup); - return false; + if (!sObjectMgr->GetCreatureTemplate(cond->SourceGroup)) + { + sLog->outError("SourceEntry %u in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceGroup); + return false; + } + ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(cond->SourceEntry); + if (!itemTemplate) + { + sLog->outError("SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceEntry); + return false; + } + break; } - ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(cond->SourceEntry); - if (!itemTemplate) - { - sLog->outError("SourceEntry %u in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceEntry); - return false; - } - break; - } case CONDITION_SOURCE_TYPE_GOSSIP_MENU: case CONDITION_SOURCE_TYPE_GOSSIP_MENU_OPTION: case CONDITION_SOURCE_TYPE_SMART_EVENT: @@ -1604,15 +1603,16 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (cond->ConditionType == CONDITION_NONE - || (cond->ConditionType >= CONDITION_TC_END && cond->ConditionType <= CONDITION_AC_START) - || (cond->ConditionType >= CONDITION_AC_END) - ) + || (cond->ConditionType >= CONDITION_TC_END && cond->ConditionType <= CONDITION_AC_START) + || (cond->ConditionType >= CONDITION_AC_END) + ) { sLog->outErrorDb("SourceEntry %u in `condition` table has an invalid ConditionType (%u), ignoring.", cond->SourceEntry, uint32(cond->ConditionType)); return false; } - switch (cond->ConditionType) { + switch (cond->ConditionType) + { case CONDITION_TERRAIN_SWAP: case CONDITION_DIFFICULTY_ID: sLog->outErrorDb("SourceEntry %u in `condition` table has a ConditionType that is not supported on 3.3.5a (%u), ignoring.", @@ -1640,566 +1640,566 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) switch (cond->ConditionType) { case CONDITION_AURA: - { - if (!sSpellMgr->GetSpellInfo(cond->ConditionValue1)) { - sLog->outErrorDb("Aura condition has non existing spell (Id: %d), skipped", cond->ConditionValue1); - return false; - } + if (!sSpellMgr->GetSpellInfo(cond->ConditionValue1)) + { + sLog->outErrorDb("Aura condition has non existing spell (Id: %d), skipped", cond->ConditionValue1); + return false; + } - if (cond->ConditionValue2 > EFFECT_2) - { - sLog->outErrorDb("Aura condition has non existing effect index (%u) (must be 0..2), skipped", cond->ConditionValue2); - return false; + if (cond->ConditionValue2 > EFFECT_2) + { + sLog->outErrorDb("Aura condition has non existing effect index (%u) (must be 0..2), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("Aura condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue3) - sLog->outErrorDb("Aura condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_ITEM: - { - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(cond->ConditionValue1); - if (!proto) { - sLog->outErrorDb("Item condition has non existing item (%u), skipped", cond->ConditionValue1); - return false; - } + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(cond->ConditionValue1); + if (!proto) + { + sLog->outErrorDb("Item condition has non existing item (%u), skipped", cond->ConditionValue1); + return false; + } - if (!cond->ConditionValue2) - { - sLog->outErrorDb("Item condition has 0 set for item count in value2 (%u), skipped", cond->ConditionValue2); - return false; + if (!cond->ConditionValue2) + { + sLog->outErrorDb("Item condition has 0 set for item count in value2 (%u), skipped", cond->ConditionValue2); + return false; + } + break; } - break; - } case CONDITION_ITEM_EQUIPPED: - { - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(cond->ConditionValue1); - if (!proto) { - sLog->outErrorDb("ItemEquipped condition has non existing item (%u), skipped", cond->ConditionValue1); - return false; - } + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(cond->ConditionValue1); + if (!proto) + { + sLog->outErrorDb("ItemEquipped condition has non existing item (%u), skipped", cond->ConditionValue1); + return false; + } - if (cond->ConditionValue2) - sLog->outErrorDb("ItemEquipped condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("ItemEquipped condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } + if (cond->ConditionValue2) + sLog->outErrorDb("ItemEquipped condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("ItemEquipped condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } case CONDITION_ZONEID: - { - AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(cond->ConditionValue1); - if (!areaEntry) { - sLog->outErrorDb("ZoneID condition has non existing area (%u), skipped", cond->ConditionValue1); - return false; - } + AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(cond->ConditionValue1); + if (!areaEntry) + { + sLog->outErrorDb("ZoneID condition has non existing area (%u), skipped", cond->ConditionValue1); + return false; + } - if (areaEntry->zone != 0) - { - sLog->outErrorDb("ZoneID condition requires to be in area (%u) which is a subzone but zone expected, skipped", cond->ConditionValue1); - return false; - } + if (areaEntry->zone != 0) + { + sLog->outErrorDb("ZoneID condition requires to be in area (%u) which is a subzone but zone expected, skipped", cond->ConditionValue1); + return false; + } - if (cond->ConditionValue2) - sLog->outErrorDb("ZoneID condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("ZoneID condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } + if (cond->ConditionValue2) + sLog->outErrorDb("ZoneID condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("ZoneID condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } case CONDITION_REPUTATION_RANK: - { - FactionEntry const* factionEntry = sFactionStore.LookupEntry(cond->ConditionValue1); - if (!factionEntry) { - sLog->outErrorDb("Reputation condition has non existing faction (%u), skipped", cond->ConditionValue1); - return false; + FactionEntry const* factionEntry = sFactionStore.LookupEntry(cond->ConditionValue1); + if (!factionEntry) + { + sLog->outErrorDb("Reputation condition has non existing faction (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("Reputation condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue3) - sLog->outErrorDb("Reputation condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_TEAM: - { - if (cond->ConditionValue1 != ALLIANCE && cond->ConditionValue1 != HORDE) { - sLog->outErrorDb("Team condition specifies unknown team (%u), skipped", cond->ConditionValue1); - return false; - } + if (cond->ConditionValue1 != ALLIANCE && cond->ConditionValue1 != HORDE) + { + sLog->outErrorDb("Team condition specifies unknown team (%u), skipped", cond->ConditionValue1); + return false; + } - if (cond->ConditionValue2) - sLog->outErrorDb("Team condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Team condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } + if (cond->ConditionValue2) + sLog->outErrorDb("Team condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Team condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } case CONDITION_SKILL: - { - SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(cond->ConditionValue1); - if (!pSkill) { - sLog->outErrorDb("Skill condition specifies non-existing skill (%u), skipped", cond->ConditionValue1); - return false; - } + SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(cond->ConditionValue1); + if (!pSkill) + { + sLog->outErrorDb("Skill condition specifies non-existing skill (%u), skipped", cond->ConditionValue1); + return false; + } - if (cond->ConditionValue2 < 1 || cond->ConditionValue2 > sWorld->GetConfigMaxSkillValue()) - { - sLog->outErrorDb("Skill condition specifies invalid skill value (%u), skipped", cond->ConditionValue2); - return false; + if (cond->ConditionValue2 < 1 || cond->ConditionValue2 > sWorld->GetConfigMaxSkillValue()) + { + sLog->outErrorDb("Skill condition specifies invalid skill value (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("Skill condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue3) - sLog->outErrorDb("Skill condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_QUESTREWARDED: case CONDITION_QUESTTAKEN: case CONDITION_QUEST_NONE: case CONDITION_QUEST_COMPLETE: case CONDITION_QUEST_SATISFY_EXCLUSIVE: - { - if (!sObjectMgr->GetQuestTemplate(cond->ConditionValue1)) { - sLog->outErrorDb("Quest condition specifies non-existing quest (%u), skipped", cond->ConditionValue1); - return false; - } - - if (cond->ConditionValue2 > 1) - sLog->outErrorDb("Quest condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Quest condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_ACTIVE_EVENT: - { - GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); - if (cond->ConditionValue1 >=events.size() || !events[cond->ConditionValue1].isValid()) - { - sLog->outErrorDb("ActiveEvent condition has non existing event id (%u), skipped", cond->ConditionValue1); - return false; - } - - if (cond->ConditionValue2) - sLog->outErrorDb("ActiveEvent condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("ActiveEvent condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_ACHIEVEMENT: - { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(cond->ConditionValue1); - if (!achievement) - { - sLog->outErrorDb("Achivement condition has non existing achivement id (%u), skipped", cond->ConditionValue1); - return false; - } - - if (cond->ConditionValue2) - sLog->outErrorDb("Achivement condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Achivement condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_CLASS: - { - if (!(cond->ConditionValue1 & CLASSMASK_ALL_PLAYABLE)) - { - sLog->outErrorDb("Class condition has non existing classmask (%u), skipped", cond->ConditionValue1 & ~CLASSMASK_ALL_PLAYABLE); - return false; - } - - if (cond->ConditionValue2) - sLog->outErrorDb("Class condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Class condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_RACE: - { - if (!(cond->ConditionValue1 & RACEMASK_ALL_PLAYABLE)) - { - sLog->outErrorDb("Race condition has non existing racemask (%u), skipped", cond->ConditionValue1 & ~RACEMASK_ALL_PLAYABLE); - return false; - } - - if (cond->ConditionValue2) - sLog->outErrorDb("Race condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Race condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_GENDER: - { - if (!Player::IsValidGender(uint8(cond->ConditionValue1))) - { - sLog->outError("Gender condition has invalid gender (%u), skipped", cond->ConditionValue1); - return false; - } - - if (cond->ConditionValue2) - sLog->outError("Gender condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outError("Gender condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_MAPID: - { - MapEntry const* me = sMapStore.LookupEntry(cond->ConditionValue1); - if (!me) - { - sLog->outErrorDb("Map condition has non existing map (%u), skipped", cond->ConditionValue1); - return false; - } - - if (cond->ConditionValue2) - sLog->outErrorDb("Map condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Map condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_SPELL: - { - if (!sSpellMgr->GetSpellInfo(cond->ConditionValue1)) - { - sLog->outErrorDb("Spell condition has non existing spell (Id: %d), skipped", cond->ConditionValue1); - return false; - } - - if (cond->ConditionValue2) - sLog->outErrorDb("Spell condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Spell condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_LEVEL: - { - if (cond->ConditionValue2 >= COMP_TYPE_MAX) - { - sLog->outErrorDb("Level condition has invalid option (%u), skipped", cond->ConditionValue2); - return false; - } - if (cond->ConditionValue3) - sLog->outErrorDb("Level condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_DRUNKENSTATE: - { - if (cond->ConditionValue1 > DRUNKEN_SMASHED) - { - sLog->outErrorDb("DrunkState condition has invalid state (%u), skipped", cond->ConditionValue1); - return false; - } - if (cond->ConditionValue2) - { - sLog->outErrorDb("DrunkState condition has useless data in value2 (%u)!", cond->ConditionValue2); - return false; - } - if (cond->ConditionValue3) - sLog->outErrorDb("DrunkState condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_NEAR_CREATURE: - { - if (!sObjectMgr->GetCreatureTemplate(cond->ConditionValue1)) - { - sLog->outErrorDb("NearCreature condition has non existing creature template entry (%u), skipped", cond->ConditionValue1); - return false; - } - break; - } - case CONDITION_NEAR_GAMEOBJECT: - { - if (!sObjectMgr->GetGameObjectTemplate(cond->ConditionValue1)) - { - sLog->outErrorDb("NearGameObject condition has non existing gameobject template entry (%u), skipped", cond->ConditionValue1); - return false; - } - if (cond->ConditionValue3) - sLog->outErrorDb("NearGameObject condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } - case CONDITION_OBJECT_ENTRY_GUID: - { - switch (cond->ConditionValue1) - { - case TYPEID_UNIT: - if (cond->ConditionValue2 && !sObjectMgr->GetCreatureTemplate(cond->ConditionValue2)) - { - sLog->outErrorDb("ObjectEntryGuid condition has non existing creature template entry (%u), skipped", cond->ConditionValue2); - return false; - } - if (cond->ConditionValue3 > 1) - { - if (CreatureData const* creatureData = sObjectMgr->GetCreatureData(cond->ConditionValue3)) - { - if (cond->ConditionValue2 && creatureData->id != cond->ConditionValue2) - { - sLog->outErrorDb("ObjectEntryGuid condition has guid %u set but does not match creature entry (%u), skipped", cond->ConditionValue3, cond->ConditionValue2); - return false; - } - } - else - { - sLog->outErrorDb("ObjectEntryGuid condition has non existing creature guid (%u), skipped", cond->ConditionValue3); - return false; - } - } - break; - case TYPEID_GAMEOBJECT: - if (cond->ConditionValue2 && !sObjectMgr->GetGameObjectTemplate(cond->ConditionValue2)) - { - sLog->outErrorDb("ObjectEntryGuid condition has non existing gameobject template entry (%u), skipped", cond->ConditionValue2); - return false; - } - if (cond->ConditionValue3) - { - if (GameObjectData const* goData = sObjectMgr->GetGOData(cond->ConditionValue3)) - { - if (cond->ConditionValue2 && goData->id != cond->ConditionValue2) - { - sLog->outErrorDb("ObjectEntryGuid condition has guid %u set but does not match gameobject entry (%u), skipped", cond->ConditionValue3, cond->ConditionValue2); - return false; - } - } - else - { - sLog->outErrorDb("ObjectEntryGuid condition has non existing gameobject guid (%u), skipped", cond->ConditionValue3); - return false; - } - } - break; - case TYPEID_PLAYER: - case TYPEID_CORPSE: - if (cond->ConditionValue2) - sLog->outErrorDb("ObjectEntryGuid condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("ObjectEntryGuid condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - default: - sLog->outErrorDb("ObjectEntryGuid condition has wrong typeid set (%u), skipped", cond->ConditionValue1); + if (!sObjectMgr->GetQuestTemplate(cond->ConditionValue1)) + { + sLog->outErrorDb("Quest condition specifies non-existing quest (%u), skipped", cond->ConditionValue1); return false; + } + + if (cond->ConditionValue2 > 1) + sLog->outErrorDb("Quest condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Quest condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_ACTIVE_EVENT: + { + GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); + if (cond->ConditionValue1 >= events.size() || !events[cond->ConditionValue1].isValid()) + { + sLog->outErrorDb("ActiveEvent condition has non existing event id (%u), skipped", cond->ConditionValue1); + return false; + } + + if (cond->ConditionValue2) + sLog->outErrorDb("ActiveEvent condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("ActiveEvent condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_ACHIEVEMENT: + { + AchievementEntry const* achievement = sAchievementStore.LookupEntry(cond->ConditionValue1); + if (!achievement) + { + sLog->outErrorDb("Achivement condition has non existing achivement id (%u), skipped", cond->ConditionValue1); + return false; + } + + if (cond->ConditionValue2) + sLog->outErrorDb("Achivement condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Achivement condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_CLASS: + { + if (!(cond->ConditionValue1 & CLASSMASK_ALL_PLAYABLE)) + { + sLog->outErrorDb("Class condition has non existing classmask (%u), skipped", cond->ConditionValue1 & ~CLASSMASK_ALL_PLAYABLE); + return false; + } + + if (cond->ConditionValue2) + sLog->outErrorDb("Class condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Class condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_RACE: + { + if (!(cond->ConditionValue1 & RACEMASK_ALL_PLAYABLE)) + { + sLog->outErrorDb("Race condition has non existing racemask (%u), skipped", cond->ConditionValue1 & ~RACEMASK_ALL_PLAYABLE); + return false; + } + + if (cond->ConditionValue2) + sLog->outErrorDb("Race condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Race condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_GENDER: + { + if (!Player::IsValidGender(uint8(cond->ConditionValue1))) + { + sLog->outError("Gender condition has invalid gender (%u), skipped", cond->ConditionValue1); + return false; + } + + if (cond->ConditionValue2) + sLog->outError("Gender condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outError("Gender condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_MAPID: + { + MapEntry const* me = sMapStore.LookupEntry(cond->ConditionValue1); + if (!me) + { + sLog->outErrorDb("Map condition has non existing map (%u), skipped", cond->ConditionValue1); + return false; + } + + if (cond->ConditionValue2) + sLog->outErrorDb("Map condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Map condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_SPELL: + { + if (!sSpellMgr->GetSpellInfo(cond->ConditionValue1)) + { + sLog->outErrorDb("Spell condition has non existing spell (Id: %d), skipped", cond->ConditionValue1); + return false; + } + + if (cond->ConditionValue2) + sLog->outErrorDb("Spell condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Spell condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_LEVEL: + { + if (cond->ConditionValue2 >= COMP_TYPE_MAX) + { + sLog->outErrorDb("Level condition has invalid option (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("Level condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_DRUNKENSTATE: + { + if (cond->ConditionValue1 > DRUNKEN_SMASHED) + { + sLog->outErrorDb("DrunkState condition has invalid state (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue2) + { + sLog->outErrorDb("DrunkState condition has useless data in value2 (%u)!", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("DrunkState condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_NEAR_CREATURE: + { + if (!sObjectMgr->GetCreatureTemplate(cond->ConditionValue1)) + { + sLog->outErrorDb("NearCreature condition has non existing creature template entry (%u), skipped", cond->ConditionValue1); + return false; + } + break; + } + case CONDITION_NEAR_GAMEOBJECT: + { + if (!sObjectMgr->GetGameObjectTemplate(cond->ConditionValue1)) + { + sLog->outErrorDb("NearGameObject condition has non existing gameobject template entry (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("NearGameObject condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } + case CONDITION_OBJECT_ENTRY_GUID: + { + switch (cond->ConditionValue1) + { + case TYPEID_UNIT: + if (cond->ConditionValue2 && !sObjectMgr->GetCreatureTemplate(cond->ConditionValue2)) + { + sLog->outErrorDb("ObjectEntryGuid condition has non existing creature template entry (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3 > 1) + { + if (CreatureData const* creatureData = sObjectMgr->GetCreatureData(cond->ConditionValue3)) + { + if (cond->ConditionValue2 && creatureData->id != cond->ConditionValue2) + { + sLog->outErrorDb("ObjectEntryGuid condition has guid %u set but does not match creature entry (%u), skipped", cond->ConditionValue3, cond->ConditionValue2); + return false; + } + } + else + { + sLog->outErrorDb("ObjectEntryGuid condition has non existing creature guid (%u), skipped", cond->ConditionValue3); + return false; + } + } + break; + case TYPEID_GAMEOBJECT: + if (cond->ConditionValue2 && !sObjectMgr->GetGameObjectTemplate(cond->ConditionValue2)) + { + sLog->outErrorDb("ObjectEntryGuid condition has non existing gameobject template entry (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + { + if (GameObjectData const* goData = sObjectMgr->GetGOData(cond->ConditionValue3)) + { + if (cond->ConditionValue2 && goData->id != cond->ConditionValue2) + { + sLog->outErrorDb("ObjectEntryGuid condition has guid %u set but does not match gameobject entry (%u), skipped", cond->ConditionValue3, cond->ConditionValue2); + return false; + } + } + else + { + sLog->outErrorDb("ObjectEntryGuid condition has non existing gameobject guid (%u), skipped", cond->ConditionValue3); + return false; + } + } + break; + case TYPEID_PLAYER: + case TYPEID_CORPSE: + if (cond->ConditionValue2) + sLog->outErrorDb("ObjectEntryGuid condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("ObjectEntryGuid condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + default: + sLog->outErrorDb("ObjectEntryGuid condition has wrong typeid set (%u), skipped", cond->ConditionValue1); + return false; + } + break; } - break; - } case CONDITION_TYPE_MASK: - { - if (!cond->ConditionValue1 || (cond->ConditionValue1 & ~(TYPEMASK_UNIT | TYPEMASK_PLAYER | TYPEMASK_GAMEOBJECT | TYPEMASK_CORPSE))) { - sLog->outErrorDb("TypeMask condition has invalid typemask set (%u), skipped", cond->ConditionValue2); - return false; + if (!cond->ConditionValue1 || (cond->ConditionValue1 & ~(TYPEMASK_UNIT | TYPEMASK_PLAYER | TYPEMASK_GAMEOBJECT | TYPEMASK_CORPSE))) + { + sLog->outErrorDb("TypeMask condition has invalid typemask set (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue2) + sLog->outErrorDb("TypeMask condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("TypeMask condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue2) - sLog->outErrorDb("TypeMask condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("TypeMask condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_RELATION_TO: - { - if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) { - sLog->outErrorDb("RelationTo condition has invalid ConditionValue1(ConditionTarget selection) (%u), skipped", cond->ConditionValue1); - return false; + if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) + { + sLog->outErrorDb("RelationTo condition has invalid ConditionValue1(ConditionTarget selection) (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue1 == cond->ConditionTarget) + { + sLog->outErrorDb("RelationTo condition has ConditionValue1(ConditionTarget selection) set to self (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue2 >= RELATION_MAX) + { + sLog->outErrorDb("RelationTo condition has invalid ConditionValue2(RelationType) (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("RelationTo condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue1 == cond->ConditionTarget) - { - sLog->outErrorDb("RelationTo condition has ConditionValue1(ConditionTarget selection) set to self (%u), skipped", cond->ConditionValue1); - return false; - } - if (cond->ConditionValue2 >= RELATION_MAX) - { - sLog->outErrorDb("RelationTo condition has invalid ConditionValue2(RelationType) (%u), skipped", cond->ConditionValue2); - return false; - } - if (cond->ConditionValue3) - sLog->outErrorDb("RelationTo condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_REACTION_TO: - { - if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) { - sLog->outErrorDb("ReactionTo condition has invalid ConditionValue1(ConditionTarget selection) (%u), skipped", cond->ConditionValue1); - return false; + if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) + { + sLog->outErrorDb("ReactionTo condition has invalid ConditionValue1(ConditionTarget selection) (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue1 == cond->ConditionTarget) + { + sLog->outErrorDb("ReactionTo condition has ConditionValue1(ConditionTarget selection) set to self (%u), skipped", cond->ConditionValue1); + return false; + } + if (!cond->ConditionValue2) + { + sLog->outErrorDb("mConditionValue2 condition has invalid ConditionValue2(rankMask) (%u), skipped", cond->ConditionValue2); + return false; + } + break; } - if (cond->ConditionValue1 == cond->ConditionTarget) - { - sLog->outErrorDb("ReactionTo condition has ConditionValue1(ConditionTarget selection) set to self (%u), skipped", cond->ConditionValue1); - return false; - } - if (!cond->ConditionValue2) - { - sLog->outErrorDb("mConditionValue2 condition has invalid ConditionValue2(rankMask) (%u), skipped", cond->ConditionValue2); - return false; - } - break; - } case CONDITION_DISTANCE_TO: - { - if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) { - sLog->outErrorDb("DistanceTo condition has invalid ConditionValue1(ConditionTarget selection) (%u), skipped", cond->ConditionValue1); - return false; + if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) + { + sLog->outErrorDb("DistanceTo condition has invalid ConditionValue1(ConditionTarget selection) (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue1 == cond->ConditionTarget) + { + sLog->outErrorDb("DistanceTo condition has ConditionValue1(ConditionTarget selection) set to self (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue3 >= COMP_TYPE_MAX) + { + sLog->outErrorDb("DistanceTo condition has invalid ComparisionType (%u), skipped", cond->ConditionValue3); + return false; + } + break; } - if (cond->ConditionValue1 == cond->ConditionTarget) - { - sLog->outErrorDb("DistanceTo condition has ConditionValue1(ConditionTarget selection) set to self (%u), skipped", cond->ConditionValue1); - return false; - } - if (cond->ConditionValue3 >= COMP_TYPE_MAX) - { - sLog->outErrorDb("DistanceTo condition has invalid ComparisionType (%u), skipped", cond->ConditionValue3); - return false; - } - break; - } case CONDITION_ALIVE: - { - if (cond->ConditionValue1) - sLog->outErrorDb("Alive condition has useless data in value1 (%u)!", cond->ConditionValue1); - if (cond->ConditionValue2) - sLog->outErrorDb("Alive condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Alive condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } + { + if (cond->ConditionValue1) + sLog->outErrorDb("Alive condition has useless data in value1 (%u)!", cond->ConditionValue1); + if (cond->ConditionValue2) + sLog->outErrorDb("Alive condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Alive condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } case CONDITION_HP_VAL: - { - if (cond->ConditionValue2 >= COMP_TYPE_MAX) { - sLog->outErrorDb("HpVal condition has invalid ComparisionType (%u), skipped", cond->ConditionValue2); - return false; + if (cond->ConditionValue2 >= COMP_TYPE_MAX) + { + sLog->outErrorDb("HpVal condition has invalid ComparisionType (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("HpVal condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue3) - sLog->outErrorDb("HpVal condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_HP_PCT: - { - if (cond->ConditionValue1 > 100) { - sLog->outErrorDb("HpPct condition has too big percent value (%u), skipped", cond->ConditionValue1); - return false; + if (cond->ConditionValue1 > 100) + { + sLog->outErrorDb("HpPct condition has too big percent value (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue2 >= COMP_TYPE_MAX) + { + sLog->outErrorDb("HpPct condition has invalid ComparisionType (%u), skipped", cond->ConditionValue2); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("HpPct condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue2 >= COMP_TYPE_MAX) - { - sLog->outErrorDb("HpPct condition has invalid ComparisionType (%u), skipped", cond->ConditionValue2); - return false; - } - if (cond->ConditionValue3) - sLog->outErrorDb("HpPct condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_AREAID: case CONDITION_INSTANCE_INFO: break; case CONDITION_WORLD_STATE: - { - if (!sWorld->getWorldState(cond->ConditionValue1)) { - sLog->outErrorDb("World state condition has non existing world state in value1 (%u), skipped", cond->ConditionValue1); - return false; + if (!sWorld->getWorldState(cond->ConditionValue1)) + { + sLog->outErrorDb("World state condition has non existing world state in value1 (%u), skipped", cond->ConditionValue1); + return false; + } + if (cond->ConditionValue3) + sLog->outErrorDb("World state condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; } - if (cond->ConditionValue3) - sLog->outErrorDb("World state condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } case CONDITION_PHASEMASK: - { - if (cond->ConditionValue2) - sLog->outErrorDb("Phasemask condition has useless data in value2 (%u)!", cond->ConditionValue2); - if (cond->ConditionValue3) - sLog->outErrorDb("Phasemask condition has useless data in value3 (%u)!", cond->ConditionValue3); - break; - } + { + if (cond->ConditionValue2) + sLog->outErrorDb("Phasemask condition has useless data in value2 (%u)!", cond->ConditionValue2); + if (cond->ConditionValue3) + sLog->outErrorDb("Phasemask condition has useless data in value3 (%u)!", cond->ConditionValue3); + break; + } case CONDITION_TITLE: - { - CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(cond->ConditionValue1); - if (!titleEntry) { - sLog->outErrorDb("Title condition has non existing title in value1 (%u), skipped", cond->ConditionValue1); - return false; + CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(cond->ConditionValue1); + if (!titleEntry) + { + sLog->outErrorDb("Title condition has non existing title in value1 (%u), skipped", cond->ConditionValue1); + return false; + } + break; } - break; - } case CONDITION_SPAWNMASK: - { - if (cond->ConditionValue1 > SPAWNMASK_RAID_ALL) { - sLog->outError("SpawnMask condition has non existing SpawnMask in value1 (%u), skipped", cond->ConditionValue1); - return false; + if (cond->ConditionValue1 > SPAWNMASK_RAID_ALL) + { + sLog->outError("SpawnMask condition has non existing SpawnMask in value1 (%u), skipped", cond->ConditionValue1); + return false; + } + break; } - break; - } case CONDITION_UNIT_STATE: - { - if (!(cond->ConditionValue1 & UNIT_STATE_ALL_STATE_SUPPORTED)) { - sLog->outError("UnitState condition has non existing UnitState in value1 (%u), skipped", cond->ConditionValue1); - return false; + if (!(cond->ConditionValue1 & UNIT_STATE_ALL_STATE_SUPPORTED)) + { + sLog->outError("UnitState condition has non existing UnitState in value1 (%u), skipped", cond->ConditionValue1); + return false; + } + break; } - break; - } case CONDITION_CREATURE_TYPE: - { - if (!cond->ConditionValue1 || cond->ConditionValue1 > CREATURE_TYPE_GAS_CLOUD) { - sLog->outError("CreatureType condition has non existing CreatureType in value1 (%u), skipped", cond->ConditionValue1); - return false; + if (!cond->ConditionValue1 || cond->ConditionValue1 > CREATURE_TYPE_GAS_CLOUD) + { + sLog->outError("CreatureType condition has non existing CreatureType in value1 (%u), skipped", cond->ConditionValue1); + return false; + } + break; } - break; - } case CONDITION_REALM_ACHIEVEMENT: - { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(cond->ConditionValue1); - if (!achievement) { - sLog->outError("CONDITION_REALM_ACHIEVEMENT has non existing realm first achivement id (%u), skipped.", cond->ConditionValue1); - return false; + AchievementEntry const* achievement = sAchievementStore.LookupEntry(cond->ConditionValue1); + if (!achievement) + { + sLog->outError("CONDITION_REALM_ACHIEVEMENT has non existing realm first achivement id (%u), skipped.", cond->ConditionValue1); + return false; + } + break; } - break; - } case CONDITION_IN_WATER: - { - break; - } + { + break; + } case CONDITION_QUEST_OBJECTIVE_PROGRESS: - { - const Quest* quest = sObjectMgr->GetQuestTemplate(cond->ConditionValue1); - if (!quest) { - sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS points to non-existing quest (%u), skipped.", cond->ConditionValue1); - return false; - } + const Quest* quest = sObjectMgr->GetQuestTemplate(cond->ConditionValue1); + if (!quest) + { + sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS points to non-existing quest (%u), skipped.", cond->ConditionValue1); + return false; + } - if (cond->ConditionValue2 > 3) - { - sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS has out-of-range quest objective index specified (%u), it must be a number between 0 and 3. skipped.", cond->ConditionValue2); - return false; - } + if (cond->ConditionValue2 > 3) + { + sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS has out-of-range quest objective index specified (%u), it must be a number between 0 and 3. skipped.", cond->ConditionValue2); + return false; + } - if (quest->RequiredNpcOrGo[cond->ConditionValue2] == 0) - { - sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective %u for quest %u, but the field RequiredNPCOrGo%u is 0, skipped.", cond->ConditionValue2, cond->ConditionValue1, cond->ConditionValue2); - return false; - } + if (quest->RequiredNpcOrGo[cond->ConditionValue2] == 0) + { + sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective %u for quest %u, but the field RequiredNPCOrGo%u is 0, skipped.", cond->ConditionValue2, cond->ConditionValue1, cond->ConditionValue2); + return false; + } - if (cond->ConditionValue3 > quest->RequiredNpcOrGoCount[cond->ConditionValue2]) - { - sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective count %u in value3, but quest %u has a maximum objective count of %u in RequiredNPCOrGOCount%u, skipped.", cond->ConditionValue3, cond->ConditionValue2, quest->RequiredNpcOrGoCount[cond->ConditionValue2], cond->ConditionValue2); - return false; + if (cond->ConditionValue3 > quest->RequiredNpcOrGoCount[cond->ConditionValue2]) + { + sLog->outErrorDb("CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective count %u in value3, but quest %u has a maximum objective count of %u in RequiredNPCOrGOCount%u, skipped.", cond->ConditionValue3, cond->ConditionValue2, quest->RequiredNpcOrGoCount[cond->ConditionValue2], cond->ConditionValue2); + return false; + } + break; } - break; - } case CONDITION_HAS_AURA_TYPE: - { - if (cond->ConditionValue1 == SPELL_AURA_NONE || cond->ConditionValue1 >= TOTAL_AURAS) { - sLog->outErrorDb("Has Aura Effect condition has non existing aura (%u), skipped", cond->ConditionValue1); - return false; + if (cond->ConditionValue1 == SPELL_AURA_NONE || cond->ConditionValue1 >= TOTAL_AURAS) + { + sLog->outErrorDb("Has Aura Effect condition has non existing aura (%u), skipped", cond->ConditionValue1); + return false; + } + break; } - break; - } default: break; } diff --git a/src/server/game/Conditions/ConditionMgr.h b/src/server/game/Conditions/ConditionMgr.h index ebfcdf6f6..b562c93f6 100644 --- a/src/server/game/Conditions/ConditionMgr.h +++ b/src/server/game/Conditions/ConditionMgr.h @@ -19,7 +19,8 @@ class LootTemplate; struct Condition; enum ConditionTypes -{ // value1 value2 value3 +{ + // value1 value2 value3 CONDITION_NONE = 0, // 0 0 0 always true CONDITION_AURA = 1, // spell_id effindex use target? true if player (or target, if value3) has aura of spell_id with effect effindex CONDITION_ITEM = 2, // item_id count bank true if has #count of item_ids (if 'bank' is set it searches in bank slots too) @@ -228,46 +229,46 @@ typedef std::map ConditionReferenceContainer;//only used class ConditionMgr { - private: - ConditionMgr(); - ~ConditionMgr(); +private: + ConditionMgr(); + ~ConditionMgr(); - public: - static ConditionMgr* instance(); +public: + static ConditionMgr* instance(); - void LoadConditions(bool isReload = false); - bool isConditionTypeValid(Condition* cond); - ConditionList GetConditionReferences(uint32 refId); + void LoadConditions(bool isReload = false); + bool isConditionTypeValid(Condition* cond); + ConditionList GetConditionReferences(uint32 refId); - uint32 GetSearcherTypeMaskForConditionList(ConditionList const& conditions); - bool IsObjectMeetToConditions(WorldObject* object, ConditionList const& conditions); - bool IsObjectMeetToConditions(WorldObject* object1, WorldObject* object2, ConditionList const& conditions); - bool IsObjectMeetToConditions(ConditionSourceInfo& sourceInfo, ConditionList const& conditions); - bool CanHaveSourceGroupSet(ConditionSourceType sourceType) const; - bool CanHaveSourceIdSet(ConditionSourceType sourceType) const; - ConditionList GetConditionsForNotGroupedEntry(ConditionSourceType sourceType, uint32 entry); - ConditionList GetConditionsForSpellClickEvent(uint32 creatureId, uint32 spellId); - ConditionList GetConditionsForSmartEvent(int32 entryOrGuid, uint32 eventId, uint32 sourceType); - ConditionList GetConditionsForVehicleSpell(uint32 creatureId, uint32 spellId); - ConditionList GetConditionsForNpcVendorEvent(uint32 creatureId, uint32 itemId); + uint32 GetSearcherTypeMaskForConditionList(ConditionList const& conditions); + bool IsObjectMeetToConditions(WorldObject* object, ConditionList const& conditions); + bool IsObjectMeetToConditions(WorldObject* object1, WorldObject* object2, ConditionList const& conditions); + bool IsObjectMeetToConditions(ConditionSourceInfo& sourceInfo, ConditionList const& conditions); + bool CanHaveSourceGroupSet(ConditionSourceType sourceType) const; + bool CanHaveSourceIdSet(ConditionSourceType sourceType) const; + ConditionList GetConditionsForNotGroupedEntry(ConditionSourceType sourceType, uint32 entry); + ConditionList GetConditionsForSpellClickEvent(uint32 creatureId, uint32 spellId); + ConditionList GetConditionsForSmartEvent(int32 entryOrGuid, uint32 eventId, uint32 sourceType); + ConditionList GetConditionsForVehicleSpell(uint32 creatureId, uint32 spellId); + ConditionList GetConditionsForNpcVendorEvent(uint32 creatureId, uint32 itemId); - private: - bool isSourceTypeValid(Condition* cond); - bool addToLootTemplate(Condition* cond, LootTemplate* loot); - bool addToGossipMenus(Condition* cond); - bool addToGossipMenuItems(Condition* cond); - bool addToSpellImplicitTargetConditions(Condition* cond); - bool IsObjectMeetToConditionList(ConditionSourceInfo& sourceInfo, ConditionList const& conditions); +private: + bool isSourceTypeValid(Condition* cond); + bool addToLootTemplate(Condition* cond, LootTemplate* loot); + bool addToGossipMenus(Condition* cond); + bool addToGossipMenuItems(Condition* cond); + bool addToSpellImplicitTargetConditions(Condition* cond); + bool IsObjectMeetToConditionList(ConditionSourceInfo& sourceInfo, ConditionList const& conditions); - void Clean(); // free up resources - std::list AllocatedMemoryStore; // some garbage collection :) + void Clean(); // free up resources + std::list AllocatedMemoryStore; // some garbage collection :) - ConditionContainer ConditionStore; - ConditionReferenceContainer ConditionReferenceStore; - CreatureSpellConditionContainer VehicleSpellConditionStore; - CreatureSpellConditionContainer SpellClickEventConditionStore; - NpcVendorConditionContainer NpcVendorConditionContainerStore; - SmartEventConditionContainer SmartEventConditionStore; + ConditionContainer ConditionStore; + ConditionReferenceContainer ConditionReferenceStore; + CreatureSpellConditionContainer VehicleSpellConditionStore; + CreatureSpellConditionContainer SpellClickEventConditionStore; + NpcVendorConditionContainer NpcVendorConditionContainerStore; + SmartEventConditionContainer SmartEventConditionStore; }; #define sConditionMgr ConditionMgr::instance() diff --git a/src/server/game/Conditions/DisableMgr.cpp b/src/server/game/Conditions/DisableMgr.cpp index 6f58dd8bd..8bbac4d02 100644 --- a/src/server/game/Conditions/DisableMgr.cpp +++ b/src/server/game/Conditions/DisableMgr.cpp @@ -15,350 +15,349 @@ namespace DisableMgr { -namespace -{ - struct DisableData + namespace { - uint8 flags; - std::set params[2]; // params0, params1 - }; + struct DisableData + { + uint8 flags; + std::set params[2]; // params0, params1 + }; - // single disables here with optional data - typedef std::map DisableTypeMap; - // global disable map by source - typedef std::map DisableMap; + // single disables here with optional data + typedef std::map DisableTypeMap; + // global disable map by source + typedef std::map DisableMap; - DisableMap m_DisableMap; + DisableMap m_DisableMap; - uint8 MAX_DISABLE_TYPES = 9; -} - -void LoadDisables() -{ - uint32 oldMSTime = getMSTime(); - - // reload case - for (DisableMap::iterator itr = m_DisableMap.begin(); itr != m_DisableMap.end(); ++itr) - itr->second.clear(); - - m_DisableMap.clear(); - - QueryResult result = WorldDatabase.Query("SELECT sourceType, entry, flags, params_0, params_1 FROM disables"); - - uint32 total_count = 0; - - if (!result) - { - sLog->outString(">> Loaded 0 disables. DB table `disables` is empty!"); - sLog->outString(); - return; + uint8 MAX_DISABLE_TYPES = 9; } - Field* fields; - do + void LoadDisables() { - fields = result->Fetch(); - DisableType type = DisableType(fields[0].GetUInt32()); - if (type >= MAX_DISABLE_TYPES) + uint32 oldMSTime = getMSTime(); + + // reload case + for (DisableMap::iterator itr = m_DisableMap.begin(); itr != m_DisableMap.end(); ++itr) + itr->second.clear(); + + m_DisableMap.clear(); + + QueryResult result = WorldDatabase.Query("SELECT sourceType, entry, flags, params_0, params_1 FROM disables"); + + uint32 total_count = 0; + + if (!result) { - sLog->outErrorDb("Invalid type %u specified in `disables` table, skipped.", type); - continue; + sLog->outString(">> Loaded 0 disables. DB table `disables` is empty!"); + sLog->outString(); + return; } - uint32 entry = fields[1].GetUInt32(); - uint8 flags = fields[2].GetUInt8(); - std::string params_0 = fields[3].GetString(); - std::string params_1 = fields[4].GetString(); + Field* fields; + do + { + fields = result->Fetch(); + DisableType type = DisableType(fields[0].GetUInt32()); + if (type >= MAX_DISABLE_TYPES) + { + sLog->outErrorDb("Invalid type %u specified in `disables` table, skipped.", type); + continue; + } - DisableData data; - data.flags = flags; + uint32 entry = fields[1].GetUInt32(); + uint8 flags = fields[2].GetUInt8(); + std::string params_0 = fields[3].GetString(); + std::string params_1 = fields[4].GetString(); + + DisableData data; + data.flags = flags; + + switch (type) + { + case DISABLE_TYPE_GO_LOS: + if (!sObjectMgr->GetGameObjectTemplate(entry)) + { + sLog->outErrorDb("Gameobject entry %u from `disables` doesn't exist in dbc, skipped.", entry); + continue; + } + if (flags) + sLog->outErrorDb("Disable flags specified for gameobject %u, useless data.", entry); + break; + case DISABLE_TYPE_SPELL: + if (!(sSpellMgr->GetSpellInfo(entry) || flags & SPELL_DISABLE_DEPRECATED_SPELL)) + { + sLog->outErrorDb("Spell entry %u from `disables` doesn't exist in dbc, skipped.", entry); + continue; + } + + if (!flags || flags > MAX_SPELL_DISABLE_TYPE) + { + sLog->outErrorDb("Disable flags for spell %u are invalid, skipped.", entry); + continue; + } + + if (flags & SPELL_DISABLE_MAP) + { + Tokenizer tokens(params_0, ','); + for (uint8 i = 0; i < tokens.size(); ) + data.params[0].insert(atoi(tokens[i++])); + } + + if (flags & SPELL_DISABLE_AREA) + { + Tokenizer tokens(params_1, ','); + for (uint8 i = 0; i < tokens.size(); ) + data.params[1].insert(atoi(tokens[i++])); + } + + // xinef: if spell has disabled los, add flag + if (flags & SPELL_DISABLE_LOS) + { + SpellInfo* spellInfo = const_cast(sSpellMgr->GetSpellInfo(entry)); + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + } + + break; + // checked later + case DISABLE_TYPE_QUEST: + break; + case DISABLE_TYPE_MAP: + case DISABLE_TYPE_LFG_MAP: + { + MapEntry const* mapEntry = sMapStore.LookupEntry(entry); + if (!mapEntry) + { + sLog->outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry); + continue; + } + bool isFlagInvalid = false; + switch (mapEntry->map_type) + { + case MAP_COMMON: + if (flags) + isFlagInvalid = true; + break; + case MAP_INSTANCE: + case MAP_RAID: + if (flags & DUNGEON_STATUSFLAG_HEROIC && !GetMapDifficultyData(entry, DUNGEON_DIFFICULTY_HEROIC)) + isFlagInvalid = true; + else if (flags & RAID_STATUSFLAG_10MAN_HEROIC && !GetMapDifficultyData(entry, RAID_DIFFICULTY_10MAN_HEROIC)) + isFlagInvalid = true; + else if (flags & RAID_STATUSFLAG_25MAN_HEROIC && !GetMapDifficultyData(entry, RAID_DIFFICULTY_25MAN_HEROIC)) + isFlagInvalid = true; + break; + case MAP_BATTLEGROUND: + case MAP_ARENA: + sLog->outErrorDb("Battleground map %u specified to be disabled in map case, skipped.", entry); + continue; + } + if (isFlagInvalid) + { + sLog->outErrorDb("Disable flags for map %u are invalid, skipped.", entry); + continue; + } + break; + } + case DISABLE_TYPE_BATTLEGROUND: + if (!sBattlemasterListStore.LookupEntry(entry)) + { + sLog->outErrorDb("Battleground entry %u from `disables` doesn't exist in dbc, skipped.", entry); + continue; + } + if (flags) + sLog->outErrorDb("Disable flags specified for battleground %u, useless data.", entry); + break; + case DISABLE_TYPE_OUTDOORPVP: + if (entry > MAX_OUTDOORPVP_TYPES) + { + sLog->outErrorDb("OutdoorPvPTypes value %u from `disables` is invalid, skipped.", entry); + continue; + } + if (flags) + sLog->outErrorDb("Disable flags specified for outdoor PvP %u, useless data.", entry); + break; + case DISABLE_TYPE_ACHIEVEMENT_CRITERIA: + if (!sAchievementCriteriaStore.LookupEntry(entry)) + { + sLog->outErrorDb("Achievement Criteria entry %u from `disables` doesn't exist in dbc, skipped.", entry); + continue; + } + if (flags) + sLog->outErrorDb("Disable flags specified for Achievement Criteria %u, useless data.", entry); + break; + case DISABLE_TYPE_VMAP: + { + MapEntry const* mapEntry = sMapStore.LookupEntry(entry); + if (!mapEntry) + { + sLog->outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry); + continue; + } + switch (mapEntry->map_type) + { + case MAP_COMMON: + if (flags & VMAP_DISABLE_AREAFLAG) + sLog->outString("Areaflag disabled for world map %u.", entry); + if (flags & VMAP_DISABLE_LIQUIDSTATUS) + sLog->outString("Liquid status disabled for world map %u.", entry); + break; + case MAP_INSTANCE: + case MAP_RAID: + if (flags & VMAP_DISABLE_HEIGHT) + sLog->outString("Height disabled for instance map %u.", entry); + if (flags & VMAP_DISABLE_LOS) + sLog->outString("LoS disabled for instance map %u.", entry); + break; + case MAP_BATTLEGROUND: + if (flags & VMAP_DISABLE_HEIGHT) + sLog->outString("Height disabled for battleground map %u.", entry); + if (flags & VMAP_DISABLE_LOS) + sLog->outString("LoS disabled for battleground map %u.", entry); + break; + case MAP_ARENA: + if (flags & VMAP_DISABLE_HEIGHT) + sLog->outString("Height disabled for arena map %u.", entry); + if (flags & VMAP_DISABLE_LOS) + sLog->outString("LoS disabled for arena map %u.", entry); + break; + default: + break; + } + break; + } + default: + break; + } + + m_DisableMap[type].insert(DisableTypeMap::value_type(entry, data)); + ++total_count; + } while (result->NextRow()); + + sLog->outString(">> Loaded %u disables in %u ms", total_count, GetMSTimeDiffToNow(oldMSTime)); + sLog->outString(); + } + + void CheckQuestDisables() + { + uint32 oldMSTime = getMSTime(); + + uint32 count = m_DisableMap[DISABLE_TYPE_QUEST].size(); + if (!count) + { + sLog->outString(">> Checked 0 quest disables."); + sLog->outString(); + return; + } + + // check only quests, rest already done at startup + for (DisableTypeMap::iterator itr = m_DisableMap[DISABLE_TYPE_QUEST].begin(); itr != m_DisableMap[DISABLE_TYPE_QUEST].end();) + { + const uint32 entry = itr->first; + if (!sObjectMgr->GetQuestTemplate(entry)) + { + sLog->outErrorDb("Quest entry %u from `disables` doesn't exist, skipped.", entry); + m_DisableMap[DISABLE_TYPE_QUEST].erase(itr++); + continue; + } + if (itr->second.flags) + sLog->outErrorDb("Disable flags specified for quest %u, useless data.", entry); + ++itr; + } + + sLog->outString(">> Checked %u quest disables in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + sLog->outString(); + } + + bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags) + { + ASSERT(type < MAX_DISABLE_TYPES); + if (m_DisableMap[type].empty()) + return false; + + DisableTypeMap::iterator itr = m_DisableMap[type].find(entry); + if (itr == m_DisableMap[type].end()) // not disabled + return false; switch (type) { - case DISABLE_TYPE_GO_LOS: - if (!sObjectMgr->GetGameObjectTemplate(entry)) - { - sLog->outErrorDb("Gameobject entry %u from `disables` doesn't exist in dbc, skipped.", entry); - continue; - } - if (flags) - sLog->outErrorDb("Disable flags specified for gameobject %u, useless data.", entry); - break; case DISABLE_TYPE_SPELL: - if (!(sSpellMgr->GetSpellInfo(entry) || flags & SPELL_DISABLE_DEPRECATED_SPELL)) { - sLog->outErrorDb("Spell entry %u from `disables` doesn't exist in dbc, skipped.", entry); - continue; - } + uint8 spellFlags = itr->second.flags; + if (unit) + { + if ((spellFlags & SPELL_DISABLE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || + (unit->GetTypeId() == TYPEID_UNIT && ((unit->IsPet() && spellFlags & SPELL_DISABLE_PET) || spellFlags & SPELL_DISABLE_CREATURE))) + { + if (spellFlags & SPELL_DISABLE_MAP) + { + std::set const& mapIds = itr->second.params[0]; + if (mapIds.find(unit->GetMapId()) != mapIds.end()) + return true; // Spell is disabled on current map - if (!flags || flags > MAX_SPELL_DISABLE_TYPE) - { - sLog->outErrorDb("Disable flags for spell %u are invalid, skipped.", entry); - continue; - } + if (!(spellFlags & SPELL_DISABLE_AREA)) + return false; // Spell is disabled on another map, but not this one, return false - if (flags & SPELL_DISABLE_MAP) - { - Tokenizer tokens(params_0, ','); - for (uint8 i = 0; i < tokens.size(); ) - data.params[0].insert(atoi(tokens[i++])); - } + // Spell is disabled in an area, but not explicitly our current mapId. Continue processing. + } - if (flags & SPELL_DISABLE_AREA) - { - Tokenizer tokens(params_1, ','); - for (uint8 i = 0; i < tokens.size(); ) - data.params[1].insert(atoi(tokens[i++])); - } + if (spellFlags & SPELL_DISABLE_AREA) + { + std::set const& areaIds = itr->second.params[1]; + if (areaIds.find(unit->GetAreaId()) != areaIds.end()) + return true; // Spell is disabled in this area + return false; // Spell is disabled in another area, but not this one, return false + } + else + return true; // Spell disabled for all maps + } - // xinef: if spell has disabled los, add flag - if (flags & SPELL_DISABLE_LOS) - { - SpellInfo* spellInfo = const_cast(sSpellMgr->GetSpellInfo(entry)); - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - } + return false; + } + else if (spellFlags & SPELL_DISABLE_DEPRECATED_SPELL) // call not from spellcast + return true; - break; - // checked later - case DISABLE_TYPE_QUEST: - break; + break; + } case DISABLE_TYPE_MAP: case DISABLE_TYPE_LFG_MAP: - { - MapEntry const* mapEntry = sMapStore.LookupEntry(entry); - if (!mapEntry) + if (Player const* player = unit->ToPlayer()) { - sLog->outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry); - continue; - } - bool isFlagInvalid = false; - switch (mapEntry->map_type) - { - case MAP_COMMON: - if (flags) - isFlagInvalid = true; - break; - case MAP_INSTANCE: - case MAP_RAID: - if (flags & DUNGEON_STATUSFLAG_HEROIC && !GetMapDifficultyData(entry, DUNGEON_DIFFICULTY_HEROIC)) - isFlagInvalid = true; - else if (flags & RAID_STATUSFLAG_10MAN_HEROIC && !GetMapDifficultyData(entry, RAID_DIFFICULTY_10MAN_HEROIC)) - isFlagInvalid = true; - else if (flags & RAID_STATUSFLAG_25MAN_HEROIC && !GetMapDifficultyData(entry, RAID_DIFFICULTY_25MAN_HEROIC)) - isFlagInvalid = true; - break; - case MAP_BATTLEGROUND: - case MAP_ARENA: - sLog->outErrorDb("Battleground map %u specified to be disabled in map case, skipped.", entry); - continue; - } - if (isFlagInvalid) - { - sLog->outErrorDb("Disable flags for map %u are invalid, skipped.", entry); - continue; - } - break; - } - case DISABLE_TYPE_BATTLEGROUND: - if (!sBattlemasterListStore.LookupEntry(entry)) - { - sLog->outErrorDb("Battleground entry %u from `disables` doesn't exist in dbc, skipped.", entry); - continue; - } - if (flags) - sLog->outErrorDb("Disable flags specified for battleground %u, useless data.", entry); - break; - case DISABLE_TYPE_OUTDOORPVP: - if (entry > MAX_OUTDOORPVP_TYPES) - { - sLog->outErrorDb("OutdoorPvPTypes value %u from `disables` is invalid, skipped.", entry); - continue; - } - if (flags) - sLog->outErrorDb("Disable flags specified for outdoor PvP %u, useless data.", entry); - break; - case DISABLE_TYPE_ACHIEVEMENT_CRITERIA: - if (!sAchievementCriteriaStore.LookupEntry(entry)) - { - sLog->outErrorDb("Achievement Criteria entry %u from `disables` doesn't exist in dbc, skipped.", entry); - continue; - } - if (flags) - sLog->outErrorDb("Disable flags specified for Achievement Criteria %u, useless data.", entry); - break; - case DISABLE_TYPE_VMAP: - { - MapEntry const* mapEntry = sMapStore.LookupEntry(entry); - if (!mapEntry) - { - sLog->outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry); - continue; - } - switch (mapEntry->map_type) - { - case MAP_COMMON: - if (flags & VMAP_DISABLE_AREAFLAG) - sLog->outString("Areaflag disabled for world map %u.", entry); - if (flags & VMAP_DISABLE_LIQUIDSTATUS) - sLog->outString("Liquid status disabled for world map %u.", entry); - break; - case MAP_INSTANCE: - case MAP_RAID: - if (flags & VMAP_DISABLE_HEIGHT) - sLog->outString("Height disabled for instance map %u.", entry); - if (flags & VMAP_DISABLE_LOS) - sLog->outString("LoS disabled for instance map %u.", entry); - break; - case MAP_BATTLEGROUND: - if (flags & VMAP_DISABLE_HEIGHT) - sLog->outString("Height disabled for battleground map %u.", entry); - if (flags & VMAP_DISABLE_LOS) - sLog->outString("LoS disabled for battleground map %u.", entry); - break; - case MAP_ARENA: - if (flags & VMAP_DISABLE_HEIGHT) - sLog->outString("Height disabled for arena map %u.", entry); - if (flags & VMAP_DISABLE_LOS) - sLog->outString("LoS disabled for arena map %u.", entry); - break; - default: - break; - } - break; - } - default: - break; - } - - m_DisableMap[type].insert(DisableTypeMap::value_type(entry, data)); - ++total_count; - } - while (result->NextRow()); - - sLog->outString(">> Loaded %u disables in %u ms", total_count, GetMSTimeDiffToNow(oldMSTime)); - sLog->outString(); -} - -void CheckQuestDisables() -{ - uint32 oldMSTime = getMSTime(); - - uint32 count = m_DisableMap[DISABLE_TYPE_QUEST].size(); - if (!count) - { - sLog->outString(">> Checked 0 quest disables."); - sLog->outString(); - return; - } - - // check only quests, rest already done at startup - for (DisableTypeMap::iterator itr = m_DisableMap[DISABLE_TYPE_QUEST].begin(); itr != m_DisableMap[DISABLE_TYPE_QUEST].end();) - { - const uint32 entry = itr->first; - if (!sObjectMgr->GetQuestTemplate(entry)) - { - sLog->outErrorDb("Quest entry %u from `disables` doesn't exist, skipped.", entry); - m_DisableMap[DISABLE_TYPE_QUEST].erase(itr++); - continue; - } - if (itr->second.flags) - sLog->outErrorDb("Disable flags specified for quest %u, useless data.", entry); - ++itr; - } - - sLog->outString(">> Checked %u quest disables in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - sLog->outString(); -} - -bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags) -{ - ASSERT(type < MAX_DISABLE_TYPES); - if (m_DisableMap[type].empty()) - return false; - - DisableTypeMap::iterator itr = m_DisableMap[type].find(entry); - if (itr == m_DisableMap[type].end()) // not disabled - return false; - - switch (type) - { - case DISABLE_TYPE_SPELL: - { - uint8 spellFlags = itr->second.flags; - if (unit) - { - if ((spellFlags & SPELL_DISABLE_PLAYER && unit->GetTypeId() == TYPEID_PLAYER) || - (unit->GetTypeId() == TYPEID_UNIT && ((unit->IsPet() && spellFlags & SPELL_DISABLE_PET) || spellFlags & SPELL_DISABLE_CREATURE))) - { - if (spellFlags & SPELL_DISABLE_MAP) + MapEntry const* mapEntry = sMapStore.LookupEntry(entry); + if (mapEntry->IsDungeon()) { - std::set const& mapIds = itr->second.params[0]; - if (mapIds.find(unit->GetMapId()) != mapIds.end()) - return true; // Spell is disabled on current map - - if (!(spellFlags & SPELL_DISABLE_AREA)) - return false; // Spell is disabled on another map, but not this one, return false - - // Spell is disabled in an area, but not explicitly our current mapId. Continue processing. + uint8 disabledModes = itr->second.flags; + Difficulty targetDifficulty = player->GetDifficulty(mapEntry->IsRaid()); + GetDownscaledMapDifficultyData(entry, targetDifficulty); + switch (targetDifficulty) + { + case DUNGEON_DIFFICULTY_NORMAL: + return disabledModes & DUNGEON_STATUSFLAG_NORMAL; + case DUNGEON_DIFFICULTY_HEROIC: + return disabledModes & DUNGEON_STATUSFLAG_HEROIC; + case RAID_DIFFICULTY_10MAN_HEROIC: + return disabledModes & RAID_STATUSFLAG_10MAN_HEROIC; + case RAID_DIFFICULTY_25MAN_HEROIC: + return disabledModes & RAID_STATUSFLAG_25MAN_HEROIC; + } } - - if (spellFlags & SPELL_DISABLE_AREA) - { - std::set const& areaIds = itr->second.params[1]; - if (areaIds.find(unit->GetAreaId()) != areaIds.end()) - return true; // Spell is disabled in this area - return false; // Spell is disabled in another area, but not this one, return false - } - else - return true; // Spell disabled for all maps + else if (mapEntry->map_type == MAP_COMMON) + return true; } - return false; - } - else if (spellFlags & SPELL_DISABLE_DEPRECATED_SPELL) // call not from spellcast + case DISABLE_TYPE_QUEST: + return true; + case DISABLE_TYPE_BATTLEGROUND: + case DISABLE_TYPE_OUTDOORPVP: + case DISABLE_TYPE_ACHIEVEMENT_CRITERIA: + return true; + case DISABLE_TYPE_VMAP: + return flags & itr->second.flags; + case DISABLE_TYPE_GO_LOS: return true; - - break; } - case DISABLE_TYPE_MAP: - case DISABLE_TYPE_LFG_MAP: - if (Player const* player = unit->ToPlayer()) - { - MapEntry const* mapEntry = sMapStore.LookupEntry(entry); - if (mapEntry->IsDungeon()) - { - uint8 disabledModes = itr->second.flags; - Difficulty targetDifficulty = player->GetDifficulty(mapEntry->IsRaid()); - GetDownscaledMapDifficultyData(entry, targetDifficulty); - switch (targetDifficulty) - { - case DUNGEON_DIFFICULTY_NORMAL: - return disabledModes & DUNGEON_STATUSFLAG_NORMAL; - case DUNGEON_DIFFICULTY_HEROIC: - return disabledModes & DUNGEON_STATUSFLAG_HEROIC; - case RAID_DIFFICULTY_10MAN_HEROIC: - return disabledModes & RAID_STATUSFLAG_10MAN_HEROIC; - case RAID_DIFFICULTY_25MAN_HEROIC: - return disabledModes & RAID_STATUSFLAG_25MAN_HEROIC; - } - } - else if (mapEntry->map_type == MAP_COMMON) - return true; - } - return false; - case DISABLE_TYPE_QUEST: - return true; - case DISABLE_TYPE_BATTLEGROUND: - case DISABLE_TYPE_OUTDOORPVP: - case DISABLE_TYPE_ACHIEVEMENT_CRITERIA: - return true; - case DISABLE_TYPE_VMAP: - return flags & itr->second.flags; - case DISABLE_TYPE_GO_LOS: - return true; - } - return false; -} + return false; + } } // Namespace diff --git a/src/server/game/DataStores/DBCStores.cpp b/src/server/game/DataStores/DBCStores.cpp index 8778ac1d0..0ab7daf2e 100644 --- a/src/server/game/DataStores/DBCStores.cpp +++ b/src/server/game/DataStores/DBCStores.cpp @@ -345,13 +345,13 @@ void LoadDBCStores(const std::string& dataPath) LOAD_DBC(sVehicleSeatStore, "VehicleSeat.dbc", "vehicleseat_dbc"); LOAD_DBC(sWMOAreaTableStore, "WMOAreaTable.dbc", "wmoareatable_dbc"); LOAD_DBC(sWorldMapAreaStore, "WorldMapArea.dbc", "worldmaparea_dbc"); - LOAD_DBC(sWorldMapOverlayStore, "WorldMapOverlay.dbc", "worldmapoverlay_dbc"); + LOAD_DBC(sWorldMapOverlayStore, "WorldMapOverlay.dbc", "worldmapoverlay_dbc"); #undef LOAD_DBC for (CharStartOutfitEntry const* outfit : sCharStartOutfitStore) sCharStartOutfitMap[outfit->Race | (outfit->Class << 8) | (outfit->Gender << 16)] = outfit; - + for (FactionEntry const* faction : sFactionStore) { if (faction->team) @@ -360,7 +360,7 @@ void LoadDBCStores(const std::string& dataPath) flist.push_back(faction->ID); } } - + for (GameObjectDisplayInfoEntry const* info : sGameObjectDisplayInfoStore) { if (info->maxX < info->minX) @@ -372,7 +372,7 @@ void LoadDBCStores(const std::string& dataPath) if (info->maxZ < info->minZ) std::swap(*(float*)(&info->maxZ), *(float*)(&info->minZ)); } - + // fill data for (MapDifficultyEntry const* entry : sMapDifficultyStore) sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = MapDifficulty(entry->resetTime, entry->maxPlayers, entry->areaTriggerText[0] != '\0'); @@ -380,7 +380,7 @@ void LoadDBCStores(const std::string& dataPath) for (PvPDifficultyEntry const* entry : sPvPDifficultyStore) if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); - + for (auto i : sSpellStore) if (i->Category) sSpellsByCategoryStore[i->Category].insert(i->Id); @@ -459,12 +459,12 @@ void LoadDBCStores(const std::string& dataPath) sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabId; } } - + for (uint32 i = 1; i < sTaxiPathStore.GetNumRows(); ++i) if (TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(i)) sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID, entry->price); - + // Calculate path nodes count uint32 pathCount = sTaxiPathStore.GetNumRows(); @@ -499,7 +499,7 @@ void LoadDBCStores(const std::string& dataPath) memset(sHordeTaxiNodesMask, 0, sizeof(sHordeTaxiNodesMask)); memset(sAllianceTaxiNodesMask, 0, sizeof(sAllianceTaxiNodesMask)); memset(sDeathKnightTaxiNodesMask, 0, sizeof(sDeathKnightTaxiNodesMask)); - + for (uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i) { TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i); @@ -526,7 +526,7 @@ void LoadDBCStores(const std::string& dataPath) // valid taxi network node uint8 field = (uint8)((i - 1) / 32); - uint32 submask = 1<<((i-1)%32); + uint32 submask = 1 << ((i - 1) % 32); sTaxiNodesMask[field] |= submask; if (node->MountCreatureID[0] && node->MountCreatureID[0] != 32981) @@ -550,7 +550,7 @@ void LoadDBCStores(const std::string& dataPath) for (TransportAnimationEntry const* anim : sTransportAnimationStore) sTransportMgr->AddPathNodeToTransport(anim->TransportEntry, anim->TimeSeg, anim); - + for (TransportRotationEntry const* rot : sTransportRotationStore) sTransportMgr->AddPathRotationToTransport(rot->TransportEntry, rot->TimeSeg, rot); @@ -575,11 +575,11 @@ void LoadDBCStores(const std::string& dataPath) // Check loaded DBC files proper version if (!sAreaTableStore.LookupEntry(4987) || // last area added in 3.3.5a - !sCharTitlesStore.LookupEntry(177) || // last char title added in 3.3.5a - !sGemPropertiesStore.LookupEntry(1629) || // last added spell in 3.3.5a - !sItemExtendedCostStore.LookupEntry(2997) || // last item extended cost added in 3.3.5a - !sMapStore.LookupEntry(724) || // last map added in 3.3.5a - !sSpellStore.LookupEntry(80864) ) // last client known item added in 3.3.5a + !sCharTitlesStore.LookupEntry(177) || // last char title added in 3.3.5a + !sGemPropertiesStore.LookupEntry(1629) || // last added spell in 3.3.5a + !sItemExtendedCostStore.LookupEntry(2997) || // last item extended cost added in 3.3.5a + !sMapStore.LookupEntry(724) || // last map added in 3.3.5a + !sSpellStore.LookupEntry(80864) ) // last client known item added in 3.3.5a { sLog->outError("You have _outdated_ DBC data. Please extract correct versions from current using client."); exit(1); @@ -622,7 +622,7 @@ TalentSpellPos const* GetTalentSpellPos(uint32 spellId) uint32 GetTalentSpellCost(uint32 spellId) { if (TalentSpellPos const* pos = GetTalentSpellPos(spellId)) - return pos->rank+1; + return pos->rank + 1; return 0; } @@ -659,9 +659,12 @@ ContentLevels GetContentLevelsForMapAndZone(uint32 mapid, uint32 zoneId) switch (mapEntry->Expansion()) { - default: return CONTENT_1_60; - case 1: return CONTENT_61_70; - case 2: return CONTENT_71_80; + default: + return CONTENT_1_60; + case 1: + return CONTENT_61_70; + case 2: + return CONTENT_71_80; } } @@ -674,8 +677,8 @@ void Zone2MapCoordinates(float& x, float& y, uint32 zone) return; std::swap(x, y); // at client map coords swapped - x = x*((maEntry->x2-maEntry->x1)/100)+maEntry->x1; - y = y*((maEntry->y2-maEntry->y1)/100)+maEntry->y1; // client y coord from top to down + x = x * ((maEntry->x2 - maEntry->x1) / 100) + maEntry->x1; + y = y * ((maEntry->y2 - maEntry->y1) / 100) + maEntry->y1; // client y coord from top to down } void Map2ZoneCoordinates(float& x, float& y, uint32 zone) @@ -686,8 +689,8 @@ void Map2ZoneCoordinates(float& x, float& y, uint32 zone) if (!maEntry) return; - x = (x-maEntry->x1)/((maEntry->x2-maEntry->x1)/100); - y = (y-maEntry->y1)/((maEntry->y2-maEntry->y1)/100); // client y coord from top to down + x = (x - maEntry->x1) / ((maEntry->x2 - maEntry->x1) / 100); + y = (y - maEntry->y1) / ((maEntry->y2 - maEntry->y1) / 100); // client y coord from top to down std::swap(x, y); // client have map coords swapped } @@ -697,7 +700,7 @@ MapDifficulty const* GetMapDifficultyData(uint32 mapId, Difficulty difficulty) return itr != sMapDifficultyMap.end() ? &itr->second : nullptr; } -MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &difficulty) +MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty& difficulty) { uint32 tmpDiff = difficulty; @@ -760,7 +763,7 @@ uint32 const* GetTalentTabPages(uint8 cls) } bool IsSharedDifficultyMap(uint32 mapid) -{ +{ return sWorld->getBoolConfig(CONFIG_INSTANCE_SHARED_ID) && (mapid == 631 || mapid == 724); } diff --git a/src/server/game/DataStores/DBCStores.h b/src/server/game/DataStores/DBCStores.h index cc3832701..2a50eb5b6 100644 --- a/src/server/game/DataStores/DBCStores.h +++ b/src/server/game/DataStores/DBCStores.h @@ -31,12 +31,12 @@ enum ContentLevels }; ContentLevels GetContentLevelsForMapAndZone(uint32 mapid, uint32 zoneId); -void Zone2MapCoordinates(float &x, float &y, uint32 zone); -void Map2ZoneCoordinates(float &x, float &y, uint32 zone); +void Zone2MapCoordinates(float& x, float& y, uint32 zone); +void Map2ZoneCoordinates(float& x, float& y, uint32 zone); typedef std::map MapDifficultyMap; MapDifficulty const* GetMapDifficultyData(uint32 mapId, Difficulty difficulty); -MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &difficulty); +MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty& difficulty); bool IsSharedDifficultyMap(uint32 mapid); diff --git a/src/server/game/DungeonFinding/LFG.cpp b/src/server/game/DungeonFinding/LFG.cpp index 6aa1ea315..2419b9738 100644 --- a/src/server/game/DungeonFinding/LFG.cpp +++ b/src/server/game/DungeonFinding/LFG.cpp @@ -65,30 +65,30 @@ namespace lfg int32 entry = LANG_LFG_ERROR; switch (state) { - case LFG_STATE_NONE: - entry = LANG_LFG_STATE_NONE; - break; - case LFG_STATE_ROLECHECK: - entry = LANG_LFG_STATE_ROLECHECK; - break; - case LFG_STATE_QUEUED: - entry = LANG_LFG_STATE_QUEUED; - break; - case LFG_STATE_PROPOSAL: - entry = LANG_LFG_STATE_PROPOSAL; - break; - case LFG_STATE_DUNGEON: - entry = LANG_LFG_STATE_DUNGEON; - break; - case LFG_STATE_BOOT: - entry = LANG_LFG_STATE_BOOT; - break; - case LFG_STATE_FINISHED_DUNGEON: - entry = LANG_LFG_STATE_FINISHED_DUNGEON; - break; - case LFG_STATE_RAIDBROWSER: - entry = LANG_LFG_STATE_RAIDBROWSER; - break; + case LFG_STATE_NONE: + entry = LANG_LFG_STATE_NONE; + break; + case LFG_STATE_ROLECHECK: + entry = LANG_LFG_STATE_ROLECHECK; + break; + case LFG_STATE_QUEUED: + entry = LANG_LFG_STATE_QUEUED; + break; + case LFG_STATE_PROPOSAL: + entry = LANG_LFG_STATE_PROPOSAL; + break; + case LFG_STATE_DUNGEON: + entry = LANG_LFG_STATE_DUNGEON; + break; + case LFG_STATE_BOOT: + entry = LANG_LFG_STATE_BOOT; + break; + case LFG_STATE_FINISHED_DUNGEON: + entry = LANG_LFG_STATE_FINISHED_DUNGEON; + break; + case LFG_STATE_RAIDBROWSER: + entry = LANG_LFG_STATE_RAIDBROWSER; + break; } return std::string(sObjectMgr->GetAcoreStringForDBCLocale(entry)); diff --git a/src/server/game/DungeonFinding/LFG.h b/src/server/game/DungeonFinding/LFG.h index 71420e6d4..18e6e7edb 100644 --- a/src/server/game/DungeonFinding/LFG.h +++ b/src/server/game/DungeonFinding/LFG.h @@ -15,163 +15,246 @@ namespace lfg { -enum LFGEnum -{ - LFG_TANKS_NEEDED = 1, - LFG_HEALERS_NEEDED = 1, - LFG_DPS_NEEDED = 3 -}; - -enum LfgRoles -{ - PLAYER_ROLE_NONE = 0x00, - PLAYER_ROLE_LEADER = 0x01, - PLAYER_ROLE_TANK = 0x02, - PLAYER_ROLE_HEALER = 0x04, - PLAYER_ROLE_DAMAGE = 0x08 -}; - -enum LfgUpdateType -{ - LFG_UPDATETYPE_DEFAULT = 0, // Internal Use - LFG_UPDATETYPE_LEADER_UNK1 = 1, // FIXME: At group leave - LFG_UPDATETYPE_LEAVE_RAIDBROWSER = 2, - LFG_UPDATETYPE_JOIN_RAIDBROWSER = 3, - LFG_UPDATETYPE_ROLECHECK_ABORTED = 4, - LFG_UPDATETYPE_JOIN_QUEUE = 5, - LFG_UPDATETYPE_ROLECHECK_FAILED = 6, - LFG_UPDATETYPE_REMOVED_FROM_QUEUE = 7, - LFG_UPDATETYPE_PROPOSAL_FAILED = 8, - LFG_UPDATETYPE_PROPOSAL_DECLINED = 9, - LFG_UPDATETYPE_GROUP_FOUND = 10, - LFG_UPDATETYPE_ADDED_TO_QUEUE = 12, - LFG_UPDATETYPE_PROPOSAL_BEGIN = 13, - LFG_UPDATETYPE_UPDATE_STATUS = 14, - LFG_UPDATETYPE_GROUP_MEMBER_OFFLINE = 15, - LFG_UPDATETYPE_GROUP_DISBAND_UNK16 = 16, // FIXME: Sometimes at group disband -}; - -enum LfgState -{ - LFG_STATE_NONE, // Not using LFG / LFR - LFG_STATE_ROLECHECK, // Rolecheck active - LFG_STATE_QUEUED, // Queued - LFG_STATE_PROPOSAL, // Proposal active - LFG_STATE_BOOT, // Vote kick active - LFG_STATE_DUNGEON, // In LFG Group, in a Dungeon - LFG_STATE_FINISHED_DUNGEON, // In LFG Group, in a finished Dungeon - LFG_STATE_RAIDBROWSER // Using Raid finder -}; - -/// Instance lock types -enum LfgLockStatusType -{ - LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION = 1, - LFG_LOCKSTATUS_TOO_LOW_LEVEL = 2, - LFG_LOCKSTATUS_TOO_HIGH_LEVEL = 3, - LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE = 4, - LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE = 5, - LFG_LOCKSTATUS_RAID_LOCKED = 6, - LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL = 1001, - LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL = 1002, - LFG_LOCKSTATUS_QUEST_NOT_COMPLETED = 1022, - LFG_LOCKSTATUS_MISSING_ITEM = 1025, - LFG_LOCKSTATUS_NOT_IN_SEASON = 1031, - LFG_LOCKSTATUS_MISSING_ACHIEVEMENT = 1034 -}; - -/// Answer state (Also used to check compatibilites) -enum LfgAnswer -{ - LFG_ANSWER_PENDING = -1, - LFG_ANSWER_DENY = 0, - LFG_ANSWER_AGREE = 1 -}; - -class Lfg5Guids; - -typedef std::list Lfg5GuidsList; -typedef std::set LfgDungeonSet; -typedef std::map LfgLockMap; -typedef std::map LfgLockPartyMap; -typedef std::set LfgGuidSet; -typedef std::list LfgGuidList; -typedef std::map LfgRolesMap; -typedef std::map LfgGroupsMap; - -class Lfg5Guids -{ -public: - uint64 guid[5]; - LfgRolesMap* roles; - Lfg5Guids() + enum LFGEnum { - memset(&guid, 0, 5*8); - roles = nullptr; - } + LFG_TANKS_NEEDED = 1, + LFG_HEALERS_NEEDED = 1, + LFG_DPS_NEEDED = 3 + }; - Lfg5Guids(uint64 g) + enum LfgRoles { - memset(&guid, 0, 5*8); - guid[0] = g; - roles = nullptr; - } + PLAYER_ROLE_NONE = 0x00, + PLAYER_ROLE_LEADER = 0x01, + PLAYER_ROLE_TANK = 0x02, + PLAYER_ROLE_HEALER = 0x04, + PLAYER_ROLE_DAMAGE = 0x08 + }; - Lfg5Guids(Lfg5Guids const& x) + enum LfgUpdateType { - memcpy(guid, x.guid, 5*8); - roles = x.roles ? (new LfgRolesMap(*(x.roles))) : nullptr; - } + LFG_UPDATETYPE_DEFAULT = 0, // Internal Use + LFG_UPDATETYPE_LEADER_UNK1 = 1, // FIXME: At group leave + LFG_UPDATETYPE_LEAVE_RAIDBROWSER = 2, + LFG_UPDATETYPE_JOIN_RAIDBROWSER = 3, + LFG_UPDATETYPE_ROLECHECK_ABORTED = 4, + LFG_UPDATETYPE_JOIN_QUEUE = 5, + LFG_UPDATETYPE_ROLECHECK_FAILED = 6, + LFG_UPDATETYPE_REMOVED_FROM_QUEUE = 7, + LFG_UPDATETYPE_PROPOSAL_FAILED = 8, + LFG_UPDATETYPE_PROPOSAL_DECLINED = 9, + LFG_UPDATETYPE_GROUP_FOUND = 10, + LFG_UPDATETYPE_ADDED_TO_QUEUE = 12, + LFG_UPDATETYPE_PROPOSAL_BEGIN = 13, + LFG_UPDATETYPE_UPDATE_STATUS = 14, + LFG_UPDATETYPE_GROUP_MEMBER_OFFLINE = 15, + LFG_UPDATETYPE_GROUP_DISBAND_UNK16 = 16, // FIXME: Sometimes at group disband + }; - Lfg5Guids(Lfg5Guids const& x, bool /*copyRoles*/) + enum LfgState { - memcpy(guid, x.guid, 5*8); - roles = nullptr; - } + LFG_STATE_NONE, // Not using LFG / LFR + LFG_STATE_ROLECHECK, // Rolecheck active + LFG_STATE_QUEUED, // Queued + LFG_STATE_PROPOSAL, // Proposal active + LFG_STATE_BOOT, // Vote kick active + LFG_STATE_DUNGEON, // In LFG Group, in a Dungeon + LFG_STATE_FINISHED_DUNGEON, // In LFG Group, in a finished Dungeon + LFG_STATE_RAIDBROWSER // Using Raid finder + }; - ~Lfg5Guids() { delete roles; } - void addRoles(LfgRolesMap const& r) { roles = new LfgRolesMap(r); } - void clear() { memset(&guid, 0, 5*8); } - bool empty() const { return guid[0] == 0; } - uint64 front() const { return guid[0]; } - - uint8 size() const + /// Instance lock types + enum LfgLockStatusType { - if (guid[2]) + LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION = 1, + LFG_LOCKSTATUS_TOO_LOW_LEVEL = 2, + LFG_LOCKSTATUS_TOO_HIGH_LEVEL = 3, + LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE = 4, + LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE = 5, + LFG_LOCKSTATUS_RAID_LOCKED = 6, + LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL = 1001, + LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL = 1002, + LFG_LOCKSTATUS_QUEST_NOT_COMPLETED = 1022, + LFG_LOCKSTATUS_MISSING_ITEM = 1025, + LFG_LOCKSTATUS_NOT_IN_SEASON = 1031, + LFG_LOCKSTATUS_MISSING_ACHIEVEMENT = 1034 + }; + + /// Answer state (Also used to check compatibilites) + enum LfgAnswer + { + LFG_ANSWER_PENDING = -1, + LFG_ANSWER_DENY = 0, + LFG_ANSWER_AGREE = 1 + }; + + class Lfg5Guids; + + typedef std::list Lfg5GuidsList; + typedef std::set LfgDungeonSet; + typedef std::map LfgLockMap; + typedef std::map LfgLockPartyMap; + typedef std::set LfgGuidSet; + typedef std::list LfgGuidList; + typedef std::map LfgRolesMap; + typedef std::map LfgGroupsMap; + + class Lfg5Guids + { + public: + uint64 guid[5]; + LfgRolesMap* roles; + Lfg5Guids() { - if (guid[4]) - { - return 5; - } - else if (guid[3]) - { - return 4; - } - - return 3; - } - else if (guid[1]) - { - return 2; - } - else if (guid[0]) - { - return 1; + memset(&guid, 0, 5 * 8); + roles = nullptr; } - return 0; - } - - void insert(const uint64& g) - { - // avoid loops for performance - if (guid[0] == 0) + Lfg5Guids(uint64 g) { + memset(&guid, 0, 5 * 8); guid[0] = g; - return; + roles = nullptr; } - if (g <= guid[0]) + Lfg5Guids(Lfg5Guids const& x) + { + memcpy(guid, x.guid, 5 * 8); + roles = x.roles ? (new LfgRolesMap(*(x.roles))) : nullptr; + } + + Lfg5Guids(Lfg5Guids const& x, bool /*copyRoles*/) + { + memcpy(guid, x.guid, 5 * 8); + roles = nullptr; + } + + ~Lfg5Guids() { delete roles; } + void addRoles(LfgRolesMap const& r) { roles = new LfgRolesMap(r); } + void clear() { memset(&guid, 0, 5 * 8); } + bool empty() const { return guid[0] == 0; } + uint64 front() const { return guid[0]; } + + uint8 size() const + { + if (guid[2]) + { + if (guid[4]) + { + return 5; + } + else if (guid[3]) + { + return 4; + } + + return 3; + } + else if (guid[1]) + { + return 2; + } + else if (guid[0]) + { + return 1; + } + + return 0; + } + + void insert(const uint64& g) + { + // avoid loops for performance + if (guid[0] == 0) + { + guid[0] = g; + return; + } + + if (g <= guid[0]) + { + if (guid[3]) + { + guid[4] = guid[3]; + } + + if (guid[2]) + { + guid[3] = guid[2]; + } + + if (guid[1]) + { + guid[2] = guid[1]; + } + + + guid[1] = guid[0]; + guid[0] = g; + + return; + } + + if (guid[1] == 0) + { + guid[1] = g; + return; + } + + if (g <= guid[1]) + { + if (guid[3]) + { + guid[4] = guid[3]; + } + + if (guid[2]) + { + guid[3] = guid[2]; + } + + guid[2] = guid[1]; + guid[1] = g; + + return; + } + + if (guid[2] == 0) + { + guid[2] = g; + return; + } + + if (g <= guid[2]) + { + if (guid[3]) + { + guid[4] = guid[3]; + } + + guid[3] = guid[2]; + guid[2] = g; + + return; + } + + if (guid[3] == 0) + { + guid[3] = g; + return; + } + + if (g <= guid[3]) + { + guid[4] = guid[3]; + guid[3] = g; + return; + } + + guid[4] = g; + } + + void force_insert_front(const uint64& g) { if (guid[3]) { @@ -188,296 +271,213 @@ public: guid[2] = guid[1]; } - guid[1] = guid[0]; guid[0] = g; - - return; } - if (guid[1] == 0) + void remove(const uint64& g) { - guid[1] = g; - return; - } - - if (g <= guid[1]) - { - if (guid[3]) + // avoid loops for performance + if (guid[0] == g) { - guid[4] = guid[3]; - } + if (guid[1]) + { + guid[0] = guid[1]; + } + else + { + guid[0] = 0; + return; + } - if (guid[2]) - { - guid[3] = guid[2]; - } + if (guid[2]) + { + guid[1] = guid[2]; + } + else + { + guid[1] = 0; + return; + } - guid[2] = guid[1]; - guid[1] = g; + if (guid[3]) + { + guid[2] = guid[3]; + } + else + { + guid[2] = 0; + return; + } - return; - } + if (guid[4]) + { + guid[3] = guid[4]; + } + else + { + guid[3] = 0; + return; + } - if (guid[2] == 0) - { - guid[2] = g; - return; - } - - if (g <= guid[2]) - { - if (guid[3]) - { - guid[4] = guid[3]; - } - - guid[3] = guid[2]; - guid[2] = g; - - return; - } - - if (guid[3] == 0) - { - guid[3] = g; - return; - } - - if (g <= guid[3]) - { - guid[4] = guid[3]; - guid[3] = g; - return; - } - - guid[4] = g; - } - - void force_insert_front(const uint64& g) - { - if (guid[3]) - { - guid[4] = guid[3]; - } - - if (guid[2]) - { - guid[3] = guid[2]; - } - - if (guid[1]) - { - guid[2] = guid[1]; - } - - guid[1] = guid[0]; - guid[0] = g; - } - - void remove(const uint64& g) - { - // avoid loops for performance - if (guid[0] == g) - { - if (guid[1]) - { - guid[0] = guid[1]; - } - else - { - guid[0] = 0; + guid[4] = 0; return; } - if (guid[2]) + if (guid[1] == g) { - guid[1] = guid[2]; - } - else - { - guid[1] = 0; + if (guid[2]) + { + guid[1] = guid[2]; + } + else + { + guid[1] = 0; + return; + } + + if (guid[3]) + { + guid[2] = guid[3]; + } + else + { + guid[2] = 0; + return; + } + + if (guid[4]) + { + guid[3] = guid[4]; + } + else + { + guid[3] = 0; + return; + } + + guid[4] = 0; return; } - if (guid[3]) + if (guid[2] == g) { - guid[2] = guid[3]; - } - else - { - guid[2] = 0; + if (guid[3]) + { + guid[2] = guid[3]; + } + else + { + guid[2] = 0; + return; + } + + if (guid[4]) + { + guid[3] = guid[4]; + } + else + { + guid[3] = 0; + return; + } + + guid[4] = 0; return; } - if (guid[4]) + if (guid[3] == g) { - guid[3] = guid[4]; - } - else - { - guid[3] = 0; + if (guid[4]) + { + guid[3] = guid[4]; + } + else + { + guid[3] = 0; + return; + } + + guid[4] = 0; return; } - guid[4] = 0; - return; + if (guid[4] == g) + { + guid[4] = 0; + } } - if (guid[1] == g) + bool hasGuid(const uint64& g) const { - if (guid[2]) - { - guid[1] = guid[2]; - } - else - { - guid[1] = 0; - return; - } - - if (guid[3]) - { - guid[2] = guid[3]; - } - else - { - guid[2] = 0; - return; - } - - if (guid[4]) - { - guid[3] = guid[4]; - } - else - { - guid[3] = 0; - return; - } - - guid[4] = 0; - return; + return g && (guid[0] == g || guid[1] == g || guid[2] == g || guid[3] == g || guid[4] == g); } - if (guid[2] == g) + bool operator<(const Lfg5Guids& x) const { - if (guid[3]) + if (guid[0] <= x.guid[0]) { - guid[2] = guid[3]; - } - else - { - guid[2] = 0; - return; - } - - if (guid[4]) - { - guid[3] = guid[4]; - } - else - { - guid[3] = 0; - return; - } - - guid[4] = 0; - return; - } - - if (guid[3] == g) - { - if (guid[4]) - { - guid[3] = guid[4]; - } - else - { - guid[3] = 0; - return; - } - - guid[4] = 0; - return; - } - - if (guid[4] == g) - { - guid[4] = 0; - } - } - - bool hasGuid(const uint64& g) const - { - return g && (guid[0] == g || guid[1] == g || guid[2] == g || guid[3] == g || guid[4] == g); - } - - bool operator<(const Lfg5Guids& x) const - { - if (guid[0] <= x.guid[0]) - { - if (guid[0] != x.guid[0]) - { - return true; - } - - if (guid[1] <= x.guid[1]) - { - if (guid[1] != x.guid[1]) + if (guid[0] != x.guid[0]) { return true; } - if (guid[2] <= x.guid[2]) + if (guid[1] <= x.guid[1]) { - if (guid[2] != x.guid[2]) + if (guid[1] != x.guid[1]) { return true; } - if (guid[3] <= x.guid[3]) + if (guid[2] <= x.guid[2]) { - if (guid[3] != x.guid[3]) + if (guid[2] != x.guid[2]) { return true; } - if (guid[4] <= x.guid[4]) + if (guid[3] <= x.guid[3]) { - return !(guid[4] == x.guid[4]); + if (guid[3] != x.guid[3]) + { + return true; + } + + if (guid[4] <= x.guid[4]) + { + return !(guid[4] == x.guid[4]); + } } } } } + + return false; } - return false; - } + bool operator==(const Lfg5Guids& x) const + { + return guid[0] == x.guid[0] && guid[1] == x.guid[1] && guid[2] == x.guid[2] && guid[3] == x.guid[3] && guid[4] == x.guid[4]; + } - bool operator==(const Lfg5Guids& x) const - { - return guid[0] == x.guid[0] && guid[1] == x.guid[1] && guid[2] == x.guid[2] && guid[3] == x.guid[3] && guid[4] == x.guid[4]; - } + void operator=(const Lfg5Guids& x) + { + memcpy(guid, x.guid, 5 * 8); + delete roles; + roles = x.roles ? (new LfgRolesMap(*(x.roles))) : nullptr; + } - void operator=(const Lfg5Guids& x) - { - memcpy(guid, x.guid, 5*8); - delete roles; - roles = x.roles ? (new LfgRolesMap(*(x.roles))) : nullptr; - } + std::string toString() const // for debugging + { + std::ostringstream o; + o << GUID_LOPART(guid[0]) << "," << GUID_LOPART(guid[1]) << "," << GUID_LOPART(guid[2]) << "," << GUID_LOPART(guid[3]) << "," << GUID_LOPART(guid[4]) << ":" << (roles ? 1 : 0); + return o.str(); + } + }; - std::string toString() const // for debugging - { - std::ostringstream o; - o << GUID_LOPART(guid[0]) << "," << GUID_LOPART(guid[1]) << "," << GUID_LOPART(guid[2]) << "," << GUID_LOPART(guid[3]) << "," << GUID_LOPART(guid[4]) << ":" << (roles ? 1 : 0); - return o.str(); - } -}; - -std::string ConcatenateDungeons(LfgDungeonSet const& dungeons); -std::string GetRolesString(uint8 roles); -std::string GetStateString(LfgState state); + std::string ConcatenateDungeons(LfgDungeonSet const& dungeons); + std::string GetRolesString(uint8 roles); + std::string GetStateString(LfgState state); } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGGroupData.cpp b/src/server/game/DungeonFinding/LFGGroupData.cpp index 310cb33fd..3ea166c38 100644 --- a/src/server/game/DungeonFinding/LFGGroupData.cpp +++ b/src/server/game/DungeonFinding/LFGGroupData.cpp @@ -10,110 +10,110 @@ namespace lfg { -LfgGroupData::LfgGroupData(): m_State(LFG_STATE_NONE), m_OldState(LFG_STATE_NONE), - m_Leader(0), m_Dungeon(0), m_KicksLeft(LFG_GROUP_MAX_KICKS) -{ } + LfgGroupData::LfgGroupData(): m_State(LFG_STATE_NONE), m_OldState(LFG_STATE_NONE), + m_Leader(0), m_Dungeon(0), m_KicksLeft(LFG_GROUP_MAX_KICKS) + { } -LfgGroupData::~LfgGroupData() -{ } + LfgGroupData::~LfgGroupData() + { } -bool LfgGroupData::IsLfgGroup() -{ - return m_OldState != LFG_STATE_NONE; -} - -void LfgGroupData::SetState(LfgState state) -{ - switch (state) + bool LfgGroupData::IsLfgGroup() { - case LFG_STATE_NONE: - m_Dungeon = 0; - m_KicksLeft = LFG_GROUP_MAX_KICKS; - [[fallthrough]]; - case LFG_STATE_FINISHED_DUNGEON: - case LFG_STATE_DUNGEON: - m_OldState = state; - [[fallthrough]]; - default: - m_State = state; + return m_OldState != LFG_STATE_NONE; } -} -void LfgGroupData::RestoreState() -{ - m_State = m_OldState; -} + void LfgGroupData::SetState(LfgState state) + { + switch (state) + { + case LFG_STATE_NONE: + m_Dungeon = 0; + m_KicksLeft = LFG_GROUP_MAX_KICKS; + [[fallthrough]]; + case LFG_STATE_FINISHED_DUNGEON: + case LFG_STATE_DUNGEON: + m_OldState = state; + [[fallthrough]]; + default: + m_State = state; + } + } -void LfgGroupData::AddPlayer(uint64 guid) -{ - m_Players.insert(guid); -} + void LfgGroupData::RestoreState() + { + m_State = m_OldState; + } -uint8 LfgGroupData::RemovePlayer(uint64 guid) -{ - LfgGuidSet::iterator it = m_Players.find(guid); - if (it != m_Players.end()) - m_Players.erase(it); - return uint8(m_Players.size()); -} + void LfgGroupData::AddPlayer(uint64 guid) + { + m_Players.insert(guid); + } -void LfgGroupData::RemoveAllPlayers() -{ - m_Players.clear(); -} + uint8 LfgGroupData::RemovePlayer(uint64 guid) + { + LfgGuidSet::iterator it = m_Players.find(guid); + if (it != m_Players.end()) + m_Players.erase(it); + return uint8(m_Players.size()); + } -void LfgGroupData::SetLeader(uint64 guid) -{ - m_Leader = guid; -} + void LfgGroupData::RemoveAllPlayers() + { + m_Players.clear(); + } -void LfgGroupData::SetDungeon(uint32 dungeon) -{ - m_Dungeon = dungeon; -} + void LfgGroupData::SetLeader(uint64 guid) + { + m_Leader = guid; + } -void LfgGroupData::DecreaseKicksLeft() -{ - if (m_KicksLeft) - --m_KicksLeft; -} + void LfgGroupData::SetDungeon(uint32 dungeon) + { + m_Dungeon = dungeon; + } -LfgState LfgGroupData::GetState() const -{ - return m_State; -} + void LfgGroupData::DecreaseKicksLeft() + { + if (m_KicksLeft) + --m_KicksLeft; + } -LfgState LfgGroupData::GetOldState() const -{ - return m_OldState; -} + LfgState LfgGroupData::GetState() const + { + return m_State; + } -LfgGuidSet const& LfgGroupData::GetPlayers() const -{ - return m_Players; -} + LfgState LfgGroupData::GetOldState() const + { + return m_OldState; + } -uint8 LfgGroupData::GetPlayerCount() const -{ - return m_Players.size(); -} + LfgGuidSet const& LfgGroupData::GetPlayers() const + { + return m_Players; + } -uint64 LfgGroupData::GetLeader() const -{ - return m_Leader; -} + uint8 LfgGroupData::GetPlayerCount() const + { + return m_Players.size(); + } -uint32 LfgGroupData::GetDungeon(bool asId /* = true */) const -{ - if (asId) - return (m_Dungeon & 0x00FFFFFF); - else - return m_Dungeon; -} + uint64 LfgGroupData::GetLeader() const + { + return m_Leader; + } -uint8 LfgGroupData::GetKicksLeft() const -{ - return m_KicksLeft; -} + uint32 LfgGroupData::GetDungeon(bool asId /* = true */) const + { + if (asId) + return (m_Dungeon & 0x00FFFFFF); + else + return m_Dungeon; + } + + uint8 LfgGroupData::GetKicksLeft() const + { + return m_KicksLeft; + } } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGGroupData.h b/src/server/game/DungeonFinding/LFGGroupData.h index 24607f5d8..5d73dfd9e 100644 --- a/src/server/game/DungeonFinding/LFGGroupData.h +++ b/src/server/game/DungeonFinding/LFGGroupData.h @@ -12,16 +12,16 @@ namespace lfg { -enum LfgGroupEnum -{ - LFG_GROUP_MAX_KICKS = 3, -}; + enum LfgGroupEnum + { + LFG_GROUP_MAX_KICKS = 3, + }; -/** - Stores all lfg data needed about a group. -*/ -class LfgGroupData -{ + /** + Stores all lfg data needed about a group. + */ + class LfgGroupData + { public: LfgGroupData(); ~LfgGroupData(); @@ -65,7 +65,7 @@ class LfgGroupData uint32 m_Dungeon; ///< Dungeon entry // Vote Kick uint8 m_KicksLeft; ///< Number of kicks left -}; + }; } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index 221ae176a..3ed818450 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -27,730 +27,1262 @@ namespace lfg { -LFGMgr::LFGMgr(): m_lfgProposalId(1), m_options(sWorld->getIntConfig(CONFIG_LFG_OPTIONSMASK)) -{ - new LFGPlayerScript(); - new LFGGroupScript(); - - for (uint8 team=0; team<2; ++team) + LFGMgr::LFGMgr(): m_lfgProposalId(1), m_options(sWorld->getIntConfig(CONFIG_LFG_OPTIONSMASK)) { - m_raidBrowserUpdateTimer[team] = 10000; - m_raidBrowserLastUpdatedDungeonId[team] = 0; - } -} + new LFGPlayerScript(); + new LFGGroupScript(); -LFGMgr::~LFGMgr() -{ - for (LfgRewardContainer::iterator itr = RewardMapStore.begin(); itr != RewardMapStore.end(); ++itr) - delete itr->second; -} - -LFGMgr* LFGMgr::instance() -{ - static LFGMgr instance; - return &instance; -} - -void LFGMgr::_LoadFromDB(Field* fields, uint64 guid) -{ - if (!fields) - return; - - if (!IS_GROUP_GUID(guid)) - return; - - SetLeader(guid, MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER)); - - uint32 dungeon = fields[17].GetUInt32(); - uint8 state = fields[18].GetUInt8(); - - if (!dungeon || !state) - return; - - SetDungeon(guid, dungeon); - - switch (state) - { - case LFG_STATE_DUNGEON: - case LFG_STATE_FINISHED_DUNGEON: - SetState(guid, (LfgState)state); - break; - default: - break; - } -} - -void LFGMgr::_SaveToDB(uint64 guid) -{ - if (!IS_GROUP_GUID(guid)) - return; - - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_LFG_DATA); - stmt->setUInt32(0, GUID_LOPART(guid)); - stmt->setUInt32(1, GetDungeon(guid)); - stmt->setUInt32(2, GetState(guid)); - CharacterDatabase.Execute(stmt); -} - -/// Load rewards for completing dungeons -void LFGMgr::LoadRewards() -{ - uint32 oldMSTime = getMSTime(); - - for (LfgRewardContainer::iterator itr = RewardMapStore.begin(); itr != RewardMapStore.end(); ++itr) - delete itr->second; - RewardMapStore.clear(); - - // ORDER BY is very important for GetRandomDungeonReward! - QueryResult result = WorldDatabase.Query("SELECT dungeonId, maxLevel, firstQuestId, otherQuestId FROM lfg_dungeon_rewards ORDER BY dungeonId, maxLevel ASC"); - - if (!result) - { - sLog->outError(">> Loaded 0 lfg dungeon rewards. DB table `lfg_dungeon_rewards` is empty!"); - return; + for (uint8 team = 0; team < 2; ++team) + { + m_raidBrowserUpdateTimer[team] = 10000; + m_raidBrowserLastUpdatedDungeonId[team] = 0; + } } - uint32 count = 0; - - Field* fields = nullptr; - do + LFGMgr::~LFGMgr() { - fields = result->Fetch(); - uint32 dungeonId = fields[0].GetUInt32(); - uint32 maxLevel = fields[1].GetUInt8(); - uint32 firstQuestId = fields[2].GetUInt32(); - uint32 otherQuestId = fields[3].GetUInt32(); - - if (!GetLFGDungeonEntry(dungeonId)) - { - sLog->outError("Dungeon %u specified in table `lfg_dungeon_rewards` does not exist!", dungeonId); - continue; - } - - if (!maxLevel || maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) - { - sLog->outError("Level %u specified for dungeon %u in table `lfg_dungeon_rewards` can never be reached!", maxLevel, dungeonId); - maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); - } - - if (!firstQuestId || !sObjectMgr->GetQuestTemplate(firstQuestId)) - { - sLog->outError("First quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", firstQuestId, dungeonId); - continue; - } - - if (otherQuestId && !sObjectMgr->GetQuestTemplate(otherQuestId)) - { - sLog->outError("Other quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", otherQuestId, dungeonId); - otherQuestId = 0; - } - - RewardMapStore.insert(LfgRewardContainer::value_type(dungeonId, new LfgReward(maxLevel, firstQuestId, otherQuestId))); - ++count; + for (LfgRewardContainer::iterator itr = RewardMapStore.begin(); itr != RewardMapStore.end(); ++itr) + delete itr->second; } - while (result->NextRow()); - sLog->outString(">> Loaded %u lfg dungeon rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - sLog->outString(); -} - -LFGDungeonData const* LFGMgr::GetLFGDungeon(uint32 id) -{ - LFGDungeonContainer::const_iterator itr = LfgDungeonStore.find(id); - if (itr != LfgDungeonStore.end()) - return &(itr->second); - - return nullptr; -} - -void LFGMgr::LoadLFGDungeons(bool reload /* = false */) -{ - uint32 oldMSTime = getMSTime(); - - LfgDungeonStore.clear(); - - // Initialize Dungeon map with data from dbcs - for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i) + LFGMgr* LFGMgr::instance() { - LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(i); - if (!dungeon) - continue; + static LFGMgr instance; + return &instance; + } - switch (dungeon->type) + void LFGMgr::_LoadFromDB(Field* fields, uint64 guid) + { + if (!fields) + return; + + if (!IS_GROUP_GUID(guid)) + return; + + SetLeader(guid, MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER)); + + uint32 dungeon = fields[17].GetUInt32(); + uint8 state = fields[18].GetUInt8(); + + if (!dungeon || !state) + return; + + SetDungeon(guid, dungeon); + + switch (state) { - case LFG_TYPE_DUNGEON: - case LFG_TYPE_HEROIC: - case LFG_TYPE_RAID: - case LFG_TYPE_RANDOM: - LfgDungeonStore[dungeon->ID] = LFGDungeonData(dungeon); + case LFG_STATE_DUNGEON: + case LFG_STATE_FINISHED_DUNGEON: + SetState(guid, (LfgState)state); + break; + default: break; } } - // Fill teleport locations from DB - // 0 1 2 3 4 - QueryResult result = WorldDatabase.Query("SELECT dungeonId, position_x, position_y, position_z, orientation FROM lfg_dungeon_template"); - - if (!result) + void LFGMgr::_SaveToDB(uint64 guid) { - sLog->outError(">> Loaded 0 lfg entrance positions. DB table `lfg_dungeon_template` is empty!"); - return; + if (!IS_GROUP_GUID(guid)) + return; + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_LFG_DATA); + stmt->setUInt32(0, GUID_LOPART(guid)); + stmt->setUInt32(1, GetDungeon(guid)); + stmt->setUInt32(2, GetState(guid)); + CharacterDatabase.Execute(stmt); } - uint32 count = 0; - - do + /// Load rewards for completing dungeons + void LFGMgr::LoadRewards() { - Field* fields = result->Fetch(); - uint32 dungeonId = fields[0].GetUInt32(); - LFGDungeonContainer::iterator dungeonItr = LfgDungeonStore.find(dungeonId); - if (dungeonItr == LfgDungeonStore.end()) + uint32 oldMSTime = getMSTime(); + + for (LfgRewardContainer::iterator itr = RewardMapStore.begin(); itr != RewardMapStore.end(); ++itr) + delete itr->second; + RewardMapStore.clear(); + + // ORDER BY is very important for GetRandomDungeonReward! + QueryResult result = WorldDatabase.Query("SELECT dungeonId, maxLevel, firstQuestId, otherQuestId FROM lfg_dungeon_rewards ORDER BY dungeonId, maxLevel ASC"); + + if (!result) { - sLog->outError("table `lfg_dungeon_template` contains coordinates for wrong dungeon %u", dungeonId); - continue; + sLog->outError(">> Loaded 0 lfg dungeon rewards. DB table `lfg_dungeon_rewards` is empty!"); + return; } - LFGDungeonData& data = dungeonItr->second; - data.x = fields[1].GetFloat(); - data.y = fields[2].GetFloat(); - data.z = fields[3].GetFloat(); - data.o = fields[4].GetFloat(); + uint32 count = 0; - ++count; - } - while (result->NextRow()); - - sLog->outString(">> Loaded %u lfg entrance positions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - - // Fill all other teleport coords from areatriggers - for (LFGDungeonContainer::iterator itr = LfgDungeonStore.begin(); itr != LfgDungeonStore.end(); ++itr) - { - LFGDungeonData& dungeon = itr->second; - - // No teleport coords in database, load from areatriggers - if (dungeon.type != LFG_TYPE_RANDOM && dungeon.x == 0.0f && dungeon.y == 0.0f && dungeon.z == 0.0f) + Field* fields = nullptr; + do { - AreaTriggerTeleport const* at = sObjectMgr->GetMapEntranceTrigger(dungeon.map); - if (!at) + fields = result->Fetch(); + uint32 dungeonId = fields[0].GetUInt32(); + uint32 maxLevel = fields[1].GetUInt8(); + uint32 firstQuestId = fields[2].GetUInt32(); + uint32 otherQuestId = fields[3].GetUInt32(); + + if (!GetLFGDungeonEntry(dungeonId)) { - sLog->outError("LFGMgr::LoadLFGDungeons: Failed to load dungeon %s, cant find areatrigger for map %u", dungeon.name.c_str(), dungeon.map); + sLog->outError("Dungeon %u specified in table `lfg_dungeon_rewards` does not exist!", dungeonId); continue; } - dungeon.map = at->target_mapId; - dungeon.x = at->target_X; - dungeon.y = at->target_Y; - dungeon.z = at->target_Z; - dungeon.o = at->target_Orientation; - } - - if (dungeon.type != LFG_TYPE_RANDOM) - CachedDungeonMapStore[dungeon.group].insert(dungeon.id); - CachedDungeonMapStore[0].insert(dungeon.id); - } - - if (reload) - { - CachedDungeonMapStore.clear(); - // Recalculate locked dungeons - for (LfgPlayerDataContainer::const_iterator it = PlayersStore.begin(); it != PlayersStore.end(); ++it) - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(it->first)) - InitializeLockedDungeons(player); - } -} - -void LFGMgr::Update(uint32 tdiff, uint8 task) -{ - if (!isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - if (task == 0) - { - time_t currTime = time(nullptr); - - // Remove obsolete role checks - for (LfgRoleCheckContainer::iterator it = RoleChecksStore.begin(); it != RoleChecksStore.end();) - { - LfgRoleCheckContainer::iterator itRoleCheck = it++; - LfgRoleCheck& roleCheck = itRoleCheck->second; - if (currTime < roleCheck.cancelTime) - continue; - roleCheck.state = LFG_ROLECHECK_MISSING_ROLE; - - for (LfgRolesMap::const_iterator itRoles = roleCheck.roles.begin(); itRoles != roleCheck.roles.end(); ++itRoles) + if (!maxLevel || maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) { - uint64 guid = itRoles->first; - RestoreState(guid, "Remove Obsolete RoleCheck"); - SendLfgRoleCheckUpdate(guid, roleCheck); - if (guid == roleCheck.leader) - SendLfgJoinResult(guid, LfgJoinResultData(LFG_JOIN_FAILED, LFG_ROLECHECK_MISSING_ROLE)); + sLog->outError("Level %u specified for dungeon %u in table `lfg_dungeon_rewards` can never be reached!", maxLevel, dungeonId); + maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); } - RestoreState(itRoleCheck->first, "Remove Obsolete RoleCheck"); - RoleChecksStore.erase(itRoleCheck); - } - - // Remove obsolete proposals - for (LfgProposalContainer::iterator it = ProposalsStore.begin(); it != ProposalsStore.end();) - { - LfgProposalContainer::iterator itRemove = it++; - if (itRemove->second.cancelTime < currTime) - RemoveProposal(itRemove, LFG_UPDATETYPE_PROPOSAL_FAILED); - } - - // Remove obsolete kicks - for (LfgPlayerBootContainer::iterator it = BootsStore.begin(); it != BootsStore.end();) - { - LfgPlayerBootContainer::iterator itBoot = it++; - LfgPlayerBoot& boot = itBoot->second; - if (boot.cancelTime < currTime) + if (!firstQuestId || !sObjectMgr->GetQuestTemplate(firstQuestId)) { - boot.inProgress = false; - for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes) + sLog->outError("First quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", firstQuestId, dungeonId); + continue; + } + + if (otherQuestId && !sObjectMgr->GetQuestTemplate(otherQuestId)) + { + sLog->outError("Other quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", otherQuestId, dungeonId); + otherQuestId = 0; + } + + RewardMapStore.insert(LfgRewardContainer::value_type(dungeonId, new LfgReward(maxLevel, firstQuestId, otherQuestId))); + ++count; + } while (result->NextRow()); + + sLog->outString(">> Loaded %u lfg dungeon rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + sLog->outString(); + } + + LFGDungeonData const* LFGMgr::GetLFGDungeon(uint32 id) + { + LFGDungeonContainer::const_iterator itr = LfgDungeonStore.find(id); + if (itr != LfgDungeonStore.end()) + return &(itr->second); + + return nullptr; + } + + void LFGMgr::LoadLFGDungeons(bool reload /* = false */) + { + uint32 oldMSTime = getMSTime(); + + LfgDungeonStore.clear(); + + // Initialize Dungeon map with data from dbcs + for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i) + { + LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(i); + if (!dungeon) + continue; + + switch (dungeon->type) + { + case LFG_TYPE_DUNGEON: + case LFG_TYPE_HEROIC: + case LFG_TYPE_RAID: + case LFG_TYPE_RANDOM: + LfgDungeonStore[dungeon->ID] = LFGDungeonData(dungeon); + break; + } + } + + // Fill teleport locations from DB + // 0 1 2 3 4 + QueryResult result = WorldDatabase.Query("SELECT dungeonId, position_x, position_y, position_z, orientation FROM lfg_dungeon_template"); + + if (!result) + { + sLog->outError(">> Loaded 0 lfg entrance positions. DB table `lfg_dungeon_template` is empty!"); + return; + } + + uint32 count = 0; + + do + { + Field* fields = result->Fetch(); + uint32 dungeonId = fields[0].GetUInt32(); + LFGDungeonContainer::iterator dungeonItr = LfgDungeonStore.find(dungeonId); + if (dungeonItr == LfgDungeonStore.end()) + { + sLog->outError("table `lfg_dungeon_template` contains coordinates for wrong dungeon %u", dungeonId); + continue; + } + + LFGDungeonData& data = dungeonItr->second; + data.x = fields[1].GetFloat(); + data.y = fields[2].GetFloat(); + data.z = fields[3].GetFloat(); + data.o = fields[4].GetFloat(); + + ++count; + } while (result->NextRow()); + + sLog->outString(">> Loaded %u lfg entrance positions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + + // Fill all other teleport coords from areatriggers + for (LFGDungeonContainer::iterator itr = LfgDungeonStore.begin(); itr != LfgDungeonStore.end(); ++itr) + { + LFGDungeonData& dungeon = itr->second; + + // No teleport coords in database, load from areatriggers + if (dungeon.type != LFG_TYPE_RANDOM && dungeon.x == 0.0f && dungeon.y == 0.0f && dungeon.z == 0.0f) + { + AreaTriggerTeleport const* at = sObjectMgr->GetMapEntranceTrigger(dungeon.map); + if (!at) { - uint64 pguid = itVotes->first; - if (pguid != boot.victim) - SendLfgBootProposalUpdate(pguid, boot); - SetState(pguid, LFG_STATE_DUNGEON); + sLog->outError("LFGMgr::LoadLFGDungeons: Failed to load dungeon %s, cant find areatrigger for map %u", dungeon.name.c_str(), dungeon.map); + continue; } - SetState(itBoot->first, LFG_STATE_DUNGEON); - BootsStore.erase(itBoot); + + dungeon.map = at->target_mapId; + dungeon.x = at->target_X; + dungeon.y = at->target_Y; + dungeon.z = at->target_Z; + dungeon.o = at->target_Orientation; } - } - } - else if (task == 1) - { - this->lastProposalId = m_lfgProposalId; // pussywizard: task 2 is done independantly, store previous value in LFGMgr for future use - uint8 newGroupsProcessed = 0; - // Check if a proposal can be formed with the new groups being added - for (LfgQueueContainer::iterator it = QueuesStore.begin(); it != QueuesStore.end(); ++it) - { - newGroupsProcessed += it->second.FindGroups(); - if (newGroupsProcessed) - break; + + if (dungeon.type != LFG_TYPE_RANDOM) + CachedDungeonMapStore[dungeon.group].insert(dungeon.id); + CachedDungeonMapStore[0].insert(dungeon.id); } - // Update all players status queue info - if (!newGroupsProcessed) // don't do this on updates that precessed groups (performance) - for (LfgQueueContainer::iterator it = QueuesStore.begin(); it != QueuesStore.end(); ++it) - it->second.UpdateQueueTimers(tdiff); - } - else if (task == 2) - { - if (lastProposalId != m_lfgProposalId) + if (reload) { - // pussywizard: only one proposal can be created in World::Update (during maps update), and it has id == m_lfgProposalId, so try to find only that one, dunno why for loop here xD - for (LfgProposalContainer::const_iterator itProposal = ProposalsStore.find(m_lfgProposalId); itProposal != ProposalsStore.end(); ++itProposal) + CachedDungeonMapStore.clear(); + // Recalculate locked dungeons + for (LfgPlayerDataContainer::const_iterator it = PlayersStore.begin(); it != PlayersStore.end(); ++it) + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(it->first)) + InitializeLockedDungeons(player); + } + } + + void LFGMgr::Update(uint32 tdiff, uint8 task) + { + if (!isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + if (task == 0) + { + time_t currTime = time(nullptr); + + // Remove obsolete role checks + for (LfgRoleCheckContainer::iterator it = RoleChecksStore.begin(); it != RoleChecksStore.end();) { - uint32 proposalId = itProposal->first; - LfgProposal& proposal = ProposalsStore[proposalId]; + LfgRoleCheckContainer::iterator itRoleCheck = it++; + LfgRoleCheck& roleCheck = itRoleCheck->second; + if (currTime < roleCheck.cancelTime) + continue; + roleCheck.state = LFG_ROLECHECK_MISSING_ROLE; - uint64 guid = 0; - for (LfgProposalPlayerContainer::const_iterator itPlayers = proposal.players.begin(); itPlayers != proposal.players.end(); ++itPlayers) + for (LfgRolesMap::const_iterator itRoles = roleCheck.roles.begin(); itRoles != roleCheck.roles.end(); ++itRoles) { - guid = itPlayers->first; - SetState(guid, LFG_STATE_PROPOSAL); - if (uint64 gguid = GetGroup(guid)) + uint64 guid = itRoles->first; + RestoreState(guid, "Remove Obsolete RoleCheck"); + SendLfgRoleCheckUpdate(guid, roleCheck); + if (guid == roleCheck.leader) + SendLfgJoinResult(guid, LfgJoinResultData(LFG_JOIN_FAILED, LFG_ROLECHECK_MISSING_ROLE)); + } + + RestoreState(itRoleCheck->first, "Remove Obsolete RoleCheck"); + RoleChecksStore.erase(itRoleCheck); + } + + // Remove obsolete proposals + for (LfgProposalContainer::iterator it = ProposalsStore.begin(); it != ProposalsStore.end();) + { + LfgProposalContainer::iterator itRemove = it++; + if (itRemove->second.cancelTime < currTime) + RemoveProposal(itRemove, LFG_UPDATETYPE_PROPOSAL_FAILED); + } + + // Remove obsolete kicks + for (LfgPlayerBootContainer::iterator it = BootsStore.begin(); it != BootsStore.end();) + { + LfgPlayerBootContainer::iterator itBoot = it++; + LfgPlayerBoot& boot = itBoot->second; + if (boot.cancelTime < currTime) + { + boot.inProgress = false; + for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes) { - SetState(gguid, LFG_STATE_PROPOSAL); - SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_PROPOSAL_BEGIN, GetSelectedDungeons(guid), GetComment(guid))); + uint64 pguid = itVotes->first; + if (pguid != boot.victim) + SendLfgBootProposalUpdate(pguid, boot); + SetState(pguid, LFG_STATE_DUNGEON); } - else - SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_PROPOSAL_BEGIN, GetSelectedDungeons(guid), GetComment(guid))); - SendLfgUpdateProposal(guid, proposal); + SetState(itBoot->first, LFG_STATE_DUNGEON); + BootsStore.erase(itBoot); } - - if (proposal.state == LFG_PROPOSAL_SUCCESS) // pussywizard: no idea what's the purpose of this xD - UpdateProposal(proposalId, guid, true); } } - - UpdateRaidBrowser(tdiff); - } -} - -/** - Generate the dungeon lock map for a given player - - @param[in] player Player we need to initialize the lock status map -*/ -void LFGMgr::InitializeLockedDungeons(Player* player, uint8 level /* = 0 */) -{ - uint64 guid = player->GetGUID(); - if (!level) - level = player->getLevel(); - uint8 expansion = player->GetSession()->Expansion(); - LfgDungeonSet const& dungeons = GetDungeonsByRandom(0); - LfgLockMap lock; - - float avgItemLevel = player->GetAverageItemLevelForDF(); - - for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it) - { - LFGDungeonData const* dungeon = GetLFGDungeon(*it); - if (!dungeon) // should never happen - We provide a list from sLFGDungeonStore - continue; - MapEntry const* mapEntry = sMapStore.LookupEntry(dungeon->map); - - uint32 lockData = 0; - if (dungeon->expansion > expansion) - lockData = LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION; - else if (DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, dungeon->map, player)) - lockData = LFG_LOCKSTATUS_RAID_LOCKED; - else if (DisableMgr::IsDisabledFor(DISABLE_TYPE_LFG_MAP, dungeon->map, player)) - lockData = LFG_LOCKSTATUS_RAID_LOCKED; - else if (dungeon->difficulty > DUNGEON_DIFFICULTY_NORMAL && (!mapEntry || !mapEntry->IsRaid()) && sInstanceSaveMgr->PlayerIsPermBoundToInstance(player->GetGUIDLow(), dungeon->map, Difficulty(dungeon->difficulty))) - lockData = LFG_LOCKSTATUS_RAID_LOCKED; - else if (dungeon->minlevel > level) - lockData = LFG_LOCKSTATUS_TOO_LOW_LEVEL; - else if (dungeon->maxlevel < level) - lockData = LFG_LOCKSTATUS_TOO_HIGH_LEVEL; - else if (dungeon->seasonal && !IsSeasonActive(dungeon->id)) - lockData = LFG_LOCKSTATUS_NOT_IN_SEASON; - else if (AccessRequirement const* ar = sObjectMgr->GetAccessRequirement(dungeon->map, Difficulty(dungeon->difficulty))) + else if (task == 1) { - if (ar->achievement && !player->HasAchieved(ar->achievement)) - lockData = LFG_LOCKSTATUS_MISSING_ACHIEVEMENT; - else if (ar->reqItemLevel && (float)ar->reqItemLevel > avgItemLevel) - lockData = LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE; - else if (player->GetTeamId() == TEAM_ALLIANCE && ar->quest_A && !player->GetQuestRewardStatus(ar->quest_A)) - lockData = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED; - else if (player->GetTeamId() == TEAM_HORDE && ar->quest_H && !player->GetQuestRewardStatus(ar->quest_H)) - lockData = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED; - else - if (ar->item) + this->lastProposalId = m_lfgProposalId; // pussywizard: task 2 is done independantly, store previous value in LFGMgr for future use + uint8 newGroupsProcessed = 0; + // Check if a proposal can be formed with the new groups being added + for (LfgQueueContainer::iterator it = QueuesStore.begin(); it != QueuesStore.end(); ++it) + { + newGroupsProcessed += it->second.FindGroups(); + if (newGroupsProcessed) + break; + } + + // Update all players status queue info + if (!newGroupsProcessed) // don't do this on updates that precessed groups (performance) + for (LfgQueueContainer::iterator it = QueuesStore.begin(); it != QueuesStore.end(); ++it) + it->second.UpdateQueueTimers(tdiff); + } + else if (task == 2) + { + if (lastProposalId != m_lfgProposalId) + { + // pussywizard: only one proposal can be created in World::Update (during maps update), and it has id == m_lfgProposalId, so try to find only that one, dunno why for loop here xD + for (LfgProposalContainer::const_iterator itProposal = ProposalsStore.find(m_lfgProposalId); itProposal != ProposalsStore.end(); ++itProposal) + { + uint32 proposalId = itProposal->first; + LfgProposal& proposal = ProposalsStore[proposalId]; + + uint64 guid = 0; + for (LfgProposalPlayerContainer::const_iterator itPlayers = proposal.players.begin(); itPlayers != proposal.players.end(); ++itPlayers) + { + guid = itPlayers->first; + SetState(guid, LFG_STATE_PROPOSAL); + if (uint64 gguid = GetGroup(guid)) + { + SetState(gguid, LFG_STATE_PROPOSAL); + SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_PROPOSAL_BEGIN, GetSelectedDungeons(guid), GetComment(guid))); + } + else + SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_PROPOSAL_BEGIN, GetSelectedDungeons(guid), GetComment(guid))); + SendLfgUpdateProposal(guid, proposal); + } + + if (proposal.state == LFG_PROPOSAL_SUCCESS) // pussywizard: no idea what's the purpose of this xD + UpdateProposal(proposalId, guid, true); + } + } + + UpdateRaidBrowser(tdiff); + } + } + + /** + Generate the dungeon lock map for a given player + + @param[in] player Player we need to initialize the lock status map + */ + void LFGMgr::InitializeLockedDungeons(Player* player, uint8 level /* = 0 */) + { + uint64 guid = player->GetGUID(); + if (!level) + level = player->getLevel(); + uint8 expansion = player->GetSession()->Expansion(); + LfgDungeonSet const& dungeons = GetDungeonsByRandom(0); + LfgLockMap lock; + + float avgItemLevel = player->GetAverageItemLevelForDF(); + + for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it) + { + LFGDungeonData const* dungeon = GetLFGDungeon(*it); + if (!dungeon) // should never happen - We provide a list from sLFGDungeonStore + continue; + MapEntry const* mapEntry = sMapStore.LookupEntry(dungeon->map); + + uint32 lockData = 0; + if (dungeon->expansion > expansion) + lockData = LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION; + else if (DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, dungeon->map, player)) + lockData = LFG_LOCKSTATUS_RAID_LOCKED; + else if (DisableMgr::IsDisabledFor(DISABLE_TYPE_LFG_MAP, dungeon->map, player)) + lockData = LFG_LOCKSTATUS_RAID_LOCKED; + else if (dungeon->difficulty > DUNGEON_DIFFICULTY_NORMAL && (!mapEntry || !mapEntry->IsRaid()) && sInstanceSaveMgr->PlayerIsPermBoundToInstance(player->GetGUIDLow(), dungeon->map, Difficulty(dungeon->difficulty))) + lockData = LFG_LOCKSTATUS_RAID_LOCKED; + else if (dungeon->minlevel > level) + lockData = LFG_LOCKSTATUS_TOO_LOW_LEVEL; + else if (dungeon->maxlevel < level) + lockData = LFG_LOCKSTATUS_TOO_HIGH_LEVEL; + else if (dungeon->seasonal && !IsSeasonActive(dungeon->id)) + lockData = LFG_LOCKSTATUS_NOT_IN_SEASON; + else if (AccessRequirement const* ar = sObjectMgr->GetAccessRequirement(dungeon->map, Difficulty(dungeon->difficulty))) + { + if (ar->achievement && !player->HasAchieved(ar->achievement)) + lockData = LFG_LOCKSTATUS_MISSING_ACHIEVEMENT; + else if (ar->reqItemLevel && (float)ar->reqItemLevel > avgItemLevel) + lockData = LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE; + else if (player->GetTeamId() == TEAM_ALLIANCE && ar->quest_A && !player->GetQuestRewardStatus(ar->quest_A)) + lockData = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED; + else if (player->GetTeamId() == TEAM_HORDE && ar->quest_H && !player->GetQuestRewardStatus(ar->quest_H)) + lockData = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED; + else if (ar->item) { if (!player->HasItemCount(ar->item) && (!ar->item2 || !player->HasItemCount(ar->item2))) lockData = LFG_LOCKSTATUS_MISSING_ITEM; } else if (ar->item2 && !player->HasItemCount(ar->item2)) lockData = LFG_LOCKSTATUS_MISSING_ITEM; - } - - - sScriptMgr->OnInitializeLockedDungeons(player, level, lockData); - - /* TODO VoA closed if WG is not under team control (LFG_LOCKSTATUS_RAID_LOCKED) - lockData = LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE; - lockData = LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE; - lockData = LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL; - lockData = LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL; - */ - - if (lockData) - lock[dungeon->Entry()] = lockData; - } - - sScriptMgr->OnAfterInitializeLockedDungeons(player); - - SetLockedDungeons(guid, lock); -} - -/** - Adds the player/group to lfg queue. If player is in a group then it is the leader - of the group tying to join the group. Join conditions are checked before adding - to the new queue. - - @param[in] player Player trying to join (or leader of group trying to join) - @param[in] roles Player selected roles - @param[in] dungeons Dungeons the player/group is applying for - @param[in] comment Player selected comment -*/ -void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const std::string& comment) -{ - if (!player || dungeons.empty()) - return; - - Group* grp = player->GetGroup(); - uint64 guid = player->GetGUID(); - uint64 gguid = grp ? grp->GetGUID() : guid; - LfgJoinResultData joinData; - LfgGuidSet players; - uint32 rDungeonId = 0; - bool isContinue = grp && grp->isLFGGroup() && GetState(gguid) != LFG_STATE_FINISHED_DUNGEON; - - if (grp && (grp->isBGGroup() || grp->isBFGroup())) - return; - - // pussywizard: can't join LFG/LFR while using LFR - if (GetState(player->GetGUID()) == LFG_STATE_RAIDBROWSER) - { - LfgDungeonSet tmp; - SendRaidBrowserJoinedPacket(player, tmp, ""); // the df "eye" can disappear in various case, resend if needed - return; - } - - // Do not allow to change dungeon in the middle of a current dungeon - if (isContinue) - { - dungeons.clear(); - dungeons.insert(GetDungeon(gguid)); - } - - LfgState state = GetState(gguid); - switch (state) - { - case LFG_STATE_ROLECHECK: // if joining again during rolecheck (eg. many players clicked continue inside instance) - if (IS_GROUP_GUID(gguid)) - UpdateRoleCheck(gguid); // abort role check and remove from RoleChecksStore - break; - case LFG_STATE_QUEUED: // joining again while in a queue - { - LFGQueue& queue = GetQueue(gguid); - queue.RemoveFromQueue(gguid); } - break; - case LFG_STATE_PROPOSAL: // if joining again during proposal - joinData.result = LFG_JOIN_INTERNAL_ERROR; - break; - /*case LFG_STATE_FINISHED_DUNGEON: - if (grp && grp->isLFGGroup()) - joinData.result = LFG_JOIN_PARTY_NOT_MEET_REQS; - break; - */ - default: - break; - } - // Check if all dungeons are valid - bool isRaid = false; - if (joinData.result == LFG_JOIN_OK) - { - bool isDungeon = false; - for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end() && joinData.result == LFG_JOIN_OK; ++it) - { - LfgType type = GetDungeonType(*it); - switch (type) - { - case LFG_TYPE_RANDOM: - if (dungeons.size() > 1) // Only allow 1 random dungeon - { - joinData.result = LFG_JOIN_DUNGEON_INVALID; - } - else - { - rDungeonId = (*dungeons.begin()); - } - // No break on purpose (Random can only be dungeon or heroic dungeon) - [[fallthrough]]; - case LFG_TYPE_HEROIC: - case LFG_TYPE_DUNGEON: - if (isRaid) - { - joinData.result = LFG_JOIN_MIXED_RAID_DUNGEON; - } - isDungeon = true; - break; - case LFG_TYPE_RAID: - if (isDungeon) - { - joinData.result = LFG_JOIN_MIXED_RAID_DUNGEON; - } - isRaid = true; - break; - default: - sLog->outError("Wrong dungeon type %u for dungeon %u", type, *it); - joinData.result = LFG_JOIN_DUNGEON_INVALID; - break; - } + + sScriptMgr->OnInitializeLockedDungeons(player, level, lockData); + + /* TODO VoA closed if WG is not under team control (LFG_LOCKSTATUS_RAID_LOCKED) + lockData = LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE; + lockData = LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE; + lockData = LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL; + lockData = LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL; + */ + + if (lockData) + lock[dungeon->Entry()] = lockData; } + + sScriptMgr->OnAfterInitializeLockedDungeons(player); + + SetLockedDungeons(guid, lock); } - if (!isRaid && joinData.result == LFG_JOIN_OK) + /** + Adds the player/group to lfg queue. If player is in a group then it is the leader + of the group tying to join the group. Join conditions are checked before adding + to the new queue. + + @param[in] player Player trying to join (or leader of group trying to join) + @param[in] roles Player selected roles + @param[in] dungeons Dungeons the player/group is applying for + @param[in] comment Player selected comment + */ + void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const std::string& comment) { - // Check player or group member restrictions - if (player->InBattleground() || player->InArena() || player->InBattlegroundQueue()) - joinData.result = LFG_JOIN_USING_BG_SYSTEM; - else if (player->HasAura(LFG_SPELL_DUNGEON_DESERTER)) - joinData.result = LFG_JOIN_DESERTER; - else if (dungeons.empty()) - joinData.result = LFG_JOIN_NOT_MEET_REQS; - else if (grp) - { - if (grp->GetMembersCount() > MAXGROUPSIZE) - joinData.result = LFG_JOIN_TOO_MUCH_MEMBERS; - else - { - uint8 memberCount = 0; - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && joinData.result == LFG_JOIN_OK; itr = itr->next()) - { - if (Player* plrg = itr->GetSource()) - { - if (plrg->HasAura(LFG_SPELL_DUNGEON_DESERTER)) - joinData.result = LFG_JOIN_PARTY_DESERTER; - else if (plrg->InBattleground() || plrg->InArena() || plrg->InBattlegroundQueue()) - joinData.result = LFG_JOIN_USING_BG_SYSTEM; - ++memberCount; - players.insert(plrg->GetGUID()); - } - } - - if (joinData.result == LFG_JOIN_OK && memberCount != grp->GetMembersCount()) - joinData.result = LFG_JOIN_DISCONNECTED; - } - } - else - players.insert(player->GetGUID()); - - // Xinef: Check dungeon cooldown only for random dungeons - // Xinef: Moreover check this only if dungeon is not started, afterwards its obvious that players will have the cooldown - if (joinData.result == LFG_JOIN_OK && !isContinue && rDungeonId) - { - if (player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) // xinef: added !isContinue - joinData.result = LFG_JOIN_RANDOM_COOLDOWN; - else if (grp) - { - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && joinData.result == LFG_JOIN_OK; itr = itr->next()) - if (Player* plrg = itr->GetSource()) - if (plrg->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) // xinef: added !isContinue - joinData.result = LFG_JOIN_PARTY_RANDOM_COOLDOWN; - } - } - } - - if (isRaid) - players.insert(player->GetGUID()); - - if (joinData.result == LFG_JOIN_OK) - { - // Expand random dungeons and check restrictions - if (rDungeonId) - dungeons = GetDungeonsByRandom(rDungeonId); - - // if we have lockmap then there are no compatible dungeons - // xinef: dont check compatibile dungeons for already running group (bind problems) - if (!isContinue) - { - GetCompatibleDungeons(dungeons, players, joinData.lockmap); - if (dungeons.empty()) - joinData.result = grp ? LFG_JOIN_PARTY_NOT_MEET_REQS : LFG_JOIN_NOT_MEET_REQS; - } - } - - // pussywizard: - if (isRaid && grp && (grp->isLFGGroup() || guid != grp->GetLeaderGUID())) - return; - - // Can't join. Send result - if (joinData.result != LFG_JOIN_OK) - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::Join: [" UI64FMTD "] joining with %u members. result: %u", guid, grp ? grp->GetMembersCount() : 1, joinData.result); -#endif - if (!dungeons.empty()) // Only should show lockmap when have no dungeons available - joinData.lockmap.clear(); - player->GetSession()->SendLfgJoinResult(joinData); - return; - } - - SetComment(guid, comment); - - if (isRaid) - { - if (grp) - roles = PLAYER_ROLE_LEADER; - else - roles &= (PLAYER_ROLE_TANK | PLAYER_ROLE_HEALER | PLAYER_ROLE_DAMAGE); - if (!roles) + if (!player || dungeons.empty()) return; - JoinRaidBrowser(player, roles, dungeons, comment); - SetState(guid, LFG_STATE_RAIDBROWSER); - SendRaidBrowserJoinedPacket(player, dungeons, comment); - return; - } - std::string debugNames = ""; - if (grp) // Begin rolecheck - { - // Create new rolecheck - LfgRoleCheck& roleCheck = RoleChecksStore[gguid]; - roleCheck.roles.clear(); // pussywizard: NEW rolecheck, not old one with trash data >_> - roleCheck.cancelTime = time_t(time(nullptr)) + LFG_TIME_ROLECHECK; - roleCheck.state = LFG_ROLECHECK_INITIALITING; - roleCheck.leader = guid; - roleCheck.dungeons = dungeons; - roleCheck.rDungeonId = rDungeonId; + Group* grp = player->GetGroup(); + uint64 guid = player->GetGUID(); + uint64 gguid = grp ? grp->GetGUID() : guid; + LfgJoinResultData joinData; + LfgGuidSet players; + uint32 rDungeonId = 0; + bool isContinue = grp && grp->isLFGGroup() && GetState(gguid) != LFG_STATE_FINISHED_DUNGEON; - if (rDungeonId) + if (grp && (grp->isBGGroup() || grp->isBFGroup())) + return; + + // pussywizard: can't join LFG/LFR while using LFR + if (GetState(player->GetGUID()) == LFG_STATE_RAIDBROWSER) + { + LfgDungeonSet tmp; + SendRaidBrowserJoinedPacket(player, tmp, ""); // the df "eye" can disappear in various case, resend if needed + return; + } + + // Do not allow to change dungeon in the middle of a current dungeon + if (isContinue) { dungeons.clear(); - dungeons.insert(rDungeonId); + dungeons.insert(GetDungeon(gguid)); } - SetState(gguid, LFG_STATE_ROLECHECK); - // Send update to player - LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment); - for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) + LfgState state = GetState(gguid); + switch (state) { - if (Player* plrg = itr->GetSource()) + case LFG_STATE_ROLECHECK: // if joining again during rolecheck (eg. many players clicked continue inside instance) + if (IS_GROUP_GUID(gguid)) + UpdateRoleCheck(gguid); // abort role check and remove from RoleChecksStore + break; + case LFG_STATE_QUEUED: // joining again while in a queue + { + LFGQueue& queue = GetQueue(gguid); + queue.RemoveFromQueue(gguid); + } + break; + case LFG_STATE_PROPOSAL: // if joining again during proposal + joinData.result = LFG_JOIN_INTERNAL_ERROR; + break; + /*case LFG_STATE_FINISHED_DUNGEON: + if (grp && grp->isLFGGroup()) + joinData.result = LFG_JOIN_PARTY_NOT_MEET_REQS; + break; + */ + default: + break; + } + + // Check if all dungeons are valid + bool isRaid = false; + if (joinData.result == LFG_JOIN_OK) + { + bool isDungeon = false; + for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end() && joinData.result == LFG_JOIN_OK; ++it) { - uint64 pguid = plrg->GetGUID(); - plrg->GetSession()->SendLfgUpdateParty(updateData); - SetState(pguid, LFG_STATE_ROLECHECK); - if (!isContinue) - SetSelectedDungeons(pguid, dungeons); - roleCheck.roles[pguid] = 0; - if (!debugNames.empty()) - debugNames.append(", "); - debugNames.append(plrg->GetName()); + LfgType type = GetDungeonType(*it); + switch (type) + { + case LFG_TYPE_RANDOM: + if (dungeons.size() > 1) // Only allow 1 random dungeon + { + joinData.result = LFG_JOIN_DUNGEON_INVALID; + } + else + { + rDungeonId = (*dungeons.begin()); + } + // No break on purpose (Random can only be dungeon or heroic dungeon) + [[fallthrough]]; + case LFG_TYPE_HEROIC: + case LFG_TYPE_DUNGEON: + if (isRaid) + { + joinData.result = LFG_JOIN_MIXED_RAID_DUNGEON; + } + isDungeon = true; + break; + case LFG_TYPE_RAID: + if (isDungeon) + { + joinData.result = LFG_JOIN_MIXED_RAID_DUNGEON; + } + isRaid = true; + break; + default: + sLog->outError("Wrong dungeon type %u for dungeon %u", type, *it); + joinData.result = LFG_JOIN_DUNGEON_INVALID; + break; + } } } - // Update leader role - UpdateRoleCheck(gguid, guid, roles); - } - else // Add player to queue - { - LfgRolesMap rolesMap; - rolesMap[guid] = roles; - LFGQueue& queue = GetQueue(guid); - queue.AddQueueData(guid, time(nullptr), dungeons, rolesMap); - if (!isContinue) + if (!isRaid && joinData.result == LFG_JOIN_OK) { + // Check player or group member restrictions + if (player->InBattleground() || player->InArena() || player->InBattlegroundQueue()) + joinData.result = LFG_JOIN_USING_BG_SYSTEM; + else if (player->HasAura(LFG_SPELL_DUNGEON_DESERTER)) + joinData.result = LFG_JOIN_DESERTER; + else if (dungeons.empty()) + joinData.result = LFG_JOIN_NOT_MEET_REQS; + else if (grp) + { + if (grp->GetMembersCount() > MAXGROUPSIZE) + joinData.result = LFG_JOIN_TOO_MUCH_MEMBERS; + else + { + uint8 memberCount = 0; + for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && joinData.result == LFG_JOIN_OK; itr = itr->next()) + { + if (Player* plrg = itr->GetSource()) + { + if (plrg->HasAura(LFG_SPELL_DUNGEON_DESERTER)) + joinData.result = LFG_JOIN_PARTY_DESERTER; + else if (plrg->InBattleground() || plrg->InArena() || plrg->InBattlegroundQueue()) + joinData.result = LFG_JOIN_USING_BG_SYSTEM; + ++memberCount; + players.insert(plrg->GetGUID()); + } + } + + if (joinData.result == LFG_JOIN_OK && memberCount != grp->GetMembersCount()) + joinData.result = LFG_JOIN_DISCONNECTED; + } + } + else + players.insert(player->GetGUID()); + + // Xinef: Check dungeon cooldown only for random dungeons + // Xinef: Moreover check this only if dungeon is not started, afterwards its obvious that players will have the cooldown + if (joinData.result == LFG_JOIN_OK && !isContinue && rDungeonId) + { + if (player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) // xinef: added !isContinue + joinData.result = LFG_JOIN_RANDOM_COOLDOWN; + else if (grp) + { + for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && joinData.result == LFG_JOIN_OK; itr = itr->next()) + if (Player* plrg = itr->GetSource()) + if (plrg->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) // xinef: added !isContinue + joinData.result = LFG_JOIN_PARTY_RANDOM_COOLDOWN; + } + } + } + + if (isRaid) + players.insert(player->GetGUID()); + + if (joinData.result == LFG_JOIN_OK) + { + // Expand random dungeons and check restrictions + if (rDungeonId) + dungeons = GetDungeonsByRandom(rDungeonId); + + // if we have lockmap then there are no compatible dungeons + // xinef: dont check compatibile dungeons for already running group (bind problems) + if (!isContinue) + { + GetCompatibleDungeons(dungeons, players, joinData.lockmap); + if (dungeons.empty()) + joinData.result = grp ? LFG_JOIN_PARTY_NOT_MEET_REQS : LFG_JOIN_NOT_MEET_REQS; + } + } + + // pussywizard: + if (isRaid && grp && (grp->isLFGGroup() || guid != grp->GetLeaderGUID())) + return; + + // Can't join. Send result + if (joinData.result != LFG_JOIN_OK) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::Join: [" UI64FMTD "] joining with %u members. result: %u", guid, grp ? grp->GetMembersCount() : 1, joinData.result); +#endif + if (!dungeons.empty()) // Only should show lockmap when have no dungeons available + joinData.lockmap.clear(); + player->GetSession()->SendLfgJoinResult(joinData); + return; + } + + SetComment(guid, comment); + + if (isRaid) + { + if (grp) + roles = PLAYER_ROLE_LEADER; + else + roles &= (PLAYER_ROLE_TANK | PLAYER_ROLE_HEALER | PLAYER_ROLE_DAMAGE); + if (!roles) + return; + JoinRaidBrowser(player, roles, dungeons, comment); + SetState(guid, LFG_STATE_RAIDBROWSER); + SendRaidBrowserJoinedPacket(player, dungeons, comment); + return; + } + + std::string debugNames = ""; + if (grp) // Begin rolecheck + { + // Create new rolecheck + LfgRoleCheck& roleCheck = RoleChecksStore[gguid]; + roleCheck.roles.clear(); // pussywizard: NEW rolecheck, not old one with trash data >_> + roleCheck.cancelTime = time_t(time(nullptr)) + LFG_TIME_ROLECHECK; + roleCheck.state = LFG_ROLECHECK_INITIALITING; + roleCheck.leader = guid; + roleCheck.dungeons = dungeons; + roleCheck.rDungeonId = rDungeonId; + if (rDungeonId) { dungeons.clear(); dungeons.insert(rDungeonId); } - SetSelectedDungeons(guid, dungeons); + + SetState(gguid, LFG_STATE_ROLECHECK); + // Send update to player + LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment); + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) + { + if (Player* plrg = itr->GetSource()) + { + uint64 pguid = plrg->GetGUID(); + plrg->GetSession()->SendLfgUpdateParty(updateData); + SetState(pguid, LFG_STATE_ROLECHECK); + if (!isContinue) + SetSelectedDungeons(pguid, dungeons); + roleCheck.roles[pguid] = 0; + if (!debugNames.empty()) + debugNames.append(", "); + debugNames.append(plrg->GetName()); + } + } + // Update leader role + UpdateRoleCheck(gguid, guid, roles); } - // Send update to player - player->GetSession()->SendLfgJoinResult(joinData); - player->GetSession()->SendLfgUpdatePlayer(LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment)); - SetState(guid, LFG_STATE_QUEUED); - SetRoles(guid, roles); - debugNames.append(player->GetName()); + else // Add player to queue + { + LfgRolesMap rolesMap; + rolesMap[guid] = roles; + LFGQueue& queue = GetQueue(guid); + queue.AddQueueData(guid, time(nullptr), dungeons, rolesMap); + + if (!isContinue) + { + if (rDungeonId) + { + dungeons.clear(); + dungeons.insert(rDungeonId); + } + SetSelectedDungeons(guid, dungeons); + } + // Send update to player + player->GetSession()->SendLfgJoinResult(joinData); + player->GetSession()->SendLfgUpdatePlayer(LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment)); + SetState(guid, LFG_STATE_QUEUED); + SetRoles(guid, roles); + debugNames.append(player->GetName()); + } + + /*if (sLog->ShouldLog(LOG_FILTER_LFG, LOG_LEVEL_DEBUG)) + { + std::ostringstream o; + o << "LFGMgr::Join: [" << guid << "] joined (" << (grp ? "group" : "player") << ") Members: " << debugNames.c_str() + << ". Dungeons (" << uint32(dungeons.size()) << "): " << ConcatenateDungeons(dungeons); + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug((LOG_FILTER_LFG, "%s", o.str().c_str()); + #endif + }*/ } - /*if (sLog->ShouldLog(LOG_FILTER_LFG, LOG_LEVEL_DEBUG)) - { - std::ostringstream o; - o << "LFGMgr::Join: [" << guid << "] joined (" << (grp ? "group" : "player") << ") Members: " << debugNames.c_str() - << ". Dungeons (" << uint32(dungeons.size()) << "): " << ConcatenateDungeons(dungeons); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug((LOG_FILTER_LFG, "%s", o.str().c_str()); -#endif - }*/ -} + /** + Leaves Dungeon System. Player/Group is removed from queue, rolechecks, proposals + or votekicks. Player or group needs to be not NULL and using Dungeon System -/** - Leaves Dungeon System. Player/Group is removed from queue, rolechecks, proposals - or votekicks. Player or group needs to be not NULL and using Dungeon System - - @param[in] guid Player or group guid -*/ -void LFGMgr::LeaveLfg(uint64 guid) -{ - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::Leave: [" UI64FMTD "]", guid); - uint64 gguid = IS_GROUP_GUID(guid) ? guid : GetGroup(guid); - LfgState state = GetState(guid); - switch (state) + @param[in] guid Player or group guid + */ + void LFGMgr::LeaveLfg(uint64 guid) { - case LFG_STATE_QUEUED: - if (gguid) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::Leave: [" UI64FMTD "]", guid); + uint64 gguid = IS_GROUP_GUID(guid) ? guid : GetGroup(guid); + LfgState state = GetState(guid); + switch (state) + { + case LFG_STATE_QUEUED: + if (gguid) + { + LFGQueue& queue = GetQueue(gguid); + queue.RemoveFromQueue(gguid); + SetState(gguid, LFG_STATE_NONE); + const LfgGuidSet& players = GetPlayers(gguid); + for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) + { + SetState(*it, LFG_STATE_NONE); + SendLfgUpdateParty(*it, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); + } + } + else + { + LFGQueue& queue = GetQueue(guid); + queue.RemoveFromQueue(guid); + SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); + SetState(guid, LFG_STATE_NONE); + } + break; + case LFG_STATE_ROLECHECK: + if (gguid) + UpdateRoleCheck(gguid); // No player to update role = LFG_ROLECHECK_ABORTED + break; + case LFG_STATE_PROPOSAL: + { + // Remove from Proposals + LfgProposalContainer::iterator it = ProposalsStore.begin(); + uint64 pguid = gguid == guid ? GetLeader(gguid) : guid; + while (it != ProposalsStore.end()) + { + LfgProposalPlayerContainer::iterator itPlayer = it->second.players.find(pguid); + if (itPlayer != it->second.players.end()) + { + // Mark the player/leader of group who left as didn't accept the proposal + itPlayer->second.accept = LFG_ANSWER_DENY; + break; + } + ++it; + } + + // Remove from queue - if proposal is found, RemoveProposal will call RemoveFromQueue + if (it != ProposalsStore.end()) + RemoveProposal(it, LFG_UPDATETYPE_PROPOSAL_DECLINED); + break; + } + case LFG_STATE_NONE: + break; + case LFG_STATE_DUNGEON: + case LFG_STATE_FINISHED_DUNGEON: + case LFG_STATE_BOOT: + if (guid != gguid) // Player + SetState(guid, LFG_STATE_NONE); + break; + case LFG_STATE_RAIDBROWSER: + LeaveRaidBrowser(guid); + SetCanOverrideRBState(guid, true); + SetState(guid, LFG_STATE_NONE); + SetCanOverrideRBState(guid, false); + SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_LEAVE_RAIDBROWSER)); + SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_LEAVE_RAIDBROWSER)); + break; + } + } + + void LFGMgr::JoinRaidBrowser(Player* player, uint8 roles, LfgDungeonSet& dungeons, std::string comment) + { + // pussywizard: client limit for comment length is 64 @ 3.3.5a + if (comment.size() > 64) + comment = comment.substr(0, 64); + + RBEntryInfo entry(roles, comment); + for (LfgDungeonSet::const_iterator itr = dungeons.begin(); itr != dungeons.end(); ++itr) + if (GetLFGDungeon(*itr)) // ensure dungeon data exists for such dungeon id + { + RaidBrowserStore[player->GetTeamId()][*itr][player->GetGUIDLow()] = entry; + RBUsedDungeonsStore[player->GetTeamId()].insert(*itr); + } + } + + void LFGMgr::LeaveRaidBrowser(uint64 guid) + { + uint32 guidLow = GUID_LOPART(guid); + for (uint8 team = 0; team < 2; ++team) + for (RBStoreMap::iterator itr = RaidBrowserStore[team].begin(); itr != RaidBrowserStore[team].end(); ++itr) + itr->second.erase(guidLow); + } + + void LFGMgr::SendRaidBrowserJoinedPacket(Player* p, LfgDungeonSet& dungeons, std::string comment) + { + if (dungeons.empty()) + { + RBEntryInfoMap::iterator iter; + uint8 team = p->GetTeamId(); + bool setComment = true; + for (RBStoreMap::iterator itr = RaidBrowserStore[team].begin(); itr != RaidBrowserStore[team].end(); ++itr) + if ((iter = itr->second.find(p->GetGUIDLow())) != itr->second.end()) + { + dungeons.insert(itr->first); + if (setComment) + { + comment = iter->second.comment; + setComment = false; + } + } + } + LfgJoinResultData joinData; + p->GetSession()->SendLfgJoinResult(joinData); + LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_RAIDBROWSER, dungeons, comment); + if (p->GetGroup()) + p->GetSession()->SendLfgUpdateParty(updateData); + else + p->GetSession()->SendLfgUpdatePlayer(updateData); + } + + void LFGMgr::LfrSearchAdd(Player* p, uint32 dungeonId) + { + RBSearchersStore[p->GetTeamId()][p->GetGUIDLow()] = dungeonId; + } + + void LFGMgr::LfrSearchRemove(Player* p) + { + RBSearchersStore[p->GetTeamId()].erase(p->GetGUIDLow()); + } + + void LFGMgr::SendRaidBrowserCachedList(Player* player, uint32 dungeonId) + { + RBCacheMap::iterator itr = RBCacheStore[player->GetTeamId()].find(dungeonId); + if (itr != RBCacheStore[player->GetTeamId()].end()) + { + player->GetSession()->SendPacket(&(itr->second)); + return; + } + // send empty packet if cache not found + WorldPacket data(SMSG_UPDATE_LFG_LIST, 1000); + data << (uint32)LFG_TYPE_RAID; + data << (uint32)dungeonId; + data << (uint8)0; + data << (uint32)0; + data << (uint32)0; + data << (uint32)0; + data << (uint32)0; + player->GetSession()->SendPacket(&data); + } + + void LFGMgr::UpdateRaidBrowser(uint32 diff) + { + for (uint8 team = 0; team < 2; ++team) + { + if (m_raidBrowserUpdateTimer[team] > diff) + m_raidBrowserUpdateTimer[team] -= diff; + else + m_raidBrowserUpdateTimer[team] = 0; + } + + if (getMSTimeDiff(World::GetGameTimeMS(), getMSTime()) > (70 * 7) / 5) // prevent lagging + return; + + uint64 guid, groupGuid, instanceGuid; + uint8 level, Class, race, talents[3]; + float iLevel, mp5, mp5combat, baseAP, rangedAP; + int32 spellDamage, spellHeal; + uint32 dungeonId, encounterMask, maxPower; + uint32 deletedCounter, groupCounter, playerCounter; + ByteBuffer buffer_deleted, buffer_groups, buffer_players; + std::string emptyComment; + std::set deletedGroups, deletedGroupsToErase; + RBInternalInfoMap copy; + + for (uint8 team = 0; team < 2; ++team) + { + if (m_raidBrowserLastUpdatedDungeonId[team] == 0) // new loop + { + if (m_raidBrowserUpdateTimer[team] > 0) // allowed only with some time interval + continue; + else // reset timer + m_raidBrowserUpdateTimer[team] = 5000; + } + + RBUsedDungeonsSet::const_iterator neitr, titr; + for (neitr = RBUsedDungeonsStore[team].begin(); neitr != RBUsedDungeonsStore[team].end(); ) + { + titr = neitr++; + dungeonId = (*titr); + + // go to next dungeon than previously (one dungeon updated in one LFGMgr::UpdateRaidBrowser) + if (dungeonId <= m_raidBrowserLastUpdatedDungeonId[team]) + continue; + m_raidBrowserLastUpdatedDungeonId[team] = dungeonId; + + RBEntryInfoMap& entryInfoMap = RaidBrowserStore[team][dungeonId]; + LFGDungeonData const* dungeonData = GetLFGDungeon(dungeonId); // checked if exists before inserting to the container + RBInternalInfoMap& currInternalInfoMap = RBInternalInfoStoreCurr[team][dungeonId]; + for (RBEntryInfoMap::const_iterator sitr = entryInfoMap.begin(); sitr != entryInfoMap.end(); ++sitr) + { + guid = MAKE_NEW_GUID(sitr->first, 0, HIGHGUID_PLAYER); + groupGuid = 0; + Player* p = ObjectAccessor::FindPlayerInOrOutOfWorld(guid); + ASSERT(p); + if (sitr->second.roles == PLAYER_ROLE_LEADER) + { + ASSERT(p->GetGroup()); + groupGuid = p->GetGroup()->GetGUID(); + } + encounterMask = 0; + instanceGuid = 0; + if (InstancePlayerBind* bind = sInstanceSaveMgr->PlayerGetBoundInstance(sitr->first, dungeonData->map, dungeonData->difficulty)) + if (bind->perm) + { + instanceGuid = MAKE_NEW_GUID(bind->save->GetInstanceId(), 0, HIGHGUID_INSTANCE); + encounterMask = bind->save->GetCompletedEncounterMask(); + } + + talents[0] = 0; + talents[1] = 0; + talents[2] = 0; + p->GetTalentTreePoints(talents); + spellDamage = p->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_ALL); + spellHeal = p->SpellBaseHealingBonusDone(SPELL_SCHOOL_MASK_ALL); + mp5 = p->GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER); + mp5combat = p->GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER); + baseAP = p->GetTotalAttackPowerValue(BASE_ATTACK); + rangedAP = p->GetTotalAttackPowerValue(RANGED_ATTACK); + maxPower = 0; + if (p->getClass() == CLASS_DRUID) + maxPower = p->GetMaxPower(POWER_MANA); + else + maxPower = (p->getPowerType() == POWER_RAGE || p->getPowerType() == POWER_RUNIC_POWER) ? p->GetMaxPower(p->getPowerType()) / 10 : p->GetMaxPower(p->getPowerType()); + + currInternalInfoMap[sitr->first] = RBInternalInfo(guid, sitr->second.comment, groupGuid != 0, groupGuid, sitr->second.roles, encounterMask, instanceGuid, + 1, p->getLevel(), p->getClass(), p->getRace(), p->GetAverageItemLevel(), + talents, p->m_last_area_id, p->GetArmor(), (uint32)std::max(0, spellDamage), (uint32)std::max(0, spellHeal), + p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_MELEE), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_RANGED), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_SPELL), std::max(0.0f, mp5), std::max(0.0f, mp5combat), + std::max(baseAP, rangedAP), (uint32)p->GetStat(STAT_AGILITY), p->GetMaxHealth(), maxPower, p->GetDefenseSkillValue(), + p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_DODGE), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_BLOCK), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_PARRY), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_HASTE_SPELL), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_EXPERTISE)); + + if (!groupGuid) + continue; + for (Group::member_citerator mitr = p->GetGroup()->GetMemberSlots().begin(); mitr != p->GetGroup()->GetMemberSlots().end(); ++mitr) + { + if (mitr->guid == sitr->first) // leader already added + continue; + guid = MAKE_NEW_GUID(mitr->guid, 0, HIGHGUID_PLAYER); + level = 1; + Class = 0; + race = 0; + iLevel = 0.0f; + talents[0] = 0; + talents[1] = 0; + talents[2] = 0; + if (const GlobalPlayerData* gpd = sWorld->GetGlobalPlayerData(mitr->guid)) + { + level = gpd->level; + Class = gpd->playerClass; + race = gpd->race; + } + Player* mplr = ObjectAccessor::FindPlayerInOrOutOfWorld(guid); + if (mplr) + { + iLevel = mplr->GetAverageItemLevel(); + mplr->GetTalentTreePoints(talents); + } + currInternalInfoMap[mitr->guid] = RBInternalInfo(guid, emptyComment, false, groupGuid, 0, 0, 0, + (mplr ? 1 : 0), level, Class, race, iLevel, + talents, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0); + } + } + + copy.clear(); + copy = currInternalInfoMap; // will be saved as prev at the end + + // compare prev with curr to build difference packet + deletedCounter = 0; + groupCounter = 0; + playerCounter = 0; + buffer_deleted.clear(); + buffer_groups.clear(); + buffer_players.clear(); + deletedGroups.clear(); + deletedGroupsToErase.clear(); + + RBInternalInfoMap& prevInternalInfoMap = RBInternalInfoStorePrev[team][dungeonId]; + RBInternalInfoMap::iterator iter, iterTmp; + for (RBInternalInfoMap::const_iterator sitr = prevInternalInfoMap.begin(); sitr != prevInternalInfoMap.end(); ++sitr) + { + iter = currInternalInfoMap.find(sitr->first); + if (iter == currInternalInfoMap.end()) // was -> isn't + { + if (sitr->second.isGroupLeader) + deletedGroups.insert(sitr->second.groupGuid); + ++deletedCounter; + buffer_deleted << (uint64)sitr->second.guid; + } + else // was -> is + { + if (sitr->second.isGroupLeader) // was a leader + { + if (!iter->second.isGroupLeader) // leader -> no longer a leader + deletedGroups.insert(sitr->second.groupGuid); + else if (sitr->second.groupGuid != iter->second.groupGuid) // leader -> leader of another group + { + deletedGroups.insert(sitr->second.groupGuid); + deletedGroupsToErase.insert(iter->second.groupGuid); + ++groupCounter; + RBPacketAppendGroup(iter->second, buffer_groups); + } + else if (sitr->second.comment != iter->second.comment || sitr->second.encounterMask != iter->second.encounterMask || sitr->second.instanceGuid != iter->second.instanceGuid) // leader -> nothing changed + { + ++groupCounter; + RBPacketAppendGroup(iter->second, buffer_groups); + } + } + else if (iter->second.isGroupLeader) // wasn't a leader -> is a leader + { + deletedGroupsToErase.insert(iter->second.groupGuid); + ++groupCounter; + RBPacketAppendGroup(iter->second, buffer_groups); + } + + if (!iter->second._online) // if offline, copy previous stats (itemLevel, talents, area, etc.) + { + iterTmp = copy.find(sitr->first); // copied container is for building a full packet, so modify it there (currInternalInfoMap is erased) + iterTmp->second.CopyStats(sitr->second); + if (!sitr->second.PlayerSameAs(iterTmp->second)) // player info changed + { + ++playerCounter; + RBPacketAppendPlayer(iterTmp->second, buffer_players); + } + } + else if (!sitr->second.PlayerSameAs(iter->second)) // player info changed + { + ++playerCounter; + RBPacketAppendPlayer(iter->second, buffer_players); + } + currInternalInfoMap.erase(iter); + } + } + // left entries (new) + for (RBInternalInfoMap::const_iterator sitr = currInternalInfoMap.begin(); sitr != currInternalInfoMap.end(); ++sitr) + { + if (sitr->second.isGroupLeader) + { + deletedGroupsToErase.insert(sitr->second.groupGuid); + ++groupCounter; + RBPacketAppendGroup(sitr->second, buffer_groups); + } + ++playerCounter; + RBPacketAppendPlayer(sitr->second, buffer_players); + } + + if (!deletedGroupsToErase.empty()) + for (std::set::const_iterator sitr = deletedGroupsToErase.begin(); sitr != deletedGroupsToErase.end(); ++sitr) + deletedGroups.erase(*sitr); + + if (!deletedGroups.empty()) + for (std::set::const_iterator sitr = deletedGroups.begin(); sitr != deletedGroups.end(); ++sitr) + { + ++deletedCounter; + buffer_deleted << (*sitr); + } + + WorldPacket differencePacket(SMSG_UPDATE_LFG_LIST, 1000); + RBPacketBuildDifference(differencePacket, dungeonId, deletedCounter, buffer_deleted, groupCounter, buffer_groups, playerCounter, buffer_players); + WorldPacket fullPacket(SMSG_UPDATE_LFG_LIST, 1000); + RBPacketBuildFull(fullPacket, dungeonId, copy); + + RBCacheStore[team][dungeonId] = fullPacket; + prevInternalInfoMap = copy; + currInternalInfoMap.clear(); + + if (entryInfoMap.empty()) + RBUsedDungeonsStore[team].erase(titr); + + // send difference packet to browsing players + for (RBSearchersMap::const_iterator sitr = RBSearchersStore[team].begin(); sitr != RBSearchersStore[team].end(); ++sitr) + if (sitr->second == dungeonId) + if (Player* p = ObjectAccessor::FindPlayerInOrOutOfWorld(MAKE_NEW_GUID(sitr->first, 0, HIGHGUID_PLAYER))) + p->GetSession()->SendPacket(&differencePacket); + + break; // one dungeon updated in one LFGMgr::UpdateRaidBrowser + } + + // already updated all in this time interval + if (neitr == RBUsedDungeonsStore[team].end()) + m_raidBrowserLastUpdatedDungeonId[team] = 0; + } + } + + void LFGMgr::RBPacketAppendGroup(const RBInternalInfo& info, ByteBuffer& buffer) + { + buffer << (uint64)info.groupGuid; + uint32 flags = LFG_UPDATE_FLAG_COMMENT | LFG_UPDATE_FLAG_ROLES | LFG_UPDATE_FLAG_BINDED; + buffer << (uint32)flags; + if (flags & LFG_UPDATE_FLAG_COMMENT) + buffer << info.comment; + if (flags & LFG_UPDATE_FLAG_ROLES) + for (uint8 j = 0; j < 3; ++j) + buffer << (uint8)0; + if (!(flags & LFG_UPDATE_FLAG_BINDED)) + return; + buffer << (uint64)info.instanceGuid; + buffer << (uint32)info.encounterMask; + } + + void LFGMgr::RBPacketAppendPlayer(const RBInternalInfo& info, ByteBuffer& buffer) + { + buffer << (uint64)info.guid; + uint32 flags = LFG_UPDATE_FLAG_CHARACTERINFO | LFG_UPDATE_FLAG_ROLES | LFG_UPDATE_FLAG_COMMENT | (info.groupGuid ? LFG_UPDATE_FLAG_GROUPGUID : LFG_UPDATE_FLAG_BINDED) | (info.isGroupLeader ? LFG_UPDATE_FLAG_GROUPLEADER : 0) | (!info.groupGuid || info.isGroupLeader ? LFG_UPDATE_FLAG_AREA : 0); + buffer << (uint32)flags; + + if (flags & LFG_UPDATE_FLAG_CHARACTERINFO) + { + buffer << (uint8)info._level; + buffer << (uint8)info._class; + buffer << (uint8)info._race; + buffer << (uint8)info._talents0; + buffer << (uint8)info._talents1; + buffer << (uint8)info._talents2; + buffer << (uint32)info._armor; + buffer << (uint32)info._spellDamage; + buffer << (uint32)info._spellHeal; + buffer << (uint32)info._critRatingMelee; + buffer << (uint32)info._critRatingRanged; + buffer << (uint32)info._critRatingSpell; + buffer << (float)info._mp5; + buffer << (float)info._mp5combat; + buffer << (uint32)info._attackPower; + buffer << (uint32)info._agility; + buffer << (uint32)info._health; + buffer << (uint32)info._mana; + buffer << (uint32)info._online; // talentpoints, used as online/offline marker :D + buffer << (float)info._avgItemLevel; // avgitemlevel + buffer << (uint32)info._defenseSkill; + buffer << (uint32)info._dodgeRating; + buffer << (uint32)info._blockRating; + buffer << (uint32)info._parryRating; + buffer << (uint32)info._hasteRating; + buffer << (uint32)info._expertiseRating; + } + + if (flags & LFG_UPDATE_FLAG_COMMENT) + buffer << (info.groupGuid ? std::string("") : info.comment); + if (flags & LFG_UPDATE_FLAG_GROUPLEADER) + buffer << (uint8)1; // isLFM + if (flags & LFG_UPDATE_FLAG_GROUPGUID) + buffer << (uint64)info.groupGuid; + if (flags & LFG_UPDATE_FLAG_ROLES) + buffer << (uint8)(info.groupGuid ? (info.isGroupLeader ? PLAYER_ROLE_LEADER : 0) : info.roles); + if (flags & LFG_UPDATE_FLAG_AREA) + buffer << (uint32)info._area; + if (flags & LFG_UPDATE_FLAG_STATUS) + buffer << (uint8)0; + if (!(flags & LFG_UPDATE_FLAG_BINDED)) + return; + buffer << (uint64)info.instanceGuid; + buffer << (uint32)info.encounterMask; + } + + void LFGMgr::RBPacketBuildDifference(WorldPacket& differencePacket, uint32 dungeonId, uint32 deletedCounter, ByteBuffer& buffer_deleted, uint32 groupCounter, ByteBuffer& buffer_groups, uint32 playerCounter, ByteBuffer& buffer_players) + { + differencePacket << (uint32)LFG_TYPE_RAID; + differencePacket << (uint32)dungeonId; + differencePacket << (uint8)1; + differencePacket << (uint32)deletedCounter; + differencePacket.append(buffer_deleted); + differencePacket << (uint32)groupCounter; + differencePacket << (uint32)0; + differencePacket.append(buffer_groups); + differencePacket << (uint32)playerCounter; + differencePacket << (uint32)0; + differencePacket.append(buffer_players); + } + + void LFGMgr::RBPacketBuildFull(WorldPacket& fullPacket, uint32 dungeonId, RBInternalInfoMap& infoMap) + { + fullPacket << (uint32)LFG_TYPE_RAID; + fullPacket << (uint32)dungeonId; + fullPacket << (uint8)0; + uint32 groupCounter = 0, playerCounter = 0; + ByteBuffer buffer_groups, buffer_players; + for (RBInternalInfoMap::const_iterator itr = infoMap.begin(); itr != infoMap.end(); ++itr) + { + if (itr->second.isGroupLeader) + { + ++groupCounter; + RBPacketAppendGroup(itr->second, buffer_groups); + } + ++playerCounter; + RBPacketAppendPlayer(itr->second, buffer_players); + } + fullPacket << (uint32)groupCounter; + fullPacket << (uint32)0; + fullPacket.append(buffer_groups); + fullPacket << (uint32)playerCounter; + fullPacket << (uint32)0; + fullPacket.append(buffer_players); + } + + // pussywizard: + void LFGMgr::LeaveAllLfgQueues(uint64 guid, bool allowgroup, uint64 groupguid) + { + uint64 pguid = 0, gguid = 0; + if (IS_GROUP_GUID(guid)) + gguid = guid; + else if (groupguid && IS_GROUP_GUID(groupguid)) + { + pguid = guid; + gguid = groupguid; + } + else + { + pguid = guid; + gguid = GetGroup(guid); + } + if (!allowgroup) + gguid = 0; + + if (pguid) + for (lfg::LfgQueueContainer::iterator itr = QueuesStore.begin(); itr != QueuesStore.end(); ++itr) + itr->second.RemoveFromQueue(pguid); + if (gguid) + for (lfg::LfgQueueContainer::iterator itr = QueuesStore.begin(); itr != QueuesStore.end(); ++itr) + itr->second.RemoveFromQueue(gguid); + + if (pguid && !gguid) + { + if (GetState(pguid) == LFG_STATE_QUEUED) + { + SendLfgUpdatePlayer(pguid, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); + SetState(pguid, LFG_STATE_NONE); + } + } + if (gguid) + { + if (GetState(gguid) == LFG_STATE_QUEUED) { - LFGQueue& queue = GetQueue(gguid); - queue.RemoveFromQueue(gguid); SetState(gguid, LFG_STATE_NONE); const LfgGuidSet& players = GetPlayers(gguid); for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) @@ -759,1901 +1291,1371 @@ void LFGMgr::LeaveLfg(uint64 guid) SendLfgUpdateParty(*it, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); } } + } + } + + /** + Update the Role check info with the player selected role. + + @param[in] grp Group guid to update rolecheck + @param[in] guid Player guid (0 = rolecheck failed) + @param[in] roles Player selected roles + */ + void LFGMgr::UpdateRoleCheck(uint64 gguid, uint64 guid /* = 0 */, uint8 roles /* = PLAYER_ROLE_NONE */) + { + if (!gguid) + return; + + LfgRolesMap check_roles; + LfgRoleCheckContainer::iterator itRoleCheck = RoleChecksStore.find(gguid); + if (itRoleCheck == RoleChecksStore.end()) + return; + + LfgRoleCheck& roleCheck = itRoleCheck->second; + bool sendRoleChosen = roleCheck.state != LFG_ROLECHECK_DEFAULT && guid; + + if (!guid) + roleCheck.state = LFG_ROLECHECK_ABORTED; + else if (roles < PLAYER_ROLE_TANK) // Player selected no role. + roleCheck.state = LFG_ROLECHECK_NO_ROLE; + else + { + roleCheck.roles[guid] = roles; + + // Check if all players have selected a role + LfgRolesMap::const_iterator itRoles = roleCheck.roles.begin(); + while (itRoles != roleCheck.roles.end() && itRoles->second != PLAYER_ROLE_NONE) + ++itRoles; + + if (itRoles == roleCheck.roles.end()) + { + // use temporal var to check roles, CheckGroupRoles modifies the roles + check_roles = roleCheck.roles; + roleCheck.state = CheckGroupRoles(check_roles) ? LFG_ROLECHECK_FINISHED : LFG_ROLECHECK_WRONG_ROLES; + } + } + + LfgDungeonSet dungeons; + if (roleCheck.rDungeonId) + dungeons.insert(roleCheck.rDungeonId); + else + dungeons = roleCheck.dungeons; + + LfgJoinResultData joinData = LfgJoinResultData(LFG_JOIN_FAILED, roleCheck.state); + for (LfgRolesMap::const_iterator it = roleCheck.roles.begin(); it != roleCheck.roles.end(); ++it) + { + uint64 pguid = it->first; + + if (sendRoleChosen) + SendLfgRoleChosen(pguid, guid, roles); + + SendLfgRoleCheckUpdate(pguid, roleCheck); + switch (roleCheck.state) + { + case LFG_ROLECHECK_INITIALITING: + continue; + case LFG_ROLECHECK_FINISHED: + SetState(pguid, LFG_STATE_QUEUED); + SetRoles(pguid, it->second); + SendLfgUpdateParty(pguid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, dungeons, GetComment(pguid))); + break; + default: + if (roleCheck.leader == pguid) + SendLfgJoinResult(pguid, joinData); + SendLfgUpdateParty(pguid, LfgUpdateData(LFG_UPDATETYPE_ROLECHECK_FAILED)); + RestoreState(pguid, "Rolecheck Failed"); + break; + } + } + + if (roleCheck.state == LFG_ROLECHECK_FINISHED) + { + SetState(gguid, LFG_STATE_QUEUED); + LFGQueue& queue = GetQueue(gguid); + queue.AddQueueData(gguid, time_t(time(nullptr)), roleCheck.dungeons, roleCheck.roles); + RoleChecksStore.erase(itRoleCheck); + } + else if (roleCheck.state != LFG_ROLECHECK_INITIALITING) + { + RestoreState(gguid, "Rolecheck Failed"); + RoleChecksStore.erase(itRoleCheck); + } + } + + /** + Given a list of dungeons remove the dungeons players have restrictions. + + @param[in, out] dungeons Dungeons to check restrictions + @param[in] players Set of players to check their dungeon restrictions + @param[out] lockMap Map of players Lock status info of given dungeons (Empty if dungeons is not empty) + */ + void LFGMgr::GetCompatibleDungeons(LfgDungeonSet& dungeons, LfgGuidSet const& players, LfgLockPartyMap& lockMap) + { + lockMap.clear(); + for (LfgGuidSet::const_iterator it = players.begin(); it != players.end() && !dungeons.empty(); ++it) + { + uint64 guid = (*it); + LfgLockMap const& cachedLockMap = GetLockedDungeons(guid); + for (LfgLockMap::const_iterator it2 = cachedLockMap.begin(); it2 != cachedLockMap.end() && !dungeons.empty(); ++it2) + { + uint32 dungeonId = (it2->first & 0x00FFFFFF); // Compare dungeon ids + LfgDungeonSet::iterator itDungeon = dungeons.find(dungeonId); + if (itDungeon != dungeons.end()) + { + dungeons.erase(itDungeon); + lockMap[guid][dungeonId] = it2->second; + } + } + } + if (!dungeons.empty()) + lockMap.clear(); + } + + uint8 LFGMgr::CheckGroupRoles(LfgRolesMap& groles, bool removeLeaderFlag /*= true*/) + { + if (groles.empty()) + return 0; + + uint8 damage = 0; + uint8 tank = 0; + uint8 healer = 0; + + if (removeLeaderFlag) + for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it) + it->second &= ~PLAYER_ROLE_LEADER; + + for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it) + { + if (it->second == PLAYER_ROLE_NONE) + return 0; + + if (it->second & PLAYER_ROLE_DAMAGE) + { + if (it->second != PLAYER_ROLE_DAMAGE) + { + it->second -= PLAYER_ROLE_DAMAGE; + if (uint8 x = CheckGroupRoles(groles, false)) + return x; + it->second += PLAYER_ROLE_DAMAGE; + } + else if (damage == LFG_DPS_NEEDED) + return 0; + else + damage++; + } + + if (it->second & PLAYER_ROLE_HEALER) + { + if (it->second != PLAYER_ROLE_HEALER) + { + it->second -= PLAYER_ROLE_HEALER; + if (uint8 x = CheckGroupRoles(groles, false)) + return x; + it->second += PLAYER_ROLE_HEALER; + } + else if (healer == LFG_HEALERS_NEEDED) + return 0; + else + healer++; + } + + if (it->second & PLAYER_ROLE_TANK) + { + if (it->second != PLAYER_ROLE_TANK) + { + it->second -= PLAYER_ROLE_TANK; + if (uint8 x = CheckGroupRoles(groles, false)) + return x; + it->second += PLAYER_ROLE_TANK; + } + else if (tank == LFG_TANKS_NEEDED) + return 0; + else + tank++; + } + } + if ((tank + healer + damage) == uint8(groles.size())) + return (8 * tank + 4 * healer + damage); + return 0; + } + + /** + Makes a new group given a proposal + @param[in] proposal Proposal to get info from + */ + void LFGMgr::MakeNewGroup(LfgProposal const& proposal) + { + LfgGuidList players; + LfgGuidList playersToTeleport; + + for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + { + uint64 guid = it->first; + if (guid == proposal.leader) + players.push_front(guid); else + players.push_back(guid); + + if (proposal.isNew || GetGroup(guid) != proposal.group) + playersToTeleport.push_back(guid); + } + + // Set the dungeon difficulty + LFGDungeonData const* dungeon = GetLFGDungeon(proposal.dungeonId); + ASSERT(dungeon); + + Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(GUID_LOPART(proposal.group)) : nullptr; + uint64 oldGroupGUID = 0; + for (LfgGuidList::const_iterator it = players.begin(); it != players.end(); ++it) + { + uint64 pguid = (*it); + Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(pguid); + if (!player) + continue; + + Group* group = player->GetGroup(); + + // Xinef: Apply Random Buff + if (grp && !grp->IsLfgWithBuff()) + { + if (!group || group->GetGUID() != oldGroupGUID) + grp->AddLfgBuffFlag(); + else + oldGroupGUID = group->GetGUID(); + } + + // Xinef: Store amount of random players player grouped with + if (group) + { + SetRandomPlayersCount(pguid, group->GetMembersCount() >= MAXGROUPSIZE ? 0 : MAXGROUPSIZE - group->GetMembersCount()); + oldGroupGUID = group->GetGUID(); + if (group != grp) + group->RemoveMember(player->GetGUID()); + } + else + SetRandomPlayersCount(pguid, MAXGROUPSIZE - 1); + + if (!grp) + { + grp = new Group(); + grp->ConvertToLFG(); + grp->Create(player); + uint64 gguid = grp->GetGUID(); + SetState(gguid, LFG_STATE_PROPOSAL); + sGroupMgr->AddGroup(grp); + } + else if (group != grp) + { + // pussywizard: + if (!grp->IsFull()) + grp->AddMember(player); + //else // some cleanup? LeaveLFG? + // ; + } + + grp->SetLfgRoles(pguid, proposal.players.find(pguid)->second.role); + } + + // pussywizard: crashfix, group wasn't created when iterating players (no player found by guid), proposal is deleted by the calling function + if (!grp) + return; + + grp->SetDungeonDifficulty(Difficulty(dungeon->difficulty)); + uint64 gguid = grp->GetGUID(); + SetDungeon(gguid, dungeon->Entry()); + SetState(gguid, LFG_STATE_DUNGEON); + + _SaveToDB(gguid); + + bool randomDungeon = false; + // Teleport Player + for (LfgGuidList::const_iterator it = playersToTeleport.begin(); it != playersToTeleport.end(); ++it) + if (Player* player = ObjectAccessor::FindPlayer(*it)) + { + if (player->GetGroup() != grp) // pussywizard: could not add because group was full (some shitness happened) + continue; + // Add the cooldown spell if queued for a random dungeon + // xinef: add aura + if ((randomDungeon || selectedRandomLfgDungeon(player->GetGUID())) && !player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) + { + randomDungeon = true; + player->AddAura(LFG_SPELL_DUNGEON_COOLDOWN, player); + } + TeleportPlayer(player, false); + } + + if (randomDungeon) + grp->AddLfgRandomInstanceFlag(); + if (Difficulty(dungeon->difficulty) == DUNGEON_DIFFICULTY_HEROIC) + grp->AddLfgHeroicFlag(); + + // Update group info + grp->SendUpdate(); + } + + uint32 LFGMgr::AddProposal(LfgProposal& proposal) + { + proposal.id = ++m_lfgProposalId; + ProposalsStore[m_lfgProposalId] = proposal; + return m_lfgProposalId; + } + + /** + Update Proposal info with player answer + + @param[in] proposalId Proposal id to be updated + @param[in] guid Player guid to update answer + @param[in] accept Player answer + */ + void LFGMgr::UpdateProposal(uint32 proposalId, uint64 guid, bool accept) + { + // Check if the proposal exists + LfgProposalContainer::iterator itProposal = ProposalsStore.find(proposalId); + if (itProposal == ProposalsStore.end()) + return; + + LfgProposal& proposal = itProposal->second; + + // Check if proposal have the current player + LfgProposalPlayerContainer::iterator itProposalPlayer = proposal.players.find(guid); + if (itProposalPlayer == proposal.players.end()) + return; + + LfgProposalPlayer& player = itProposalPlayer->second; + player.accept = LfgAnswer(accept); + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::UpdateProposal: Player [" UI64FMTD "] of proposal %u selected: %u", guid, proposalId, accept); +#endif + if (!accept) + { + RemoveProposal(itProposal, LFG_UPDATETYPE_PROPOSAL_DECLINED); + return; + } + + // check if all have answered and reorder players (leader first) + bool allAnswered = true; + for (LfgProposalPlayerContainer::const_iterator itPlayers = proposal.players.begin(); itPlayers != proposal.players.end(); ++itPlayers) + if (itPlayers->second.accept != LFG_ANSWER_AGREE) // No answer (-1) or not accepted (0) + allAnswered = false; + + if (!allAnswered) + { + for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + SendLfgUpdateProposal(it->first, proposal); + + return; + } + + bool sendUpdate = proposal.state != LFG_PROPOSAL_SUCCESS; + proposal.state = LFG_PROPOSAL_SUCCESS; + time_t joinTime = time(nullptr); + + LFGQueue& queue = GetQueue(guid); + LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_GROUP_FOUND); + for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + { + uint64 pguid = it->first; + uint64 gguid = it->second.group; + uint32 dungeonId = (*GetSelectedDungeons(pguid).begin()); + int32 waitTime = -1; + if (sendUpdate) + SendLfgUpdateProposal(pguid, proposal); + + if (gguid) + { + waitTime = int32((joinTime - queue.GetJoinTime(gguid)) / IN_MILLISECONDS); + SendLfgUpdateParty(pguid, updateData); + } + else + { + waitTime = int32((joinTime - queue.GetJoinTime(pguid)) / IN_MILLISECONDS); + SendLfgUpdatePlayer(pguid, updateData); + } + updateData.updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE; + SendLfgUpdatePlayer(pguid, updateData); + SendLfgUpdateParty(pguid, updateData); + + // Update timers + uint8 role = GetRoles(pguid); + role &= ~PLAYER_ROLE_LEADER; + switch (role) + { + case PLAYER_ROLE_DAMAGE: + queue.UpdateWaitTimeDps(waitTime, dungeonId); + break; + case PLAYER_ROLE_HEALER: + queue.UpdateWaitTimeHealer(waitTime, dungeonId); + break; + case PLAYER_ROLE_TANK: + queue.UpdateWaitTimeTank(waitTime, dungeonId); + break; + default: + queue.UpdateWaitTimeAvg(waitTime, dungeonId); + break; + } + + SetState(pguid, LFG_STATE_DUNGEON); + } + + // Remove players/groups from Queue + for (uint8 i = 0; i < 5 && proposal.queues.guid[i]; ++i) + queue.RemoveQueueData(proposal.queues.guid[i]); + + MakeNewGroup(proposal); + ProposalsStore.erase(itProposal); + } + + /** + Remove a proposal from the pool, remove the group that didn't accept (if needed) and readd the other members to the queue + + @param[in] itProposal Iterator to the proposal to remove + @param[in] type Type of removal (LFG_UPDATETYPE_PROPOSAL_FAILED, LFG_UPDATETYPE_PROPOSAL_DECLINED) + */ + void LFGMgr::RemoveProposal(LfgProposalContainer::iterator itProposal, LfgUpdateType type) + { + LfgProposal& proposal = itProposal->second; + proposal.state = LFG_PROPOSAL_FAILED; + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: Proposal %u, state FAILED, UpdateType %u", itProposal->first, type); +#endif + // Mark all people that didn't answered as no accept + if (type == LFG_UPDATETYPE_PROPOSAL_FAILED) + for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + if (it->second.accept == LFG_ANSWER_PENDING) + it->second.accept = LFG_ANSWER_DENY; + + // pussywizard: add cooldown for not accepting (after 40 secs) or declining + for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + if (it->second.accept == LFG_ANSWER_DENY) + if (Player* plr = sObjectAccessor->FindPlayer(it->first)) + if (Aura* aura = plr->AddAura(LFG_SPELL_DUNGEON_COOLDOWN, plr)) + aura->SetDuration(150 * IN_MILLISECONDS); + + // Mark players/groups to be removed + LfgGuidSet toRemove; + for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + { + if (it->second.accept == LFG_ANSWER_AGREE) + continue; + + uint64 guid = it->second.group ? it->second.group : it->first; + // Player didn't accept or still pending when no secs left + if (it->second.accept == LFG_ANSWER_DENY || type == LFG_UPDATETYPE_PROPOSAL_FAILED) + { + it->second.accept = LFG_ANSWER_DENY; + toRemove.insert(guid); + } + } + + // Notify players + for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) + { + uint64 guid = it->first; + uint64 gguid = it->second.group ? it->second.group : guid; + + SendLfgUpdateProposal(guid, proposal); + + if (toRemove.find(gguid) != toRemove.end()) // Didn't accept or in same group that someone that didn't accept + { + LfgUpdateData updateData; + if (it->second.accept == LFG_ANSWER_DENY) + { + updateData.updateType = type; +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: [" UI64FMTD "] didn't accept. Removing from queue and compatible cache", guid); +#endif + } + else + { + updateData.updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE; +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: [" UI64FMTD "] in same group that someone that didn't accept. Removing from queue and compatible cache", guid); +#endif + } + + RestoreState(guid, "Proposal Fail (didn't accepted or in group with someone that didn't accept"); + if (gguid != guid) + { + RestoreState(it->second.group, "Proposal Fail (someone in group didn't accepted)"); + SendLfgUpdateParty(guid, updateData); + } + else + SendLfgUpdatePlayer(guid, updateData); + } + else + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: Readding [" UI64FMTD "] to queue.", guid); +#endif + SetState(guid, LFG_STATE_QUEUED); + if (gguid != guid) + { + SetState(gguid, LFG_STATE_QUEUED); + SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, GetSelectedDungeons(guid), GetComment(guid))); + } + else + SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, GetSelectedDungeons(guid), GetComment(guid))); + } + } + + LFGQueue& queue = GetQueue(proposal.players.begin()->first); + // Remove players/groups from queue + for (LfgGuidSet::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it) + { + uint64 guid = *it; + queue.RemoveFromQueue(guid); + proposal.queues.remove(guid); + } + + // Readd to queue + for (uint8 i = 0; i < 5 && proposal.queues.guid[i]; ++i) + { + // xinef: this will work as data is not deleted, only references to this data are cleared + // xinef: when new proposal is created + // xinef: successful proposal is also taken into account is similar manner + queue.AddToQueue(proposal.queues.guid[i], true); + } + + ProposalsStore.erase(itProposal); + } + + /** + Initialize a boot kick vote + + @param[in] gguid Group the vote kicks belongs to + @param[in] kicker Kicker guid + @param[in] victim Victim guid + @param[in] reason Kick reason + */ + void LFGMgr::InitBoot(uint64 gguid, uint64 kicker, uint64 victim, std::string const& reason) + { + SetState(gguid, LFG_STATE_BOOT); + + LfgPlayerBoot& boot = BootsStore[gguid]; + boot.inProgress = true; + boot.cancelTime = time_t(time(nullptr)) + LFG_TIME_BOOT; + boot.reason = reason; + boot.victim = victim; + + LfgGuidSet const& players = GetPlayers(gguid); + + // Set votes + for (LfgGuidSet::const_iterator itr = players.begin(); itr != players.end(); ++itr) + { + uint64 guid = (*itr); + SetState(guid, LFG_STATE_BOOT); + boot.votes[guid] = LFG_ANSWER_PENDING; + } + + boot.votes[victim] = LFG_ANSWER_DENY; // Victim auto vote NO + boot.votes[kicker] = LFG_ANSWER_AGREE; // Kicker auto vote YES + + // Notify players + for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) + SendLfgBootProposalUpdate(*it, boot); + } + + /** + Update Boot info with player answer + + @param[in] guid Player who has answered + @param[in] player answer + */ + void LFGMgr::UpdateBoot(uint64 guid, bool accept) + { + uint64 gguid = GetGroup(guid); + if (!gguid) + return; + + LfgPlayerBootContainer::iterator itBoot = BootsStore.find(gguid); + if (itBoot == BootsStore.end()) + return; + + LfgPlayerBoot& boot = itBoot->second; + + if (boot.votes[guid] != LFG_ANSWER_PENDING) // Cheat check: Player can't vote twice + return; + + boot.votes[guid] = LfgAnswer(accept); + + uint8 votesNum = 0; + uint8 agreeNum = 0; + for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes) + { + if (itVotes->second != LFG_ANSWER_PENDING) + { + ++votesNum; + if (itVotes->second == LFG_ANSWER_AGREE) + ++agreeNum; + } + } + + // if we don't have enough votes (agree or deny) do nothing + if (agreeNum < LFG_GROUP_KICK_VOTES_NEEDED && (votesNum - agreeNum) < LFG_GROUP_KICK_VOTES_NEEDED) + return; + + // Send update info to all players + boot.inProgress = false; + for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes) + { + uint64 pguid = itVotes->first; + if (pguid != boot.victim) + { + SetState(pguid, LFG_STATE_DUNGEON); + SendLfgBootProposalUpdate(pguid, boot); + } + } + + SetState(gguid, LFG_STATE_DUNGEON); + if (agreeNum == LFG_GROUP_KICK_VOTES_NEEDED) // Vote passed - Kick player + { + if (Group* group = sGroupMgr->GetGroupByGUID(GUID_LOPART(gguid))) + Player::RemoveFromGroup(group, boot.victim, GROUP_REMOVEMETHOD_KICK_LFG); + DecreaseKicksLeft(gguid); + } + BootsStore.erase(itBoot); + } + + /** + Teleports the player in or out the dungeon + + @param[in] player Player to teleport + @param[in] out Teleport out (true) or in (false) + @param[in] fromOpcode Function called from opcode handlers? (Default false) + */ + void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false*/) + { + LFGDungeonData const* dungeon = nullptr; + Group* group = player->GetGroup(); + + if (group && group->isLFGGroup()) + dungeon = GetLFGDungeon(GetDungeon(group->GetGUID())); + + if (!dungeon) + { + player->GetSession()->SendLfgTeleportError(uint8(LFG_TELEPORTERROR_INVALID_LOCATION)); + return; + } + + if (out) + { + if (player->GetMapId() == uint32(dungeon->map)) + player->TeleportToEntryPoint(); + + return; + } + + LfgTeleportError error = LFG_TELEPORTERROR_OK; + + if (!player->IsAlive()) + error = LFG_TELEPORTERROR_PLAYER_DEAD; + else if (player->IsFalling() || player->HasUnitState(UNIT_STATE_JUMPING)) + error = LFG_TELEPORTERROR_FALLING; + else if (player->IsMirrorTimerActive(FATIGUE_TIMER)) + error = LFG_TELEPORTERROR_FATIGUE; + else if (player->GetVehicle()) + error = LFG_TELEPORTERROR_IN_VEHICLE; + else if (player->GetCharmGUID()) + error = LFG_TELEPORTERROR_CHARMING; + else if (player->GetMapId() != uint32(dungeon->map)) // Do not teleport players in dungeon to the entrance + { + uint32 mapid = dungeon->map; + float x = dungeon->x; + float y = dungeon->y; + float z = dungeon->z; + float orientation = dungeon->o; + + if (!fromOpcode) + { + // Select a player inside to be teleported to + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) + { + Player* plrg = itr->GetSource(); + if (plrg && plrg != player && plrg->GetMapId() == uint32(dungeon->map)) + { + mapid = plrg->GetMapId(); + x = plrg->GetPositionX(); + y = plrg->GetPositionY(); + z = plrg->GetPositionZ(); + orientation = plrg->GetOrientation(); + break; + } + } + } + + if (!player->GetMap()->IsDungeon()) + player->SetEntryPoint(); + + if (!player->TeleportTo(mapid, x, y, z, orientation)) + error = LFG_TELEPORTERROR_INVALID_LOCATION; + } + else + error = LFG_TELEPORTERROR_INVALID_LOCATION; + + if (error != LFG_TELEPORTERROR_OK) + player->GetSession()->SendLfgTeleportError(uint8(error)); + + //sLog->outDebug(LOG_FILTER_LFG, "TeleportPlayer: Player %s is being teleported in to map %u " + // "(x: %f, y: %f, z: %f) Result: %u", player->GetName().c_str(), dungeon->map, + // dungeon->x, dungeon->y, dungeon->z, error); + } + + /** + Finish a dungeon and give reward, if any. + + @param[in] guid Group guid + @param[in] dungeonId Dungeonid + */ + void LFGMgr::FinishDungeon(uint64 gguid, const uint32 dungeonId, const Map* currMap) + { + uint32 gDungeonId = GetDungeon(gguid); + if (gDungeonId != dungeonId) + { + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] Finished dungeon %u but group queued for %u. Ignoring", gguid, dungeonId, gDungeonId); + return; + } + + if (GetState(gguid) == LFG_STATE_FINISHED_DUNGEON) // Shouldn't happen. Do not reward multiple times + { + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] Already rewarded group. Ignoring", gguid); + return; + } + + SetState(gguid, LFG_STATE_FINISHED_DUNGEON); + _SaveToDB(gguid); // pussywizard + + const LfgGuidSet& players = GetPlayers(gguid); + for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) + { + uint64 guid = (*it); + if (GetState(guid) == LFG_STATE_FINISHED_DUNGEON) + { + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] Already rewarded player. Ignoring", guid); + continue; + } + + uint32 rDungeonId = 0; + const LfgDungeonSet& dungeons = GetSelectedDungeons(guid); + if (!dungeons.empty()) + rDungeonId = (*dungeons.begin()); + + SetState(guid, LFG_STATE_FINISHED_DUNGEON); + + // Give rewards only if its a random dungeon + LFGDungeonData const* dungeon = GetLFGDungeon(rDungeonId); + + if (!dungeon || (dungeon->type != LFG_TYPE_RANDOM && !dungeon->seasonal)) + { + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] dungeon %u is not random or seasonal", guid, rDungeonId); + continue; + } + + Player* player = ObjectAccessor::FindPlayer(guid); + if (!player || player->FindMap() != currMap) // pussywizard: currMap - multithreading crash if on other map (map id check is not enough, binding system is not reliable) + { + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] not found in world", guid); + continue; + } + + LFGDungeonData const* dungeonDone = GetLFGDungeon(dungeonId); + uint32 mapId = dungeonDone ? uint32(dungeonDone->map) : 0; + + if (player->GetMapId() != mapId) + { + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] is in map %u and should be in %u to get reward", guid, player->GetMapId(), mapId); + continue; + } + + // Xinef: Update achievements, set correct amount of randomly grouped players + if (dungeon->difficulty == DUNGEON_DIFFICULTY_HEROIC) + if (uint8 count = GetRandomPlayersCount(player->GetGUID())) + player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS, count); + + LfgReward const* reward = GetRandomDungeonReward(rDungeonId, player->getLevel()); + if (!reward) + continue; + + bool done = false; + Quest const* quest = sObjectMgr->GetQuestTemplate(reward->firstQuest); + if (!quest) + continue; + + // if we can take the quest, means that we haven't done this kind of "run", IE: First Heroic Random of Day. + if (player->CanRewardQuest(quest, false)) + player->RewardQuest(quest, 0, NULL, false); + else + { + done = true; + quest = sObjectMgr->GetQuestTemplate(reward->otherQuest); + if (!quest) + continue; + // we give reward without informing client (retail does this) + player->RewardQuest(quest, 0, NULL, false); + } + + // Give rewards + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] done dungeon %u, %s previously done.", player->GetGUID(), GetDungeon(gguid), done ? " " : " not"); + LfgPlayerRewardData data = LfgPlayerRewardData(dungeon->Entry(), GetDungeon(gguid, false), done, quest); + player->GetSession()->SendLfgPlayerReward(data); + } + } + + // --------------------------------------------------------------------------// + // Auxiliar Functions + // --------------------------------------------------------------------------// + + /** + Get the dungeon list that can be done given a random dungeon entry. + + @param[in] randomdungeon Random dungeon id (if value = 0 will return all dungeons) + @returns Set of dungeons that can be done. + */ + LfgDungeonSet const& LFGMgr::GetDungeonsByRandom(uint32 randomdungeon) + { + LFGDungeonData const* dungeon = GetLFGDungeon(randomdungeon); + uint32 group = dungeon ? dungeon->group : 0; + return CachedDungeonMapStore[group]; + } + + /** + Get the reward of a given random dungeon at a certain level + + @param[in] dungeon dungeon id + @param[in] level Player level + @returns Reward + */ + LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level) + { + LfgReward const* rew = nullptr; + LfgRewardContainerBounds bounds = RewardMapStore.equal_range(dungeon & 0x00FFFFFF); + for (LfgRewardContainer::const_iterator itr = bounds.first; itr != bounds.second; ++itr) + { + rew = itr->second; + // ordered properly at loading + if (itr->second->maxLevel >= level) + break; + } + + return rew; + } + + /** + Given a Dungeon id returns the dungeon Type + + @param[in] dungeon dungeon id + @returns Dungeon type + */ + LfgType LFGMgr::GetDungeonType(uint32 dungeonId) + { + LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId); + if (!dungeon) + return LFG_TYPE_NONE; + + return LfgType(dungeon->type); + } + + LfgState LFGMgr::GetState(uint64 guid) + { + LfgState state; + if (IS_GROUP_GUID(guid)) + state = GroupsStore[guid].GetState(); + else + state = PlayersStore[guid].GetState(); + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetState: [" UI64FMTD "] = %u", guid, state); +#endif + return state; + } + + LfgState LFGMgr::GetOldState(uint64 guid) + { + LfgState state; + if (IS_GROUP_GUID(guid)) + state = GroupsStore[guid].GetOldState(); + else + state = PlayersStore[guid].GetOldState(); + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetOldState: [" UI64FMTD "] = %u", guid, state); +#endif + return state; + } + + uint32 LFGMgr::GetDungeon(uint64 guid, bool asId /*= true */) + { + uint32 dungeon = GroupsStore[guid].GetDungeon(asId); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetDungeon: [" UI64FMTD "] asId: %u = %u", guid, asId, dungeon); +#endif + return dungeon; + } + + uint32 LFGMgr::GetDungeonMapId(uint64 guid) + { + uint32 dungeonId = GroupsStore[guid].GetDungeon(true); + uint32 mapId = 0; + if (dungeonId) + if (LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId)) + mapId = dungeon->map; + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetDungeonMapId: [" UI64FMTD "] = %u (DungeonId = %u)", guid, mapId, dungeonId); +#endif + return mapId; + } + + uint8 LFGMgr::GetRoles(uint64 guid) + { + uint8 roles = PlayersStore[guid].GetRoles(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetRoles: [" UI64FMTD "] = %u", guid, roles); +#endif + return roles; + } + + const std::string& LFGMgr::GetComment(uint64 guid) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetComment: [" UI64FMTD "] = %s", guid, PlayersStore[guid].GetComment().c_str()); +#endif + return PlayersStore[guid].GetComment(); + } + + LfgDungeonSet const& LFGMgr::GetSelectedDungeons(uint64 guid) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetSelectedDungeons: [" UI64FMTD "]", guid); +#endif + return PlayersStore[guid].GetSelectedDungeons(); + } + + LfgLockMap const& LFGMgr::GetLockedDungeons(uint64 guid) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetLockedDungeons: [" UI64FMTD "]", guid); +#endif + return PlayersStore[guid].GetLockedDungeons(); + } + + uint8 LFGMgr::GetKicksLeft(uint64 guid) + { + uint8 kicks = GroupsStore[guid].GetKicksLeft(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetKicksLeft: [" UI64FMTD "] = %u", guid, kicks); +#endif + return kicks; + } + + void LFGMgr::RestoreState(uint64 guid, char const* /*debugMsg*/) + { + if (IS_GROUP_GUID(guid)) + { + LfgGroupData& data = GroupsStore[guid]; + /*if (sLog->ShouldLog(LOG_FILTER_LFG, LOG_LEVEL_DEBUG)) + { + std::string const& ps = GetStateString(data.GetState()); + std::string const& os = GetStateString(data.GetOldState()); + sLog->outTrace(LOG_FILTER_LFG, "LFGMgr::RestoreState: Group: [" UI64FMTD "] (%s) State: %s, oldState: %s", + guid, debugMsg, ps.c_str(), os.c_str()); + }*/ + + data.RestoreState(); + } + else + { + LfgPlayerData& data = PlayersStore[guid]; + /*if (sLog->ShouldLog(LOG_FILTER_LFG, LOG_LEVEL_DEBUG)) + { + std::string const& ps = GetStateString(data.GetState()); + std::string const& os = GetStateString(data.GetOldState()); + sLog->outTrace(LOG_FILTER_LFG, "LFGMgr::RestoreState: Player: [" UI64FMTD "] (%s) State: %s, oldState: %s", + guid, debugMsg, ps.c_str(), os.c_str()); + }*/ + data.RestoreState(); + } + } + + void LFGMgr::SetState(uint64 guid, LfgState state) + { + if (IS_GROUP_GUID(guid)) + { + LfgGroupData& data = GroupsStore[guid]; + std::string ns = GetStateString(state); + std::string ps = GetStateString(data.GetState()); + std::string os = GetStateString(data.GetOldState()); + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetState: Group: [" UI64FMTD "] newState: %s, previous: %s, oldState: %s", guid, ns.c_str(), ps.c_str(), os.c_str()); + data.SetState(state); + } + else + { + LfgPlayerData& data = PlayersStore[guid]; + std::string ns = GetStateString(state); + std::string ps = GetStateString(data.GetState()); + std::string os = GetStateString(data.GetOldState()); + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetState: Player: [" UI64FMTD "] newState: %s, previous: %s, oldState: %s", guid, ns.c_str(), ps.c_str(), os.c_str()); + data.SetState(state); + } + } + + void LFGMgr::SetCanOverrideRBState(uint64 guid, bool val) + { + PlayersStore[guid].SetCanOverrideRBState(val); + } + + void LFGMgr::SetDungeon(uint64 guid, uint32 dungeon) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetDungeon: [" UI64FMTD "] dungeon %u", guid, dungeon); +#endif + GroupsStore[guid].SetDungeon(dungeon); + } + + void LFGMgr::SetRoles(uint64 guid, uint8 roles) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetRoles: [" UI64FMTD "] roles: %u", guid, roles); +#endif + PlayersStore[guid].SetRoles(roles); + } + + void LFGMgr::SetComment(uint64 guid, std::string const& comment) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetComment: [" UI64FMTD "] comment: %s", guid, comment.c_str()); +#endif + PlayersStore[guid].SetComment(comment); + } + + void LFGMgr::LfrSetComment(Player* p, std::string comment) + { + // pussywizard: client limit for comment length is 64 @ 3.3.5a + if (comment.size() > 64) + comment = comment.substr(0, 64); + + uint8 teamId = p->GetTeamId(); + RBEntryInfoMap::iterator iter; + for (RBStoreMap::iterator itr = RaidBrowserStore[teamId].begin(); itr != RaidBrowserStore[teamId].end(); ++itr) + if ((iter = itr->second.find(p->GetGUIDLow())) != itr->second.end()) + iter->second.comment = comment; + } + + void LFGMgr::SetSelectedDungeons(uint64 guid, LfgDungeonSet const& dungeons) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetLockedDungeons: [" UI64FMTD "]", guid); +#endif + PlayersStore[guid].SetSelectedDungeons(dungeons); + } + + void LFGMgr::SetLockedDungeons(uint64 guid, LfgLockMap const& lock) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetLockedDungeons: [" UI64FMTD "]", guid); +#endif + PlayersStore[guid].SetLockedDungeons(lock); + } + + void LFGMgr::DecreaseKicksLeft(uint64 guid) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::DecreaseKicksLeft: [" UI64FMTD "]", guid); +#endif + GroupsStore[guid].DecreaseKicksLeft(); + } + + void LFGMgr::RemoveGroupData(uint64 guid) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveGroupData: [" UI64FMTD "]", guid); +#endif + LfgGroupDataContainer::iterator it = GroupsStore.find(guid); + if (it == GroupsStore.end()) + return; + + LfgState state = GetState(guid); + // If group is being formed after proposal success do nothing more + LfgGuidSet const& players = it->second.GetPlayers(); + for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) + { + uint64 guid = (*it); + SetGroup(*it, 0); + if (state != LFG_STATE_PROPOSAL) + { + SetState(*it, LFG_STATE_NONE); + SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); + } + } + GroupsStore.erase(it); + } + + TeamId LFGMgr::GetTeam(uint64 guid) + { + return PlayersStore[guid].GetTeam(); + } + + uint8 LFGMgr::RemovePlayerFromGroup(uint64 gguid, uint64 guid) + { + return GroupsStore[gguid].RemovePlayer(guid); + } + + void LFGMgr::AddPlayerToGroup(uint64 gguid, uint64 guid) + { + GroupsStore[gguid].AddPlayer(guid); + } + + void LFGMgr::SetLeader(uint64 gguid, uint64 leader) + { + GroupsStore[gguid].SetLeader(leader); + } + + void LFGMgr::SetTeam(uint64 guid, TeamId teamId) + { + if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP)) + teamId = TEAM_ALLIANCE; // @Not Sure About That TeamId is supposed to be uint8 Team = 0(@TrinityCore) + + PlayersStore[guid].SetTeam(teamId); + } + + uint64 LFGMgr::GetGroup(uint64 guid) + { + return PlayersStore[guid].GetGroup(); + } + + void LFGMgr::SetGroup(uint64 guid, uint64 group) + { + PlayersStore[guid].SetGroup(group); + } + + LfgGuidSet const& LFGMgr::GetPlayers(uint64 guid) + { + return GroupsStore[guid].GetPlayers(); + } + + uint8 LFGMgr::GetPlayerCount(uint64 guid) + { + return GroupsStore[guid].GetPlayerCount(); + } + + uint64 LFGMgr::GetLeader(uint64 guid) + { + return GroupsStore[guid].GetLeader(); + } + + void LFGMgr::SetRandomPlayersCount(uint64 guid, uint8 count) + { + PlayersStore[guid].SetRandomPlayersCount(count); + } + + uint8 LFGMgr::GetRandomPlayersCount(uint64 guid) + { + return PlayersStore[guid].GetRandomPlayersCount(); + } + + bool LFGMgr::HasIgnore(uint64 guid1, uint64 guid2) + { + Player* plr1 = ObjectAccessor::FindPlayerInOrOutOfWorld(guid1); + Player* plr2 = ObjectAccessor::FindPlayerInOrOutOfWorld(guid2); + uint32 low1 = GUID_LOPART(guid1); + uint32 low2 = GUID_LOPART(guid2); + return plr1 && plr2 && (plr1->GetSocial()->HasIgnore(low2) || plr2->GetSocial()->HasIgnore(low1)); + } + + void LFGMgr::SendLfgRoleChosen(uint64 guid, uint64 pguid, uint8 roles) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgRoleChosen(pguid, roles); + } + + void LFGMgr::SendLfgRoleCheckUpdate(uint64 guid, LfgRoleCheck const& roleCheck) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgRoleCheckUpdate(roleCheck); + } + + void LFGMgr::SendLfgUpdatePlayer(uint64 guid, LfgUpdateData const& data) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgUpdatePlayer(data); + } + + void LFGMgr::SendLfgUpdateParty(uint64 guid, LfgUpdateData const& data) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgUpdateParty(data); + } + + void LFGMgr::SendLfgJoinResult(uint64 guid, LfgJoinResultData const& data) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgJoinResult(data); + } + + void LFGMgr::SendLfgBootProposalUpdate(uint64 guid, LfgPlayerBoot const& boot) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgBootProposalUpdate(boot); + } + + void LFGMgr::SendLfgUpdateProposal(uint64 guid, LfgProposal const& proposal) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgUpdateProposal(proposal); + } + + void LFGMgr::SendLfgQueueStatus(uint64 guid, LfgQueueStatusData const& data) + { + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) + player->GetSession()->SendLfgQueueStatus(data); + } + + bool LFGMgr::IsLfgGroup(uint64 guid) + { + return guid && IS_GROUP_GUID(guid) && GroupsStore[guid].IsLfgGroup(); + } + + LFGQueue& LFGMgr::GetQueue(uint64 guid) + { + uint8 queueId = 0; + if (IS_GROUP_GUID(guid)) + { + LfgGuidSet const& players = GetPlayers(guid); + uint64 pguid = players.empty() ? 0 : (*players.begin()); + if (pguid) + queueId = GetTeam(pguid); + else + queueId = GetTeam(GetLeader(guid)); + } + else + queueId = GetTeam(guid); + return QueuesStore[queueId]; + } + + bool LFGMgr::AllQueued(Lfg5Guids const& check) + { + bool ok = true; + + if (check.empty()) + return false; + + for (uint8 i = 0; i < 5 && check.guid[i]; ++i) + { + uint64 guid = check.guid[i]; + if (GetState(guid) != LFG_STATE_QUEUED) { LFGQueue& queue = GetQueue(guid); queue.RemoveFromQueue(guid); - SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); - SetState(guid, LFG_STATE_NONE); - } - break; - case LFG_STATE_ROLECHECK: - if (gguid) - UpdateRoleCheck(gguid); // No player to update role = LFG_ROLECHECK_ABORTED - break; - case LFG_STATE_PROPOSAL: - { - // Remove from Proposals - LfgProposalContainer::iterator it = ProposalsStore.begin(); - uint64 pguid = gguid == guid ? GetLeader(gguid) : guid; - while (it != ProposalsStore.end()) - { - LfgProposalPlayerContainer::iterator itPlayer = it->second.players.find(pguid); - if (itPlayer != it->second.players.end()) - { - // Mark the player/leader of group who left as didn't accept the proposal - itPlayer->second.accept = LFG_ANSWER_DENY; - break; - } - ++it; - } - - // Remove from queue - if proposal is found, RemoveProposal will call RemoveFromQueue - if (it != ProposalsStore.end()) - RemoveProposal(it, LFG_UPDATETYPE_PROPOSAL_DECLINED); - break; - } - case LFG_STATE_NONE: - break; - case LFG_STATE_DUNGEON: - case LFG_STATE_FINISHED_DUNGEON: - case LFG_STATE_BOOT: - if (guid != gguid) // Player - SetState(guid, LFG_STATE_NONE); - break; - case LFG_STATE_RAIDBROWSER: - LeaveRaidBrowser(guid); - SetCanOverrideRBState(guid, true); - SetState(guid, LFG_STATE_NONE); - SetCanOverrideRBState(guid, false); - SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_LEAVE_RAIDBROWSER)); - SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_LEAVE_RAIDBROWSER)); - break; - } -} - -void LFGMgr::JoinRaidBrowser(Player* player, uint8 roles, LfgDungeonSet& dungeons, std::string comment) -{ - // pussywizard: client limit for comment length is 64 @ 3.3.5a - if (comment.size() > 64) - comment = comment.substr(0, 64); - - RBEntryInfo entry(roles, comment); - for (LfgDungeonSet::const_iterator itr = dungeons.begin(); itr != dungeons.end(); ++itr) - if (GetLFGDungeon(*itr)) // ensure dungeon data exists for such dungeon id - { - RaidBrowserStore[player->GetTeamId()][*itr][player->GetGUIDLow()] = entry; - RBUsedDungeonsStore[player->GetTeamId()].insert(*itr); - } -} - -void LFGMgr::LeaveRaidBrowser(uint64 guid) -{ - uint32 guidLow = GUID_LOPART(guid); - for (uint8 team=0; team<2; ++team) - for (RBStoreMap::iterator itr = RaidBrowserStore[team].begin(); itr != RaidBrowserStore[team].end(); ++itr) - itr->second.erase(guidLow); -} - -void LFGMgr::SendRaidBrowserJoinedPacket(Player* p, LfgDungeonSet& dungeons, std::string comment) -{ - if (dungeons.empty()) - { - RBEntryInfoMap::iterator iter; - uint8 team = p->GetTeamId(); - bool setComment = true; - for (RBStoreMap::iterator itr = RaidBrowserStore[team].begin(); itr != RaidBrowserStore[team].end(); ++itr) - if ((iter = itr->second.find(p->GetGUIDLow())) != itr->second.end()) - { - dungeons.insert(itr->first); - if (setComment) - { - comment = iter->second.comment; - setComment = false; - } - } - } - LfgJoinResultData joinData; - p->GetSession()->SendLfgJoinResult(joinData); - LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_RAIDBROWSER, dungeons, comment); - if (p->GetGroup()) - p->GetSession()->SendLfgUpdateParty(updateData); - else - p->GetSession()->SendLfgUpdatePlayer(updateData); -} - -void LFGMgr::LfrSearchAdd(Player* p, uint32 dungeonId) -{ - RBSearchersStore[p->GetTeamId()][p->GetGUIDLow()] = dungeonId; -} - -void LFGMgr::LfrSearchRemove(Player* p) -{ - RBSearchersStore[p->GetTeamId()].erase(p->GetGUIDLow()); -} - -void LFGMgr::SendRaidBrowserCachedList(Player* player, uint32 dungeonId) -{ - RBCacheMap::iterator itr = RBCacheStore[player->GetTeamId()].find(dungeonId); - if (itr != RBCacheStore[player->GetTeamId()].end()) - { - player->GetSession()->SendPacket(&(itr->second)); - return; - } - // send empty packet if cache not found - WorldPacket data(SMSG_UPDATE_LFG_LIST, 1000); - data << (uint32)LFG_TYPE_RAID; - data << (uint32)dungeonId; - data << (uint8)0; - data << (uint32)0; - data << (uint32)0; - data << (uint32)0; - data << (uint32)0; - player->GetSession()->SendPacket(&data); -} - -void LFGMgr::UpdateRaidBrowser(uint32 diff) -{ - for (uint8 team=0; team<2; ++team) - { - if (m_raidBrowserUpdateTimer[team] > diff) - m_raidBrowserUpdateTimer[team] -= diff; - else - m_raidBrowserUpdateTimer[team] = 0; - } - - if (getMSTimeDiff(World::GetGameTimeMS(), getMSTime()) > (70*7)/5) // prevent lagging - return; - - uint64 guid, groupGuid, instanceGuid; - uint8 level, Class, race, talents[3]; - float iLevel, mp5, mp5combat, baseAP, rangedAP; - int32 spellDamage, spellHeal; - uint32 dungeonId, encounterMask, maxPower; - uint32 deletedCounter, groupCounter, playerCounter; - ByteBuffer buffer_deleted, buffer_groups, buffer_players; - std::string emptyComment; - std::set deletedGroups, deletedGroupsToErase; - RBInternalInfoMap copy; - - for (uint8 team=0; team<2; ++team) - { - if (m_raidBrowserLastUpdatedDungeonId[team] == 0) // new loop - { - if (m_raidBrowserUpdateTimer[team] > 0) // allowed only with some time interval - continue; - else // reset timer - m_raidBrowserUpdateTimer[team] = 5000; - } - - RBUsedDungeonsSet::const_iterator neitr, titr; - for (neitr = RBUsedDungeonsStore[team].begin(); neitr != RBUsedDungeonsStore[team].end(); ) - { - titr = neitr++; - dungeonId = (*titr); - - // go to next dungeon than previously (one dungeon updated in one LFGMgr::UpdateRaidBrowser) - if (dungeonId <= m_raidBrowserLastUpdatedDungeonId[team]) - continue; - m_raidBrowserLastUpdatedDungeonId[team] = dungeonId; - - RBEntryInfoMap& entryInfoMap = RaidBrowserStore[team][dungeonId]; - LFGDungeonData const* dungeonData = GetLFGDungeon(dungeonId); // checked if exists before inserting to the container - RBInternalInfoMap& currInternalInfoMap = RBInternalInfoStoreCurr[team][dungeonId]; - for (RBEntryInfoMap::const_iterator sitr = entryInfoMap.begin(); sitr != entryInfoMap.end(); ++sitr) - { - guid = MAKE_NEW_GUID(sitr->first, 0, HIGHGUID_PLAYER); - groupGuid = 0; - Player* p = ObjectAccessor::FindPlayerInOrOutOfWorld(guid); - ASSERT(p); - if (sitr->second.roles == PLAYER_ROLE_LEADER) - { - ASSERT(p->GetGroup()); - groupGuid = p->GetGroup()->GetGUID(); - } - encounterMask = 0; - instanceGuid = 0; - if (InstancePlayerBind* bind = sInstanceSaveMgr->PlayerGetBoundInstance(sitr->first, dungeonData->map, dungeonData->difficulty)) - if (bind->perm) - { - instanceGuid = MAKE_NEW_GUID(bind->save->GetInstanceId(), 0, HIGHGUID_INSTANCE); - encounterMask = bind->save->GetCompletedEncounterMask(); - } - - talents[0] = 0; - talents[1] = 0; - talents[2] = 0; - p->GetTalentTreePoints(talents); - spellDamage = p->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_ALL); - spellHeal = p->SpellBaseHealingBonusDone(SPELL_SCHOOL_MASK_ALL); - mp5 = p->GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER); - mp5combat = p->GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER); - baseAP = p->GetTotalAttackPowerValue(BASE_ATTACK); - rangedAP = p->GetTotalAttackPowerValue(RANGED_ATTACK); - maxPower = 0; - if (p->getClass() == CLASS_DRUID) - maxPower = p->GetMaxPower(POWER_MANA); - else - maxPower = (p->getPowerType() == POWER_RAGE || p->getPowerType() == POWER_RUNIC_POWER) ? p->GetMaxPower(p->getPowerType())/10 : p->GetMaxPower(p->getPowerType()); - - currInternalInfoMap[sitr->first] = RBInternalInfo(guid, sitr->second.comment, groupGuid != 0, groupGuid, sitr->second.roles, encounterMask, instanceGuid, - 1, p->getLevel(), p->getClass(), p->getRace(), p->GetAverageItemLevel(), - talents, p->m_last_area_id, p->GetArmor(), (uint32)std::max(0, spellDamage), (uint32)std::max(0, spellHeal), - p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_MELEE), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_RANGED), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_CRIT_SPELL), std::max(0.0f, mp5), std::max(0.0f, mp5combat), - std::max(baseAP, rangedAP), (uint32)p->GetStat(STAT_AGILITY), p->GetMaxHealth(), maxPower, p->GetDefenseSkillValue(), - p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_DODGE), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_BLOCK), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_PARRY), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_HASTE_SPELL), p->GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_EXPERTISE)); - - if (!groupGuid) - continue; - for (Group::member_citerator mitr = p->GetGroup()->GetMemberSlots().begin(); mitr != p->GetGroup()->GetMemberSlots().end(); ++mitr) - { - if (mitr->guid == sitr->first) // leader already added - continue; - guid = MAKE_NEW_GUID(mitr->guid, 0, HIGHGUID_PLAYER); - level = 1; - Class = 0; - race = 0; - iLevel = 0.0f; - talents[0] = 0; - talents[1] = 0; - talents[2] = 0; - if (const GlobalPlayerData* gpd = sWorld->GetGlobalPlayerData(mitr->guid)) - { - level = gpd->level; - Class = gpd->playerClass; - race = gpd->race; - } - Player* mplr = ObjectAccessor::FindPlayerInOrOutOfWorld(guid); - if (mplr) - { - iLevel = mplr->GetAverageItemLevel(); - mplr->GetTalentTreePoints(talents); - } - currInternalInfoMap[mitr->guid] = RBInternalInfo(guid, emptyComment, false, groupGuid, 0, 0, 0, - (mplr ? 1 : 0), level, Class, race, iLevel, - talents, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0); - } - } - - copy.clear(); - copy = currInternalInfoMap; // will be saved as prev at the end - - // compare prev with curr to build difference packet - deletedCounter = 0; groupCounter = 0; playerCounter = 0; - buffer_deleted.clear(); buffer_groups.clear(); buffer_players.clear(); - deletedGroups.clear(); deletedGroupsToErase.clear(); - - RBInternalInfoMap& prevInternalInfoMap = RBInternalInfoStorePrev[team][dungeonId]; - RBInternalInfoMap::iterator iter, iterTmp; - for (RBInternalInfoMap::const_iterator sitr = prevInternalInfoMap.begin(); sitr != prevInternalInfoMap.end(); ++sitr) - { - iter = currInternalInfoMap.find(sitr->first); - if (iter == currInternalInfoMap.end()) // was -> isn't - { - if (sitr->second.isGroupLeader) - deletedGroups.insert(sitr->second.groupGuid); - ++deletedCounter; - buffer_deleted << (uint64)sitr->second.guid; - } - else // was -> is - { - if (sitr->second.isGroupLeader) // was a leader - { - if (!iter->second.isGroupLeader) // leader -> no longer a leader - deletedGroups.insert(sitr->second.groupGuid); - else if (sitr->second.groupGuid != iter->second.groupGuid) // leader -> leader of another group - { - deletedGroups.insert(sitr->second.groupGuid); - deletedGroupsToErase.insert(iter->second.groupGuid); - ++groupCounter; - RBPacketAppendGroup(iter->second, buffer_groups); - } - else if (sitr->second.comment != iter->second.comment || sitr->second.encounterMask != iter->second.encounterMask || sitr->second.instanceGuid != iter->second.instanceGuid) // leader -> nothing changed - { - ++groupCounter; - RBPacketAppendGroup(iter->second, buffer_groups); - } - } - else if (iter->second.isGroupLeader) // wasn't a leader -> is a leader - { - deletedGroupsToErase.insert(iter->second.groupGuid); - ++groupCounter; - RBPacketAppendGroup(iter->second, buffer_groups); - } - - if (!iter->second._online) // if offline, copy previous stats (itemLevel, talents, area, etc.) - { - iterTmp = copy.find(sitr->first); // copied container is for building a full packet, so modify it there (currInternalInfoMap is erased) - iterTmp->second.CopyStats(sitr->second); - if (!sitr->second.PlayerSameAs(iterTmp->second)) // player info changed - { - ++playerCounter; - RBPacketAppendPlayer(iterTmp->second, buffer_players); - } - } - else if (!sitr->second.PlayerSameAs(iter->second)) // player info changed - { - ++playerCounter; - RBPacketAppendPlayer(iter->second, buffer_players); - } - currInternalInfoMap.erase(iter); - } - } - // left entries (new) - for (RBInternalInfoMap::const_iterator sitr = currInternalInfoMap.begin(); sitr != currInternalInfoMap.end(); ++sitr) - { - if (sitr->second.isGroupLeader) - { - deletedGroupsToErase.insert(sitr->second.groupGuid); - ++groupCounter; - RBPacketAppendGroup(sitr->second, buffer_groups); - } - ++playerCounter; - RBPacketAppendPlayer(sitr->second, buffer_players); - } - - if (!deletedGroupsToErase.empty()) - for (std::set::const_iterator sitr = deletedGroupsToErase.begin(); sitr != deletedGroupsToErase.end(); ++sitr) - deletedGroups.erase(*sitr); - - if (!deletedGroups.empty()) - for (std::set::const_iterator sitr = deletedGroups.begin(); sitr != deletedGroups.end(); ++sitr) - { - ++deletedCounter; - buffer_deleted << (*sitr); - } - - WorldPacket differencePacket(SMSG_UPDATE_LFG_LIST, 1000); - RBPacketBuildDifference(differencePacket, dungeonId, deletedCounter, buffer_deleted, groupCounter, buffer_groups, playerCounter, buffer_players); - WorldPacket fullPacket(SMSG_UPDATE_LFG_LIST, 1000); - RBPacketBuildFull(fullPacket, dungeonId, copy); - - RBCacheStore[team][dungeonId] = fullPacket; - prevInternalInfoMap = copy; - currInternalInfoMap.clear(); - - if (entryInfoMap.empty()) - RBUsedDungeonsStore[team].erase(titr); - - // send difference packet to browsing players - for (RBSearchersMap::const_iterator sitr = RBSearchersStore[team].begin(); sitr != RBSearchersStore[team].end(); ++sitr) - if (sitr->second == dungeonId) - if (Player* p = ObjectAccessor::FindPlayerInOrOutOfWorld(MAKE_NEW_GUID(sitr->first, 0, HIGHGUID_PLAYER))) - p->GetSession()->SendPacket(&differencePacket); - - break; // one dungeon updated in one LFGMgr::UpdateRaidBrowser - } - - // already updated all in this time interval - if (neitr == RBUsedDungeonsStore[team].end()) - m_raidBrowserLastUpdatedDungeonId[team] = 0; - } -} - -void LFGMgr::RBPacketAppendGroup(const RBInternalInfo& info, ByteBuffer& buffer) -{ - buffer << (uint64)info.groupGuid; - uint32 flags = LFG_UPDATE_FLAG_COMMENT | LFG_UPDATE_FLAG_ROLES | LFG_UPDATE_FLAG_BINDED; - buffer << (uint32)flags; - if (flags & LFG_UPDATE_FLAG_COMMENT) - buffer << info.comment; - if (flags & LFG_UPDATE_FLAG_ROLES) - for (uint8 j=0; j<3; ++j) - buffer << (uint8)0; - if (!(flags & LFG_UPDATE_FLAG_BINDED)) - return; - buffer << (uint64)info.instanceGuid; - buffer << (uint32)info.encounterMask; -} - -void LFGMgr::RBPacketAppendPlayer(const RBInternalInfo& info, ByteBuffer& buffer) -{ - buffer << (uint64)info.guid; - uint32 flags = LFG_UPDATE_FLAG_CHARACTERINFO | LFG_UPDATE_FLAG_ROLES | LFG_UPDATE_FLAG_COMMENT | (info.groupGuid ? LFG_UPDATE_FLAG_GROUPGUID : LFG_UPDATE_FLAG_BINDED) | (info.isGroupLeader ? LFG_UPDATE_FLAG_GROUPLEADER : 0) | (!info.groupGuid || info.isGroupLeader ? LFG_UPDATE_FLAG_AREA : 0); - buffer << (uint32)flags; - - if (flags & LFG_UPDATE_FLAG_CHARACTERINFO) - { - buffer << (uint8)info._level; - buffer << (uint8)info._class; - buffer << (uint8)info._race; - buffer << (uint8)info._talents0; - buffer << (uint8)info._talents1; - buffer << (uint8)info._talents2; - buffer << (uint32)info._armor; - buffer << (uint32)info._spellDamage; - buffer << (uint32)info._spellHeal; - buffer << (uint32)info._critRatingMelee; - buffer << (uint32)info._critRatingRanged; - buffer << (uint32)info._critRatingSpell; - buffer << (float)info._mp5; - buffer << (float)info._mp5combat; - buffer << (uint32)info._attackPower; - buffer << (uint32)info._agility; - buffer << (uint32)info._health; - buffer << (uint32)info._mana; - buffer << (uint32)info._online; // talentpoints, used as online/offline marker :D - buffer << (float)info._avgItemLevel; // avgitemlevel - buffer << (uint32)info._defenseSkill; - buffer << (uint32)info._dodgeRating; - buffer << (uint32)info._blockRating; - buffer << (uint32)info._parryRating; - buffer << (uint32)info._hasteRating; - buffer << (uint32)info._expertiseRating; - } - - if (flags & LFG_UPDATE_FLAG_COMMENT) - buffer << (info.groupGuid ? std::string("") : info.comment); - if (flags & LFG_UPDATE_FLAG_GROUPLEADER) - buffer << (uint8)1; // isLFM - if (flags & LFG_UPDATE_FLAG_GROUPGUID) - buffer << (uint64)info.groupGuid; - if (flags & LFG_UPDATE_FLAG_ROLES) - buffer << (uint8)(info.groupGuid ? (info.isGroupLeader ? PLAYER_ROLE_LEADER : 0) : info.roles); - if (flags & LFG_UPDATE_FLAG_AREA) - buffer << (uint32)info._area; - if (flags & LFG_UPDATE_FLAG_STATUS) - buffer << (uint8)0; - if (!(flags & LFG_UPDATE_FLAG_BINDED)) - return; - buffer << (uint64)info.instanceGuid; - buffer << (uint32)info.encounterMask; -} - -void LFGMgr::RBPacketBuildDifference(WorldPacket& differencePacket, uint32 dungeonId, uint32 deletedCounter, ByteBuffer& buffer_deleted, uint32 groupCounter, ByteBuffer& buffer_groups, uint32 playerCounter, ByteBuffer& buffer_players) -{ - differencePacket << (uint32)LFG_TYPE_RAID; - differencePacket << (uint32)dungeonId; - differencePacket << (uint8)1; - differencePacket << (uint32)deletedCounter; - differencePacket.append(buffer_deleted); - differencePacket << (uint32)groupCounter; - differencePacket << (uint32)0; - differencePacket.append(buffer_groups); - differencePacket << (uint32)playerCounter; - differencePacket << (uint32)0; - differencePacket.append(buffer_players); -} - -void LFGMgr::RBPacketBuildFull(WorldPacket& fullPacket, uint32 dungeonId, RBInternalInfoMap& infoMap) -{ - fullPacket << (uint32)LFG_TYPE_RAID; - fullPacket << (uint32)dungeonId; - fullPacket << (uint8)0; - uint32 groupCounter = 0, playerCounter = 0; - ByteBuffer buffer_groups, buffer_players; - for (RBInternalInfoMap::const_iterator itr = infoMap.begin(); itr != infoMap.end(); ++itr) - { - if (itr->second.isGroupLeader) - { - ++groupCounter; - RBPacketAppendGroup(itr->second, buffer_groups); - } - ++playerCounter; - RBPacketAppendPlayer(itr->second, buffer_players); - } - fullPacket << (uint32)groupCounter; - fullPacket << (uint32)0; - fullPacket.append(buffer_groups); - fullPacket << (uint32)playerCounter; - fullPacket << (uint32)0; - fullPacket.append(buffer_players); -} - -// pussywizard: -void LFGMgr::LeaveAllLfgQueues(uint64 guid, bool allowgroup, uint64 groupguid) -{ - uint64 pguid = 0, gguid = 0; - if (IS_GROUP_GUID(guid)) - gguid = guid; - else if (groupguid && IS_GROUP_GUID(groupguid)) - { - pguid = guid; - gguid = groupguid; - } - else - { - pguid = guid; - gguid = GetGroup(guid); - } - if (!allowgroup) - gguid = 0; - - if (pguid) - for (lfg::LfgQueueContainer::iterator itr = QueuesStore.begin(); itr != QueuesStore.end(); ++itr) - itr->second.RemoveFromQueue(pguid); - if (gguid) - for (lfg::LfgQueueContainer::iterator itr = QueuesStore.begin(); itr != QueuesStore.end(); ++itr) - itr->second.RemoveFromQueue(gguid); - - if (pguid && !gguid) - { - if (GetState(pguid) == LFG_STATE_QUEUED) - { - SendLfgUpdatePlayer(pguid, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); - SetState(pguid, LFG_STATE_NONE); - } - } - if (gguid) - { - if (GetState(gguid) == LFG_STATE_QUEUED) - { - SetState(gguid, LFG_STATE_NONE); - const LfgGuidSet& players = GetPlayers(gguid); - for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) - { - SetState(*it, LFG_STATE_NONE); - SendLfgUpdateParty(*it, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); - } - } - } -} - -/** - Update the Role check info with the player selected role. - - @param[in] grp Group guid to update rolecheck - @param[in] guid Player guid (0 = rolecheck failed) - @param[in] roles Player selected roles -*/ -void LFGMgr::UpdateRoleCheck(uint64 gguid, uint64 guid /* = 0 */, uint8 roles /* = PLAYER_ROLE_NONE */) -{ - if (!gguid) - return; - - LfgRolesMap check_roles; - LfgRoleCheckContainer::iterator itRoleCheck = RoleChecksStore.find(gguid); - if (itRoleCheck == RoleChecksStore.end()) - return; - - LfgRoleCheck& roleCheck = itRoleCheck->second; - bool sendRoleChosen = roleCheck.state != LFG_ROLECHECK_DEFAULT && guid; - - if (!guid) - roleCheck.state = LFG_ROLECHECK_ABORTED; - else if (roles < PLAYER_ROLE_TANK) // Player selected no role. - roleCheck.state = LFG_ROLECHECK_NO_ROLE; - else - { - roleCheck.roles[guid] = roles; - - // Check if all players have selected a role - LfgRolesMap::const_iterator itRoles = roleCheck.roles.begin(); - while (itRoles != roleCheck.roles.end() && itRoles->second != PLAYER_ROLE_NONE) - ++itRoles; - - if (itRoles == roleCheck.roles.end()) - { - // use temporal var to check roles, CheckGroupRoles modifies the roles - check_roles = roleCheck.roles; - roleCheck.state = CheckGroupRoles(check_roles) ? LFG_ROLECHECK_FINISHED : LFG_ROLECHECK_WRONG_ROLES; - } - } - - LfgDungeonSet dungeons; - if (roleCheck.rDungeonId) - dungeons.insert(roleCheck.rDungeonId); - else - dungeons = roleCheck.dungeons; - - LfgJoinResultData joinData = LfgJoinResultData(LFG_JOIN_FAILED, roleCheck.state); - for (LfgRolesMap::const_iterator it = roleCheck.roles.begin(); it != roleCheck.roles.end(); ++it) - { - uint64 pguid = it->first; - - if (sendRoleChosen) - SendLfgRoleChosen(pguid, guid, roles); - - SendLfgRoleCheckUpdate(pguid, roleCheck); - switch (roleCheck.state) - { - case LFG_ROLECHECK_INITIALITING: - continue; - case LFG_ROLECHECK_FINISHED: - SetState(pguid, LFG_STATE_QUEUED); - SetRoles(pguid, it->second); - SendLfgUpdateParty(pguid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, dungeons, GetComment(pguid))); - break; - default: - if (roleCheck.leader == pguid) - SendLfgJoinResult(pguid, joinData); - SendLfgUpdateParty(pguid, LfgUpdateData(LFG_UPDATETYPE_ROLECHECK_FAILED)); - RestoreState(pguid, "Rolecheck Failed"); - break; - } - } - - if (roleCheck.state == LFG_ROLECHECK_FINISHED) - { - SetState(gguid, LFG_STATE_QUEUED); - LFGQueue& queue = GetQueue(gguid); - queue.AddQueueData(gguid, time_t(time(nullptr)), roleCheck.dungeons, roleCheck.roles); - RoleChecksStore.erase(itRoleCheck); - } - else if (roleCheck.state != LFG_ROLECHECK_INITIALITING) - { - RestoreState(gguid, "Rolecheck Failed"); - RoleChecksStore.erase(itRoleCheck); - } -} - -/** - Given a list of dungeons remove the dungeons players have restrictions. - - @param[in, out] dungeons Dungeons to check restrictions - @param[in] players Set of players to check their dungeon restrictions - @param[out] lockMap Map of players Lock status info of given dungeons (Empty if dungeons is not empty) -*/ -void LFGMgr::GetCompatibleDungeons(LfgDungeonSet& dungeons, LfgGuidSet const& players, LfgLockPartyMap& lockMap) -{ - lockMap.clear(); - for (LfgGuidSet::const_iterator it = players.begin(); it != players.end() && !dungeons.empty(); ++it) - { - uint64 guid = (*it); - LfgLockMap const& cachedLockMap = GetLockedDungeons(guid); - for (LfgLockMap::const_iterator it2 = cachedLockMap.begin(); it2 != cachedLockMap.end() && !dungeons.empty(); ++it2) - { - uint32 dungeonId = (it2->first & 0x00FFFFFF); // Compare dungeon ids - LfgDungeonSet::iterator itDungeon = dungeons.find(dungeonId); - if (itDungeon != dungeons.end()) - { - dungeons.erase(itDungeon); - lockMap[guid][dungeonId] = it2->second; - } - } - } - if (!dungeons.empty()) - lockMap.clear(); -} - -uint8 LFGMgr::CheckGroupRoles(LfgRolesMap& groles, bool removeLeaderFlag /*= true*/) -{ - if (groles.empty()) - return 0; - - uint8 damage = 0; - uint8 tank = 0; - uint8 healer = 0; - - if (removeLeaderFlag) - for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it) - it->second &= ~PLAYER_ROLE_LEADER; - - for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it) - { - if (it->second == PLAYER_ROLE_NONE) - return 0; - - if (it->second & PLAYER_ROLE_DAMAGE) - { - if (it->second != PLAYER_ROLE_DAMAGE) - { - it->second -= PLAYER_ROLE_DAMAGE; - if (uint8 x = CheckGroupRoles(groles, false)) - return x; - it->second += PLAYER_ROLE_DAMAGE; - } - else if (damage == LFG_DPS_NEEDED) - return 0; - else - damage++; - } - - if (it->second & PLAYER_ROLE_HEALER) - { - if (it->second != PLAYER_ROLE_HEALER) - { - it->second -= PLAYER_ROLE_HEALER; - if (uint8 x = CheckGroupRoles(groles, false)) - return x; - it->second += PLAYER_ROLE_HEALER; - } - else if (healer == LFG_HEALERS_NEEDED) - return 0; - else - healer++; - } - - if (it->second & PLAYER_ROLE_TANK) - { - if (it->second != PLAYER_ROLE_TANK) - { - it->second -= PLAYER_ROLE_TANK; - if (uint8 x = CheckGroupRoles(groles, false)) - return x; - it->second += PLAYER_ROLE_TANK; - } - else if (tank == LFG_TANKS_NEEDED) - return 0; - else - tank++; - } - } - if ((tank + healer + damage) == uint8(groles.size())) - return (8*tank + 4*healer + damage); - return 0; -} - -/** - Makes a new group given a proposal - @param[in] proposal Proposal to get info from -*/ -void LFGMgr::MakeNewGroup(LfgProposal const& proposal) -{ - LfgGuidList players; - LfgGuidList playersToTeleport; - - for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - { - uint64 guid = it->first; - if (guid == proposal.leader) - players.push_front(guid); - else - players.push_back(guid); - - if (proposal.isNew || GetGroup(guid) != proposal.group) - playersToTeleport.push_back(guid); - } - - // Set the dungeon difficulty - LFGDungeonData const* dungeon = GetLFGDungeon(proposal.dungeonId); - ASSERT(dungeon); - - Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(GUID_LOPART(proposal.group)) : nullptr; - uint64 oldGroupGUID = 0; - for (LfgGuidList::const_iterator it = players.begin(); it != players.end(); ++it) - { - uint64 pguid = (*it); - Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(pguid); - if (!player) - continue; - - Group* group = player->GetGroup(); - - // Xinef: Apply Random Buff - if (grp && !grp->IsLfgWithBuff()) - { - if (!group || group->GetGUID() != oldGroupGUID) - grp->AddLfgBuffFlag(); - else - oldGroupGUID = group->GetGUID(); - } - - // Xinef: Store amount of random players player grouped with - if (group) - { - SetRandomPlayersCount(pguid, group->GetMembersCount() >= MAXGROUPSIZE ? 0 : MAXGROUPSIZE-group->GetMembersCount()); - oldGroupGUID = group->GetGUID(); - if (group != grp) - group->RemoveMember(player->GetGUID()); - } - else - SetRandomPlayersCount(pguid, MAXGROUPSIZE-1); - - if (!grp) - { - grp = new Group(); - grp->ConvertToLFG(); - grp->Create(player); - uint64 gguid = grp->GetGUID(); - SetState(gguid, LFG_STATE_PROPOSAL); - sGroupMgr->AddGroup(grp); - } - else if (group != grp) - { - // pussywizard: - if (!grp->IsFull()) - grp->AddMember(player); - //else // some cleanup? LeaveLFG? - // ; - } - - grp->SetLfgRoles(pguid, proposal.players.find(pguid)->second.role); - } - - // pussywizard: crashfix, group wasn't created when iterating players (no player found by guid), proposal is deleted by the calling function - if (!grp) - return; - - grp->SetDungeonDifficulty(Difficulty(dungeon->difficulty)); - uint64 gguid = grp->GetGUID(); - SetDungeon(gguid, dungeon->Entry()); - SetState(gguid, LFG_STATE_DUNGEON); - - _SaveToDB(gguid); - - bool randomDungeon = false; - // Teleport Player - for (LfgGuidList::const_iterator it = playersToTeleport.begin(); it != playersToTeleport.end(); ++it) - if (Player* player = ObjectAccessor::FindPlayer(*it)) - { - if (player->GetGroup() != grp) // pussywizard: could not add because group was full (some shitness happened) - continue; - // Add the cooldown spell if queued for a random dungeon - // xinef: add aura - if ((randomDungeon || selectedRandomLfgDungeon(player->GetGUID())) && !player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) - { - randomDungeon = true; - player->AddAura(LFG_SPELL_DUNGEON_COOLDOWN, player); - } - TeleportPlayer(player, false); - } - - if (randomDungeon) - grp->AddLfgRandomInstanceFlag(); - if (Difficulty(dungeon->difficulty) == DUNGEON_DIFFICULTY_HEROIC) - grp->AddLfgHeroicFlag(); - - // Update group info - grp->SendUpdate(); -} - -uint32 LFGMgr::AddProposal(LfgProposal& proposal) -{ - proposal.id = ++m_lfgProposalId; - ProposalsStore[m_lfgProposalId] = proposal; - return m_lfgProposalId; -} - -/** - Update Proposal info with player answer - - @param[in] proposalId Proposal id to be updated - @param[in] guid Player guid to update answer - @param[in] accept Player answer -*/ -void LFGMgr::UpdateProposal(uint32 proposalId, uint64 guid, bool accept) -{ - // Check if the proposal exists - LfgProposalContainer::iterator itProposal = ProposalsStore.find(proposalId); - if (itProposal == ProposalsStore.end()) - return; - - LfgProposal& proposal = itProposal->second; - - // Check if proposal have the current player - LfgProposalPlayerContainer::iterator itProposalPlayer = proposal.players.find(guid); - if (itProposalPlayer == proposal.players.end()) - return; - - LfgProposalPlayer& player = itProposalPlayer->second; - player.accept = LfgAnswer(accept); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::UpdateProposal: Player [" UI64FMTD "] of proposal %u selected: %u", guid, proposalId, accept); -#endif - if (!accept) - { - RemoveProposal(itProposal, LFG_UPDATETYPE_PROPOSAL_DECLINED); - return; - } - - // check if all have answered and reorder players (leader first) - bool allAnswered = true; - for (LfgProposalPlayerContainer::const_iterator itPlayers = proposal.players.begin(); itPlayers != proposal.players.end(); ++itPlayers) - if (itPlayers->second.accept != LFG_ANSWER_AGREE) // No answer (-1) or not accepted (0) - allAnswered = false; - - if (!allAnswered) - { - for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - SendLfgUpdateProposal(it->first, proposal); - - return; - } - - bool sendUpdate = proposal.state != LFG_PROPOSAL_SUCCESS; - proposal.state = LFG_PROPOSAL_SUCCESS; - time_t joinTime = time(nullptr); - - LFGQueue& queue = GetQueue(guid); - LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_GROUP_FOUND); - for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - { - uint64 pguid = it->first; - uint64 gguid = it->second.group; - uint32 dungeonId = (*GetSelectedDungeons(pguid).begin()); - int32 waitTime = -1; - if (sendUpdate) - SendLfgUpdateProposal(pguid, proposal); - - if (gguid) - { - waitTime = int32((joinTime - queue.GetJoinTime(gguid)) / IN_MILLISECONDS); - SendLfgUpdateParty(pguid, updateData); - } - else - { - waitTime = int32((joinTime - queue.GetJoinTime(pguid)) / IN_MILLISECONDS); - SendLfgUpdatePlayer(pguid, updateData); - } - updateData.updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE; - SendLfgUpdatePlayer(pguid, updateData); - SendLfgUpdateParty(pguid, updateData); - - // Update timers - uint8 role = GetRoles(pguid); - role &= ~PLAYER_ROLE_LEADER; - switch (role) - { - case PLAYER_ROLE_DAMAGE: - queue.UpdateWaitTimeDps(waitTime, dungeonId); - break; - case PLAYER_ROLE_HEALER: - queue.UpdateWaitTimeHealer(waitTime, dungeonId); - break; - case PLAYER_ROLE_TANK: - queue.UpdateWaitTimeTank(waitTime, dungeonId); - break; - default: - queue.UpdateWaitTimeAvg(waitTime, dungeonId); - break; - } - - SetState(pguid, LFG_STATE_DUNGEON); - } - - // Remove players/groups from Queue - for (uint8 i=0; i<5 && proposal.queues.guid[i]; ++i) - queue.RemoveQueueData(proposal.queues.guid[i]); - - MakeNewGroup(proposal); - ProposalsStore.erase(itProposal); -} - -/** - Remove a proposal from the pool, remove the group that didn't accept (if needed) and readd the other members to the queue - - @param[in] itProposal Iterator to the proposal to remove - @param[in] type Type of removal (LFG_UPDATETYPE_PROPOSAL_FAILED, LFG_UPDATETYPE_PROPOSAL_DECLINED) -*/ -void LFGMgr::RemoveProposal(LfgProposalContainer::iterator itProposal, LfgUpdateType type) -{ - LfgProposal& proposal = itProposal->second; - proposal.state = LFG_PROPOSAL_FAILED; - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: Proposal %u, state FAILED, UpdateType %u", itProposal->first, type); -#endif - // Mark all people that didn't answered as no accept - if (type == LFG_UPDATETYPE_PROPOSAL_FAILED) - for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - if (it->second.accept == LFG_ANSWER_PENDING) - it->second.accept = LFG_ANSWER_DENY; - - // pussywizard: add cooldown for not accepting (after 40 secs) or declining - for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - if (it->second.accept == LFG_ANSWER_DENY) - if (Player* plr = sObjectAccessor->FindPlayer(it->first)) - if (Aura* aura = plr->AddAura(LFG_SPELL_DUNGEON_COOLDOWN, plr)) - aura->SetDuration(150*IN_MILLISECONDS); - - // Mark players/groups to be removed - LfgGuidSet toRemove; - for (LfgProposalPlayerContainer::iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - { - if (it->second.accept == LFG_ANSWER_AGREE) - continue; - - uint64 guid = it->second.group ? it->second.group : it->first; - // Player didn't accept or still pending when no secs left - if (it->second.accept == LFG_ANSWER_DENY || type == LFG_UPDATETYPE_PROPOSAL_FAILED) - { - it->second.accept = LFG_ANSWER_DENY; - toRemove.insert(guid); - } - } - - // Notify players - for (LfgProposalPlayerContainer::const_iterator it = proposal.players.begin(); it != proposal.players.end(); ++it) - { - uint64 guid = it->first; - uint64 gguid = it->second.group ? it->second.group : guid; - - SendLfgUpdateProposal(guid, proposal); - - if (toRemove.find(gguid) != toRemove.end()) // Didn't accept or in same group that someone that didn't accept - { - LfgUpdateData updateData; - if (it->second.accept == LFG_ANSWER_DENY) - { - updateData.updateType = type; -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: [" UI64FMTD "] didn't accept. Removing from queue and compatible cache", guid); -#endif - } - else - { - updateData.updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE; -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: [" UI64FMTD "] in same group that someone that didn't accept. Removing from queue and compatible cache", guid); -#endif - } - - RestoreState(guid, "Proposal Fail (didn't accepted or in group with someone that didn't accept"); - if (gguid != guid) - { - RestoreState(it->second.group, "Proposal Fail (someone in group didn't accepted)"); - SendLfgUpdateParty(guid, updateData); - } - else - SendLfgUpdatePlayer(guid, updateData); - } - else - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveProposal: Readding [" UI64FMTD "] to queue.", guid); -#endif - SetState(guid, LFG_STATE_QUEUED); - if (gguid != guid) - { - SetState(gguid, LFG_STATE_QUEUED); - SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, GetSelectedDungeons(guid), GetComment(guid))); - } - else - SendLfgUpdatePlayer(guid, LfgUpdateData(LFG_UPDATETYPE_ADDED_TO_QUEUE, GetSelectedDungeons(guid), GetComment(guid))); - } - } - - LFGQueue& queue = GetQueue(proposal.players.begin()->first); - // Remove players/groups from queue - for (LfgGuidSet::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it) - { - uint64 guid = *it; - queue.RemoveFromQueue(guid); - proposal.queues.remove(guid); - } - - // Readd to queue - for (uint8 i=0; i<5 && proposal.queues.guid[i]; ++i) - { - // xinef: this will work as data is not deleted, only references to this data are cleared - // xinef: when new proposal is created - // xinef: successful proposal is also taken into account is similar manner - queue.AddToQueue(proposal.queues.guid[i], true); - } - - ProposalsStore.erase(itProposal); -} - -/** - Initialize a boot kick vote - - @param[in] gguid Group the vote kicks belongs to - @param[in] kicker Kicker guid - @param[in] victim Victim guid - @param[in] reason Kick reason -*/ -void LFGMgr::InitBoot(uint64 gguid, uint64 kicker, uint64 victim, std::string const& reason) -{ - SetState(gguid, LFG_STATE_BOOT); - - LfgPlayerBoot& boot = BootsStore[gguid]; - boot.inProgress = true; - boot.cancelTime = time_t(time(nullptr)) + LFG_TIME_BOOT; - boot.reason = reason; - boot.victim = victim; - - LfgGuidSet const& players = GetPlayers(gguid); - - // Set votes - for (LfgGuidSet::const_iterator itr = players.begin(); itr != players.end(); ++itr) - { - uint64 guid = (*itr); - SetState(guid, LFG_STATE_BOOT); - boot.votes[guid] = LFG_ANSWER_PENDING; - } - - boot.votes[victim] = LFG_ANSWER_DENY; // Victim auto vote NO - boot.votes[kicker] = LFG_ANSWER_AGREE; // Kicker auto vote YES - - // Notify players - for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) - SendLfgBootProposalUpdate(*it, boot); -} - -/** - Update Boot info with player answer - - @param[in] guid Player who has answered - @param[in] player answer -*/ -void LFGMgr::UpdateBoot(uint64 guid, bool accept) -{ - uint64 gguid = GetGroup(guid); - if (!gguid) - return; - - LfgPlayerBootContainer::iterator itBoot = BootsStore.find(gguid); - if (itBoot == BootsStore.end()) - return; - - LfgPlayerBoot& boot = itBoot->second; - - if (boot.votes[guid] != LFG_ANSWER_PENDING) // Cheat check: Player can't vote twice - return; - - boot.votes[guid] = LfgAnswer(accept); - - uint8 votesNum = 0; - uint8 agreeNum = 0; - for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes) - { - if (itVotes->second != LFG_ANSWER_PENDING) - { - ++votesNum; - if (itVotes->second == LFG_ANSWER_AGREE) - ++agreeNum; - } - } - - // if we don't have enough votes (agree or deny) do nothing - if (agreeNum < LFG_GROUP_KICK_VOTES_NEEDED && (votesNum - agreeNum) < LFG_GROUP_KICK_VOTES_NEEDED) - return; - - // Send update info to all players - boot.inProgress = false; - for (LfgAnswerContainer::const_iterator itVotes = boot.votes.begin(); itVotes != boot.votes.end(); ++itVotes) - { - uint64 pguid = itVotes->first; - if (pguid != boot.victim) - { - SetState(pguid, LFG_STATE_DUNGEON); - SendLfgBootProposalUpdate(pguid, boot); - } - } - - SetState(gguid, LFG_STATE_DUNGEON); - if (agreeNum == LFG_GROUP_KICK_VOTES_NEEDED) // Vote passed - Kick player - { - if (Group* group = sGroupMgr->GetGroupByGUID(GUID_LOPART(gguid))) - Player::RemoveFromGroup(group, boot.victim, GROUP_REMOVEMETHOD_KICK_LFG); - DecreaseKicksLeft(gguid); - } - BootsStore.erase(itBoot); -} - -/** - Teleports the player in or out the dungeon - - @param[in] player Player to teleport - @param[in] out Teleport out (true) or in (false) - @param[in] fromOpcode Function called from opcode handlers? (Default false) -*/ -void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false*/) -{ - LFGDungeonData const* dungeon = nullptr; - Group* group = player->GetGroup(); - - if (group && group->isLFGGroup()) - dungeon = GetLFGDungeon(GetDungeon(group->GetGUID())); - - if (!dungeon) - { - player->GetSession()->SendLfgTeleportError(uint8(LFG_TELEPORTERROR_INVALID_LOCATION)); - return; - } - - if (out) - { - if (player->GetMapId() == uint32(dungeon->map)) - player->TeleportToEntryPoint(); - - return; - } - - LfgTeleportError error = LFG_TELEPORTERROR_OK; - - if (!player->IsAlive()) - error = LFG_TELEPORTERROR_PLAYER_DEAD; - else if (player->IsFalling() || player->HasUnitState(UNIT_STATE_JUMPING)) - error = LFG_TELEPORTERROR_FALLING; - else if (player->IsMirrorTimerActive(FATIGUE_TIMER)) - error = LFG_TELEPORTERROR_FATIGUE; - else if (player->GetVehicle()) - error = LFG_TELEPORTERROR_IN_VEHICLE; - else if (player->GetCharmGUID()) - error = LFG_TELEPORTERROR_CHARMING; - else if (player->GetMapId() != uint32(dungeon->map)) // Do not teleport players in dungeon to the entrance - { - uint32 mapid = dungeon->map; - float x = dungeon->x; - float y = dungeon->y; - float z = dungeon->z; - float orientation = dungeon->o; - - if (!fromOpcode) - { - // Select a player inside to be teleported to - for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) - { - Player* plrg = itr->GetSource(); - if (plrg && plrg != player && plrg->GetMapId() == uint32(dungeon->map)) - { - mapid = plrg->GetMapId(); - x = plrg->GetPositionX(); - y = plrg->GetPositionY(); - z = plrg->GetPositionZ(); - orientation = plrg->GetOrientation(); - break; - } + ok = false; } } - if (!player->GetMap()->IsDungeon()) - player->SetEntryPoint(); - - if (!player->TeleportTo(mapid, x, y, z, orientation)) - error = LFG_TELEPORTERROR_INVALID_LOCATION; - } - else - error = LFG_TELEPORTERROR_INVALID_LOCATION; - - if (error != LFG_TELEPORTERROR_OK) - player->GetSession()->SendLfgTeleportError(uint8(error)); - - //sLog->outDebug(LOG_FILTER_LFG, "TeleportPlayer: Player %s is being teleported in to map %u " - // "(x: %f, y: %f, z: %f) Result: %u", player->GetName().c_str(), dungeon->map, - // dungeon->x, dungeon->y, dungeon->z, error); -} - -/** - Finish a dungeon and give reward, if any. - - @param[in] guid Group guid - @param[in] dungeonId Dungeonid -*/ -void LFGMgr::FinishDungeon(uint64 gguid, const uint32 dungeonId, const Map* currMap) -{ - uint32 gDungeonId = GetDungeon(gguid); - if (gDungeonId != dungeonId) - { - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] Finished dungeon %u but group queued for %u. Ignoring", gguid, dungeonId, gDungeonId); - return; + return ok; } - if (GetState(gguid) == LFG_STATE_FINISHED_DUNGEON) // Shouldn't happen. Do not reward multiple times + // Only for debugging purposes + void LFGMgr::Clean() { - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] Already rewarded group. Ignoring", gguid); - return; + QueuesStore.clear(); } - SetState(gguid, LFG_STATE_FINISHED_DUNGEON); - _SaveToDB(gguid); // pussywizard - - const LfgGuidSet& players = GetPlayers(gguid); - for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) + bool LFGMgr::isOptionEnabled(uint32 option) { - uint64 guid = (*it); - if (GetState(guid) == LFG_STATE_FINISHED_DUNGEON) + return m_options & option; + } + + uint32 LFGMgr::GetOptions() + { + return m_options; + } + + void LFGMgr::SetOptions(uint32 options) + { + m_options = options; + } + + LfgUpdateData LFGMgr::GetLfgStatus(uint64 guid) + { + LfgPlayerData& playerData = PlayersStore[guid]; + return LfgUpdateData(LFG_UPDATETYPE_UPDATE_STATUS, playerData.GetState(), playerData.GetSelectedDungeons()); + } + + bool LFGMgr::IsSeasonActive(uint32 dungeonId) + { + switch (dungeonId) { - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] Already rewarded player. Ignoring", guid); - continue; + case 285: // The Headless Horseman + return IsHolidayActive(HOLIDAY_HALLOWS_END); + case 286: // The Frost Lord Ahune + return IsHolidayActive(HOLIDAY_FIRE_FESTIVAL); + case 287: // Coren Direbrew + return IsHolidayActive(HOLIDAY_BREWFEST); + case 288: // The Crown Chemical Co. + return IsHolidayActive(HOLIDAY_LOVE_IS_IN_THE_AIR); } - - uint32 rDungeonId = 0; - const LfgDungeonSet& dungeons = GetSelectedDungeons(guid); - if (!dungeons.empty()) - rDungeonId = (*dungeons.begin()); - - SetState(guid, LFG_STATE_FINISHED_DUNGEON); - - // Give rewards only if its a random dungeon - LFGDungeonData const* dungeon = GetLFGDungeon(rDungeonId); - - if (!dungeon || (dungeon->type != LFG_TYPE_RANDOM && !dungeon->seasonal)) - { - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] dungeon %u is not random or seasonal", guid, rDungeonId); - continue; - } - - Player* player = ObjectAccessor::FindPlayer(guid); - if (!player || player->FindMap() != currMap) // pussywizard: currMap - multithreading crash if on other map (map id check is not enough, binding system is not reliable) - { - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] not found in world", guid); - continue; - } - - LFGDungeonData const* dungeonDone = GetLFGDungeon(dungeonId); - uint32 mapId = dungeonDone ? uint32(dungeonDone->map) : 0; - - if (player->GetMapId() != mapId) - { - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] is in map %u and should be in %u to get reward", guid, player->GetMapId(), mapId); - continue; - } - - // Xinef: Update achievements, set correct amount of randomly grouped players - if (dungeon->difficulty == DUNGEON_DIFFICULTY_HEROIC) - if (uint8 count = GetRandomPlayersCount(player->GetGUID())) - player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS, count); - - LfgReward const* reward = GetRandomDungeonReward(rDungeonId, player->getLevel()); - if (!reward) - continue; - - bool done = false; - Quest const* quest = sObjectMgr->GetQuestTemplate(reward->firstQuest); - if (!quest) - continue; - - // if we can take the quest, means that we haven't done this kind of "run", IE: First Heroic Random of Day. - if (player->CanRewardQuest(quest, false)) - player->RewardQuest(quest, 0, NULL, false); - else - { - done = true; - quest = sObjectMgr->GetQuestTemplate(reward->otherQuest); - if (!quest) - continue; - // we give reward without informing client (retail does this) - player->RewardQuest(quest, 0, NULL, false); - } - - // Give rewards - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::FinishDungeon: [" UI64FMTD "] done dungeon %u, %s previously done.", player->GetGUID(), GetDungeon(gguid), done? " " : " not"); - LfgPlayerRewardData data = LfgPlayerRewardData(dungeon->Entry(), GetDungeon(gguid, false), done, quest); - player->GetSession()->SendLfgPlayerReward(data); - } -} - -// --------------------------------------------------------------------------// -// Auxiliar Functions -// --------------------------------------------------------------------------// - -/** - Get the dungeon list that can be done given a random dungeon entry. - - @param[in] randomdungeon Random dungeon id (if value = 0 will return all dungeons) - @returns Set of dungeons that can be done. -*/ -LfgDungeonSet const& LFGMgr::GetDungeonsByRandom(uint32 randomdungeon) -{ - LFGDungeonData const* dungeon = GetLFGDungeon(randomdungeon); - uint32 group = dungeon ? dungeon->group : 0; - return CachedDungeonMapStore[group]; -} - -/** - Get the reward of a given random dungeon at a certain level - - @param[in] dungeon dungeon id - @param[in] level Player level - @returns Reward -*/ -LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level) -{ - LfgReward const* rew = nullptr; - LfgRewardContainerBounds bounds = RewardMapStore.equal_range(dungeon & 0x00FFFFFF); - for (LfgRewardContainer::const_iterator itr = bounds.first; itr != bounds.second; ++itr) - { - rew = itr->second; - // ordered properly at loading - if (itr->second->maxLevel >= level) - break; - } - - return rew; -} - -/** - Given a Dungeon id returns the dungeon Type - - @param[in] dungeon dungeon id - @returns Dungeon type -*/ -LfgType LFGMgr::GetDungeonType(uint32 dungeonId) -{ - LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId); - if (!dungeon) - return LFG_TYPE_NONE; - - return LfgType(dungeon->type); -} - -LfgState LFGMgr::GetState(uint64 guid) -{ - LfgState state; - if (IS_GROUP_GUID(guid)) - state = GroupsStore[guid].GetState(); - else - state = PlayersStore[guid].GetState(); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetState: [" UI64FMTD "] = %u", guid, state); -#endif - return state; -} - -LfgState LFGMgr::GetOldState(uint64 guid) -{ - LfgState state; - if (IS_GROUP_GUID(guid)) - state = GroupsStore[guid].GetOldState(); - else - state = PlayersStore[guid].GetOldState(); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetOldState: [" UI64FMTD "] = %u", guid, state); -#endif - return state; -} - -uint32 LFGMgr::GetDungeon(uint64 guid, bool asId /*= true */) -{ - uint32 dungeon = GroupsStore[guid].GetDungeon(asId); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetDungeon: [" UI64FMTD "] asId: %u = %u", guid, asId, dungeon); -#endif - return dungeon; -} - -uint32 LFGMgr::GetDungeonMapId(uint64 guid) -{ - uint32 dungeonId = GroupsStore[guid].GetDungeon(true); - uint32 mapId = 0; - if (dungeonId) - if (LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId)) - mapId = dungeon->map; - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetDungeonMapId: [" UI64FMTD "] = %u (DungeonId = %u)", guid, mapId, dungeonId); -#endif - return mapId; -} - -uint8 LFGMgr::GetRoles(uint64 guid) -{ - uint8 roles = PlayersStore[guid].GetRoles(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetRoles: [" UI64FMTD "] = %u", guid, roles); -#endif - return roles; -} - -const std::string& LFGMgr::GetComment(uint64 guid) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetComment: [" UI64FMTD "] = %s", guid, PlayersStore[guid].GetComment().c_str()); -#endif - return PlayersStore[guid].GetComment(); -} - -LfgDungeonSet const& LFGMgr::GetSelectedDungeons(uint64 guid) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetSelectedDungeons: [" UI64FMTD "]", guid); -#endif - return PlayersStore[guid].GetSelectedDungeons(); -} - -LfgLockMap const& LFGMgr::GetLockedDungeons(uint64 guid) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetLockedDungeons: [" UI64FMTD "]", guid); -#endif - return PlayersStore[guid].GetLockedDungeons(); -} - -uint8 LFGMgr::GetKicksLeft(uint64 guid) -{ - uint8 kicks = GroupsStore[guid].GetKicksLeft(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::GetKicksLeft: [" UI64FMTD "] = %u", guid, kicks); -#endif - return kicks; -} - -void LFGMgr::RestoreState(uint64 guid, char const* /*debugMsg*/) -{ - if (IS_GROUP_GUID(guid)) - { - LfgGroupData& data = GroupsStore[guid]; - /*if (sLog->ShouldLog(LOG_FILTER_LFG, LOG_LEVEL_DEBUG)) - { - std::string const& ps = GetStateString(data.GetState()); - std::string const& os = GetStateString(data.GetOldState()); - sLog->outTrace(LOG_FILTER_LFG, "LFGMgr::RestoreState: Group: [" UI64FMTD "] (%s) State: %s, oldState: %s", - guid, debugMsg, ps.c_str(), os.c_str()); - }*/ - - data.RestoreState(); - } - else - { - LfgPlayerData& data = PlayersStore[guid]; - /*if (sLog->ShouldLog(LOG_FILTER_LFG, LOG_LEVEL_DEBUG)) - { - std::string const& ps = GetStateString(data.GetState()); - std::string const& os = GetStateString(data.GetOldState()); - sLog->outTrace(LOG_FILTER_LFG, "LFGMgr::RestoreState: Player: [" UI64FMTD "] (%s) State: %s, oldState: %s", - guid, debugMsg, ps.c_str(), os.c_str()); - }*/ - data.RestoreState(); - } -} - -void LFGMgr::SetState(uint64 guid, LfgState state) -{ - if (IS_GROUP_GUID(guid)) - { - LfgGroupData& data = GroupsStore[guid]; - std::string ns = GetStateString(state); - std::string ps = GetStateString(data.GetState()); - std::string os = GetStateString(data.GetOldState()); - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetState: Group: [" UI64FMTD "] newState: %s, previous: %s, oldState: %s", guid, ns.c_str(), ps.c_str(), os.c_str()); - data.SetState(state); - } - else - { - LfgPlayerData& data = PlayersStore[guid]; - std::string ns = GetStateString(state); - std::string ps = GetStateString(data.GetState()); - std::string os = GetStateString(data.GetOldState()); - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetState: Player: [" UI64FMTD "] newState: %s, previous: %s, oldState: %s", guid, ns.c_str(), ps.c_str(), os.c_str()); - data.SetState(state); - } -} - -void LFGMgr::SetCanOverrideRBState(uint64 guid, bool val) -{ - PlayersStore[guid].SetCanOverrideRBState(val); -} - -void LFGMgr::SetDungeon(uint64 guid, uint32 dungeon) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetDungeon: [" UI64FMTD "] dungeon %u", guid, dungeon); -#endif - GroupsStore[guid].SetDungeon(dungeon); -} - -void LFGMgr::SetRoles(uint64 guid, uint8 roles) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetRoles: [" UI64FMTD "] roles: %u", guid, roles); -#endif - PlayersStore[guid].SetRoles(roles); -} - -void LFGMgr::SetComment(uint64 guid, std::string const& comment) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetComment: [" UI64FMTD "] comment: %s", guid, comment.c_str()); -#endif - PlayersStore[guid].SetComment(comment); -} - -void LFGMgr::LfrSetComment(Player* p, std::string comment) -{ - // pussywizard: client limit for comment length is 64 @ 3.3.5a - if (comment.size() > 64) - comment = comment.substr(0, 64); - - uint8 teamId = p->GetTeamId(); - RBEntryInfoMap::iterator iter; - for (RBStoreMap::iterator itr = RaidBrowserStore[teamId].begin(); itr != RaidBrowserStore[teamId].end(); ++itr) - if ((iter = itr->second.find(p->GetGUIDLow())) != itr->second.end()) - iter->second.comment = comment; -} - -void LFGMgr::SetSelectedDungeons(uint64 guid, LfgDungeonSet const& dungeons) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetLockedDungeons: [" UI64FMTD "]", guid); -#endif - PlayersStore[guid].SetSelectedDungeons(dungeons); -} - -void LFGMgr::SetLockedDungeons(uint64 guid, LfgLockMap const& lock) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::SetLockedDungeons: [" UI64FMTD "]", guid); -#endif - PlayersStore[guid].SetLockedDungeons(lock); -} - -void LFGMgr::DecreaseKicksLeft(uint64 guid) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::DecreaseKicksLeft: [" UI64FMTD "]", guid); -#endif - GroupsStore[guid].DecreaseKicksLeft(); -} - -void LFGMgr::RemoveGroupData(uint64 guid) -{ -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGMgr::RemoveGroupData: [" UI64FMTD "]", guid); -#endif - LfgGroupDataContainer::iterator it = GroupsStore.find(guid); - if (it == GroupsStore.end()) - return; - - LfgState state = GetState(guid); - // If group is being formed after proposal success do nothing more - LfgGuidSet const& players = it->second.GetPlayers(); - for (LfgGuidSet::const_iterator it = players.begin(); it != players.end(); ++it) - { - uint64 guid = (*it); - SetGroup(*it, 0); - if (state != LFG_STATE_PROPOSAL) - { - SetState(*it, LFG_STATE_NONE); - SendLfgUpdateParty(guid, LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE)); - } - } - GroupsStore.erase(it); -} - -TeamId LFGMgr::GetTeam(uint64 guid) -{ - return PlayersStore[guid].GetTeam(); -} - -uint8 LFGMgr::RemovePlayerFromGroup(uint64 gguid, uint64 guid) -{ - return GroupsStore[gguid].RemovePlayer(guid); -} - -void LFGMgr::AddPlayerToGroup(uint64 gguid, uint64 guid) -{ - GroupsStore[gguid].AddPlayer(guid); -} - -void LFGMgr::SetLeader(uint64 gguid, uint64 leader) -{ - GroupsStore[gguid].SetLeader(leader); -} - -void LFGMgr::SetTeam(uint64 guid, TeamId teamId) -{ - if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP)) - teamId = TEAM_ALLIANCE; // @Not Sure About That TeamId is supposed to be uint8 Team = 0(@TrinityCore) - - PlayersStore[guid].SetTeam(teamId); -} - -uint64 LFGMgr::GetGroup(uint64 guid) -{ - return PlayersStore[guid].GetGroup(); -} - -void LFGMgr::SetGroup(uint64 guid, uint64 group) -{ - PlayersStore[guid].SetGroup(group); -} - -LfgGuidSet const& LFGMgr::GetPlayers(uint64 guid) -{ - return GroupsStore[guid].GetPlayers(); -} - -uint8 LFGMgr::GetPlayerCount(uint64 guid) -{ - return GroupsStore[guid].GetPlayerCount(); -} - -uint64 LFGMgr::GetLeader(uint64 guid) -{ - return GroupsStore[guid].GetLeader(); -} - -void LFGMgr::SetRandomPlayersCount(uint64 guid, uint8 count) -{ - PlayersStore[guid].SetRandomPlayersCount(count); -} - -uint8 LFGMgr::GetRandomPlayersCount(uint64 guid) -{ - return PlayersStore[guid].GetRandomPlayersCount(); -} - -bool LFGMgr::HasIgnore(uint64 guid1, uint64 guid2) -{ - Player* plr1 = ObjectAccessor::FindPlayerInOrOutOfWorld(guid1); - Player* plr2 = ObjectAccessor::FindPlayerInOrOutOfWorld(guid2); - uint32 low1 = GUID_LOPART(guid1); - uint32 low2 = GUID_LOPART(guid2); - return plr1 && plr2 && (plr1->GetSocial()->HasIgnore(low2) || plr2->GetSocial()->HasIgnore(low1)); -} - -void LFGMgr::SendLfgRoleChosen(uint64 guid, uint64 pguid, uint8 roles) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgRoleChosen(pguid, roles); -} - -void LFGMgr::SendLfgRoleCheckUpdate(uint64 guid, LfgRoleCheck const& roleCheck) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgRoleCheckUpdate(roleCheck); -} - -void LFGMgr::SendLfgUpdatePlayer(uint64 guid, LfgUpdateData const& data) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgUpdatePlayer(data); -} - -void LFGMgr::SendLfgUpdateParty(uint64 guid, LfgUpdateData const& data) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgUpdateParty(data); -} - -void LFGMgr::SendLfgJoinResult(uint64 guid, LfgJoinResultData const& data) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgJoinResult(data); -} - -void LFGMgr::SendLfgBootProposalUpdate(uint64 guid, LfgPlayerBoot const& boot) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgBootProposalUpdate(boot); -} - -void LFGMgr::SendLfgUpdateProposal(uint64 guid, LfgProposal const& proposal) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgUpdateProposal(proposal); -} - -void LFGMgr::SendLfgQueueStatus(uint64 guid, LfgQueueStatusData const& data) -{ - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - player->GetSession()->SendLfgQueueStatus(data); -} - -bool LFGMgr::IsLfgGroup(uint64 guid) -{ - return guid && IS_GROUP_GUID(guid) && GroupsStore[guid].IsLfgGroup(); -} - -LFGQueue& LFGMgr::GetQueue(uint64 guid) -{ - uint8 queueId = 0; - if (IS_GROUP_GUID(guid)) - { - LfgGuidSet const& players = GetPlayers(guid); - uint64 pguid = players.empty() ? 0 : (*players.begin()); - if (pguid) - queueId = GetTeam(pguid); - else - queueId = GetTeam(GetLeader(guid)); - } - else - queueId = GetTeam(guid); - return QueuesStore[queueId]; -} - -bool LFGMgr::AllQueued(Lfg5Guids const& check) -{ - bool ok = true; - - if (check.empty()) return false; + } - for (uint8 i=0; i<5 && check.guid[i]; ++i) + void LFGMgr::SetupGroupMember(uint64 guid, uint64 gguid) { - uint64 guid = check.guid[i]; - if (GetState(guid) != LFG_STATE_QUEUED) + LfgDungeonSet dungeons; + dungeons.insert(GetDungeon(gguid)); + SetSelectedDungeons(guid, dungeons); + SetState(guid, GetState(gguid)); + SetGroup(guid, gguid); + AddPlayerToGroup(gguid, guid); + } + + bool LFGMgr::selectedRandomLfgDungeon(uint64 guid) + { + if (GetState(guid) != LFG_STATE_NONE) { - LFGQueue& queue = GetQueue(guid); - queue.RemoveFromQueue(guid); - ok = false; + LfgDungeonSet const& dungeons = GetSelectedDungeons(guid); + if (!dungeons.empty()) + { + LFGDungeonData const* dungeon = GetLFGDungeon(*dungeons.begin()); + if (dungeon && (dungeon->type == LFG_TYPE_RANDOM || dungeon->seasonal)) + return true; + } } + + return false; } - return ok; -} - -// Only for debugging purposes -void LFGMgr::Clean() -{ - QueuesStore.clear(); -} - -bool LFGMgr::isOptionEnabled(uint32 option) -{ - return m_options & option; -} - -uint32 LFGMgr::GetOptions() -{ - return m_options; -} - -void LFGMgr::SetOptions(uint32 options) -{ - m_options = options; -} - -LfgUpdateData LFGMgr::GetLfgStatus(uint64 guid) -{ - LfgPlayerData& playerData = PlayersStore[guid]; - return LfgUpdateData(LFG_UPDATETYPE_UPDATE_STATUS, playerData.GetState(), playerData.GetSelectedDungeons()); -} - -bool LFGMgr::IsSeasonActive(uint32 dungeonId) -{ - switch (dungeonId) + bool LFGMgr::inLfgDungeonMap(uint64 guid, uint32 map, Difficulty difficulty) { - case 285: // The Headless Horseman - return IsHolidayActive(HOLIDAY_HALLOWS_END); - case 286: // The Frost Lord Ahune - return IsHolidayActive(HOLIDAY_FIRE_FESTIVAL); - case 287: // Coren Direbrew - return IsHolidayActive(HOLIDAY_BREWFEST); - case 288: // The Crown Chemical Co. - return IsHolidayActive(HOLIDAY_LOVE_IS_IN_THE_AIR); + if (!IS_GROUP_GUID(guid)) + guid = GetGroup(guid); + + if (uint32 dungeonId = GetDungeon(guid, true)) + if (LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId)) + if (uint32(dungeon->map) == map && dungeon->difficulty == difficulty) + return true; + + return false; } - return false; -} -void LFGMgr::SetupGroupMember(uint64 guid, uint64 gguid) -{ - LfgDungeonSet dungeons; - dungeons.insert(GetDungeon(gguid)); - SetSelectedDungeons(guid, dungeons); - SetState(guid, GetState(gguid)); - SetGroup(guid, gguid); - AddPlayerToGroup(gguid, guid); -} - -bool LFGMgr::selectedRandomLfgDungeon(uint64 guid) -{ - if (GetState(guid) != LFG_STATE_NONE) + uint32 LFGMgr::GetLFGDungeonEntry(uint32 id) { - LfgDungeonSet const& dungeons = GetSelectedDungeons(guid); - if (!dungeons.empty()) + if (id) + if (LFGDungeonData const* dungeon = GetLFGDungeon(id)) + return dungeon->Entry(); + + return 0; + } + + LfgDungeonSet LFGMgr::GetRandomAndSeasonalDungeons(uint8 level, uint8 expansion) + { + LfgDungeonSet randomDungeons; + for (lfg::LFGDungeonContainer::const_iterator itr = LfgDungeonStore.begin(); itr != LfgDungeonStore.end(); ++itr) { - LFGDungeonData const* dungeon = GetLFGDungeon(*dungeons.begin()); - if (dungeon && (dungeon->type == LFG_TYPE_RANDOM || dungeon->seasonal)) - return true; + lfg::LFGDungeonData const& dungeon = itr->second; + if ((dungeon.type == lfg::LFG_TYPE_RANDOM || (dungeon.seasonal && sLFGMgr->IsSeasonActive(dungeon.id))) + && dungeon.expansion <= expansion && dungeon.minlevel <= level && level <= dungeon.maxlevel) + randomDungeons.insert(dungeon.Entry()); } + return randomDungeons; } - return false; -} - -bool LFGMgr::inLfgDungeonMap(uint64 guid, uint32 map, Difficulty difficulty) -{ - if (!IS_GROUP_GUID(guid)) - guid = GetGroup(guid); - - if (uint32 dungeonId = GetDungeon(guid, true)) - if (LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId)) - if (uint32(dungeon->map) == map && dungeon->difficulty == difficulty) - return true; - - return false; -} - -uint32 LFGMgr::GetLFGDungeonEntry(uint32 id) -{ - if (id) - if (LFGDungeonData const* dungeon = GetLFGDungeon(id)) - return dungeon->Entry(); - - return 0; -} - -LfgDungeonSet LFGMgr::GetRandomAndSeasonalDungeons(uint8 level, uint8 expansion) -{ - LfgDungeonSet randomDungeons; - for (lfg::LFGDungeonContainer::const_iterator itr = LfgDungeonStore.begin(); itr != LfgDungeonStore.end(); ++itr) - { - lfg::LFGDungeonData const& dungeon = itr->second; - if ((dungeon.type == lfg::LFG_TYPE_RANDOM || (dungeon.seasonal && sLFGMgr->IsSeasonActive(dungeon.id))) - && dungeon.expansion <= expansion && dungeon.minlevel <= level && level <= dungeon.maxlevel) - randomDungeons.insert(dungeon.Entry()); - } - return randomDungeons; -} - } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGMgr.h b/src/server/game/DungeonFinding/LFGMgr.h index f7c8be82c..d301baddf 100644 --- a/src/server/game/DungeonFinding/LFGMgr.h +++ b/src/server/game/DungeonFinding/LFGMgr.h @@ -22,362 +22,380 @@ class Quest; namespace lfg { -enum LfgOptions -{ - LFG_OPTION_ENABLE_DUNGEON_FINDER = 0x01, - LFG_OPTION_ENABLE_RAID_BROWSER = 0x02, -}; + enum LfgOptions + { + LFG_OPTION_ENABLE_DUNGEON_FINDER = 0x01, + LFG_OPTION_ENABLE_RAID_BROWSER = 0x02, + }; -enum LFGMgrEnum -{ - LFG_TIME_ROLECHECK = 45 * IN_MILLISECONDS, - LFG_TIME_BOOT = 120, - LFG_TIME_PROPOSAL = 40, - LFG_QUEUEUPDATE_INTERVAL = 8 * IN_MILLISECONDS, - LFG_SPELL_DUNGEON_COOLDOWN = 71328, - LFG_SPELL_DUNGEON_DESERTER = 71041, - LFG_SPELL_LUCK_OF_THE_DRAW = 72221, - LFG_GROUP_KICK_VOTES_NEEDED = 3 -}; + enum LFGMgrEnum + { + LFG_TIME_ROLECHECK = 45 * IN_MILLISECONDS, + LFG_TIME_BOOT = 120, + LFG_TIME_PROPOSAL = 40, + LFG_QUEUEUPDATE_INTERVAL = 8 * IN_MILLISECONDS, + LFG_SPELL_DUNGEON_COOLDOWN = 71328, + LFG_SPELL_DUNGEON_DESERTER = 71041, + LFG_SPELL_LUCK_OF_THE_DRAW = 72221, + LFG_GROUP_KICK_VOTES_NEEDED = 3 + }; -enum LfgFlags -{ - LFG_FLAG_UNK1 = 0x1, - LFG_FLAG_UNK2 = 0x2, - LFG_FLAG_SEASONAL = 0x4, - LFG_FLAG_UNK3 = 0x8 -}; + enum LfgFlags + { + LFG_FLAG_UNK1 = 0x1, + LFG_FLAG_UNK2 = 0x2, + LFG_FLAG_SEASONAL = 0x4, + LFG_FLAG_UNK3 = 0x8 + }; -/// Determines the type of instance -enum LfgType -{ - LFG_TYPE_NONE = 0, - LFG_TYPE_DUNGEON = 1, - LFG_TYPE_RAID = 2, - LFG_TYPE_HEROIC = 5, - LFG_TYPE_RANDOM = 6 -}; + /// Determines the type of instance + enum LfgType + { + LFG_TYPE_NONE = 0, + LFG_TYPE_DUNGEON = 1, + LFG_TYPE_RAID = 2, + LFG_TYPE_HEROIC = 5, + LFG_TYPE_RANDOM = 6 + }; -/// Proposal states -enum LfgProposalState -{ - LFG_PROPOSAL_INITIATING = 0, - LFG_PROPOSAL_FAILED = 1, - LFG_PROPOSAL_SUCCESS = 2 -}; + /// Proposal states + enum LfgProposalState + { + LFG_PROPOSAL_INITIATING = 0, + LFG_PROPOSAL_FAILED = 1, + LFG_PROPOSAL_SUCCESS = 2 + }; -/// Teleport errors -enum LfgTeleportError -{ - // 7 = "You can't do that right now" | 5 = No client reaction - LFG_TELEPORTERROR_OK = 0, // Internal use - LFG_TELEPORTERROR_PLAYER_DEAD = 1, - LFG_TELEPORTERROR_FALLING = 2, - LFG_TELEPORTERROR_IN_VEHICLE = 3, - LFG_TELEPORTERROR_FATIGUE = 4, - LFG_TELEPORTERROR_INVALID_LOCATION = 6, - LFG_TELEPORTERROR_CHARMING = 8 // FIXME - It can be 7 or 8 (Need proper data) -}; + /// Teleport errors + enum LfgTeleportError + { + // 7 = "You can't do that right now" | 5 = No client reaction + LFG_TELEPORTERROR_OK = 0, // Internal use + LFG_TELEPORTERROR_PLAYER_DEAD = 1, + LFG_TELEPORTERROR_FALLING = 2, + LFG_TELEPORTERROR_IN_VEHICLE = 3, + LFG_TELEPORTERROR_FATIGUE = 4, + LFG_TELEPORTERROR_INVALID_LOCATION = 6, + LFG_TELEPORTERROR_CHARMING = 8 // FIXME - It can be 7 or 8 (Need proper data) + }; -/// Queue join results -enum LfgJoinResult -{ - // 3 = No client reaction | 18 = "Rolecheck failed" - LFG_JOIN_OK = 0, // Joined (no client msg) - LFG_JOIN_FAILED = 1, // RoleCheck Failed - LFG_JOIN_GROUPFULL = 2, // Your group is full - LFG_JOIN_INTERNAL_ERROR = 4, // Internal LFG Error - LFG_JOIN_NOT_MEET_REQS = 5, // You do not meet the requirements for the chosen dungeons - LFG_JOIN_PARTY_NOT_MEET_REQS = 6, // One or more party members do not meet the requirements for the chosen dungeons - LFG_JOIN_MIXED_RAID_DUNGEON = 7, // You cannot mix dungeons, raids, and random when picking dungeons - LFG_JOIN_MULTI_REALM = 8, // The dungeon you chose does not support players from multiple realms - LFG_JOIN_DISCONNECTED = 9, // One or more party members are pending invites or disconnected - LFG_JOIN_PARTY_INFO_FAILED = 10, // Could not retrieve information about some party members - LFG_JOIN_DUNGEON_INVALID = 11, // One or more dungeons was not valid - LFG_JOIN_DESERTER = 12, // You can not queue for dungeons until your deserter debuff wears off - LFG_JOIN_PARTY_DESERTER = 13, // One or more party members has a deserter debuff - LFG_JOIN_RANDOM_COOLDOWN = 14, // You can not queue for random dungeons while on random dungeon cooldown - LFG_JOIN_PARTY_RANDOM_COOLDOWN = 15, // One or more party members are on random dungeon cooldown - LFG_JOIN_TOO_MUCH_MEMBERS = 16, // You can not enter dungeons with more that 5 party members - LFG_JOIN_USING_BG_SYSTEM = 17 // You can not use the dungeon system while in BG or arenas -}; + /// Queue join results + enum LfgJoinResult + { + // 3 = No client reaction | 18 = "Rolecheck failed" + LFG_JOIN_OK = 0, // Joined (no client msg) + LFG_JOIN_FAILED = 1, // RoleCheck Failed + LFG_JOIN_GROUPFULL = 2, // Your group is full + LFG_JOIN_INTERNAL_ERROR = 4, // Internal LFG Error + LFG_JOIN_NOT_MEET_REQS = 5, // You do not meet the requirements for the chosen dungeons + LFG_JOIN_PARTY_NOT_MEET_REQS = 6, // One or more party members do not meet the requirements for the chosen dungeons + LFG_JOIN_MIXED_RAID_DUNGEON = 7, // You cannot mix dungeons, raids, and random when picking dungeons + LFG_JOIN_MULTI_REALM = 8, // The dungeon you chose does not support players from multiple realms + LFG_JOIN_DISCONNECTED = 9, // One or more party members are pending invites or disconnected + LFG_JOIN_PARTY_INFO_FAILED = 10, // Could not retrieve information about some party members + LFG_JOIN_DUNGEON_INVALID = 11, // One or more dungeons was not valid + LFG_JOIN_DESERTER = 12, // You can not queue for dungeons until your deserter debuff wears off + LFG_JOIN_PARTY_DESERTER = 13, // One or more party members has a deserter debuff + LFG_JOIN_RANDOM_COOLDOWN = 14, // You can not queue for random dungeons while on random dungeon cooldown + LFG_JOIN_PARTY_RANDOM_COOLDOWN = 15, // One or more party members are on random dungeon cooldown + LFG_JOIN_TOO_MUCH_MEMBERS = 16, // You can not enter dungeons with more that 5 party members + LFG_JOIN_USING_BG_SYSTEM = 17 // You can not use the dungeon system while in BG or arenas + }; -/// Role check states -enum LfgRoleCheckState -{ - LFG_ROLECHECK_DEFAULT = 0, // Internal use = Not initialized. - LFG_ROLECHECK_FINISHED = 1, // Role check finished - LFG_ROLECHECK_INITIALITING = 2, // Role check begins - LFG_ROLECHECK_MISSING_ROLE = 3, // Someone didn't selected a role after 2 mins - LFG_ROLECHECK_WRONG_ROLES = 4, // Can't form a group with that role selection - LFG_ROLECHECK_ABORTED = 5, // Someone leave the group - LFG_ROLECHECK_NO_ROLE = 6 // Someone selected no role -}; + /// Role check states + enum LfgRoleCheckState + { + LFG_ROLECHECK_DEFAULT = 0, // Internal use = Not initialized. + LFG_ROLECHECK_FINISHED = 1, // Role check finished + LFG_ROLECHECK_INITIALITING = 2, // Role check begins + LFG_ROLECHECK_MISSING_ROLE = 3, // Someone didn't selected a role after 2 mins + LFG_ROLECHECK_WRONG_ROLES = 4, // Can't form a group with that role selection + LFG_ROLECHECK_ABORTED = 5, // Someone leave the group + LFG_ROLECHECK_NO_ROLE = 6 // Someone selected no role + }; -enum LfgUpdateFlag // pussywizard: for raid browser -{ - LFG_UPDATE_FLAG_NONE = 0x00, - LFG_UPDATE_FLAG_CHARACTERINFO = 0x01, - LFG_UPDATE_FLAG_COMMENT = 0x02, - LFG_UPDATE_FLAG_GROUPLEADER = 0x04, - LFG_UPDATE_FLAG_GROUPGUID = 0x08, - LFG_UPDATE_FLAG_ROLES = 0x10, - LFG_UPDATE_FLAG_AREA = 0x20, - LFG_UPDATE_FLAG_STATUS = 0x40, - LFG_UPDATE_FLAG_BINDED = 0x80 -}; + enum LfgUpdateFlag // pussywizard: for raid browser + { + LFG_UPDATE_FLAG_NONE = 0x00, + LFG_UPDATE_FLAG_CHARACTERINFO = 0x01, + LFG_UPDATE_FLAG_COMMENT = 0x02, + LFG_UPDATE_FLAG_GROUPLEADER = 0x04, + LFG_UPDATE_FLAG_GROUPGUID = 0x08, + LFG_UPDATE_FLAG_ROLES = 0x10, + LFG_UPDATE_FLAG_AREA = 0x20, + LFG_UPDATE_FLAG_STATUS = 0x40, + LFG_UPDATE_FLAG_BINDED = 0x80 + }; -struct RBEntryInfo -{ - RBEntryInfo() {} - RBEntryInfo(uint8 _roles, std::string const& _comment) : roles(_roles), comment(_comment) {} - uint8 roles; - std::string comment; -}; + struct RBEntryInfo + { + RBEntryInfo() {} + RBEntryInfo(uint8 _roles, std::string const& _comment) : roles(_roles), comment(_comment) {} + uint8 roles; + std::string comment; + }; -struct RBInternalInfo -{ - uint64 guid; - std::string comment; - bool isGroupLeader; - uint64 groupGuid; - uint8 roles; - uint32 encounterMask; - uint64 instanceGuid; + struct RBInternalInfo + { + uint64 guid; + std::string comment; + bool isGroupLeader; + uint64 groupGuid; + uint8 roles; + uint32 encounterMask; + uint64 instanceGuid; - // additional character info parameters: - uint8 _online; - uint8 _level; - uint8 _class; - uint8 _race; - float _avgItemLevel; - // -- - uint8 _talents0; - uint8 _talents1; - uint8 _talents2; - uint32 _area; - uint32 _armor; - uint32 _spellDamage; - uint32 _spellHeal; - // -- - uint32 _critRatingMelee; - uint32 _critRatingRanged; - uint32 _critRatingSpell; - float _mp5; - float _mp5combat; - // -- - uint32 _attackPower; - uint32 _agility; - uint32 _health; - uint32 _mana; - uint32 _defenseSkill; - // -- - uint32 _dodgeRating; - uint32 _blockRating; - uint32 _parryRating; - uint32 _hasteRating; - uint32 _expertiseRating; + // additional character info parameters: + uint8 _online; + uint8 _level; + uint8 _class; + uint8 _race; + float _avgItemLevel; + // -- + uint8 _talents0; + uint8 _talents1; + uint8 _talents2; + uint32 _area; + uint32 _armor; + uint32 _spellDamage; + uint32 _spellHeal; + // -- + uint32 _critRatingMelee; + uint32 _critRatingRanged; + uint32 _critRatingSpell; + float _mp5; + float _mp5combat; + // -- + uint32 _attackPower; + uint32 _agility; + uint32 _health; + uint32 _mana; + uint32 _defenseSkill; + // -- + uint32 _dodgeRating; + uint32 _blockRating; + uint32 _parryRating; + uint32 _hasteRating; + uint32 _expertiseRating; - RBInternalInfo() {} - RBInternalInfo(uint64 guid, std::string const& comment, bool isGroupLeader, uint64 groupGuid, uint8 roles, uint32 encounterMask, uint64 instanceGuid, - uint8 _online, uint8 _level, uint8 _class, uint8 _race, float _avgItemLevel, - uint8 (&_talents)[3], uint32 _area, uint32 _armor, uint32 _spellDamage, uint32 _spellHeal, - uint32 _critRatingMelee, uint32 _critRatingRanged, uint32 _critRatingSpell, float _mp5, float _mp5combat, - uint32 _attackPower, uint32 _agility, uint32 _health, uint32 _mana, uint32 _defenseSkill, - uint32 _dodgeRating, uint32 _blockRating, uint32 _parryRating, uint32 _hasteRating, uint32 _expertiseRating) + RBInternalInfo() {} + RBInternalInfo(uint64 guid, std::string const& comment, bool isGroupLeader, uint64 groupGuid, uint8 roles, uint32 encounterMask, uint64 instanceGuid, + uint8 _online, uint8 _level, uint8 _class, uint8 _race, float _avgItemLevel, + uint8 (&_talents)[3], uint32 _area, uint32 _armor, uint32 _spellDamage, uint32 _spellHeal, + uint32 _critRatingMelee, uint32 _critRatingRanged, uint32 _critRatingSpell, float _mp5, float _mp5combat, + uint32 _attackPower, uint32 _agility, uint32 _health, uint32 _mana, uint32 _defenseSkill, + uint32 _dodgeRating, uint32 _blockRating, uint32 _parryRating, uint32 _hasteRating, uint32 _expertiseRating) : guid(guid), comment(comment), isGroupLeader(isGroupLeader), groupGuid(groupGuid), roles(roles), encounterMask(encounterMask), instanceGuid(instanceGuid), - _online(_online), _level(_level), _class(_class), _race(_race), _avgItemLevel(_avgItemLevel), - _talents0(_talents[0]), _talents1(_talents[1]), _talents2(_talents[2]), _area(_area), _armor(_armor), _spellDamage(_spellDamage), _spellHeal(_spellHeal), - _critRatingMelee(_critRatingMelee), _critRatingRanged(_critRatingRanged), _critRatingSpell(_critRatingSpell), _mp5(_mp5), _mp5combat(_mp5combat), - _attackPower(_attackPower), _agility(_agility), _health(_health), _mana(_mana), _defenseSkill(_defenseSkill), - _dodgeRating(_dodgeRating), _blockRating(_blockRating), _parryRating(_parryRating), _hasteRating(_hasteRating), _expertiseRating(_expertiseRating) + _online(_online), _level(_level), _class(_class), _race(_race), _avgItemLevel(_avgItemLevel), + _talents0(_talents[0]), _talents1(_talents[1]), _talents2(_talents[2]), _area(_area), _armor(_armor), _spellDamage(_spellDamage), _spellHeal(_spellHeal), + _critRatingMelee(_critRatingMelee), _critRatingRanged(_critRatingRanged), _critRatingSpell(_critRatingSpell), _mp5(_mp5), _mp5combat(_mp5combat), + _attackPower(_attackPower), _agility(_agility), _health(_health), _mana(_mana), _defenseSkill(_defenseSkill), + _dodgeRating(_dodgeRating), _blockRating(_blockRating), _parryRating(_parryRating), _hasteRating(_hasteRating), _expertiseRating(_expertiseRating) {} - bool PlayerSameAs(RBInternalInfo const& i) const + bool PlayerSameAs(RBInternalInfo const& i) const + { + return isGroupLeader == i.isGroupLeader && groupGuid == i.groupGuid && roles == i.roles && (isGroupLeader || (comment == i.comment && encounterMask == i.encounterMask && instanceGuid == i.instanceGuid)) + && _online == i._online && _level == i._level && _class == i._class && _race == i._race && fabs(_avgItemLevel - i._avgItemLevel) < 0.01f + && _talents0 == i._talents0 && _talents1 == i._talents1 && _talents2 == i._talents2 && _area == i._area && _armor == i._armor && _spellDamage == i._spellDamage && _spellHeal == i._spellHeal + && _critRatingMelee == i._critRatingMelee && _critRatingRanged == i._critRatingRanged && _critRatingSpell == i._critRatingSpell && fabs(_mp5 - i._mp5) < 0.01f && fabs(_mp5combat - i._mp5combat) < 0.01f + && _attackPower == i._attackPower && _agility == i._agility && _health == i._health && _mana == i._mana && _defenseSkill == i._defenseSkill + && _dodgeRating == i._dodgeRating && _blockRating == i._blockRating && _parryRating == i._parryRating && _hasteRating == i._hasteRating && _expertiseRating == i._expertiseRating; + } + void CopyStats(RBInternalInfo const& i) + { + _avgItemLevel = i._avgItemLevel; + _talents0 = i._talents0; + _talents1 = i._talents1; + _talents2 = i._talents2; + _area = i._area; + _armor = i._armor; + _spellDamage = i._spellDamage; + _spellHeal = i._spellHeal; + _critRatingMelee = i._critRatingMelee; + _critRatingRanged = i._critRatingRanged; + _critRatingSpell = i._critRatingSpell; + _mp5 = i._mp5; + _mp5combat = i._mp5combat; + _attackPower = i._attackPower; + _agility = i._agility; + _health = i._health; + _mana = i._mana; + _defenseSkill = i._defenseSkill; + _dodgeRating = i._dodgeRating; + _blockRating = i._blockRating; + _parryRating = i._parryRating; + _hasteRating = i._hasteRating; + _expertiseRating = i._expertiseRating; + } + }; + + // Forward declaration (just to have all typedef together) + struct LFGDungeonData; + struct LfgReward; + struct LfgQueueInfo; + struct LfgRoleCheck; + struct LfgProposal; + struct LfgProposalPlayer; + struct LfgPlayerBoot; + + typedef std::map LfgQueueContainer; + typedef std::multimap LfgRewardContainer; + typedef std::pair LfgRewardContainerBounds; + typedef std::map LfgCachedDungeonContainer; + typedef std::map LfgAnswerContainer; + typedef std::map LfgRoleCheckContainer; + typedef std::map LfgProposalContainer; + typedef std::map LfgProposalPlayerContainer; + typedef std::map LfgPlayerBootContainer; + typedef std::map LfgGroupDataContainer; + typedef std::map LfgPlayerDataContainer; + typedef std::unordered_map LFGDungeonContainer; + + // Data needed by SMSG_LFG_JOIN_RESULT + struct LfgJoinResultData { - return isGroupLeader == i.isGroupLeader && groupGuid == i.groupGuid && roles == i.roles && (isGroupLeader || (comment == i.comment && encounterMask == i.encounterMask && instanceGuid == i.instanceGuid)) - && _online == i._online && _level == i._level && _class == i._class && _race == i._race && fabs(_avgItemLevel-i._avgItemLevel) < 0.01f - && _talents0 == i._talents0 && _talents1 == i._talents1 && _talents2 == i._talents2 && _area == i._area && _armor == i._armor && _spellDamage == i._spellDamage && _spellHeal == i._spellHeal - && _critRatingMelee == i._critRatingMelee && _critRatingRanged == i._critRatingRanged && _critRatingSpell == i._critRatingSpell && fabs(_mp5-i._mp5) < 0.01f && fabs(_mp5combat-i._mp5combat) < 0.01f - && _attackPower == i._attackPower && _agility == i._agility && _health == i._health && _mana == i._mana && _defenseSkill == i._defenseSkill - && _dodgeRating == i._dodgeRating && _blockRating == i._blockRating && _parryRating == i._parryRating && _hasteRating == i._hasteRating && _expertiseRating == i._expertiseRating; - } - void CopyStats(RBInternalInfo const& i) + LfgJoinResultData(LfgJoinResult _result = LFG_JOIN_OK, LfgRoleCheckState _state = LFG_ROLECHECK_DEFAULT): + result(_result), state(_state) {} + LfgJoinResult result; + LfgRoleCheckState state; + LfgLockPartyMap lockmap; + }; + + // Data needed by SMSG_LFG_UPDATE_PARTY and SMSG_LFG_UPDATE_PLAYER + struct LfgUpdateData { - _avgItemLevel = i._avgItemLevel; - _talents0 = i._talents0; _talents1 = i._talents1; _talents2 = i._talents2; _area = i._area; _armor = i._armor; _spellDamage = i._spellDamage; _spellHeal = i._spellHeal; - _critRatingMelee = i._critRatingMelee; _critRatingRanged = i._critRatingRanged; _critRatingSpell = i._critRatingSpell; _mp5 = i._mp5; _mp5combat = i._mp5combat; - _attackPower = i._attackPower; _agility = i._agility; _health = i._health; _mana = i._mana; _defenseSkill = i._defenseSkill; - _dodgeRating = i._dodgeRating; _blockRating = i._blockRating; _parryRating = i._parryRating; _hasteRating = i._hasteRating; _expertiseRating = i._expertiseRating; - } -}; + LfgUpdateData(LfgUpdateType _type = LFG_UPDATETYPE_DEFAULT): updateType(_type), state(LFG_STATE_NONE), comment("") { } + LfgUpdateData(LfgUpdateType _type, LfgDungeonSet const& _dungeons, std::string const& _comment): + updateType(_type), state(LFG_STATE_NONE), dungeons(_dungeons), comment(_comment) { } + LfgUpdateData(LfgUpdateType _type, LfgState _state, LfgDungeonSet const& _dungeons, std::string const& _comment = ""): + updateType(_type), state(_state), dungeons(_dungeons), comment(_comment) { } -// Forward declaration (just to have all typedef together) -struct LFGDungeonData; -struct LfgReward; -struct LfgQueueInfo; -struct LfgRoleCheck; -struct LfgProposal; -struct LfgProposalPlayer; -struct LfgPlayerBoot; + LfgUpdateType updateType; + LfgState state; + LfgDungeonSet dungeons; + std::string comment; + }; -typedef std::map LfgQueueContainer; -typedef std::multimap LfgRewardContainer; -typedef std::pair LfgRewardContainerBounds; -typedef std::map LfgCachedDungeonContainer; -typedef std::map LfgAnswerContainer; -typedef std::map LfgRoleCheckContainer; -typedef std::map LfgProposalContainer; -typedef std::map LfgProposalPlayerContainer; -typedef std::map LfgPlayerBootContainer; -typedef std::map LfgGroupDataContainer; -typedef std::map LfgPlayerDataContainer; -typedef std::unordered_map LFGDungeonContainer; + // Data needed by SMSG_LFG_QUEUE_STATUS + struct LfgQueueStatusData + { + LfgQueueStatusData(uint32 _dungeonId = 0, int32 _waitTime = -1, int32 _waitTimeAvg = -1, int32 _waitTimeTank = -1, int32 _waitTimeHealer = -1, + int32 _waitTimeDps = -1, uint32 _queuedTime = 0, uint8 _tanks = 0, uint8 _healers = 0, uint8 _dps = 0) : + dungeonId(_dungeonId), waitTime(_waitTime), waitTimeAvg(_waitTimeAvg), waitTimeTank(_waitTimeTank), waitTimeHealer(_waitTimeHealer), + waitTimeDps(_waitTimeDps), queuedTime(_queuedTime), tanks(_tanks), healers(_healers), dps(_dps) {} -// Data needed by SMSG_LFG_JOIN_RESULT -struct LfgJoinResultData -{ - LfgJoinResultData(LfgJoinResult _result = LFG_JOIN_OK, LfgRoleCheckState _state = LFG_ROLECHECK_DEFAULT): - result(_result), state(_state) {} - LfgJoinResult result; - LfgRoleCheckState state; - LfgLockPartyMap lockmap; -}; + uint32 dungeonId; + int32 waitTime; + int32 waitTimeAvg; + int32 waitTimeTank; + int32 waitTimeHealer; + int32 waitTimeDps; + uint32 queuedTime; + uint8 tanks; + uint8 healers; + uint8 dps; + }; -// Data needed by SMSG_LFG_UPDATE_PARTY and SMSG_LFG_UPDATE_PLAYER -struct LfgUpdateData -{ - LfgUpdateData(LfgUpdateType _type = LFG_UPDATETYPE_DEFAULT): updateType(_type), state(LFG_STATE_NONE), comment("") { } - LfgUpdateData(LfgUpdateType _type, LfgDungeonSet const& _dungeons, std::string const& _comment): - updateType(_type), state(LFG_STATE_NONE), dungeons(_dungeons), comment(_comment) { } - LfgUpdateData(LfgUpdateType _type, LfgState _state, LfgDungeonSet const& _dungeons, std::string const& _comment = ""): - updateType(_type), state(_state), dungeons(_dungeons), comment(_comment) { } + struct LfgPlayerRewardData + { + LfgPlayerRewardData(uint32 random, uint32 current, bool _done, Quest const* _quest): + rdungeonEntry(random), sdungeonEntry(current), done(_done), quest(_quest) { } + uint32 rdungeonEntry; + uint32 sdungeonEntry; + bool done; + Quest const* quest; + }; - LfgUpdateType updateType; - LfgState state; - LfgDungeonSet dungeons; - std::string comment; -}; + /// Reward info + struct LfgReward + { + LfgReward(uint32 _maxLevel = 0, uint32 _firstQuest = 0, uint32 _otherQuest = 0): + maxLevel(_maxLevel), firstQuest(_firstQuest), otherQuest(_otherQuest) { } -// Data needed by SMSG_LFG_QUEUE_STATUS -struct LfgQueueStatusData -{ - LfgQueueStatusData(uint32 _dungeonId = 0, int32 _waitTime = -1, int32 _waitTimeAvg = -1, int32 _waitTimeTank = -1, int32 _waitTimeHealer = -1, - int32 _waitTimeDps = -1, uint32 _queuedTime = 0, uint8 _tanks = 0, uint8 _healers = 0, uint8 _dps = 0) : - dungeonId(_dungeonId), waitTime(_waitTime), waitTimeAvg(_waitTimeAvg), waitTimeTank(_waitTimeTank), waitTimeHealer(_waitTimeHealer), - waitTimeDps(_waitTimeDps), queuedTime(_queuedTime), tanks(_tanks), healers(_healers), dps(_dps) {} + uint32 maxLevel; + uint32 firstQuest; + uint32 otherQuest; + }; - uint32 dungeonId; - int32 waitTime; - int32 waitTimeAvg; - int32 waitTimeTank; - int32 waitTimeHealer; - int32 waitTimeDps; - uint32 queuedTime; - uint8 tanks; - uint8 healers; - uint8 dps; -}; + /// Stores player data related to proposal to join + struct LfgProposalPlayer + { + LfgProposalPlayer(): role(0), accept(LFG_ANSWER_PENDING), group(0) { } + uint8 role; ///< Proposed role + LfgAnswer accept; ///< Accept status (-1 not answer | 0 Not agree | 1 agree) + uint64 group; ///< Original group guid. 0 if no original group + }; -struct LfgPlayerRewardData -{ - LfgPlayerRewardData(uint32 random, uint32 current, bool _done, Quest const* _quest): - rdungeonEntry(random), sdungeonEntry(current), done(_done), quest(_quest) { } - uint32 rdungeonEntry; - uint32 sdungeonEntry; - bool done; - Quest const* quest; -}; - -/// Reward info -struct LfgReward -{ - LfgReward(uint32 _maxLevel = 0, uint32 _firstQuest = 0, uint32 _otherQuest = 0): - maxLevel(_maxLevel), firstQuest(_firstQuest), otherQuest(_otherQuest) { } - - uint32 maxLevel; - uint32 firstQuest; - uint32 otherQuest; -}; - -/// Stores player data related to proposal to join -struct LfgProposalPlayer -{ - LfgProposalPlayer(): role(0), accept(LFG_ANSWER_PENDING), group(0) { } - uint8 role; ///< Proposed role - LfgAnswer accept; ///< Accept status (-1 not answer | 0 Not agree | 1 agree) - uint64 group; ///< Original group guid. 0 if no original group -}; - -/// Stores group data related to proposal to join -struct LfgProposal -{ - LfgProposal(uint32 dungeon = 0): id(0), dungeonId(dungeon), state(LFG_PROPOSAL_INITIATING), - group(0), leader(0), cancelTime(0), encounters(0), isNew(true) + /// Stores group data related to proposal to join + struct LfgProposal + { + LfgProposal(uint32 dungeon = 0): id(0), dungeonId(dungeon), state(LFG_PROPOSAL_INITIATING), + group(0), leader(0), cancelTime(0), encounters(0), isNew(true) { } - uint32 id; ///< Proposal Id - uint32 dungeonId; ///< Dungeon to join - LfgProposalState state; ///< State of the proposal - uint64 group; ///< Proposal group (0 if new) - uint64 leader; ///< Leader guid. - time_t cancelTime; ///< Time when we will cancel this proposal - uint32 encounters; ///< Dungeon Encounters - bool isNew; ///< Determines if it's new group or not - Lfg5Guids queues; ///< Queue Ids to remove/readd - LfgGuidList showorder; ///< Show order in update window - LfgProposalPlayerContainer players; ///< Players data -}; + uint32 id; ///< Proposal Id + uint32 dungeonId; ///< Dungeon to join + LfgProposalState state; ///< State of the proposal + uint64 group; ///< Proposal group (0 if new) + uint64 leader; ///< Leader guid. + time_t cancelTime; ///< Time when we will cancel this proposal + uint32 encounters; ///< Dungeon Encounters + bool isNew; ///< Determines if it's new group or not + Lfg5Guids queues; ///< Queue Ids to remove/readd + LfgGuidList showorder; ///< Show order in update window + LfgProposalPlayerContainer players; ///< Players data + }; -/// Stores all rolecheck info of a group that wants to join -struct LfgRoleCheck -{ - time_t cancelTime; ///< Time when the rolecheck will fail - LfgRolesMap roles; ///< Player selected roles - LfgRoleCheckState state; ///< State of the rolecheck - LfgDungeonSet dungeons; ///< Dungeons group is applying for (expanded random dungeons) - uint32 rDungeonId; ///< Random Dungeon Id. - uint64 leader; ///< Leader of the group -}; + /// Stores all rolecheck info of a group that wants to join + struct LfgRoleCheck + { + time_t cancelTime; ///< Time when the rolecheck will fail + LfgRolesMap roles; ///< Player selected roles + LfgRoleCheckState state; ///< State of the rolecheck + LfgDungeonSet dungeons; ///< Dungeons group is applying for (expanded random dungeons) + uint32 rDungeonId; ///< Random Dungeon Id. + uint64 leader; ///< Leader of the group + }; -/// Stores information of a current vote to kick someone from a group -struct LfgPlayerBoot -{ - time_t cancelTime; ///< Time left to vote - bool inProgress; ///< Vote in progress - LfgAnswerContainer votes; ///< Player votes (-1 not answer | 0 Not agree | 1 agree) - uint64 victim; ///< Player guid to be kicked (can't vote) - std::string reason; ///< kick reason -}; + /// Stores information of a current vote to kick someone from a group + struct LfgPlayerBoot + { + time_t cancelTime; ///< Time left to vote + bool inProgress; ///< Vote in progress + LfgAnswerContainer votes; ///< Player votes (-1 not answer | 0 Not agree | 1 agree) + uint64 victim; ///< Player guid to be kicked (can't vote) + std::string reason; ///< kick reason + }; -struct LFGDungeonData -{ - LFGDungeonData(): id(0), name(""), map(0), type(0), expansion(0), group(0), minlevel(0), - maxlevel(0), difficulty(REGULAR_DIFFICULTY), seasonal(false), x(0.0f), y(0.0f), z(0.0f), o(0.0f) + struct LFGDungeonData + { + LFGDungeonData(): id(0), name(""), map(0), type(0), expansion(0), group(0), minlevel(0), + maxlevel(0), difficulty(REGULAR_DIFFICULTY), seasonal(false), x(0.0f), y(0.0f), z(0.0f), o(0.0f) { } - LFGDungeonData(LFGDungeonEntry const* dbc): id(dbc->ID), name(dbc->name[0]), map(dbc->map), - type(dbc->type), expansion(dbc->expansion), group(dbc->grouptype), - minlevel(dbc->minlevel), maxlevel(dbc->maxlevel), difficulty(Difficulty(dbc->difficulty)), - seasonal(dbc->flags & LFG_FLAG_SEASONAL), x(0.0f), y(0.0f), z(0.0f), o(0.0f) + LFGDungeonData(LFGDungeonEntry const* dbc): id(dbc->ID), name(dbc->name[0]), map(dbc->map), + type(dbc->type), expansion(dbc->expansion), group(dbc->grouptype), + minlevel(dbc->minlevel), maxlevel(dbc->maxlevel), difficulty(Difficulty(dbc->difficulty)), + seasonal(dbc->flags & LFG_FLAG_SEASONAL), x(0.0f), y(0.0f), z(0.0f), o(0.0f) { } - uint32 id; - std::string name; - uint16 map; - uint8 type; - uint8 expansion; - uint8 group; - uint8 minlevel; - uint8 maxlevel; - Difficulty difficulty; - bool seasonal; - float x, y, z, o; + uint32 id; + std::string name; + uint16 map; + uint8 type; + uint8 expansion; + uint8 group; + uint8 minlevel; + uint8 maxlevel; + Difficulty difficulty; + bool seasonal; + float x, y, z, o; - // Helpers - uint32 Entry() const { return id + (type << 24); } -}; + // Helpers + uint32 Entry() const { return id + (type << 24); } + }; -class LFGMgr -{ + class LFGMgr + { private: LFGMgr(); ~LFGMgr(); @@ -528,7 +546,7 @@ class LFGMgr /// Checks if all players are queued bool AllQueued(Lfg5Guids const& check); /// Checks if given roles match, modifies given roles map with new roles - static uint8 CheckGroupRoles(LfgRolesMap &groles, bool removeLeaderFlag = true); + static uint8 CheckGroupRoles(LfgRolesMap& groles, bool removeLeaderFlag = true); /// Checks if given players are ignoring each other static bool HasIgnore(uint64 guid1, uint64 guid2); /// Sends queue status to player @@ -553,7 +571,7 @@ class LFGMgr void MakeNewGroup(LfgProposal const& proposal); // Generic - LFGQueue &GetQueue(uint64 guid); + LFGQueue& GetQueue(uint64 guid); LfgDungeonSet const& GetDungeonsByRandom(uint32 randomdungeon); LfgType GetDungeonType(uint32 dungeon); @@ -585,7 +603,7 @@ class LFGMgr LfgPlayerBootContainer BootsStore; ///< Current player kicks LfgPlayerDataContainer PlayersStore; ///< Player data LfgGroupDataContainer GroupsStore; ///< Group data -}; + }; } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGPlayerData.cpp b/src/server/game/DungeonFinding/LFGPlayerData.cpp index 73b2cbdd5..31ce34e3d 100644 --- a/src/server/game/DungeonFinding/LFGPlayerData.cpp +++ b/src/server/game/DungeonFinding/LFGPlayerData.cpp @@ -10,126 +10,126 @@ namespace lfg { -LfgPlayerData::LfgPlayerData(): m_State(LFG_STATE_NONE), m_OldState(LFG_STATE_NONE), m_canOverrideRBState(false), - m_TeamId(TEAM_ALLIANCE), m_Group(0), m_Roles(0), m_Comment("") -{} + LfgPlayerData::LfgPlayerData(): m_State(LFG_STATE_NONE), m_OldState(LFG_STATE_NONE), m_canOverrideRBState(false), + m_TeamId(TEAM_ALLIANCE), m_Group(0), m_Roles(0), m_Comment("") + {} -LfgPlayerData::~LfgPlayerData() -{ -} - -void LfgPlayerData::SetState(LfgState state) -{ - if (m_State == LFG_STATE_RAIDBROWSER && state != LFG_STATE_RAIDBROWSER && !CanOverrideRBState()) - return; - - switch (state) + LfgPlayerData::~LfgPlayerData() { - case LFG_STATE_NONE: - case LFG_STATE_FINISHED_DUNGEON: - m_Roles = 0; + } + + void LfgPlayerData::SetState(LfgState state) + { + if (m_State == LFG_STATE_RAIDBROWSER && state != LFG_STATE_RAIDBROWSER && !CanOverrideRBState()) + return; + + switch (state) + { + case LFG_STATE_NONE: + case LFG_STATE_FINISHED_DUNGEON: + m_Roles = 0; + m_SelectedDungeons.clear(); + m_Comment = ""; + [[fallthrough]]; + case LFG_STATE_DUNGEON: + m_OldState = state; + [[fallthrough]]; + default: + m_State = state; + } + } + + void LfgPlayerData::RestoreState() + { + if (m_State == LFG_STATE_RAIDBROWSER && m_OldState != LFG_STATE_RAIDBROWSER && !CanOverrideRBState()) + return; + + if (m_OldState == LFG_STATE_NONE) + { m_SelectedDungeons.clear(); - m_Comment = ""; - [[fallthrough]]; - case LFG_STATE_DUNGEON: - m_OldState = state; - [[fallthrough]]; - default: - m_State = state; + m_Roles = 0; + } + m_State = m_OldState; } -} -void LfgPlayerData::RestoreState() -{ - if (m_State == LFG_STATE_RAIDBROWSER && m_OldState != LFG_STATE_RAIDBROWSER && !CanOverrideRBState()) - return; - - if (m_OldState == LFG_STATE_NONE) + void LfgPlayerData::SetLockedDungeons(LfgLockMap const& lockStatus) { - m_SelectedDungeons.clear(); - m_Roles = 0; + m_LockedDungeons = lockStatus; } - m_State = m_OldState; -} -void LfgPlayerData::SetLockedDungeons(LfgLockMap const& lockStatus) -{ - m_LockedDungeons = lockStatus; -} + void LfgPlayerData::SetTeam(TeamId teamId) + { + m_TeamId = teamId; + } -void LfgPlayerData::SetTeam(TeamId teamId) -{ - m_TeamId = teamId; -} + void LfgPlayerData::SetGroup(uint64 group) + { + m_Group = group; + } -void LfgPlayerData::SetGroup(uint64 group) -{ - m_Group = group; -} + void LfgPlayerData::SetRoles(uint8 roles) + { + m_Roles = roles; + } -void LfgPlayerData::SetRoles(uint8 roles) -{ - m_Roles = roles; -} + void LfgPlayerData::SetComment(std::string const& comment) + { + m_Comment = comment; + } -void LfgPlayerData::SetComment(std::string const& comment) -{ - m_Comment = comment; -} + void LfgPlayerData::SetSelectedDungeons(LfgDungeonSet const& dungeons) + { + m_SelectedDungeons = dungeons; + } -void LfgPlayerData::SetSelectedDungeons(LfgDungeonSet const& dungeons) -{ - m_SelectedDungeons = dungeons; -} + void LfgPlayerData::SetRandomPlayersCount(uint8 count) + { + m_randomPlayers = count; + } -void LfgPlayerData::SetRandomPlayersCount(uint8 count) -{ - m_randomPlayers = count; -} + uint8 LfgPlayerData::GetRandomPlayersCount() const + { + return m_randomPlayers; + } -uint8 LfgPlayerData::GetRandomPlayersCount() const -{ - return m_randomPlayers; -} + LfgState LfgPlayerData::GetState() const + { + return m_State; + } -LfgState LfgPlayerData::GetState() const -{ - return m_State; -} + LfgState LfgPlayerData::GetOldState() const + { + return m_OldState; + } -LfgState LfgPlayerData::GetOldState() const -{ - return m_OldState; -} + const LfgLockMap& LfgPlayerData::GetLockedDungeons() const + { + return m_LockedDungeons; + } -const LfgLockMap& LfgPlayerData::GetLockedDungeons() const -{ - return m_LockedDungeons; -} + TeamId LfgPlayerData::GetTeam() const + { + return m_TeamId; + } -TeamId LfgPlayerData::GetTeam() const -{ - return m_TeamId; -} + uint64 LfgPlayerData::GetGroup() const + { + return m_Group; + } -uint64 LfgPlayerData::GetGroup() const -{ - return m_Group; -} + uint8 LfgPlayerData::GetRoles() const + { + return m_Roles; + } -uint8 LfgPlayerData::GetRoles() const -{ - return m_Roles; -} + std::string const& LfgPlayerData::GetComment() const + { + return m_Comment; + } -std::string const& LfgPlayerData::GetComment() const -{ - return m_Comment; -} - -LfgDungeonSet const& LfgPlayerData::GetSelectedDungeons() const -{ - return m_SelectedDungeons; -} + LfgDungeonSet const& LfgPlayerData::GetSelectedDungeons() const + { + return m_SelectedDungeons; + } } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGPlayerData.h b/src/server/game/DungeonFinding/LFGPlayerData.h index c01de3f2e..30783010a 100644 --- a/src/server/game/DungeonFinding/LFGPlayerData.h +++ b/src/server/game/DungeonFinding/LFGPlayerData.h @@ -12,12 +12,12 @@ namespace lfg { -/** - Stores all lfg data needed about the player. -*/ + /** + Stores all lfg data needed about the player. + */ -class LfgPlayerData -{ + class LfgPlayerData + { public: LfgPlayerData(); ~LfgPlayerData(); @@ -65,7 +65,7 @@ class LfgPlayerData uint8 m_Roles; ///< Roles the player selected when joined LFG std::string m_Comment; ///< Player comment used when joined LFG LfgDungeonSet m_SelectedDungeons; ///< Selected Dungeons when joined LFG -}; + }; } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGQueue.cpp b/src/server/game/DungeonFinding/LFGQueue.cpp index eaf7e8c59..00799010b 100644 --- a/src/server/game/DungeonFinding/LFGQueue.cpp +++ b/src/server/game/DungeonFinding/LFGQueue.cpp @@ -29,562 +29,562 @@ namespace lfg { -void LFGQueue::AddToQueue(uint64 guid, bool failedProposal) -{ - //sLog->outString("ADD AddToQueue: %u, failed proposal: %u", GUID_LOPART(guid), failedProposal ? 1 : 0); - LfgQueueDataContainer::iterator itQueue = QueueDataStore.find(guid); - if (itQueue == QueueDataStore.end()) - { - sLog->outError("LFGQueue::AddToQueue: Queue data not found for [" UI64FMTD "]", guid); - return; - } - //sLog->outString("AddToQueue success: %u", GUID_LOPART(guid)); - AddToNewQueue(guid, failedProposal); -} - -void LFGQueue::RemoveFromQueue(uint64 guid, bool partial) -{ - //sLog->outString("REMOVE RemoveFromQueue: %u, partial: %u", GUID_LOPART(guid), partial ? 1 : 0); - RemoveFromNewQueue(guid); - RemoveFromCompatibles(guid); - - LfgQueueDataContainer::iterator itDelete = QueueDataStore.end(); - for (LfgQueueDataContainer::iterator itr = QueueDataStore.begin(); itr != QueueDataStore.end(); ++itr) - { - if (itr->first != guid) - { - if (itr->second.bestCompatible.hasGuid(guid)) - { - //sLog->outString("CLEAR bestCompatible: %s, because of guid: %u", itr->second.bestCompatible.toString().c_str(), GUID_LOPART(guid)); - itr->second.bestCompatible.clear(); - } - } - else - { - //sLog->outString("CLEAR bestCompatible SELF: %s, because of guid: %u", itr->second.bestCompatible.toString().c_str(), GUID_LOPART(guid)); - //itr->second.bestCompatible.clear(); // don't clear here, because UpdateQueueTimers will try to find with every diff update - itDelete = itr; - } - } - - // xinef: partial - if (!partial && itDelete != QueueDataStore.end()) - { - //sLog->outString("ERASE QueueDataStore for: %u", GUID_LOPART(guid)); - //sLog->outString("ERASE QueueDataStore for: %u, itDelete: %u,%u,%u", GUID_LOPART(guid), itDelete->second.dps, itDelete->second.healers, itDelete->second.tanks); - QueueDataStore.erase(itDelete); - //sLog->outString("ERASE QueueDataStore for: %u SUCCESS", GUID_LOPART(guid)); - } -} - -void LFGQueue::AddToNewQueue(uint64 guid, bool front) -{ - if (front) - { - //sLog->outString("ADD AddToNewQueue at FRONT: %u", GUID_LOPART(guid)); - restoredAfterProposal.push_back(guid); - newToQueueStore.push_front(guid); - } - else - { - //sLog->outString("ADD AddToNewQueue at the END: %u", GUID_LOPART(guid)); - newToQueueStore.push_back(guid); - } -} - -void LFGQueue::RemoveFromNewQueue(uint64 guid) -{ - //sLog->outString("REMOVE RemoveFromNewQueue: %u", GUID_LOPART(guid)); - newToQueueStore.remove(guid); - restoredAfterProposal.remove(guid); -} - -void LFGQueue::AddQueueData(uint64 guid, time_t joinTime, LfgDungeonSet const& dungeons, LfgRolesMap const& rolesMap) -{ - //sLog->outString("JOINED AddQueueData: %u", GUID_LOPART(guid)); - QueueDataStore[guid] = LfgQueueData(joinTime, dungeons, rolesMap); - AddToQueue(guid); -} - -void LFGQueue::RemoveQueueData(uint64 guid) -{ - //sLog->outString("LEFT RemoveQueueData: %u", GUID_LOPART(guid)); - LfgQueueDataContainer::iterator it = QueueDataStore.find(guid); - if (it != QueueDataStore.end()) - QueueDataStore.erase(it); -} - -void LFGQueue::UpdateWaitTimeAvg(int32 waitTime, uint32 dungeonId) -{ - LfgWaitTime &wt = waitTimesAvgStore[dungeonId]; - uint32 old_number = wt.number++; - wt.time = int32((wt.time * old_number + waitTime) / wt.number); -} - -void LFGQueue::UpdateWaitTimeTank(int32 waitTime, uint32 dungeonId) -{ - LfgWaitTime &wt = waitTimesTankStore[dungeonId]; - uint32 old_number = wt.number++; - wt.time = int32((wt.time * old_number + waitTime) / wt.number); -} - -void LFGQueue::UpdateWaitTimeHealer(int32 waitTime, uint32 dungeonId) -{ - LfgWaitTime &wt = waitTimesHealerStore[dungeonId]; - uint32 old_number = wt.number++; - wt.time = int32((wt.time * old_number + waitTime) / wt.number); -} - -void LFGQueue::UpdateWaitTimeDps(int32 waitTime, uint32 dungeonId) -{ - LfgWaitTime &wt = waitTimesDpsStore[dungeonId]; - uint32 old_number = wt.number++; - wt.time = int32((wt.time * old_number + waitTime) / wt.number); -} - -void LFGQueue::RemoveFromCompatibles(uint64 guid) -{ - //sLog->outString("COMPATIBLES REMOVE for: %u", GUID_LOPART(guid)); - for (LfgCompatibleContainer::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ++it) - if (it->hasGuid(guid)) - { - //sLog->outString("Removed Compatible: %s, because of guid: %u", it->toString().c_str(), GUID_LOPART(guid)); - it->clear(); // set to 0, this will be removed while iterating in FindNewGroups - } - for (LfgCompatibleContainer::iterator itr = CompatibleTempList.begin(); itr != CompatibleTempList.end(); ) - { - LfgCompatibleContainer::iterator it = itr++; - if (it->hasGuid(guid)) - { - //sLog->outString("Erased Temp Compatible: %s, because of guid: %u", it->toString().c_str(), GUID_LOPART(guid)); - CompatibleTempList.erase(it); - } - } -} - -void LFGQueue::AddToCompatibles(Lfg5Guids const& key) -{ - //sLog->outString("COMPATIBLES ADD: %s", key.toString().c_str()); - CompatibleTempList.push_back(key); -} - -uint8 LFGQueue::FindGroups() -{ - //sLog->outString("FIND GROUPS!"); - uint8 newGroupsProcessed = 0; - if (!newToQueueStore.empty()) - { - ++newGroupsProcessed; - uint64 newGuid = newToQueueStore.front(); - bool pushCompatiblesToFront = (std::find(restoredAfterProposal.begin(), restoredAfterProposal.end(), newGuid) != restoredAfterProposal.end()); - //sLog->outString("newToQueueStore guid: %u, front: %u", GUID_LOPART(newGuid), pushCompatiblesToFront ? 1 : 0); - RemoveFromNewQueue(newGuid); - - FindNewGroups(newGuid); - - CompatibleList.splice((pushCompatiblesToFront ? CompatibleList.begin() : CompatibleList.end()), CompatibleTempList); - CompatibleTempList.clear(); - - return newGroupsProcessed; // pussywizard: only one per update, shouldn't be a problem - } - return newGroupsProcessed; -} - -LfgCompatibility LFGQueue::FindNewGroups(const uint64& newGuid) -{ - // each combination of dps+heal+tank (tank*8 + heal+4 + dps) has a value assigned 0..15 - // first 16 bits of the mask are for marking if such combination was found once, second 16 bits for marking second occurence of that combination, etc - uint64 foundMask = 0; - uint32 foundCount = 0; - - //sLog->outString("FIND NEW GROUPS for: %u", GUID_LOPART(newGuid)); - - // we have to take into account that FindNewGroups is called every X minutes if number of compatibles is low! - // build set of already present compatibles for this guid - std::set currentCompatibles; - for (Lfg5GuidsList::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ++it) - if (it->hasGuid(newGuid)) - { - // unset roles here so they are not copied, restore after insertion - LfgRolesMap* r = it->roles; - it->roles = nullptr; - currentCompatibles.insert(*it); - it->roles = r; - } - - LfgCompatibility selfCompatibility = LFG_COMPATIBILITY_PENDING; - if (currentCompatibles.empty()) - { - selfCompatibility = CheckCompatibility(Lfg5Guids(), newGuid, foundMask, foundCount, currentCompatibles); - if (selfCompatibility != LFG_COMPATIBLES_WITH_LESS_PLAYERS) // group is already compatible (a party of 5 players) - return selfCompatibility; - } - - for (Lfg5GuidsList::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ) - { - Lfg5GuidsList::iterator itr = it++; - if (itr->empty()) - { - //sLog->outString("ERASE from CompatibleList"); - CompatibleList.erase(itr); - continue; - } - LfgCompatibility compatibility = CheckCompatibility(*itr, newGuid, foundMask, foundCount, currentCompatibles); - if (compatibility == LFG_COMPATIBLES_MATCH) - return LFG_COMPATIBLES_MATCH; - if ((foundMask & 0x3FFF3FFF3FFF3FFF) == 0x3FFF3FFF3FFF3FFF) // each combination of dps+heal+tank already found 4 times - break; - } - - return selfCompatibility; -} - -LfgCompatibility LFGQueue::CheckCompatibility(Lfg5Guids const& checkWith, const uint64& newGuid, uint64& foundMask, uint32& foundCount, const std::set& currentCompatibles) -{ - //sLog->outString("CHECK CheckCompatibility: %s, new guid: %u", checkWith.toString().c_str(), GUID_LOPART(newGuid)); - Lfg5Guids check(checkWith, false); // here newGuid is at front - Lfg5Guids strGuids(checkWith, false); // here guids are sorted - check.force_insert_front(newGuid); - strGuids.insert(newGuid); - - if (!currentCompatibles.empty() && currentCompatibles.find(strGuids) != currentCompatibles.end()) - return LFG_INCOMPATIBLES_TOO_MUCH_PLAYERS; - - LfgProposal proposal; - LfgDungeonSet proposalDungeons; - LfgGroupsMap proposalGroups; - LfgRolesMap proposalRoles; - - // Check if more than one LFG group and number of players joining - uint8 numPlayers = 0; - uint8 numLfgGroups = 0; - uint64 guid; - uint64 addToFoundMask = 0; - - for (uint8 i=0; i<5 && (guid=check.guid[i]) != 0 && numLfgGroups < 2 && numPlayers <= MAXGROUPSIZE; ++i) + void LFGQueue::AddToQueue(uint64 guid, bool failedProposal) { + //sLog->outString("ADD AddToQueue: %u, failed proposal: %u", GUID_LOPART(guid), failedProposal ? 1 : 0); LfgQueueDataContainer::iterator itQueue = QueueDataStore.find(guid); if (itQueue == QueueDataStore.end()) { - sLog->outError("LFGQueue::CheckCompatibility: [" UI64FMTD "] is not queued but listed as queued!", guid); - RemoveFromQueue(guid); - return LFG_COMPATIBILITY_PENDING; - } - - // Store group so we don't need to call Mgr to get it later (if it's player group will be 0 otherwise would have joined as group) - for (LfgRolesMap::const_iterator it2 = itQueue->second.roles.begin(); it2 != itQueue->second.roles.end(); ++it2) - proposalGroups[it2->first] = IS_GROUP_GUID(itQueue->first) ? itQueue->first : 0; - - numPlayers += itQueue->second.roles.size(); - - if (sLFGMgr->IsLfgGroup(guid)) - { - if (!numLfgGroups) - proposal.group = guid; - ++numLfgGroups; + sLog->outError("LFGQueue::AddToQueue: Queue data not found for [" UI64FMTD "]", guid); + return; } + //sLog->outString("AddToQueue success: %u", GUID_LOPART(guid)); + AddToNewQueue(guid, failedProposal); } - if (numLfgGroups > 1) - return LFG_INCOMPATIBLES_MULTIPLE_LFG_GROUPS; - - // Group with less that MAXGROUPSIZE members always compatible - if (check.size() == 1 && numPlayers < MAXGROUPSIZE) + void LFGQueue::RemoveFromQueue(uint64 guid, bool partial) { - LfgQueueDataContainer::iterator itQueue = QueueDataStore.find(check.front()); - LfgRolesMap roles = itQueue->second.roles; - uint8 roleCheckResult = LFGMgr::CheckGroupRoles(roles); - strGuids.addRoles(roles); - itQueue->second.bestCompatible.clear(); // this may be left after a failed proposal (not cleared, because UpdateQueueTimers would try to generate it with every update) - //UpdateBestCompatibleInQueue(itQueue, strGuids); - AddToCompatibles(strGuids); - if (roleCheckResult && roleCheckResult <= 15) - foundMask |= ( (((uint64)1)<<(roleCheckResult-1)) | (((uint64)1)<<(16+roleCheckResult-1)) | (((uint64)1)<<(32+roleCheckResult-1)) | (((uint64)1)<<(48+roleCheckResult-1)) ); - return LFG_COMPATIBLES_WITH_LESS_PLAYERS; - } + //sLog->outString("REMOVE RemoveFromQueue: %u, partial: %u", GUID_LOPART(guid), partial ? 1 : 0); + RemoveFromNewQueue(guid); + RemoveFromCompatibles(guid); - if (numPlayers > MAXGROUPSIZE) - return LFG_INCOMPATIBLES_TOO_MUCH_PLAYERS; - - // If it's single group no need to check for duplicate players, ignores, bad roles or bad dungeons as it's been checked before joining - if (check.size() > 1) - { - for (uint8 i=0; i<5 && check.guid[i]; ++i) + LfgQueueDataContainer::iterator itDelete = QueueDataStore.end(); + for (LfgQueueDataContainer::iterator itr = QueueDataStore.begin(); itr != QueueDataStore.end(); ++itr) { - const LfgRolesMap &roles = QueueDataStore[check.guid[i]].roles; - for (LfgRolesMap::const_iterator itRoles = roles.begin(); itRoles != roles.end(); ++itRoles) + if (itr->first != guid) { - LfgRolesMap::const_iterator itPlayer; - for (itPlayer = proposalRoles.begin(); itPlayer != proposalRoles.end(); ++itPlayer) + if (itr->second.bestCompatible.hasGuid(guid)) { - if (itRoles->first == itPlayer->first) - { - // pussywizard: LFG ZOMG! this means that this player was in two different LfgQueueData (in QueueDataStore), and at least one of them is a group guid, because we do checks so there aren't 2 same guids in current CHECK - //sLog->outError("LFGQueue::CheckCompatibility: ERROR! Player multiple times in queue! [" UI64FMTD "]", itRoles->first); - break; - } - else if (sLFGMgr->HasIgnore(itRoles->first, itPlayer->first)) - break; + //sLog->outString("CLEAR bestCompatible: %s, because of guid: %u", itr->second.bestCompatible.toString().c_str(), GUID_LOPART(guid)); + itr->second.bestCompatible.clear(); } - if (itPlayer == proposalRoles.end()) - proposalRoles[itRoles->first] = itRoles->second; - else - break; - } - } - - if (numPlayers != proposalRoles.size()) - return LFG_INCOMPATIBLES_HAS_IGNORES; - - uint8 roleCheckResult = LFGMgr::CheckGroupRoles(proposalRoles); - if (!roleCheckResult || roleCheckResult > 0xF) - return LFG_INCOMPATIBLES_NO_ROLES; - - // now, every combination can occur only 4 times (explained in FindNewGroups) - if (foundMask & (((uint64)1)<<(roleCheckResult-1))) - { - if (foundMask & (((uint64)1)<<(16+roleCheckResult-1))) - { - if (foundMask & (((uint64)1)<<(32+roleCheckResult-1))) - { - if (foundMask & (((uint64)1)<<(48+roleCheckResult-1))) - { - if (foundCount >= 10) // but only after finding at least 10 compatibles (this helps when there are few groups) - return LFG_INCOMPATIBLES_NO_ROLES; - } - else - addToFoundMask |= (((uint64)1)<<(48+roleCheckResult-1)); - } - else - addToFoundMask |= (((uint64)1)<<(32+roleCheckResult-1)); } else - addToFoundMask |= (((uint64)1)<<(16+roleCheckResult-1)); + { + //sLog->outString("CLEAR bestCompatible SELF: %s, because of guid: %u", itr->second.bestCompatible.toString().c_str(), GUID_LOPART(guid)); + //itr->second.bestCompatible.clear(); // don't clear here, because UpdateQueueTimers will try to find with every diff update + itDelete = itr; + } + } + + // xinef: partial + if (!partial && itDelete != QueueDataStore.end()) + { + //sLog->outString("ERASE QueueDataStore for: %u", GUID_LOPART(guid)); + //sLog->outString("ERASE QueueDataStore for: %u, itDelete: %u,%u,%u", GUID_LOPART(guid), itDelete->second.dps, itDelete->second.healers, itDelete->second.tanks); + QueueDataStore.erase(itDelete); + //sLog->outString("ERASE QueueDataStore for: %u SUCCESS", GUID_LOPART(guid)); + } + } + + void LFGQueue::AddToNewQueue(uint64 guid, bool front) + { + if (front) + { + //sLog->outString("ADD AddToNewQueue at FRONT: %u", GUID_LOPART(guid)); + restoredAfterProposal.push_back(guid); + newToQueueStore.push_front(guid); } else - addToFoundMask |= (((uint64)1)<<(roleCheckResult-1)); - - proposalDungeons = QueueDataStore[check.front()].dungeons; - for (uint8 i=1; i<5 && check.guid[i]; ++i) { - LfgDungeonSet temporal; - LfgDungeonSet &dungeons = QueueDataStore[check.guid[i]].dungeons; - std::set_intersection(proposalDungeons.begin(), proposalDungeons.end(), dungeons.begin(), dungeons.end(), std::inserter(temporal, temporal.begin())); - proposalDungeons = temporal; - } - - if (proposalDungeons.empty()) - return LFG_INCOMPATIBLES_NO_DUNGEONS; - } - else - { - uint64 gguid = check.front(); - const LfgQueueData &queue = QueueDataStore[gguid]; - proposalDungeons = queue.dungeons; - proposalRoles = queue.roles; - LFGMgr::CheckGroupRoles(proposalRoles); // assing new roles - } - - // Enough players? - if (numPlayers != MAXGROUPSIZE) - { - strGuids.addRoles(proposalRoles); - for (uint8 i=0; i<5 && check.guid[i]; ++i) - { - LfgQueueDataContainer::iterator itr = QueueDataStore.find(check.guid[i]); - if (!itr->second.bestCompatible.empty()) // update if groups don't have it empty (for empty it will be generated in UpdateQueueTimers) - UpdateBestCompatibleInQueue(itr, strGuids); - } - AddToCompatibles(strGuids); - foundMask |= addToFoundMask; - ++foundCount; - return LFG_COMPATIBLES_WITH_LESS_PLAYERS; - } - - uint64 gguid = check.front(); - proposal.queues = strGuids; - proposal.isNew = numLfgGroups != 1 || sLFGMgr->GetOldState(gguid) != LFG_STATE_DUNGEON; - - if (!sLFGMgr->AllQueued(check)) // can't create proposal - return LFG_COMPATIBILITY_PENDING; - - // Create a new proposal - proposal.cancelTime = time(nullptr) + LFG_TIME_PROPOSAL; - proposal.state = LFG_PROPOSAL_INITIATING; - proposal.leader = 0; - proposal.dungeonId = acore::Containers::SelectRandomContainerElement(proposalDungeons); - - bool leader = false; - for (LfgRolesMap::const_iterator itRoles = proposalRoles.begin(); itRoles != proposalRoles.end(); ++itRoles) - { - // Assing new leader - if (itRoles->second & PLAYER_ROLE_LEADER) - { - if (!leader || !proposal.leader || urand(0, 1)) - proposal.leader = itRoles->first; - leader = true; - } - else if (!leader && (!proposal.leader || urand(0, 1))) - proposal.leader = itRoles->first; - - // Assing player data and roles - LfgProposalPlayer &data = proposal.players[itRoles->first]; - data.role = itRoles->second; - data.group = proposalGroups.find(itRoles->first)->second; - if (!proposal.isNew && data.group && data.group == proposal.group) // Player from existing group, autoaccept - data.accept = LFG_ANSWER_AGREE; - } - - for (uint8 i=0; i<5 && proposal.queues.guid[i]; ++i) - RemoveFromQueue(proposal.queues.guid[i], true); - - sLFGMgr->AddProposal(proposal); - - return LFG_COMPATIBLES_MATCH; -} - -void LFGQueue::UpdateQueueTimers(uint32 diff) -{ - time_t currTime = time(nullptr); - bool sendQueueStatus = false; - - if (m_QueueStatusTimer > LFG_QUEUEUPDATE_INTERVAL) - { - m_QueueStatusTimer = 0; - sendQueueStatus = true; - } - else - m_QueueStatusTimer += diff; - - //sLog->outString("UPDATE UpdateQueueTimers"); - for (Lfg5GuidsList::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ) - { - Lfg5GuidsList::iterator itr = it++; - if (itr->empty()) - { - //sLog->outString("UpdateQueueTimers ERASE compatible"); - CompatibleList.erase(itr); + //sLog->outString("ADD AddToNewQueue at the END: %u", GUID_LOPART(guid)); + newToQueueStore.push_back(guid); } } - if (!sendQueueStatus) + void LFGQueue::RemoveFromNewQueue(uint64 guid) { - for (LfgQueueDataContainer::iterator itQueue = QueueDataStore.begin(); itQueue != QueueDataStore.end(); ) - { - if (currTime - itQueue->second.joinTime > 2*HOUR) + //sLog->outString("REMOVE RemoveFromNewQueue: %u", GUID_LOPART(guid)); + newToQueueStore.remove(guid); + restoredAfterProposal.remove(guid); + } + + void LFGQueue::AddQueueData(uint64 guid, time_t joinTime, LfgDungeonSet const& dungeons, LfgRolesMap const& rolesMap) + { + //sLog->outString("JOINED AddQueueData: %u", GUID_LOPART(guid)); + QueueDataStore[guid] = LfgQueueData(joinTime, dungeons, rolesMap); + AddToQueue(guid); + } + + void LFGQueue::RemoveQueueData(uint64 guid) + { + //sLog->outString("LEFT RemoveQueueData: %u", GUID_LOPART(guid)); + LfgQueueDataContainer::iterator it = QueueDataStore.find(guid); + if (it != QueueDataStore.end()) + QueueDataStore.erase(it); + } + + void LFGQueue::UpdateWaitTimeAvg(int32 waitTime, uint32 dungeonId) + { + LfgWaitTime& wt = waitTimesAvgStore[dungeonId]; + uint32 old_number = wt.number++; + wt.time = int32((wt.time * old_number + waitTime) / wt.number); + } + + void LFGQueue::UpdateWaitTimeTank(int32 waitTime, uint32 dungeonId) + { + LfgWaitTime& wt = waitTimesTankStore[dungeonId]; + uint32 old_number = wt.number++; + wt.time = int32((wt.time * old_number + waitTime) / wt.number); + } + + void LFGQueue::UpdateWaitTimeHealer(int32 waitTime, uint32 dungeonId) + { + LfgWaitTime& wt = waitTimesHealerStore[dungeonId]; + uint32 old_number = wt.number++; + wt.time = int32((wt.time * old_number + waitTime) / wt.number); + } + + void LFGQueue::UpdateWaitTimeDps(int32 waitTime, uint32 dungeonId) + { + LfgWaitTime& wt = waitTimesDpsStore[dungeonId]; + uint32 old_number = wt.number++; + wt.time = int32((wt.time * old_number + waitTime) / wt.number); + } + + void LFGQueue::RemoveFromCompatibles(uint64 guid) + { + //sLog->outString("COMPATIBLES REMOVE for: %u", GUID_LOPART(guid)); + for (LfgCompatibleContainer::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ++it) + if (it->hasGuid(guid)) { - uint64 guid = itQueue->first; - QueueDataStore.erase(itQueue++); - sLFGMgr->LeaveAllLfgQueues(guid, true); + //sLog->outString("Removed Compatible: %s, because of guid: %u", it->toString().c_str(), GUID_LOPART(guid)); + it->clear(); // set to 0, this will be removed while iterating in FindNewGroups + } + for (LfgCompatibleContainer::iterator itr = CompatibleTempList.begin(); itr != CompatibleTempList.end(); ) + { + LfgCompatibleContainer::iterator it = itr++; + if (it->hasGuid(guid)) + { + //sLog->outString("Erased Temp Compatible: %s, because of guid: %u", it->toString().c_str(), GUID_LOPART(guid)); + CompatibleTempList.erase(it); + } + } + } + + void LFGQueue::AddToCompatibles(Lfg5Guids const& key) + { + //sLog->outString("COMPATIBLES ADD: %s", key.toString().c_str()); + CompatibleTempList.push_back(key); + } + + uint8 LFGQueue::FindGroups() + { + //sLog->outString("FIND GROUPS!"); + uint8 newGroupsProcessed = 0; + if (!newToQueueStore.empty()) + { + ++newGroupsProcessed; + uint64 newGuid = newToQueueStore.front(); + bool pushCompatiblesToFront = (std::find(restoredAfterProposal.begin(), restoredAfterProposal.end(), newGuid) != restoredAfterProposal.end()); + //sLog->outString("newToQueueStore guid: %u, front: %u", GUID_LOPART(newGuid), pushCompatiblesToFront ? 1 : 0); + RemoveFromNewQueue(newGuid); + + FindNewGroups(newGuid); + + CompatibleList.splice((pushCompatiblesToFront ? CompatibleList.begin() : CompatibleList.end()), CompatibleTempList); + CompatibleTempList.clear(); + + return newGroupsProcessed; // pussywizard: only one per update, shouldn't be a problem + } + return newGroupsProcessed; + } + + LfgCompatibility LFGQueue::FindNewGroups(const uint64& newGuid) + { + // each combination of dps+heal+tank (tank*8 + heal+4 + dps) has a value assigned 0..15 + // first 16 bits of the mask are for marking if such combination was found once, second 16 bits for marking second occurence of that combination, etc + uint64 foundMask = 0; + uint32 foundCount = 0; + + //sLog->outString("FIND NEW GROUPS for: %u", GUID_LOPART(newGuid)); + + // we have to take into account that FindNewGroups is called every X minutes if number of compatibles is low! + // build set of already present compatibles for this guid + std::set currentCompatibles; + for (Lfg5GuidsList::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ++it) + if (it->hasGuid(newGuid)) + { + // unset roles here so they are not copied, restore after insertion + LfgRolesMap* r = it->roles; + it->roles = nullptr; + currentCompatibles.insert(*it); + it->roles = r; + } + + LfgCompatibility selfCompatibility = LFG_COMPATIBILITY_PENDING; + if (currentCompatibles.empty()) + { + selfCompatibility = CheckCompatibility(Lfg5Guids(), newGuid, foundMask, foundCount, currentCompatibles); + if (selfCompatibility != LFG_COMPATIBLES_WITH_LESS_PLAYERS) // group is already compatible (a party of 5 players) + return selfCompatibility; + } + + for (Lfg5GuidsList::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ) + { + Lfg5GuidsList::iterator itr = it++; + if (itr->empty()) + { + //sLog->outString("ERASE from CompatibleList"); + CompatibleList.erase(itr); continue; } - if (itQueue->second.bestCompatible.empty()) + LfgCompatibility compatibility = CheckCompatibility(*itr, newGuid, foundMask, foundCount, currentCompatibles); + if (compatibility == LFG_COMPATIBLES_MATCH) + return LFG_COMPATIBLES_MATCH; + if ((foundMask & 0x3FFF3FFF3FFF3FFF) == 0x3FFF3FFF3FFF3FFF) // each combination of dps+heal+tank already found 4 times + break; + } + + return selfCompatibility; + } + + LfgCompatibility LFGQueue::CheckCompatibility(Lfg5Guids const& checkWith, const uint64& newGuid, uint64& foundMask, uint32& foundCount, const std::set& currentCompatibles) + { + //sLog->outString("CHECK CheckCompatibility: %s, new guid: %u", checkWith.toString().c_str(), GUID_LOPART(newGuid)); + Lfg5Guids check(checkWith, false); // here newGuid is at front + Lfg5Guids strGuids(checkWith, false); // here guids are sorted + check.force_insert_front(newGuid); + strGuids.insert(newGuid); + + if (!currentCompatibles.empty() && currentCompatibles.find(strGuids) != currentCompatibles.end()) + return LFG_INCOMPATIBLES_TOO_MUCH_PLAYERS; + + LfgProposal proposal; + LfgDungeonSet proposalDungeons; + LfgGroupsMap proposalGroups; + LfgRolesMap proposalRoles; + + // Check if more than one LFG group and number of players joining + uint8 numPlayers = 0; + uint8 numLfgGroups = 0; + uint64 guid; + uint64 addToFoundMask = 0; + + for (uint8 i = 0; i < 5 && (guid = check.guid[i]) != 0 && numLfgGroups < 2 && numPlayers <= MAXGROUPSIZE; ++i) + { + LfgQueueDataContainer::iterator itQueue = QueueDataStore.find(guid); + if (itQueue == QueueDataStore.end()) { - uint32 numOfCompatibles = FindBestCompatibleInQueue(itQueue); - if (numOfCompatibles /*must be positive, because proposals don't delete QueueQueueData*/ && currTime-itQueue->second.lastRefreshTime >= 60 && numOfCompatibles < (5-itQueue->second.bestCompatible.roles->size())*25) + sLog->outError("LFGQueue::CheckCompatibility: [" UI64FMTD "] is not queued but listed as queued!", guid); + RemoveFromQueue(guid); + return LFG_COMPATIBILITY_PENDING; + } + + // Store group so we don't need to call Mgr to get it later (if it's player group will be 0 otherwise would have joined as group) + for (LfgRolesMap::const_iterator it2 = itQueue->second.roles.begin(); it2 != itQueue->second.roles.end(); ++it2) + proposalGroups[it2->first] = IS_GROUP_GUID(itQueue->first) ? itQueue->first : 0; + + numPlayers += itQueue->second.roles.size(); + + if (sLFGMgr->IsLfgGroup(guid)) + { + if (!numLfgGroups) + proposal.group = guid; + ++numLfgGroups; + } + } + + if (numLfgGroups > 1) + return LFG_INCOMPATIBLES_MULTIPLE_LFG_GROUPS; + + // Group with less that MAXGROUPSIZE members always compatible + if (check.size() == 1 && numPlayers < MAXGROUPSIZE) + { + LfgQueueDataContainer::iterator itQueue = QueueDataStore.find(check.front()); + LfgRolesMap roles = itQueue->second.roles; + uint8 roleCheckResult = LFGMgr::CheckGroupRoles(roles); + strGuids.addRoles(roles); + itQueue->second.bestCompatible.clear(); // this may be left after a failed proposal (not cleared, because UpdateQueueTimers would try to generate it with every update) + //UpdateBestCompatibleInQueue(itQueue, strGuids); + AddToCompatibles(strGuids); + if (roleCheckResult && roleCheckResult <= 15) + foundMask |= ( (((uint64)1) << (roleCheckResult - 1)) | (((uint64)1) << (16 + roleCheckResult - 1)) | (((uint64)1) << (32 + roleCheckResult - 1)) | (((uint64)1) << (48 + roleCheckResult - 1)) ); + return LFG_COMPATIBLES_WITH_LESS_PLAYERS; + } + + if (numPlayers > MAXGROUPSIZE) + return LFG_INCOMPATIBLES_TOO_MUCH_PLAYERS; + + // If it's single group no need to check for duplicate players, ignores, bad roles or bad dungeons as it's been checked before joining + if (check.size() > 1) + { + for (uint8 i = 0; i < 5 && check.guid[i]; ++i) + { + const LfgRolesMap& roles = QueueDataStore[check.guid[i]].roles; + for (LfgRolesMap::const_iterator itRoles = roles.begin(); itRoles != roles.end(); ++itRoles) { - itQueue->second.lastRefreshTime = currTime; - AddToQueue(itQueue->first, false); + LfgRolesMap::const_iterator itPlayer; + for (itPlayer = proposalRoles.begin(); itPlayer != proposalRoles.end(); ++itPlayer) + { + if (itRoles->first == itPlayer->first) + { + // pussywizard: LFG ZOMG! this means that this player was in two different LfgQueueData (in QueueDataStore), and at least one of them is a group guid, because we do checks so there aren't 2 same guids in current CHECK + //sLog->outError("LFGQueue::CheckCompatibility: ERROR! Player multiple times in queue! [" UI64FMTD "]", itRoles->first); + break; + } + else if (sLFGMgr->HasIgnore(itRoles->first, itPlayer->first)) + break; + } + if (itPlayer == proposalRoles.end()) + proposalRoles[itRoles->first] = itRoles->second; + else + break; } } - ++itQueue; + + if (numPlayers != proposalRoles.size()) + return LFG_INCOMPATIBLES_HAS_IGNORES; + + uint8 roleCheckResult = LFGMgr::CheckGroupRoles(proposalRoles); + if (!roleCheckResult || roleCheckResult > 0xF) + return LFG_INCOMPATIBLES_NO_ROLES; + + // now, every combination can occur only 4 times (explained in FindNewGroups) + if (foundMask & (((uint64)1) << (roleCheckResult - 1))) + { + if (foundMask & (((uint64)1) << (16 + roleCheckResult - 1))) + { + if (foundMask & (((uint64)1) << (32 + roleCheckResult - 1))) + { + if (foundMask & (((uint64)1) << (48 + roleCheckResult - 1))) + { + if (foundCount >= 10) // but only after finding at least 10 compatibles (this helps when there are few groups) + return LFG_INCOMPATIBLES_NO_ROLES; + } + else + addToFoundMask |= (((uint64)1) << (48 + roleCheckResult - 1)); + } + else + addToFoundMask |= (((uint64)1) << (32 + roleCheckResult - 1)); + } + else + addToFoundMask |= (((uint64)1) << (16 + roleCheckResult - 1)); + } + else + addToFoundMask |= (((uint64)1) << (roleCheckResult - 1)); + + proposalDungeons = QueueDataStore[check.front()].dungeons; + for (uint8 i = 1; i < 5 && check.guid[i]; ++i) + { + LfgDungeonSet temporal; + LfgDungeonSet& dungeons = QueueDataStore[check.guid[i]].dungeons; + std::set_intersection(proposalDungeons.begin(), proposalDungeons.end(), dungeons.begin(), dungeons.end(), std::inserter(temporal, temporal.begin())); + proposalDungeons = temporal; + } + + if (proposalDungeons.empty()) + return LFG_INCOMPATIBLES_NO_DUNGEONS; } - return; - } - - //sLog->outTrace(LOG_FILTER_LFG, "Updating queue timers..."); - for (LfgQueueDataContainer::iterator itQueue = QueueDataStore.begin(); itQueue != QueueDataStore.end(); ++itQueue) - { - LfgQueueData& queueinfo = itQueue->second; - uint32 dungeonId = (*queueinfo.dungeons.begin()); - uint32 queuedTime = uint32(currTime - queueinfo.joinTime); - uint8 role = PLAYER_ROLE_NONE; - int32 waitTime = -1; - int32 wtTank = waitTimesTankStore[dungeonId].time; - int32 wtHealer = waitTimesHealerStore[dungeonId].time; - int32 wtDps = waitTimesDpsStore[dungeonId].time; - int32 wtAvg = waitTimesAvgStore[dungeonId].time; - - for (LfgRolesMap::const_iterator itPlayer = queueinfo.roles.begin(); itPlayer != queueinfo.roles.end(); ++itPlayer) - role |= itPlayer->second; - role &= ~PLAYER_ROLE_LEADER; - - switch (role) - { - case PLAYER_ROLE_NONE: // Should not happen - just in case - waitTime = -1; - break; - case PLAYER_ROLE_TANK: - waitTime = wtTank; - break; - case PLAYER_ROLE_HEALER: - waitTime = wtHealer; - break; - case PLAYER_ROLE_DAMAGE: - waitTime = wtDps; - break; - default: - waitTime = wtAvg; - break; - } - - if (queueinfo.bestCompatible.empty()) - { - //sLog->outString("found empty bestCompatible"); - FindBestCompatibleInQueue(itQueue); - } - - LfgQueueStatusData queueData(dungeonId, waitTime, wtAvg, wtTank, wtHealer, wtDps, queuedTime, queueinfo.tanks, queueinfo.healers, queueinfo.dps); - for (LfgRolesMap::const_iterator itPlayer = queueinfo.roles.begin(); itPlayer != queueinfo.roles.end(); ++itPlayer) - { - uint64 pguid = itPlayer->first; - LFGMgr::SendLfgQueueStatus(pguid, queueData); - } - } -} - -time_t LFGQueue::GetJoinTime(uint64 guid) -{ - return QueueDataStore[guid].joinTime; -} - -uint32 LFGQueue::FindBestCompatibleInQueue(LfgQueueDataContainer::iterator itrQueue) -{ - uint32 numOfCompatibles = 0; - for (LfgCompatibleContainer::const_iterator itr = CompatibleList.begin(); itr != CompatibleList.end(); ++itr) - if (itr->hasGuid(itrQueue->first)) - { - ++numOfCompatibles; - UpdateBestCompatibleInQueue(itrQueue, *itr); - } - return numOfCompatibles; -} - -void LFGQueue::UpdateBestCompatibleInQueue(LfgQueueDataContainer::iterator itrQueue, Lfg5Guids const& key) -{ - //sLog->outString("UpdateBestCompatibleInQueue: %s", key.toString().c_str()); - LfgQueueData& queueData = itrQueue->second; - - uint8 storedSize = queueData.bestCompatible.size(); - uint8 size = key.size(); - - if (size <= storedSize) - return; - - queueData.bestCompatible = key; - queueData.tanks = LFG_TANKS_NEEDED; - queueData.healers = LFG_HEALERS_NEEDED; - queueData.dps = LFG_DPS_NEEDED; - for (LfgRolesMap::const_iterator it = key.roles->begin(); it != key.roles->end(); ++it) - { - uint8 role = it->second; - if (role & PLAYER_ROLE_TANK) - --queueData.tanks; - else if (role & PLAYER_ROLE_HEALER) - --queueData.healers; else - --queueData.dps; + { + uint64 gguid = check.front(); + const LfgQueueData& queue = QueueDataStore[gguid]; + proposalDungeons = queue.dungeons; + proposalRoles = queue.roles; + LFGMgr::CheckGroupRoles(proposalRoles); // assing new roles + } + + // Enough players? + if (numPlayers != MAXGROUPSIZE) + { + strGuids.addRoles(proposalRoles); + for (uint8 i = 0; i < 5 && check.guid[i]; ++i) + { + LfgQueueDataContainer::iterator itr = QueueDataStore.find(check.guid[i]); + if (!itr->second.bestCompatible.empty()) // update if groups don't have it empty (for empty it will be generated in UpdateQueueTimers) + UpdateBestCompatibleInQueue(itr, strGuids); + } + AddToCompatibles(strGuids); + foundMask |= addToFoundMask; + ++foundCount; + return LFG_COMPATIBLES_WITH_LESS_PLAYERS; + } + + uint64 gguid = check.front(); + proposal.queues = strGuids; + proposal.isNew = numLfgGroups != 1 || sLFGMgr->GetOldState(gguid) != LFG_STATE_DUNGEON; + + if (!sLFGMgr->AllQueued(check)) // can't create proposal + return LFG_COMPATIBILITY_PENDING; + + // Create a new proposal + proposal.cancelTime = time(nullptr) + LFG_TIME_PROPOSAL; + proposal.state = LFG_PROPOSAL_INITIATING; + proposal.leader = 0; + proposal.dungeonId = acore::Containers::SelectRandomContainerElement(proposalDungeons); + + bool leader = false; + for (LfgRolesMap::const_iterator itRoles = proposalRoles.begin(); itRoles != proposalRoles.end(); ++itRoles) + { + // Assing new leader + if (itRoles->second & PLAYER_ROLE_LEADER) + { + if (!leader || !proposal.leader || urand(0, 1)) + proposal.leader = itRoles->first; + leader = true; + } + else if (!leader && (!proposal.leader || urand(0, 1))) + proposal.leader = itRoles->first; + + // Assing player data and roles + LfgProposalPlayer& data = proposal.players[itRoles->first]; + data.role = itRoles->second; + data.group = proposalGroups.find(itRoles->first)->second; + if (!proposal.isNew && data.group && data.group == proposal.group) // Player from existing group, autoaccept + data.accept = LFG_ANSWER_AGREE; + } + + for (uint8 i = 0; i < 5 && proposal.queues.guid[i]; ++i) + RemoveFromQueue(proposal.queues.guid[i], true); + + sLFGMgr->AddProposal(proposal); + + return LFG_COMPATIBLES_MATCH; + } + + void LFGQueue::UpdateQueueTimers(uint32 diff) + { + time_t currTime = time(nullptr); + bool sendQueueStatus = false; + + if (m_QueueStatusTimer > LFG_QUEUEUPDATE_INTERVAL) + { + m_QueueStatusTimer = 0; + sendQueueStatus = true; + } + else + m_QueueStatusTimer += diff; + + //sLog->outString("UPDATE UpdateQueueTimers"); + for (Lfg5GuidsList::iterator it = CompatibleList.begin(); it != CompatibleList.end(); ) + { + Lfg5GuidsList::iterator itr = it++; + if (itr->empty()) + { + //sLog->outString("UpdateQueueTimers ERASE compatible"); + CompatibleList.erase(itr); + } + } + + if (!sendQueueStatus) + { + for (LfgQueueDataContainer::iterator itQueue = QueueDataStore.begin(); itQueue != QueueDataStore.end(); ) + { + if (currTime - itQueue->second.joinTime > 2 * HOUR) + { + uint64 guid = itQueue->first; + QueueDataStore.erase(itQueue++); + sLFGMgr->LeaveAllLfgQueues(guid, true); + continue; + } + if (itQueue->second.bestCompatible.empty()) + { + uint32 numOfCompatibles = FindBestCompatibleInQueue(itQueue); + if (numOfCompatibles /*must be positive, because proposals don't delete QueueQueueData*/ && currTime - itQueue->second.lastRefreshTime >= 60 && numOfCompatibles < (5 - itQueue->second.bestCompatible.roles->size()) * 25) + { + itQueue->second.lastRefreshTime = currTime; + AddToQueue(itQueue->first, false); + } + } + ++itQueue; + } + return; + } + + //sLog->outTrace(LOG_FILTER_LFG, "Updating queue timers..."); + for (LfgQueueDataContainer::iterator itQueue = QueueDataStore.begin(); itQueue != QueueDataStore.end(); ++itQueue) + { + LfgQueueData& queueinfo = itQueue->second; + uint32 dungeonId = (*queueinfo.dungeons.begin()); + uint32 queuedTime = uint32(currTime - queueinfo.joinTime); + uint8 role = PLAYER_ROLE_NONE; + int32 waitTime = -1; + int32 wtTank = waitTimesTankStore[dungeonId].time; + int32 wtHealer = waitTimesHealerStore[dungeonId].time; + int32 wtDps = waitTimesDpsStore[dungeonId].time; + int32 wtAvg = waitTimesAvgStore[dungeonId].time; + + for (LfgRolesMap::const_iterator itPlayer = queueinfo.roles.begin(); itPlayer != queueinfo.roles.end(); ++itPlayer) + role |= itPlayer->second; + role &= ~PLAYER_ROLE_LEADER; + + switch (role) + { + case PLAYER_ROLE_NONE: // Should not happen - just in case + waitTime = -1; + break; + case PLAYER_ROLE_TANK: + waitTime = wtTank; + break; + case PLAYER_ROLE_HEALER: + waitTime = wtHealer; + break; + case PLAYER_ROLE_DAMAGE: + waitTime = wtDps; + break; + default: + waitTime = wtAvg; + break; + } + + if (queueinfo.bestCompatible.empty()) + { + //sLog->outString("found empty bestCompatible"); + FindBestCompatibleInQueue(itQueue); + } + + LfgQueueStatusData queueData(dungeonId, waitTime, wtAvg, wtTank, wtHealer, wtDps, queuedTime, queueinfo.tanks, queueinfo.healers, queueinfo.dps); + for (LfgRolesMap::const_iterator itPlayer = queueinfo.roles.begin(); itPlayer != queueinfo.roles.end(); ++itPlayer) + { + uint64 pguid = itPlayer->first; + LFGMgr::SendLfgQueueStatus(pguid, queueData); + } + } + } + + time_t LFGQueue::GetJoinTime(uint64 guid) + { + return QueueDataStore[guid].joinTime; + } + + uint32 LFGQueue::FindBestCompatibleInQueue(LfgQueueDataContainer::iterator itrQueue) + { + uint32 numOfCompatibles = 0; + for (LfgCompatibleContainer::const_iterator itr = CompatibleList.begin(); itr != CompatibleList.end(); ++itr) + if (itr->hasGuid(itrQueue->first)) + { + ++numOfCompatibles; + UpdateBestCompatibleInQueue(itrQueue, *itr); + } + return numOfCompatibles; + } + + void LFGQueue::UpdateBestCompatibleInQueue(LfgQueueDataContainer::iterator itrQueue, Lfg5Guids const& key) + { + //sLog->outString("UpdateBestCompatibleInQueue: %s", key.toString().c_str()); + LfgQueueData& queueData = itrQueue->second; + + uint8 storedSize = queueData.bestCompatible.size(); + uint8 size = key.size(); + + if (size <= storedSize) + return; + + queueData.bestCompatible = key; + queueData.tanks = LFG_TANKS_NEEDED; + queueData.healers = LFG_HEALERS_NEEDED; + queueData.dps = LFG_DPS_NEEDED; + for (LfgRolesMap::const_iterator it = key.roles->begin(); it != key.roles->end(); ++it) + { + uint8 role = it->second; + if (role & PLAYER_ROLE_TANK) + --queueData.tanks; + else if (role & PLAYER_ROLE_HEALER) + --queueData.healers; + else + --queueData.dps; + } } -} } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGQueue.h b/src/server/game/DungeonFinding/LFGQueue.h index 260d677c6..394693e9e 100644 --- a/src/server/game/DungeonFinding/LFGQueue.h +++ b/src/server/game/DungeonFinding/LFGQueue.h @@ -12,57 +12,57 @@ namespace lfg { -enum LfgCompatibility -{ - LFG_COMPATIBILITY_PENDING, - LFG_INCOMPATIBLES_WRONG_GROUP_SIZE, - LFG_INCOMPATIBLES_TOO_MUCH_PLAYERS, - LFG_INCOMPATIBLES_MULTIPLE_LFG_GROUPS, - LFG_INCOMPATIBLES_HAS_IGNORES, - LFG_INCOMPATIBLES_NO_ROLES, - LFG_INCOMPATIBLES_NO_DUNGEONS, - LFG_COMPATIBLES_WITH_LESS_PLAYERS, // Values under this = not compatible (do not modify order) - LFG_COMPATIBLES_MATCH // Must be the last one -}; + enum LfgCompatibility + { + LFG_COMPATIBILITY_PENDING, + LFG_INCOMPATIBLES_WRONG_GROUP_SIZE, + LFG_INCOMPATIBLES_TOO_MUCH_PLAYERS, + LFG_INCOMPATIBLES_MULTIPLE_LFG_GROUPS, + LFG_INCOMPATIBLES_HAS_IGNORES, + LFG_INCOMPATIBLES_NO_ROLES, + LFG_INCOMPATIBLES_NO_DUNGEONS, + LFG_COMPATIBLES_WITH_LESS_PLAYERS, // Values under this = not compatible (do not modify order) + LFG_COMPATIBLES_MATCH // Must be the last one + }; -/// Stores player or group queue info -struct LfgQueueData -{ - LfgQueueData(): joinTime(time_t(time(nullptr))), lastRefreshTime(joinTime), tanks(LFG_TANKS_NEEDED), - healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) + /// Stores player or group queue info + struct LfgQueueData + { + LfgQueueData(): joinTime(time_t(time(nullptr))), lastRefreshTime(joinTime), tanks(LFG_TANKS_NEEDED), + healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) { } - LfgQueueData(time_t _joinTime, LfgDungeonSet const& _dungeons, LfgRolesMap const& _roles): - joinTime(_joinTime), lastRefreshTime(_joinTime), tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), - dps(LFG_DPS_NEEDED), dungeons(_dungeons), roles(_roles) + LfgQueueData(time_t _joinTime, LfgDungeonSet const& _dungeons, LfgRolesMap const& _roles): + joinTime(_joinTime), lastRefreshTime(_joinTime), tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), + dps(LFG_DPS_NEEDED), dungeons(_dungeons), roles(_roles) { } - time_t joinTime; ///< Player queue join time (to calculate wait times) - time_t lastRefreshTime; ///< pussywizard - uint8 tanks; ///< Tanks needed - uint8 healers; ///< Healers needed - uint8 dps; ///< Dps needed - LfgDungeonSet dungeons; ///< Selected Player/Group Dungeon/s - LfgRolesMap roles; ///< Selected Player Role/s - Lfg5Guids bestCompatible; ///< Best compatible combination of people queued -}; + time_t joinTime; ///< Player queue join time (to calculate wait times) + time_t lastRefreshTime; ///< pussywizard + uint8 tanks; ///< Tanks needed + uint8 healers; ///< Healers needed + uint8 dps; ///< Dps needed + LfgDungeonSet dungeons; ///< Selected Player/Group Dungeon/s + LfgRolesMap roles; ///< Selected Player Role/s + Lfg5Guids bestCompatible; ///< Best compatible combination of people queued + }; -struct LfgWaitTime -{ - LfgWaitTime(): time(-1), number(0) {} - int32 time; ///< Wait time - uint32 number; ///< Number of people used to get that wait time -}; + struct LfgWaitTime + { + LfgWaitTime(): time(-1), number(0) {} + int32 time; ///< Wait time + uint32 number; ///< Number of people used to get that wait time + }; -typedef std::map LfgWaitTimesContainer; -typedef std::map LfgQueueDataContainer; -typedef std::list LfgCompatibleContainer; + typedef std::map LfgWaitTimesContainer; + typedef std::map LfgQueueDataContainer; + typedef std::list LfgCompatibleContainer; -/** - Stores all data related to queue -*/ -class LFGQueue -{ + /** + Stores all data related to queue + */ + class LFGQueue + { public: // Add/Remove from queue @@ -111,7 +111,7 @@ class LFGQueue LfgWaitTimesContainer waitTimesDpsStore; ///< Average wait time to find a group queuing as dps LfgGuidList newToQueueStore; ///< New groups to add to queue LfgGuidList restoredAfterProposal; -}; + }; } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGScripts.cpp b/src/server/game/DungeonFinding/LFGScripts.cpp index 10f2e1645..7e7f62daf 100644 --- a/src/server/game/DungeonFinding/LFGScripts.cpp +++ b/src/server/game/DungeonFinding/LFGScripts.cpp @@ -21,279 +21,279 @@ namespace lfg { -LFGPlayerScript::LFGPlayerScript() : PlayerScript("LFGPlayerScript") -{ -} - -void LFGPlayerScript::OnLevelChanged(Player* player, uint8 /*oldLevel*/) -{ - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - sLFGMgr->InitializeLockedDungeons(player); -} - -void LFGPlayerScript::OnLogout(Player* player) -{ - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - if (!player->GetGroup() || !player->GetGroup()->isLFGGroup()) + LFGPlayerScript::LFGPlayerScript() : PlayerScript("LFGPlayerScript") { - player->GetSession()->SendLfgLfrList(false); - sLFGMgr->LeaveLfg(player->GetGUID()); - sLFGMgr->LeaveAllLfgQueues(player->GetGUID(), true, player->GetGroup() ? player->GetGroup()->GetGUID() : 0); - - // pussywizard: after all necessary actions handle raid browser - // pussywizard: already done above - //if (sLFGMgr->GetState(player->GetGUID()) == LFG_STATE_RAIDBROWSER) - // sLFGMgr->LeaveLfg(player->GetGUID()); } - sLFGMgr->LfrSearchRemove(player); -} - -void LFGPlayerScript::OnLogin(Player* player) -{ - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - // Temporal: Trying to determine when group data and LFG data gets desynched - uint64 guid = player->GetGUID(); - uint64 gguid = sLFGMgr->GetGroup(guid); - - if (Group const* group = player->GetGroup()) + void LFGPlayerScript::OnLevelChanged(Player* player, uint8 /*oldLevel*/) { - uint64 gguid2 = group->GetGUID(); - if (gguid != gguid2) + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + sLFGMgr->InitializeLockedDungeons(player); + } + + void LFGPlayerScript::OnLogout(Player* player) + { + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + if (!player->GetGroup() || !player->GetGroup()->isLFGGroup()) { - //sLog->outError("%s on group %u but LFG has group %u saved... Fixing.", - // player->GetSession()->GetPlayerInfo().c_str(), GUID_LOPART(gguid2), GUID_LOPART(gguid)); - sLFGMgr->SetupGroupMember(guid, group->GetGUID()); + player->GetSession()->SendLfgLfrList(false); + sLFGMgr->LeaveLfg(player->GetGUID()); + sLFGMgr->LeaveAllLfgQueues(player->GetGUID(), true, player->GetGroup() ? player->GetGroup()->GetGUID() : 0); + + // pussywizard: after all necessary actions handle raid browser + // pussywizard: already done above + //if (sLFGMgr->GetState(player->GetGUID()) == LFG_STATE_RAIDBROWSER) + // sLFGMgr->LeaveLfg(player->GetGUID()); + } + + sLFGMgr->LfrSearchRemove(player); + } + + void LFGPlayerScript::OnLogin(Player* player) + { + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + // Temporal: Trying to determine when group data and LFG data gets desynched + uint64 guid = player->GetGUID(); + uint64 gguid = sLFGMgr->GetGroup(guid); + + if (Group const* group = player->GetGroup()) + { + uint64 gguid2 = group->GetGUID(); + if (gguid != gguid2) + { + //sLog->outError("%s on group %u but LFG has group %u saved... Fixing.", + // player->GetSession()->GetPlayerInfo().c_str(), GUID_LOPART(gguid2), GUID_LOPART(gguid)); + sLFGMgr->SetupGroupMember(guid, group->GetGUID()); + } + } + + sLFGMgr->InitializeLockedDungeons(player); + sLFGMgr->SetTeam(player->GetGUID(), player->GetTeamId()); + // TODO - Restore LfgPlayerData and send proper status to player if it was in a group + } + + void LFGPlayerScript::OnBindToInstance(Player* player, Difficulty difficulty, uint32 mapId, bool /*permanent*/) + { + MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); + if (mapEntry->IsDungeon() && difficulty > DUNGEON_DIFFICULTY_NORMAL) + sLFGMgr->InitializeLockedDungeons(player); + } + + void LFGPlayerScript::OnMapChanged(Player* player) + { + Map const* map = player->GetMap(); + + if (sLFGMgr->inLfgDungeonMap(player->GetGUID(), map->GetId(), map->GetDifficulty())) + { + Group* group = player->GetGroup(); + // This function is also called when players log in + // if for some reason the LFG system recognises the player as being in a LFG dungeon, + // but the player was loaded without a valid group, we'll teleport to homebind to prevent + // crashes or other undefined behaviour + if (!group) + { + sLFGMgr->LeaveLfg(player->GetGUID()); + sLFGMgr->LeaveAllLfgQueues(player->GetGUID(), true); + player->RemoveAurasDueToSpell(LFG_SPELL_LUCK_OF_THE_DRAW); + player->TeleportTo(player->m_homebindMapId, player->m_homebindX, player->m_homebindY, player->m_homebindZ, 0.0f); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGPlayerScript::OnMapChanged, Player %s (%u) is in LFG dungeon map but does not have a valid group! Teleporting to homebind.", player->GetName().c_str(), player->GetGUIDLow()); +#endif + return; + } + + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) + if (Player* member = itr->GetSource()) + player->GetSession()->SendNameQueryOpcode(member->GetGUID()); + + if (group->IsLfgWithBuff()) + player->CastSpell(player, LFG_SPELL_LUCK_OF_THE_DRAW, true); + } + else + { + player->RemoveAurasDueToSpell(LFG_SPELL_LUCK_OF_THE_DRAW); + + // Xinef: Destroy group if only one player is left + if (Group* group = player->GetGroup()) + if (group->GetMembersCount() <= 1u) + group->Disband(); } } - sLFGMgr->InitializeLockedDungeons(player); - sLFGMgr->SetTeam(player->GetGUID(), player->GetTeamId()); - // TODO - Restore LfgPlayerData and send proper status to player if it was in a group -} - -void LFGPlayerScript::OnBindToInstance(Player* player, Difficulty difficulty, uint32 mapId, bool /*permanent*/) -{ - MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); - if (mapEntry->IsDungeon() && difficulty > DUNGEON_DIFFICULTY_NORMAL) - sLFGMgr->InitializeLockedDungeons(player); -} - -void LFGPlayerScript::OnMapChanged(Player* player) -{ - Map const* map = player->GetMap(); - - if (sLFGMgr->inLfgDungeonMap(player->GetGUID(), map->GetId(), map->GetDifficulty())) + LFGGroupScript::LFGGroupScript() : GroupScript("LFGGroupScript") { - Group* group = player->GetGroup(); - // This function is also called when players log in - // if for some reason the LFG system recognises the player as being in a LFG dungeon, - // but the player was loaded without a valid group, we'll teleport to homebind to prevent - // crashes or other undefined behaviour - if (!group) + } + + void LFGGroupScript::OnAddMember(Group* group, uint64 guid) + { + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + uint64 gguid = group->GetGUID(); + uint64 leader = group->GetLeaderGUID(); + + if (leader == guid) { - sLFGMgr->LeaveLfg(player->GetGUID()); - sLFGMgr->LeaveAllLfgQueues(player->GetGUID(), true); - player->RemoveAurasDueToSpell(LFG_SPELL_LUCK_OF_THE_DRAW); - player->TeleportTo(player->m_homebindMapId, player->m_homebindX, player->m_homebindY, player->m_homebindZ, 0.0f); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGPlayerScript::OnMapChanged, Player %s (%u) is in LFG dungeon map but does not have a valid group! Teleporting to homebind.", player->GetName().c_str(), player->GetGUIDLow()); + sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnAddMember [" UI64FMTD "]: added [" UI64FMTD "] leader " UI64FMTD "]", gguid, guid, leader); #endif + sLFGMgr->SetLeader(gguid, guid); + } + else + { + LfgState gstate = sLFGMgr->GetState(gguid); + LfgState state = sLFGMgr->GetState(guid); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnAddMember [" UI64FMTD "]: added [" UI64FMTD "] leader " UI64FMTD "] gstate: %u, state: %u", gguid, guid, leader, gstate, state); +#endif + + if (state == LFG_STATE_QUEUED) + sLFGMgr->LeaveLfg(guid); + + if (gstate == LFG_STATE_QUEUED) + sLFGMgr->LeaveLfg(gguid); + } + + if (!group->isLFGGroup()) + { + sLFGMgr->LeaveAllLfgQueues(leader, true, gguid); // pussywizard: invited, queued, party formed, neither party nor new member are queued, but leader is in queue solo! + sLFGMgr->LeaveAllLfgQueues(guid, false); + } + + sLFGMgr->SetGroup(guid, gguid); + sLFGMgr->AddPlayerToGroup(gguid, guid); + + // pussywizard: after all necessary actions handle raid browser + if (sLFGMgr->GetState(guid) == LFG_STATE_RAIDBROWSER) + sLFGMgr->LeaveLfg(guid); + } + + void LFGGroupScript::OnRemoveMember(Group* group, uint64 guid, RemoveMethod method, uint64 kicker, char const* reason) + { + // used only with EXTRA_LOGS + UNUSED(kicker); + UNUSED(reason); + + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + uint64 gguid = group->GetGUID(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnRemoveMember [" UI64FMTD "]: remove [" UI64FMTD "] Method: %d Kicker: [" UI64FMTD "] Reason: %s", gguid, guid, method, kicker, (reason ? reason : "")); +#endif + + bool isLFG = group->isLFGGroup(); + LfgState state = sLFGMgr->GetState(gguid); + + // If group is being formed after proposal success do nothing more + if (state == LFG_STATE_PROPOSAL && method == GROUP_REMOVEMETHOD_DEFAULT) + { + // LfgData: Remove player from group + sLFGMgr->SetGroup(guid, 0); + sLFGMgr->RemovePlayerFromGroup(gguid, guid); return; } - for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) - if (Player* member = itr->GetSource()) - player->GetSession()->SendNameQueryOpcode(member->GetGUID()); - - if (group->IsLfgWithBuff()) - player->CastSpell(player, LFG_SPELL_LUCK_OF_THE_DRAW, true); - } - else - { - player->RemoveAurasDueToSpell(LFG_SPELL_LUCK_OF_THE_DRAW); - - // Xinef: Destroy group if only one player is left - if (Group* group = player->GetGroup()) - if (group->GetMembersCount() <= 1u) - group->Disband(); - } -} - -LFGGroupScript::LFGGroupScript() : GroupScript("LFGGroupScript") -{ -} - -void LFGGroupScript::OnAddMember(Group* group, uint64 guid) -{ - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - uint64 gguid = group->GetGUID(); - uint64 leader = group->GetLeaderGUID(); - - if (leader == guid) - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnAddMember [" UI64FMTD "]: added [" UI64FMTD "] leader " UI64FMTD "]", gguid, guid, leader); -#endif - sLFGMgr->SetLeader(gguid, guid); - } - else - { - LfgState gstate = sLFGMgr->GetState(gguid); - LfgState state = sLFGMgr->GetState(guid); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnAddMember [" UI64FMTD "]: added [" UI64FMTD "] leader " UI64FMTD "] gstate: %u, state: %u", gguid, guid, leader, gstate, state); -#endif - - if (state == LFG_STATE_QUEUED) - sLFGMgr->LeaveLfg(guid); - - if (gstate == LFG_STATE_QUEUED) - sLFGMgr->LeaveLfg(gguid); - } - - if (!group->isLFGGroup()) - { - sLFGMgr->LeaveAllLfgQueues(leader, true, gguid); // pussywizard: invited, queued, party formed, neither party nor new member are queued, but leader is in queue solo! - sLFGMgr->LeaveAllLfgQueues(guid, false); - } - - sLFGMgr->SetGroup(guid, gguid); - sLFGMgr->AddPlayerToGroup(gguid, guid); - - // pussywizard: after all necessary actions handle raid browser - if (sLFGMgr->GetState(guid) == LFG_STATE_RAIDBROWSER) sLFGMgr->LeaveLfg(guid); -} - -void LFGGroupScript::OnRemoveMember(Group* group, uint64 guid, RemoveMethod method, uint64 kicker, char const* reason) -{ - // used only with EXTRA_LOGS - UNUSED(kicker); - UNUSED(reason); - - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - uint64 gguid = group->GetGUID(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnRemoveMember [" UI64FMTD "]: remove [" UI64FMTD "] Method: %d Kicker: [" UI64FMTD "] Reason: %s", gguid, guid, method, kicker, (reason ? reason : "")); -#endif - - bool isLFG = group->isLFGGroup(); - LfgState state = sLFGMgr->GetState(gguid); - - // If group is being formed after proposal success do nothing more - if (state == LFG_STATE_PROPOSAL && method == GROUP_REMOVEMETHOD_DEFAULT) - { - // LfgData: Remove player from group + sLFGMgr->LeaveAllLfgQueues(guid, true, gguid); sLFGMgr->SetGroup(guid, 0); - sLFGMgr->RemovePlayerFromGroup(gguid, guid); - return; - } + uint8 players = sLFGMgr->RemovePlayerFromGroup(gguid, guid); - sLFGMgr->LeaveLfg(guid); - sLFGMgr->LeaveAllLfgQueues(guid, true, gguid); - sLFGMgr->SetGroup(guid, 0); - uint8 players = sLFGMgr->RemovePlayerFromGroup(gguid, guid); + // pussywizard: after all necessary actions handle raid browser + // pussywizard: already done above + //if (sLFGMgr->GetState(guid) == LFG_STATE_RAIDBROWSER) + // sLFGMgr->LeaveLfg(guid); - // pussywizard: after all necessary actions handle raid browser - // pussywizard: already done above - //if (sLFGMgr->GetState(guid) == LFG_STATE_RAIDBROWSER) - // sLFGMgr->LeaveLfg(guid); + // Xinef: only LFG groups can go below + if (!isLFG) + return; - // Xinef: only LFG groups can go below - if (!isLFG) - return; - - if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) - { - // xinef: fixed dungeon deserter - if (method != GROUP_REMOVEMETHOD_KICK_LFG && state != LFG_STATE_FINISHED_DUNGEON && - player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN) && players >= LFG_GROUP_KICK_VOTES_NEEDED) + if (Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) { - player->AddAura(LFG_SPELL_DUNGEON_DESERTER, player); - } - //else if (state == LFG_STATE_BOOT) + // xinef: fixed dungeon deserter + if (method != GROUP_REMOVEMETHOD_KICK_LFG && state != LFG_STATE_FINISHED_DUNGEON && + player->HasAura(LFG_SPELL_DUNGEON_COOLDOWN) && players >= LFG_GROUP_KICK_VOTES_NEEDED) + { + player->AddAura(LFG_SPELL_DUNGEON_DESERTER, player); + } + //else if (state == LFG_STATE_BOOT) // Update internal kick cooldown of kicked - player->GetSession()->SendLfgUpdateParty(LfgUpdateData(LFG_UPDATETYPE_LEADER_UNK1)); - if (player->GetMap()->IsDungeon()) // Teleport player out the dungeon + player->GetSession()->SendLfgUpdateParty(LfgUpdateData(LFG_UPDATETYPE_LEADER_UNK1)); + if (player->GetMap()->IsDungeon()) // Teleport player out the dungeon + { + // Xinef: no longer valid sLFGMgr->TeleportPlayer(player, true); + if (!player->IsBeingTeleportedFar() && player->GetMapId() == sLFGMgr->GetDungeonMapId(gguid)) + player->TeleportToEntryPoint(); + } + } + + if (state != LFG_STATE_FINISHED_DUNGEON) // Need more players to finish the dungeon + if (Player* leader = ObjectAccessor::FindPlayerInOrOutOfWorld(sLFGMgr->GetLeader(gguid))) + leader->GetSession()->SendLfgOfferContinue(sLFGMgr->GetDungeon(gguid, false)); + } + + void LFGGroupScript::OnDisband(Group* group) + { + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + uint64 gguid = group->GetGUID(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnDisband [" UI64FMTD "]", gguid); +#endif + + // pussywizard: after all necessary actions handle raid browser + if (sLFGMgr->GetState(group->GetLeaderGUID()) == LFG_STATE_RAIDBROWSER) + sLFGMgr->LeaveLfg(group->GetLeaderGUID()); + + sLFGMgr->RemoveGroupData(gguid); + } + + void LFGGroupScript::OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid) + { + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + uint64 gguid = group->GetGUID(); + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnChangeLeader [" UI64FMTD "]: old [" UI64FMTD "] new [" UI64FMTD "]", gguid, newLeaderGuid, oldLeaderGuid); +#endif + sLFGMgr->SetLeader(gguid, newLeaderGuid); + + // pussywizard: after all necessary actions handle raid browser + if (sLFGMgr->GetState(oldLeaderGuid) == LFG_STATE_RAIDBROWSER) + sLFGMgr->LeaveLfg(oldLeaderGuid); + } + + void LFGGroupScript::OnInviteMember(Group* group, uint64 guid) + { + // used only with EXTRA_LOGS + UNUSED(guid); + + if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) + return; + + uint64 gguid = group->GetGUID(); + uint64 leader = group->GetLeaderGUID(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnInviteMember [" UI64FMTD "]: invite [" UI64FMTD "] leader [" UI64FMTD "]", gguid, guid, leader); +#endif + // No gguid == new group being formed + // No leader == after group creation first invite is new leader + // leader and no gguid == first invite after leader is added to new group (this is the real invite) + if (leader && !gguid) { - // Xinef: no longer valid sLFGMgr->TeleportPlayer(player, true); - if (!player->IsBeingTeleportedFar() && player->GetMapId() == sLFGMgr->GetDungeonMapId(gguid)) - player->TeleportToEntryPoint(); + sLFGMgr->LeaveLfg(leader); + sLFGMgr->LeaveAllLfgQueues(leader, true); } } - if (state != LFG_STATE_FINISHED_DUNGEON) // Need more players to finish the dungeon - if (Player* leader = ObjectAccessor::FindPlayerInOrOutOfWorld(sLFGMgr->GetLeader(gguid))) - leader->GetSession()->SendLfgOfferContinue(sLFGMgr->GetDungeon(gguid, false)); -} - -void LFGGroupScript::OnDisband(Group* group) -{ - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - uint64 gguid = group->GetGUID(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnDisband [" UI64FMTD "]", gguid); -#endif - - // pussywizard: after all necessary actions handle raid browser - if (sLFGMgr->GetState(group->GetLeaderGUID()) == LFG_STATE_RAIDBROWSER) - sLFGMgr->LeaveLfg(group->GetLeaderGUID()); - - sLFGMgr->RemoveGroupData(gguid); -} - -void LFGGroupScript::OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid) -{ - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - uint64 gguid = group->GetGUID(); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnChangeLeader [" UI64FMTD "]: old [" UI64FMTD "] new [" UI64FMTD "]", gguid, newLeaderGuid, oldLeaderGuid); -#endif - sLFGMgr->SetLeader(gguid, newLeaderGuid); - - // pussywizard: after all necessary actions handle raid browser - if (sLFGMgr->GetState(oldLeaderGuid) == LFG_STATE_RAIDBROWSER) - sLFGMgr->LeaveLfg(oldLeaderGuid); -} - -void LFGGroupScript::OnInviteMember(Group* group, uint64 guid) -{ - // used only with EXTRA_LOGS - UNUSED(guid); - - if (!sLFGMgr->isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) - return; - - uint64 gguid = group->GetGUID(); - uint64 leader = group->GetLeaderGUID(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_LFG, "LFGScripts::OnInviteMember [" UI64FMTD "]: invite [" UI64FMTD "] leader [" UI64FMTD "]", gguid, guid, leader); -#endif - // No gguid == new group being formed - // No leader == after group creation first invite is new leader - // leader and no gguid == first invite after leader is added to new group (this is the real invite) - if (leader && !gguid) - { - sLFGMgr->LeaveLfg(leader); - sLFGMgr->LeaveAllLfgQueues(leader, true); - } -} - } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGScripts.h b/src/server/game/DungeonFinding/LFGScripts.h index 56859b748..f712ab87e 100644 --- a/src/server/game/DungeonFinding/LFGScripts.h +++ b/src/server/game/DungeonFinding/LFGScripts.h @@ -18,8 +18,8 @@ class Group; namespace lfg { -class LFGPlayerScript : public PlayerScript -{ + class LFGPlayerScript : public PlayerScript + { public: LFGPlayerScript(); @@ -29,10 +29,10 @@ class LFGPlayerScript : public PlayerScript void OnLogin(Player* player); void OnBindToInstance(Player* player, Difficulty difficulty, uint32 mapId, bool permanent); void OnMapChanged(Player* player); -}; + }; -class LFGGroupScript : public GroupScript -{ + class LFGGroupScript : public GroupScript + { public: LFGGroupScript(); @@ -42,6 +42,6 @@ class LFGGroupScript : public GroupScript void OnDisband(Group* group); void OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid); void OnInviteMember(Group* group, uint64 guid); -}; + }; } // namespace lfg diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index 78ce48910..6bdeb27c2 100644 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -33,7 +33,7 @@ Corpse::~Corpse() } void Corpse::AddToWorld() -{ +{ ///- Register the corpse for guid lookup if (!IsInWorld()) sObjectAccessor->AddObject(this); @@ -42,7 +42,7 @@ void Corpse::AddToWorld() } void Corpse::RemoveFromWorld() -{ +{ ///- Remove the corpse from the accessor if (IsInWorld()) sObjectAccessor->RemoveObject(this); @@ -51,14 +51,14 @@ void Corpse::RemoveFromWorld() } bool Corpse::Create(uint32 guidlow, Map* map) -{ +{ SetMap(map); Object::_Create(guidlow, 0, HIGHGUID_CORPSE); return true; } bool Corpse::Create(uint32 guidlow, Player* owner) -{ +{ ASSERT(owner); Relocate(owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ(), owner->GetOrientation()); @@ -66,7 +66,7 @@ bool Corpse::Create(uint32 guidlow, Player* owner) if (!IsPositionValid()) { sLog->outError("Corpse (guidlow %d, owner %s) not created. Suggested coordinates isn't valid (X: %f Y: %f)", - guidlow, owner->GetName().c_str(), owner->GetPositionX(), owner->GetPositionY()); + guidlow, owner->GetName().c_str(), owner->GetPositionX(), owner->GetPositionY()); return false; } @@ -85,7 +85,7 @@ bool Corpse::Create(uint32 guidlow, Player* owner) } void Corpse::SaveToDB() -{ +{ // prevent DB data inconsistence problems and duplicates SQLTransaction trans = CharacterDatabase.BeginTransaction(); DeleteFromDB(trans); @@ -115,7 +115,7 @@ void Corpse::SaveToDB() } void Corpse::DeleteFromDB(SQLTransaction& trans) -{ +{ PreparedStatement* stmt = nullptr; if (GetType() == CORPSE_BONES) { @@ -133,7 +133,7 @@ void Corpse::DeleteFromDB(SQLTransaction& trans) } bool Corpse::LoadCorpseFromDB(uint32 guid, Field* fields) -{ +{ uint32 ownerGuid = fields[17].GetUInt32(); // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // SELECT posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, guildId, flags, dynFlags, time, corpseType, instanceId, phaseMask, corpseGuid, guid FROM corpse WHERE corpseType <> 0 @@ -169,7 +169,7 @@ bool Corpse::LoadCorpseFromDB(uint32 guid, Field* fields) if (!IsPositionValid()) { sLog->outError("Corpse (guid: %u, owner: %u) is not created, given coordinates are not valid (X: %f, Y: %f, Z: %f)", - GetGUIDLow(), GUID_LOPART(GetOwnerGUID()), posX, posY, posZ); + GetGUIDLow(), GUID_LOPART(GetOwnerGUID()), posX, posY, posZ); return false; } @@ -178,7 +178,7 @@ bool Corpse::LoadCorpseFromDB(uint32 guid, Field* fields) } bool Corpse::IsExpired(time_t t) const -{ +{ if (m_type == CORPSE_BONES) return m_time < t - 60 * MINUTE; else diff --git a/src/server/game/Entities/Corpse/Corpse.h b/src/server/game/Entities/Corpse/Corpse.h index 3c7d22a6c..f17c471b2 100644 --- a/src/server/game/Entities/Corpse/Corpse.h +++ b/src/server/game/Entities/Corpse/Corpse.h @@ -36,38 +36,38 @@ enum CorpseFlags class Corpse : public WorldObject, public GridObject { - public: - explicit Corpse(CorpseType type = CORPSE_BONES); - ~Corpse(); +public: + explicit Corpse(CorpseType type = CORPSE_BONES); + ~Corpse(); - void AddToWorld() override; - void RemoveFromWorld() override; + void AddToWorld() override; + void RemoveFromWorld() override; - bool Create(uint32 guidlow, Map* map); - bool Create(uint32 guidlow, Player* owner); + bool Create(uint32 guidlow, Map* map); + bool Create(uint32 guidlow, Player* owner); - void SaveToDB(); - bool LoadCorpseFromDB(uint32 guid, Field* fields); + void SaveToDB(); + bool LoadCorpseFromDB(uint32 guid, Field* fields); - void DeleteFromDB(SQLTransaction& trans); + void DeleteFromDB(SQLTransaction& trans); - uint64 GetOwnerGUID() const { return GetUInt64Value(CORPSE_FIELD_OWNER); } + uint64 GetOwnerGUID() const { return GetUInt64Value(CORPSE_FIELD_OWNER); } - time_t const& GetGhostTime() const { return m_time; } - void ResetGhostTime() { m_time = time(nullptr); } - CorpseType GetType() const { return m_type; } + time_t const& GetGhostTime() const { return m_time; } + void ResetGhostTime() { m_time = time(nullptr); } + CorpseType GetType() const { return m_type; } - GridCoord const& GetGridCoord() const { return _gridCoord; } - void SetGridCoord(GridCoord const& gridCoord) { _gridCoord = gridCoord; } + GridCoord const& GetGridCoord() const { return _gridCoord; } + void SetGridCoord(GridCoord const& gridCoord) { _gridCoord = gridCoord; } - Loot loot; // remove insignia ONLY at BG - Player* lootRecipient; + Loot loot; // remove insignia ONLY at BG + Player* lootRecipient; - bool IsExpired(time_t t) const; + bool IsExpired(time_t t) const; - private: - CorpseType m_type; - time_t m_time; - GridCoord _gridCoord; // gride for corpse position for fast search +private: + CorpseType m_type; + time_t m_time; + GridCoord _gridCoord; // gride for corpse position for fast search }; #endif diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 96c1f1043..4ebdbe7de 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -90,7 +90,7 @@ uint32 CreatureTemplate::GetRandomValidModelId() const if (Modelid3) modelIDs[c++] = Modelid3; if (Modelid4) modelIDs[c++] = Modelid4; - return ((c>0) ? modelIDs[urand(0, c-1)] : 0); + return ((c > 0) ? modelIDs[urand(0, c - 1)] : 0); } uint32 CreatureTemplate::GetFirstValidModelId() const @@ -160,11 +160,11 @@ bool ForcedDespawnDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) } Creature::Creature(bool isWorldObject): Unit(isWorldObject), MovableMapObject(), m_groupLootTimer(0), lootingGroupLowGUID(0), m_PlayerDamageReq(0), m_lootRecipient(0), m_lootRecipientGroup(0), -m_corpseRemoveTime(0), m_respawnTime(0), m_respawnDelay(300), m_corpseDelay(60), m_wanderDistance(0.0f), -m_transportCheckTimer(1000), lootPickPocketRestoreTime(0), m_reactState(REACT_AGGRESSIVE), m_defaultMovementType(IDLE_MOTION_TYPE), -m_DBTableGuid(0), m_equipmentId(0), m_originalEquipmentId(0), m_AlreadyCallAssistance(false), -m_AlreadySearchedAssistance(false), m_regenHealth(true), m_AI_locked(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL), m_originalEntry(0), m_moveInLineOfSightDisabled(false), m_moveInLineOfSightStrictlyDisabled(false), -m_homePosition(), m_transportHomePosition(), m_creatureInfo(nullptr), m_creatureData(nullptr), m_waypointID(0), m_path_id(0), m_formation(nullptr), _lastDamagedTime(0) + m_corpseRemoveTime(0), m_respawnTime(0), m_respawnDelay(300), m_corpseDelay(60), m_wanderDistance(0.0f), + m_transportCheckTimer(1000), lootPickPocketRestoreTime(0), m_reactState(REACT_AGGRESSIVE), m_defaultMovementType(IDLE_MOTION_TYPE), + m_DBTableGuid(0), m_equipmentId(0), m_originalEquipmentId(0), m_AlreadyCallAssistance(false), + m_AlreadySearchedAssistance(false), m_regenHealth(true), m_AI_locked(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL), m_originalEntry(0), m_moveInLineOfSightDisabled(false), m_moveInLineOfSightStrictlyDisabled(false), + m_homePosition(), m_transportHomePosition(), m_creatureInfo(nullptr), m_creatureData(nullptr), m_waypointID(0), m_path_id(0), m_formation(nullptr), _lastDamagedTime(0) { m_regenTimer = CREATURE_REGEN_INTERVAL; m_valuesCount = UNIT_END; @@ -390,7 +390,7 @@ bool Creature::InitEntry(uint32 Entry, const CreatureData* data) if (!m_wanderDistance && m_defaultMovementType == RANDOM_MOTION_TYPE) m_defaultMovementType = IDLE_MOTION_TYPE; - for (uint8 i=0; i < CREATURE_MAX_SPELLS; ++i) + for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) m_spells[i] = GetCreatureTemplate()->spells[i]; return true; @@ -506,112 +506,112 @@ void Creature::Update(uint32 diff) sLog->outError("Creature (GUID: %u Entry: %u) in wrong state: JUST_DEAD (1)", GetGUIDLow(), GetEntry()); break; case DEAD: - { - time_t now = time(nullptr); - if (m_respawnTime <= now) { - bool allowed = IsAIEnabled ? AI()->CanRespawn() : true; // First check if there are any scripts that object to us respawning - if (!allowed) // Will be rechecked on next Update call + time_t now = time(nullptr); + if (m_respawnTime <= now) + { + bool allowed = IsAIEnabled ? AI()->CanRespawn() : true; // First check if there are any scripts that object to us respawning + if (!allowed) // Will be rechecked on next Update call + break; + + uint64 dbtableHighGuid = MAKE_NEW_GUID(m_DBTableGuid, GetEntry(), HIGHGUID_UNIT); + time_t linkedRespawntime = GetMap()->GetLinkedRespawnTime(dbtableHighGuid); + if (!linkedRespawntime) // Can respawn + Respawn(); + else // the master is dead + { + uint64 targetGuid = sObjectMgr->GetLinkedRespawnGuid(dbtableHighGuid); + if (targetGuid == dbtableHighGuid) // if linking self, never respawn (check delayed to next day) + SetRespawnTime(DAY); + else + m_respawnTime = (now > linkedRespawntime ? now : linkedRespawntime) + urand(5, MINUTE); // else copy time from master and add a little + SaveRespawnTime(); // also save to DB immediately + } + } + break; + } + case CORPSE: + { + Unit::Update(diff); + // deathstate changed on spells update, prevent problems + if (m_deathState != CORPSE) break; - uint64 dbtableHighGuid = MAKE_NEW_GUID(m_DBTableGuid, GetEntry(), HIGHGUID_UNIT); - time_t linkedRespawntime = GetMap()->GetLinkedRespawnTime(dbtableHighGuid); - if (!linkedRespawntime) // Can respawn - Respawn(); - else // the master is dead + if (m_groupLootTimer && lootingGroupLowGUID) { - uint64 targetGuid = sObjectMgr->GetLinkedRespawnGuid(dbtableHighGuid); - if (targetGuid == dbtableHighGuid) // if linking self, never respawn (check delayed to next day) - SetRespawnTime(DAY); - else - m_respawnTime = (now > linkedRespawntime ? now : linkedRespawntime)+urand(5, MINUTE); // else copy time from master and add a little - SaveRespawnTime(); // also save to DB immediately + if (m_groupLootTimer <= diff) + { + Group* group = sGroupMgr->GetGroupByGUID(lootingGroupLowGUID); + if (group) + group->EndRoll(&loot, GetMap()); + m_groupLootTimer = 0; + lootingGroupLowGUID = 0; + } + else m_groupLootTimer -= diff; } - } - break; - } - case CORPSE: - { - Unit::Update(diff); - // deathstate changed on spells update, prevent problems - if (m_deathState != CORPSE) - break; - - if (m_groupLootTimer && lootingGroupLowGUID) - { - if (m_groupLootTimer <= diff) + else if (m_corpseRemoveTime <= time(nullptr)) { - Group* group = sGroupMgr->GetGroupByGUID(lootingGroupLowGUID); - if (group) - group->EndRoll(&loot, GetMap()); - m_groupLootTimer = 0; - lootingGroupLowGUID = 0; - } - else m_groupLootTimer -= diff; - } - else if (m_corpseRemoveTime <= time(nullptr)) - { - RemoveCorpse(false); + RemoveCorpse(false); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug("Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY)); + sLog->outStaticDebug("Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY)); #endif + } + break; } - break; - } case ALIVE: - { - Unit::Update(diff); + { + Unit::Update(diff); - // creature can be dead after Unit::Update call - // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly) - if (!IsAlive()) + // creature can be dead after Unit::Update call + // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly) + if (!IsAlive()) + break; + + // if creature is charmed, switch to charmed AI + if (NeedChangeAI) + { + UpdateCharmAI(); + NeedChangeAI = false; + IsAIEnabled = true; + + // xinef: update combat state, if npc is not in combat - return to spawn correctly by calling EnterEvadeMode + SelectVictim(); + } + + Unit* owner = GetCharmerOrOwner(); + if (IsCharmed() && !IsWithinDistInMap(owner, GetMap()->GetVisibilityRange())) + { + RemoveCharmAuras(); + } + + if (!IsInEvadeMode() && IsAIEnabled) + { + // do not allow the AI to be changed during update + m_AI_locked = true; + i_AI->UpdateAI(diff); + m_AI_locked = false; + } + + // creature can be dead after UpdateAI call + // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly) + if (!IsAlive()) + break; + + m_regenTimer -= diff; + if (m_regenTimer <= 0) + { + if (!IsInEvadeMode() && (!IsInCombat() || IsPolymorphed())) // regenerate health if not in combat or if polymorphed + RegenerateHealth(); + + if (getPowerType() == POWER_ENERGY) + Regenerate(POWER_ENERGY); + else + Regenerate(POWER_MANA); + + m_regenTimer += CREATURE_REGEN_INTERVAL; + } break; - - // if creature is charmed, switch to charmed AI - if (NeedChangeAI) - { - UpdateCharmAI(); - NeedChangeAI = false; - IsAIEnabled = true; - - // xinef: update combat state, if npc is not in combat - return to spawn correctly by calling EnterEvadeMode - SelectVictim(); } - - Unit* owner = GetCharmerOrOwner(); - if (IsCharmed() && !IsWithinDistInMap(owner, GetMap()->GetVisibilityRange())) - { - RemoveCharmAuras(); - } - - if (!IsInEvadeMode() && IsAIEnabled) - { - // do not allow the AI to be changed during update - m_AI_locked = true; - i_AI->UpdateAI(diff); - m_AI_locked = false; - } - - // creature can be dead after UpdateAI call - // CORPSE/DEAD state will processed at next tick (in other case death timer will be updated unexpectedly) - if (!IsAlive()) - break; - - m_regenTimer -= diff; - if (m_regenTimer <= 0) - { - if (!IsInEvadeMode() && (!IsInCombat() || IsPolymorphed())) // regenerate health if not in combat or if polymorphed - RegenerateHealth(); - - if (getPowerType() == POWER_ENERGY) - Regenerate(POWER_ENERGY); - else - Regenerate(POWER_MANA); - - m_regenTimer += CREATURE_REGEN_INTERVAL; - } - break; - } default: break; } @@ -660,38 +660,38 @@ void Creature::Regenerate(Powers power) switch (power) { case POWER_FOCUS: - { - // For hunter pets. - addvalue = 24 * sWorld->getRate(RATE_POWER_FOCUS); - break; - } - case POWER_ENERGY: - { - // For deathknight's ghoul. - addvalue = 20; - break; - } - case POWER_MANA: - { - // Combat and any controlled creature - if (IsInCombat() || GetCharmerOrOwnerGUID()) { - if (GetEntry() == NPC_IMP || GetEntry() == NPC_WATER_ELEMENTAL_TEMP || GetEntry() == NPC_WATER_ELEMENTAL_PERM) - { - addvalue = uint32((GetStat(STAT_SPIRIT) / (IsUnderLastManaUseEffect() ? 8.0f : 5.0f) + 17.0f)); - } - else if (!IsUnderLastManaUseEffect()) - { - float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA); - float Spirit = GetStat(STAT_SPIRIT); - - addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate); - } + // For hunter pets. + addvalue = 24 * sWorld->getRate(RATE_POWER_FOCUS); + break; + } + case POWER_ENERGY: + { + // For deathknight's ghoul. + addvalue = 20; + break; + } + case POWER_MANA: + { + // Combat and any controlled creature + if (IsInCombat() || GetCharmerOrOwnerGUID()) + { + if (GetEntry() == NPC_IMP || GetEntry() == NPC_WATER_ELEMENTAL_TEMP || GetEntry() == NPC_WATER_ELEMENTAL_PERM) + { + addvalue = uint32((GetStat(STAT_SPIRIT) / (IsUnderLastManaUseEffect() ? 8.0f : 5.0f) + 17.0f)); + } + else if (!IsUnderLastManaUseEffect()) + { + float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA); + float Spirit = GetStat(STAT_SPIRIT); + + addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate); + } + } + else + addvalue = maxValue / 3; + break; } - else - addvalue = maxValue / 3; - break; - } default: return; } @@ -723,7 +723,7 @@ void Creature::RegenerateHealth() // Not only pet, but any controlled creature // Xinef: fix polymorph rapid regen if (!GetCharmerOrOwnerGUID() || IsPolymorphed()) - addvalue = maxValue/3; + addvalue = maxValue / 3; else //if (GetCharmerOrOwnerGUID()) { float HealthIncreaseRate = sWorld->getRate(RATE_HEALTH); @@ -755,7 +755,7 @@ void Creature::DoFleeToGetAssistance() return; float radius = sWorld->getFloatConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS); - if (radius >0) + if (radius > 0) { Creature* creature = nullptr; @@ -864,7 +864,7 @@ bool Creature::Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, case CREATURE_ELITE_WORLDBOSS: // Xinef: Reduce corpse delay for bossess outside of instance if (!GetInstanceId()) - m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_ELITE)*2; + m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_ELITE) * 2; else m_corpseDelay = sWorld->getIntConfig(CONFIG_CORPSE_DECAY_WORLDBOSS); break; @@ -918,9 +918,15 @@ bool Creature::isCanInteractWithBattleMaster(Player* player, bool msg) const ClearGossipMenuFor(player); switch (bgTypeId) { - case BATTLEGROUND_AV: SendGossipMenuFor(player, 7616, this); break; - case BATTLEGROUND_WS: SendGossipMenuFor(player, 7599, this); break; - case BATTLEGROUND_AB: SendGossipMenuFor(player, 7642, this); break; + case BATTLEGROUND_AV: + SendGossipMenuFor(player, 7616, this); + break; + case BATTLEGROUND_WS: + SendGossipMenuFor(player, 7599, this); + break; + case BATTLEGROUND_AB: + SendGossipMenuFor(player, 7642, this); + break; case BATTLEGROUND_EY: case BATTLEGROUND_NA: case BATTLEGROUND_BE: @@ -928,8 +934,11 @@ bool Creature::isCanInteractWithBattleMaster(Player* player, bool msg) const case BATTLEGROUND_RL: case BATTLEGROUND_SA: case BATTLEGROUND_DS: - case BATTLEGROUND_RV: SendGossipMenuFor(player, 10024, this); break; - default: break; + case BATTLEGROUND_RV: + SendGossipMenuFor(player, 10024, this); + break; + default: + break; } return false; } @@ -939,8 +948,8 @@ bool Creature::isCanInteractWithBattleMaster(Player* player, bool msg) const bool Creature::isCanTrainingAndResetTalentsOf(Player* player) const { return player->getLevel() >= 10 - && GetCreatureTemplate()->trainer_type == TRAINER_TYPE_CLASS - && player->getClass() == GetCreatureTemplate()->trainer_class; + && GetCreatureTemplate()->trainer_type == TRAINER_TYPE_CLASS + && player->getClass() == GetCreatureTemplate()->trainer_class; } Player* Creature::GetLootRecipient() const @@ -967,7 +976,7 @@ void Creature::SetLootRecipient(Unit* unit, bool withGroup) { m_lootRecipient = 0; m_lootRecipientGroup = 0; - RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE|UNIT_DYNFLAG_TAPPED); + RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE | UNIT_DYNFLAG_TAPPED); return; } @@ -1036,7 +1045,7 @@ void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) if (cinfo) { if (displayId == cinfo->Modelid1 || displayId == cinfo->Modelid2 || - displayId == cinfo->Modelid3 || displayId == cinfo->Modelid4) + displayId == cinfo->Modelid3 || displayId == cinfo->Modelid4) displayId = 0; if (npcflag == cinfo->npcflag) @@ -1078,7 +1087,7 @@ void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) data.curmana = GetPower(POWER_MANA); // prevent add data integrity problems data.movementType = !m_wanderDistance && GetDefaultMovementType() == RANDOM_MOTION_TYPE - ? IDLE_MOTION_TYPE : GetDefaultMovementType(); + ? IDLE_MOTION_TYPE : GetDefaultMovementType(); data.spawnMask = spawnMask; data.npcflag = npcflag; data.unit_flags = unit_flags; @@ -1320,9 +1329,9 @@ bool Creature::LoadCreatureFromDB(uint32 guid, Map* map, bool addToMap, bool gri // xinef: fix shitness from db if ((addToMap || gridLoad) && !data->overwrittenZ) { - float tz = map->GetHeight(data->posX, data->posY, data->posZ+1.0f, true); + float tz = map->GetHeight(data->posX, data->posY, data->posZ + 1.0f, true); if (tz >= data->posZ && tz - data->posZ <= 1.0f) - const_cast(data)->posZ = tz+0.1f; + const_cast(data)->posZ = tz + 0.1f; const_cast(data)->overwrittenZ = true; } @@ -1371,7 +1380,7 @@ bool Creature::LoadCreatureFromDB(uint32 guid, Map* map, bool addToMap, bool gri curhealth = data->curhealth; if (curhealth) { - curhealth = uint32(curhealth*_GetHealthMod(GetCreatureTemplate()->rank)); + curhealth = uint32(curhealth * _GetHealthMod(GetCreatureTemplate()->rank)); if (curhealth < 1) curhealth = 1; } @@ -1501,7 +1510,7 @@ bool Creature::CanStartAttack(Unit const* who) const // This set of checks is should be done only for creatures if ((HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC) && who->GetTypeId() != TYPEID_PLAYER) || // flag is valid only for non player characters - (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC) && who->GetTypeId() == TYPEID_PLAYER)) // immune to PC and target is a player, return false + (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC) && who->GetTypeId() == TYPEID_PLAYER)) // immune to PC and target is a player, return false return false; if (Unit* owner = who->GetOwner()) @@ -1755,7 +1764,7 @@ SpellInfo const* Creature::reachWithSpellAttack(Unit* victim) if (!victim) return nullptr; - for (uint32 i=0; i < CREATURE_MAX_SPELLS; ++i) + for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { if (!m_spells[i]) continue; @@ -1770,10 +1779,10 @@ SpellInfo const* Creature::reachWithSpellAttack(Unit* victim) for (uint32 j = 0; j < MAX_SPELL_EFFECTS; j++) { if ((spellInfo->Effects[j].Effect == SPELL_EFFECT_SCHOOL_DAMAGE) || - (spellInfo->Effects[j].Effect == SPELL_EFFECT_INSTAKILL) || - (spellInfo->Effects[j].Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) || - (spellInfo->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH) - ) + (spellInfo->Effects[j].Effect == SPELL_EFFECT_INSTAKILL) || + (spellInfo->Effects[j].Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) || + (spellInfo->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH) + ) { bcontinue = false; break; @@ -1803,7 +1812,7 @@ SpellInfo const* Creature::reachWithSpellCure(Unit* victim) if (!victim) return nullptr; - for (uint32 i=0; i < CREATURE_MAX_SPELLS; ++i) + for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { if (!m_spells[i]) continue; @@ -2066,8 +2075,8 @@ bool Creature::_CanDetectFeignDeathOf(const Unit* target) const void Creature::UpdateMoveInLineOfSightState() { // xinef: pets, guardians and units with scripts / smartAI should be skipped - if (IsPet() || HasUnitTypeMask(UNIT_MASK_MINION|UNIT_MASK_SUMMON|UNIT_MASK_GUARDIAN|UNIT_MASK_CONTROLABLE_GUARDIAN) || - GetScriptId() || GetAIName() == "SmartAI") + if (IsPet() || HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_SUMMON | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN) || + GetScriptId() || GetAIName() == "SmartAI") { m_moveInLineOfSightStrictlyDisabled = false; m_moveInLineOfSightDisabled = false; @@ -2137,7 +2146,7 @@ bool Creature::CanCreatureAttack(Unit const* victim, bool skipDistCheck) const return true; // xinef: added size factor for huge npcs - float dist = std::min(GetMap()->GetVisibilityRange() + GetObjectSize()*2, 150.0f); + float dist = std::min(GetMap()->GetVisibilityRange() + GetObjectSize() * 2, 150.0f); if (Unit* unit = GetCharmerOrOwner()) return victim->IsWithinDist(unit, dist); @@ -2279,7 +2288,7 @@ void Creature::SetInCombatWithZone() return; } - Map::PlayerList const &PlList = map->GetPlayers(); + Map::PlayerList const& PlList = map->GetPlayers(); if (PlList.isEmpty()) return; @@ -2324,7 +2333,7 @@ bool Creature::IsSpellProhibited(SpellSchoolMask idSchoolMask) const void Creature::_AddCreatureSpellCooldown(uint32 spell_id, uint32 end_time) { - m_CreatureSpellCooldowns[spell_id] = World::GetGameTimeMS()+end_time; + m_CreatureSpellCooldowns[spell_id] = World::GetGameTimeMS() + end_time; } void Creature::AddSpellCooldown(uint32 spell_id, uint32 /*itemid*/, uint32 end_time, bool /*needSendToClient*/, bool /*forceSendToSpectator*/) @@ -2390,7 +2399,7 @@ bool Creature::HasSpell(uint32 spellID) const } time_t Creature::GetRespawnTimeEx() const -{ +{ time_t now = time(nullptr); if (m_respawnTime > now) @@ -2399,7 +2408,7 @@ time_t Creature::GetRespawnTimeEx() const return now; } -void Creature::GetRespawnPosition(float &x, float &y, float &z, float* ori, float* dist) const +void Creature::GetRespawnPosition(float& x, float& y, float& z, float* ori, float* dist) const { if (m_DBTableGuid) { @@ -2517,7 +2526,7 @@ uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem) { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(vItem->item); - uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime); + uint32 diff = uint32((ptime - vCount->lastIncrementTime) / vItem->incrtime); if ((vCount->count + diff * pProto->BuyCount) >= vItem->maxcount) { m_vendorItemCounts.erase(itr); @@ -2543,7 +2552,7 @@ uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 us if (itr == m_vendorItemCounts.end()) { - uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount-used_count : 0; + uint32 new_count = vItem->maxcount > used_count ? vItem->maxcount - used_count : 0; m_vendorItemCounts.push_back(VendorItemCount(vItem->item, new_count)); return new_count; } @@ -2556,14 +2565,14 @@ uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 us { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(vItem->item); - uint32 diff = uint32((ptime - vCount->lastIncrementTime)/vItem->incrtime); + uint32 diff = uint32((ptime - vCount->lastIncrementTime) / vItem->incrtime); if ((vCount->count + diff * pProto->BuyCount) < vItem->maxcount) vCount->count += diff * pProto->BuyCount; else vCount->count = vItem->maxcount; } - vCount->count = vCount->count > used_count ? vCount->count-used_count : 0; + vCount->count = vCount->count > used_count ? vCount->count - used_count : 0; vCount->lastIncrementTime = ptime; return vCount->count; } @@ -2867,5 +2876,5 @@ float Creature::GetAttackDistance(Unit const* player) const if (retDistance < 5.0f) retDistance = 5.0f; - return (retDistance*aggroRate); + return (retDistance * aggroRate); } diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index f2e774feb..1213c0c17 100644 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -153,7 +153,7 @@ struct CreatureTemplate { return (type_flags & CREATURE_TYPE_FLAG_EXOTIC_PET) != 0; } - + bool IsTameable(bool exotic) const { if (type != CREATURE_TYPE_BEAST || family == 0 || (type_flags & CREATURE_TYPE_FLAG_TAMEABLE_PET) == 0) @@ -252,9 +252,9 @@ typedef std::unordered_map EquipmentInfo struct CreatureData { CreatureData() : id(0), mapid(0), phaseMask(0), displayid(0), equipmentId(0), - posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), - wander_distance(0.0f), currentwaypoint(0), curhealth(0), curmana(0), movementType(0), - spawnMask(0), npcflag(0), unit_flags(0), dynamicflags(0), dbData(true), overwrittenZ(false) { } + posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), + wander_distance(0.0f), currentwaypoint(0), curhealth(0), curmana(0), movementType(0), + spawnMask(0), npcflag(0), unit_flags(0), dynamicflags(0), dbData(true), overwrittenZ(false) { } uint32 id; // entry in creature_template uint16 mapid; uint32 phaseMask; @@ -414,7 +414,7 @@ struct TrainerSpellData TrainerSpellMap spellList; uint32 trainerType; // trainer type based at trainer spells, can be different from creature_template value. - // req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2. + // req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2. TrainerSpell const* Find(uint32 spell_id) const; }; @@ -427,389 +427,389 @@ typedef std::map CreatureSpellCooldowns; class Creature : public Unit, public GridObject, public MovableMapObject { - public: - - explicit Creature(bool isWorldObject = false); - virtual ~Creature(); - - void AddToWorld() override; - void RemoveFromWorld() override; - - void SetObjectScale(float scale) override; - void SetDisplayId(uint32 modelId) override; - - void DisappearAndDie(); - - bool Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, uint32 vehId, float x, float y, float z, float ang, const CreatureData* data = nullptr); - bool LoadCreaturesAddon(bool reload = false); - void SelectLevel(bool changelevel = true); - void LoadEquipment(int8 id = 1, bool force = false); - - uint32 GetDBTableGUIDLow() const { return m_DBTableGuid; } - - void Update(uint32 time) override; // overwrited Unit::Update - void GetRespawnPosition(float &x, float &y, float &z, float* ori = NULL, float* dist =NULL) const; - - void SetCorpseDelay(uint32 delay) { m_corpseDelay = delay; } - uint32 GetCorpseDelay() const { return m_corpseDelay; } - bool IsRacialLeader() const { return GetCreatureTemplate()->RacialLeader; } - bool IsCivilian() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN; } - bool IsTrigger() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_TRIGGER; } - bool IsGuard() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_GUARD; } - bool CanWalk() const { return GetCreatureTemplate()->InhabitType & INHABIT_GROUND; } - bool CanSwim() const override { return (GetCreatureTemplate()->InhabitType & INHABIT_WATER) || IS_PLAYER_GUID(GetOwnerGUID()); } - bool CanFly() const override { return GetCreatureTemplate()->InhabitType & INHABIT_AIR; } - - void SetReactState(ReactStates st) { m_reactState = st; } - ReactStates GetReactState() const { return m_reactState; } - bool HasReactState(ReactStates state) const { return (m_reactState == state); } - void InitializeReactState(); - - ///// TODO RENAME THIS!!!!! - bool isCanInteractWithBattleMaster(Player* player, bool msg) const; - bool isCanTrainingAndResetTalentsOf(Player* player) const; - bool CanCreatureAttack(Unit const* victim, bool skipDistCheck = false) const; - bool IsImmunedToSpell(SpellInfo const* spellInfo) override; - - bool HasMechanicTemplateImmunity(uint32 mask) const; - // redefine Unit::IsImmunedToSpell - bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const override; - // redefine Unit::IsImmunedToSpellEffect - bool isElite() const - { - if (IsPet()) - return false; - - uint32 rank = GetCreatureTemplate()->rank; - return rank != CREATURE_ELITE_NORMAL && rank != CREATURE_ELITE_RARE; - } - - bool isWorldBoss() const - { - if (IsPet()) - return false; - - return GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_BOSS_MOB; - } - - bool IsDungeonBoss() const; - bool IsImmuneToKnockback() const; - bool IsAvoidingAOE() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_AVOID_AOE; } - - uint8 getLevelForTarget(WorldObject const* target) const override; // overwrite Unit::getLevelForTarget for boss level support - - bool IsInEvadeMode() const { return HasUnitState(UNIT_STATE_EVADE); } - - bool AIM_Initialize(CreatureAI* ai = nullptr); - void Motion_Initialize(); - - CreatureAI* AI() const { return (CreatureAI*)i_AI; } - - bool SetWalk(bool enable) override; - bool SetDisableGravity(bool disable, bool packetOnly = false) override; - bool SetSwim(bool enable) override; - bool SetCanFly(bool enable, bool packetOnly = false) override; - bool SetWaterWalking(bool enable, bool packetOnly = false) override; - bool SetFeatherFall(bool enable, bool packetOnly = false) override; - bool SetHover(bool enable, bool packetOnly = false) override; - - uint32 GetShieldBlockValue() const override - { - return (getLevel()/2 + uint32(GetStat(STAT_STRENGTH)/20)); - } - - SpellSchoolMask GetMeleeDamageSchoolMask() const override { return m_meleeDamageSchoolMask; } - void SetMeleeDamageSchool(SpellSchools school) { m_meleeDamageSchoolMask = SpellSchoolMask(1 << school); } - - void _AddCreatureSpellCooldown(uint32 spell_id, uint32 end_time); - virtual void AddSpellCooldown(uint32 spell_id, uint32 /*itemid*/, uint32 end_time, bool needSendToClient = false, bool forceSendToSpectator = false) override; - virtual bool HasSpellCooldown(uint32 spell_id) const override; - uint32 GetSpellCooldown(uint32 spell_id) const; - void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override; - bool IsSpellProhibited(SpellSchoolMask idSchoolMask) const; - - bool HasSpell(uint32 spellID) const override; - - bool UpdateEntry(uint32 entry, const CreatureData* data=NULL, bool changelevel=true ); - bool UpdateStats(Stats stat) override; - bool UpdateAllStats() override; - void UpdateResistances(uint32 school) override; - void UpdateArmor() override; - void UpdateMaxHealth() override; - void UpdateMaxPower(Powers power) override; - void UpdateAttackPowerAndDamage(bool ranged = false) override; - void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) override; - - void SetCanDualWield(bool value) override; - int8 GetOriginalEquipmentId() const { return m_originalEquipmentId; } - uint8 GetCurrentEquipmentId() { return m_equipmentId; } - void SetCurrentEquipmentId(uint8 id) { m_equipmentId = id; } - - float GetSpellDamageMod(int32 Rank); - - VendorItemData const* GetVendorItems() const; - uint32 GetVendorItemCurrentCount(VendorItem const* vItem); - uint32 UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count); - - TrainerSpellData const* GetTrainerSpells() const; - - CreatureTemplate const* GetCreatureTemplate() const { return m_creatureInfo; } - CreatureData const* GetCreatureData() const { return m_creatureData; } - CreatureAddon const* GetCreatureAddon() const; - - std::string GetAIName() const; - std::string GetScriptName() const; - uint32 GetScriptId() const; - - // override WorldObject function for proper name localization - std::string const& GetNameForLocaleIdx(LocaleConstant locale_idx) const override; - - void setDeathState(DeathState s, bool despawn = false) override; // override virtual Unit::setDeathState - - bool LoadFromDB(uint32 guid, Map* map) { return LoadCreatureFromDB(guid, map, false, true); } - bool LoadCreatureFromDB(uint32 guid, Map* map, bool addToMap = true, bool gridLoad = false); - void SaveToDB(); - // overriden in Pet - virtual void SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask); - virtual void DeleteFromDB(); // overriden in Pet - - Loot loot; - uint64 GetLootRecipientGUID() const { return m_lootRecipient; } - Player* GetLootRecipient() const; - Group* GetLootRecipientGroup() const; - bool hasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; } - bool isTappedBy(Player const* player) const; // return true if the creature is tapped by the player or a member of his party. - bool CanGeneratePickPocketLoot() const { return lootPickPocketRestoreTime == 0 || lootPickPocketRestoreTime < time(nullptr); } - void SetPickPocketLootTime() { lootPickPocketRestoreTime = time(nullptr) + MINUTE + GetCorpseDelay() + GetRespawnTime(); } - void ResetPickPocketLootTime() { lootPickPocketRestoreTime = 0; } - - void SetLootRecipient (Unit* unit, bool withGroup = true); - void AllLootRemovedFromCorpse(); - - uint16 GetLootMode() const { return m_LootMode; } - bool HasLootMode(uint16 lootMode) const { return m_LootMode & lootMode; } - void SetLootMode(uint16 lootMode) { m_LootMode = lootMode; } - void AddLootMode(uint16 lootMode) { m_LootMode |= lootMode; } - void RemoveLootMode(uint16 lootMode) { m_LootMode &= ~lootMode; } - void ResetLootMode() { m_LootMode = LOOT_MODE_DEFAULT; } - - SpellInfo const* reachWithSpellAttack(Unit* victim); - SpellInfo const* reachWithSpellCure(Unit* victim); - - uint32 m_spells[CREATURE_MAX_SPELLS]; - CreatureSpellCooldowns m_CreatureSpellCooldowns; - uint32 m_ProhibitSchoolTime[7]; - - bool CanStartAttack(Unit const* u) const; - float GetAggroRange(Unit const* target) const; - float GetAttackDistance(Unit const* player) const; - - void SendAIReaction(AiReaction reactionType); - - Unit* SelectNearestTarget(float dist = 0, bool playerOnly = false) const; - Unit* SelectNearestTargetInAttackDistance(float dist) const; - - void DoFleeToGetAssistance(); - void CallForHelp(float fRadius); - void CallAssistance(); - void SetNoCallAssistance(bool val) { m_AlreadyCallAssistance = val; } - void SetNoSearchAssistance(bool val) { m_AlreadySearchedAssistance = val; } - bool HasSearchedAssistance() { return m_AlreadySearchedAssistance; } - bool CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction = true) const; - bool _IsTargetAcceptable(const Unit* target) const; - bool _CanDetectFeignDeathOf(const Unit* target) const; // pussywizard - - // pussywizard: updated at faction change, disable move in line of sight if actual faction is not hostile to anyone - void UpdateMoveInLineOfSightState(); - bool IsMoveInLineOfSightDisabled() { return m_moveInLineOfSightDisabled; } - bool IsMoveInLineOfSightStrictlyDisabled() { return m_moveInLineOfSightStrictlyDisabled; } - - MovementGeneratorType GetDefaultMovementType() const { return m_defaultMovementType; } - void SetDefaultMovementType(MovementGeneratorType mgt) { m_defaultMovementType = mgt; } +public: + + explicit Creature(bool isWorldObject = false); + virtual ~Creature(); + + void AddToWorld() override; + void RemoveFromWorld() override; + + void SetObjectScale(float scale) override; + void SetDisplayId(uint32 modelId) override; + + void DisappearAndDie(); + + bool Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, uint32 vehId, float x, float y, float z, float ang, const CreatureData* data = nullptr); + bool LoadCreaturesAddon(bool reload = false); + void SelectLevel(bool changelevel = true); + void LoadEquipment(int8 id = 1, bool force = false); + + uint32 GetDBTableGUIDLow() const { return m_DBTableGuid; } + + void Update(uint32 time) override; // overwrited Unit::Update + void GetRespawnPosition(float& x, float& y, float& z, float* ori = NULL, float* dist = NULL) const; + + void SetCorpseDelay(uint32 delay) { m_corpseDelay = delay; } + uint32 GetCorpseDelay() const { return m_corpseDelay; } + bool IsRacialLeader() const { return GetCreatureTemplate()->RacialLeader; } + bool IsCivilian() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN; } + bool IsTrigger() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_TRIGGER; } + bool IsGuard() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_GUARD; } + bool CanWalk() const { return GetCreatureTemplate()->InhabitType & INHABIT_GROUND; } + bool CanSwim() const override { return (GetCreatureTemplate()->InhabitType & INHABIT_WATER) || IS_PLAYER_GUID(GetOwnerGUID()); } + bool CanFly() const override { return GetCreatureTemplate()->InhabitType & INHABIT_AIR; } + + void SetReactState(ReactStates st) { m_reactState = st; } + ReactStates GetReactState() const { return m_reactState; } + bool HasReactState(ReactStates state) const { return (m_reactState == state); } + void InitializeReactState(); + + ///// TODO RENAME THIS!!!!! + bool isCanInteractWithBattleMaster(Player* player, bool msg) const; + bool isCanTrainingAndResetTalentsOf(Player* player) const; + bool CanCreatureAttack(Unit const* victim, bool skipDistCheck = false) const; + bool IsImmunedToSpell(SpellInfo const* spellInfo) override; + + bool HasMechanicTemplateImmunity(uint32 mask) const; + // redefine Unit::IsImmunedToSpell + bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const override; + // redefine Unit::IsImmunedToSpellEffect + bool isElite() const + { + if (IsPet()) + return false; + + uint32 rank = GetCreatureTemplate()->rank; + return rank != CREATURE_ELITE_NORMAL && rank != CREATURE_ELITE_RARE; + } + + bool isWorldBoss() const + { + if (IsPet()) + return false; + + return GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_BOSS_MOB; + } + + bool IsDungeonBoss() const; + bool IsImmuneToKnockback() const; + bool IsAvoidingAOE() const { return GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_AVOID_AOE; } + + uint8 getLevelForTarget(WorldObject const* target) const override; // overwrite Unit::getLevelForTarget for boss level support + + bool IsInEvadeMode() const { return HasUnitState(UNIT_STATE_EVADE); } + + bool AIM_Initialize(CreatureAI* ai = nullptr); + void Motion_Initialize(); + + CreatureAI* AI() const { return (CreatureAI*)i_AI; } + + bool SetWalk(bool enable) override; + bool SetDisableGravity(bool disable, bool packetOnly = false) override; + bool SetSwim(bool enable) override; + bool SetCanFly(bool enable, bool packetOnly = false) override; + bool SetWaterWalking(bool enable, bool packetOnly = false) override; + bool SetFeatherFall(bool enable, bool packetOnly = false) override; + bool SetHover(bool enable, bool packetOnly = false) override; + + uint32 GetShieldBlockValue() const override + { + return (getLevel() / 2 + uint32(GetStat(STAT_STRENGTH) / 20)); + } + + SpellSchoolMask GetMeleeDamageSchoolMask() const override { return m_meleeDamageSchoolMask; } + void SetMeleeDamageSchool(SpellSchools school) { m_meleeDamageSchoolMask = SpellSchoolMask(1 << school); } + + void _AddCreatureSpellCooldown(uint32 spell_id, uint32 end_time); + virtual void AddSpellCooldown(uint32 spell_id, uint32 /*itemid*/, uint32 end_time, bool needSendToClient = false, bool forceSendToSpectator = false) override; + virtual bool HasSpellCooldown(uint32 spell_id) const override; + uint32 GetSpellCooldown(uint32 spell_id) const; + void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override; + bool IsSpellProhibited(SpellSchoolMask idSchoolMask) const; + + bool HasSpell(uint32 spellID) const override; + + bool UpdateEntry(uint32 entry, const CreatureData* data = NULL, bool changelevel = true ); + bool UpdateStats(Stats stat) override; + bool UpdateAllStats() override; + void UpdateResistances(uint32 school) override; + void UpdateArmor() override; + void UpdateMaxHealth() override; + void UpdateMaxPower(Powers power) override; + void UpdateAttackPowerAndDamage(bool ranged = false) override; + void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) override; + + void SetCanDualWield(bool value) override; + int8 GetOriginalEquipmentId() const { return m_originalEquipmentId; } + uint8 GetCurrentEquipmentId() { return m_equipmentId; } + void SetCurrentEquipmentId(uint8 id) { m_equipmentId = id; } + + float GetSpellDamageMod(int32 Rank); + + VendorItemData const* GetVendorItems() const; + uint32 GetVendorItemCurrentCount(VendorItem const* vItem); + uint32 UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count); + + TrainerSpellData const* GetTrainerSpells() const; + + CreatureTemplate const* GetCreatureTemplate() const { return m_creatureInfo; } + CreatureData const* GetCreatureData() const { return m_creatureData; } + CreatureAddon const* GetCreatureAddon() const; + + std::string GetAIName() const; + std::string GetScriptName() const; + uint32 GetScriptId() const; + + // override WorldObject function for proper name localization + std::string const& GetNameForLocaleIdx(LocaleConstant locale_idx) const override; + + void setDeathState(DeathState s, bool despawn = false) override; // override virtual Unit::setDeathState + + bool LoadFromDB(uint32 guid, Map* map) { return LoadCreatureFromDB(guid, map, false, true); } + bool LoadCreatureFromDB(uint32 guid, Map* map, bool addToMap = true, bool gridLoad = false); + void SaveToDB(); + // overriden in Pet + virtual void SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask); + virtual void DeleteFromDB(); // overriden in Pet + + Loot loot; + uint64 GetLootRecipientGUID() const { return m_lootRecipient; } + Player* GetLootRecipient() const; + Group* GetLootRecipientGroup() const; + bool hasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; } + bool isTappedBy(Player const* player) const; // return true if the creature is tapped by the player or a member of his party. + bool CanGeneratePickPocketLoot() const { return lootPickPocketRestoreTime == 0 || lootPickPocketRestoreTime < time(nullptr); } + void SetPickPocketLootTime() { lootPickPocketRestoreTime = time(nullptr) + MINUTE + GetCorpseDelay() + GetRespawnTime(); } + void ResetPickPocketLootTime() { lootPickPocketRestoreTime = 0; } + + void SetLootRecipient (Unit* unit, bool withGroup = true); + void AllLootRemovedFromCorpse(); + + uint16 GetLootMode() const { return m_LootMode; } + bool HasLootMode(uint16 lootMode) const { return m_LootMode & lootMode; } + void SetLootMode(uint16 lootMode) { m_LootMode = lootMode; } + void AddLootMode(uint16 lootMode) { m_LootMode |= lootMode; } + void RemoveLootMode(uint16 lootMode) { m_LootMode &= ~lootMode; } + void ResetLootMode() { m_LootMode = LOOT_MODE_DEFAULT; } + + SpellInfo const* reachWithSpellAttack(Unit* victim); + SpellInfo const* reachWithSpellCure(Unit* victim); + + uint32 m_spells[CREATURE_MAX_SPELLS]; + CreatureSpellCooldowns m_CreatureSpellCooldowns; + uint32 m_ProhibitSchoolTime[7]; + + bool CanStartAttack(Unit const* u) const; + float GetAggroRange(Unit const* target) const; + float GetAttackDistance(Unit const* player) const; + + void SendAIReaction(AiReaction reactionType); + + Unit* SelectNearestTarget(float dist = 0, bool playerOnly = false) const; + Unit* SelectNearestTargetInAttackDistance(float dist) const; + + void DoFleeToGetAssistance(); + void CallForHelp(float fRadius); + void CallAssistance(); + void SetNoCallAssistance(bool val) { m_AlreadyCallAssistance = val; } + void SetNoSearchAssistance(bool val) { m_AlreadySearchedAssistance = val; } + bool HasSearchedAssistance() { return m_AlreadySearchedAssistance; } + bool CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction = true) const; + bool _IsTargetAcceptable(const Unit* target) const; + bool _CanDetectFeignDeathOf(const Unit* target) const; // pussywizard + + // pussywizard: updated at faction change, disable move in line of sight if actual faction is not hostile to anyone + void UpdateMoveInLineOfSightState(); + bool IsMoveInLineOfSightDisabled() { return m_moveInLineOfSightDisabled; } + bool IsMoveInLineOfSightStrictlyDisabled() { return m_moveInLineOfSightStrictlyDisabled; } + + MovementGeneratorType GetDefaultMovementType() const { return m_defaultMovementType; } + void SetDefaultMovementType(MovementGeneratorType mgt) { m_defaultMovementType = mgt; } - void RemoveCorpse(bool setSpawnTime = true, bool skipVisibility = false); - - void DespawnOrUnsummon(uint32 msTimeToDespawn = 0); - - time_t const& GetRespawnTime() const { return m_respawnTime; } - time_t GetRespawnTimeEx() const; - void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(nullptr) + respawn : 0; } - void Respawn(bool force = false); - void SaveRespawnTime() override; - - uint32 GetRespawnDelay() const { return m_respawnDelay; } - void SetRespawnDelay(uint32 delay) { m_respawnDelay = delay; } + void RemoveCorpse(bool setSpawnTime = true, bool skipVisibility = false); + + void DespawnOrUnsummon(uint32 msTimeToDespawn = 0); + + time_t const& GetRespawnTime() const { return m_respawnTime; } + time_t GetRespawnTimeEx() const; + void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(nullptr) + respawn : 0; } + void Respawn(bool force = false); + void SaveRespawnTime() override; + + uint32 GetRespawnDelay() const { return m_respawnDelay; } + void SetRespawnDelay(uint32 delay) { m_respawnDelay = delay; } - float GetWanderDistance() const { return m_wanderDistance; } - void SetWanderDistance(float dist) { m_wanderDistance = dist; } - - uint32 m_groupLootTimer; // (msecs)timer used for group loot - uint32 lootingGroupLowGUID; // used to find group which is looting corpse - - void SendZoneUnderAttackMessage(Player* attacker); - - void SetInCombatWithZone(); - - bool hasQuest(uint32 quest_id) const override; - bool hasInvolvedQuest(uint32 quest_id) const override; - - bool isRegeneratingHealth() { return m_regenHealth; } - void SetRegeneratingHealth(bool c) { m_regenHealth = c; } - virtual uint8 GetPetAutoSpellSize() const { return MAX_SPELL_CHARM; } - virtual uint32 GetPetAutoSpellOnPos(uint8 pos) const - { - if (pos >= MAX_SPELL_CHARM || m_charmInfo->GetCharmSpell(pos)->GetType() != ACT_ENABLED) - return 0; - else - return m_charmInfo->GetCharmSpell(pos)->GetAction(); - } - - void SetPosition(float x, float y, float z, float o); - void SetPosition(const Position &pos) { SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation()); } - - void SetHomePosition(float x, float y, float z, float o) { m_homePosition.Relocate(x, y, z, o); } - void SetHomePosition(const Position &pos) { m_homePosition.Relocate(pos); } - void GetHomePosition(float& x, float& y, float& z, float& ori) const { m_homePosition.GetPosition(x, y, z, ori); } - Position const& GetHomePosition() const { return m_homePosition; } - - void SetTransportHomePosition(float x, float y, float z, float o) { m_transportHomePosition.Relocate(x, y, z, o); } - void SetTransportHomePosition(const Position &pos) { m_transportHomePosition.Relocate(pos); } - void GetTransportHomePosition(float& x, float& y, float& z, float& ori) const { m_transportHomePosition.GetPosition(x, y, z, ori); } - Position const& GetTransportHomePosition() const { return m_transportHomePosition; } - - uint32 GetWaypointPath() const { return m_path_id; } - void LoadPath(uint32 pathid) { m_path_id = pathid; } + float GetWanderDistance() const { return m_wanderDistance; } + void SetWanderDistance(float dist) { m_wanderDistance = dist; } + + uint32 m_groupLootTimer; // (msecs)timer used for group loot + uint32 lootingGroupLowGUID; // used to find group which is looting corpse + + void SendZoneUnderAttackMessage(Player* attacker); + + void SetInCombatWithZone(); + + bool hasQuest(uint32 quest_id) const override; + bool hasInvolvedQuest(uint32 quest_id) const override; + + bool isRegeneratingHealth() { return m_regenHealth; } + void SetRegeneratingHealth(bool c) { m_regenHealth = c; } + virtual uint8 GetPetAutoSpellSize() const { return MAX_SPELL_CHARM; } + virtual uint32 GetPetAutoSpellOnPos(uint8 pos) const + { + if (pos >= MAX_SPELL_CHARM || m_charmInfo->GetCharmSpell(pos)->GetType() != ACT_ENABLED) + return 0; + else + return m_charmInfo->GetCharmSpell(pos)->GetAction(); + } + + void SetPosition(float x, float y, float z, float o); + void SetPosition(const Position& pos) { SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation()); } + + void SetHomePosition(float x, float y, float z, float o) { m_homePosition.Relocate(x, y, z, o); } + void SetHomePosition(const Position& pos) { m_homePosition.Relocate(pos); } + void GetHomePosition(float& x, float& y, float& z, float& ori) const { m_homePosition.GetPosition(x, y, z, ori); } + Position const& GetHomePosition() const { return m_homePosition; } - uint32 GetCurrentWaypointID() const { return m_waypointID; } - void UpdateWaypointID(uint32 wpID){ m_waypointID = wpID; } + void SetTransportHomePosition(float x, float y, float z, float o) { m_transportHomePosition.Relocate(x, y, z, o); } + void SetTransportHomePosition(const Position& pos) { m_transportHomePosition.Relocate(pos); } + void GetTransportHomePosition(float& x, float& y, float& z, float& ori) const { m_transportHomePosition.GetPosition(x, y, z, ori); } + Position const& GetTransportHomePosition() const { return m_transportHomePosition; } - void SearchFormation(); - CreatureGroup* GetFormation() const { return m_formation; } - void SetFormation(CreatureGroup* formation) { m_formation = formation; } + uint32 GetWaypointPath() const { return m_path_id; } + void LoadPath(uint32 pathid) { m_path_id = pathid; } - Unit* SelectVictim(); + uint32 GetCurrentWaypointID() const { return m_waypointID; } + void UpdateWaypointID(uint32 wpID) { m_waypointID = wpID; } - void SetDisableReputationGain(bool disable) { DisableReputationGain = disable; } - bool IsReputationGainDisabled() const { return DisableReputationGain; } - bool IsDamageEnoughForLootingAndReward() const { return m_PlayerDamageReq == 0; } - void LowerPlayerDamageReq(uint32 unDamage) - { - if (m_PlayerDamageReq) - m_PlayerDamageReq > unDamage ? m_PlayerDamageReq -= unDamage : m_PlayerDamageReq = 0; - } - void ResetPlayerDamageReq() { m_PlayerDamageReq = GetHealth() / 2; } - uint32 m_PlayerDamageReq; + void SearchFormation(); + CreatureGroup* GetFormation() const { return m_formation; } + void SetFormation(CreatureGroup* formation) { m_formation = formation; } - uint32 GetOriginalEntry() const { return m_originalEntry; } - void SetOriginalEntry(uint32 entry) { m_originalEntry = entry; } + Unit* SelectVictim(); - static float _GetDamageMod(int32 Rank); + void SetDisableReputationGain(bool disable) { DisableReputationGain = disable; } + bool IsReputationGainDisabled() const { return DisableReputationGain; } + bool IsDamageEnoughForLootingAndReward() const { return m_PlayerDamageReq == 0; } + void LowerPlayerDamageReq(uint32 unDamage) + { + if (m_PlayerDamageReq) + m_PlayerDamageReq > unDamage ? m_PlayerDamageReq -= unDamage : m_PlayerDamageReq = 0; + } + void ResetPlayerDamageReq() { m_PlayerDamageReq = GetHealth() / 2; } + uint32 m_PlayerDamageReq; - float m_SightDistance, m_CombatDistance; + uint32 GetOriginalEntry() const { return m_originalEntry; } + void SetOriginalEntry(uint32 entry) { m_originalEntry = entry; } - bool m_isTempWorldObject; //true when possessed + static float _GetDamageMod(int32 Rank); - // Handling caster facing during spellcast - void SetTarget(uint64 guid) override; - void FocusTarget(Spell const* focusSpell, WorldObject const* target); - void ReleaseFocus(Spell const* focusSpell); + float m_SightDistance, m_CombatDistance; - // Part of Evade mechanics - time_t GetLastDamagedTime() const { return _lastDamagedTime; } - void SetLastDamagedTime(time_t val) { _lastDamagedTime = val; } + bool m_isTempWorldObject; //true when possessed - protected: - bool CreateFromProto(uint32 guidlow, uint32 Entry, uint32 vehId, const CreatureData* data = nullptr); - bool InitEntry(uint32 entry, const CreatureData* data=NULL); + // Handling caster facing during spellcast + void SetTarget(uint64 guid) override; + void FocusTarget(Spell const* focusSpell, WorldObject const* target); + void ReleaseFocus(Spell const* focusSpell); - // vendor items - VendorItemCounts m_vendorItemCounts; + // Part of Evade mechanics + time_t GetLastDamagedTime() const { return _lastDamagedTime; } + void SetLastDamagedTime(time_t val) { _lastDamagedTime = val; } - static float _GetHealthMod(int32 Rank); +protected: + bool CreateFromProto(uint32 guidlow, uint32 Entry, uint32 vehId, const CreatureData* data = nullptr); + bool InitEntry(uint32 entry, const CreatureData* data = NULL); - uint64 m_lootRecipient; - uint32 m_lootRecipientGroup; + // vendor items + VendorItemCounts m_vendorItemCounts; - /// Timers - time_t m_corpseRemoveTime; // (msecs)timer for death or corpse disappearance - time_t m_respawnTime; // (secs) time of next respawn - uint32 m_respawnDelay; // (secs) delay between corpse disappearance and respawning - uint32 m_corpseDelay; // (secs) delay between death and corpse disappearance - float m_wanderDistance; - uint16 m_transportCheckTimer; - uint32 lootPickPocketRestoreTime; + static float _GetHealthMod(int32 Rank); - ReactStates m_reactState; // for AI, not charmInfo - void RegenerateHealth(); - void Regenerate(Powers power); - MovementGeneratorType m_defaultMovementType; - uint32 m_DBTableGuid; ///< For new or temporary creatures is 0 for saved it is lowguid - uint8 m_equipmentId; - int8 m_originalEquipmentId; // can be -1 + uint64 m_lootRecipient; + uint32 m_lootRecipientGroup; - bool m_AlreadyCallAssistance; - bool m_AlreadySearchedAssistance; - bool m_regenHealth; - bool m_AI_locked; + /// Timers + time_t m_corpseRemoveTime; // (msecs)timer for death or corpse disappearance + time_t m_respawnTime; // (secs) time of next respawn + uint32 m_respawnDelay; // (secs) delay between corpse disappearance and respawning + uint32 m_corpseDelay; // (secs) delay between death and corpse disappearance + float m_wanderDistance; + uint16 m_transportCheckTimer; + uint32 lootPickPocketRestoreTime; - SpellSchoolMask m_meleeDamageSchoolMask; - uint32 m_originalEntry; - - bool m_moveInLineOfSightDisabled; - bool m_moveInLineOfSightStrictlyDisabled; + ReactStates m_reactState; // for AI, not charmInfo + void RegenerateHealth(); + void Regenerate(Powers power); + MovementGeneratorType m_defaultMovementType; + uint32 m_DBTableGuid; ///< For new or temporary creatures is 0 for saved it is lowguid + uint8 m_equipmentId; + int8 m_originalEquipmentId; // can be -1 - Position m_homePosition; - Position m_transportHomePosition; + bool m_AlreadyCallAssistance; + bool m_AlreadySearchedAssistance; + bool m_regenHealth; + bool m_AI_locked; - bool DisableReputationGain; + SpellSchoolMask m_meleeDamageSchoolMask; + uint32 m_originalEntry; - CreatureTemplate const* m_creatureInfo; // in difficulty mode > 0 can different from sObjectMgr->GetCreatureTemplate(GetEntry()) - CreatureData const* m_creatureData; + bool m_moveInLineOfSightDisabled; + bool m_moveInLineOfSightStrictlyDisabled; - uint16 m_LootMode; // bitmask, default LOOT_MODE_DEFAULT, determines what loot will be lootable + Position m_homePosition; + Position m_transportHomePosition; - bool IsInvisibleDueToDespawn() const override; - bool CanAlwaysSee(WorldObject const* obj) const override; + bool DisableReputationGain; - private: - void ForcedDespawn(uint32 timeMSToDespawn = 0); + CreatureTemplate const* m_creatureInfo; // in difficulty mode > 0 can different from sObjectMgr->GetCreatureTemplate(GetEntry()) + CreatureData const* m_creatureData; - //WaypointMovementGenerator vars - uint32 m_waypointID; - uint32 m_path_id; + uint16 m_LootMode; // bitmask, default LOOT_MODE_DEFAULT, determines what loot will be lootable - //Formation var - CreatureGroup* m_formation; - bool TriggerJustRespawned; + bool IsInvisibleDueToDespawn() const override; + bool CanAlwaysSee(WorldObject const* obj) const override; - time_t _lastDamagedTime; // Part of Evade mechanics +private: + void ForcedDespawn(uint32 timeMSToDespawn = 0); - Spell const* _focusSpell; ///> Locks the target during spell cast for proper facing + //WaypointMovementGenerator vars + uint32 m_waypointID; + uint32 m_path_id; + + //Formation var + CreatureGroup* m_formation; + bool TriggerJustRespawned; + + time_t _lastDamagedTime; // Part of Evade mechanics + + Spell const* _focusSpell; ///> Locks the target during spell cast for proper facing }; class AssistDelayEvent : public BasicEvent { - public: - AssistDelayEvent(uint64 victim, Unit& owner) : BasicEvent(), m_victim(victim), m_owner(owner) { } +public: + AssistDelayEvent(uint64 victim, Unit& owner) : BasicEvent(), m_victim(victim), m_owner(owner) { } - bool Execute(uint64 e_time, uint32 p_time); - void AddAssistant(uint64 guid) { m_assistants.push_back(guid); } - private: - AssistDelayEvent(); + bool Execute(uint64 e_time, uint32 p_time); + void AddAssistant(uint64 guid) { m_assistants.push_back(guid); } +private: + AssistDelayEvent(); - uint64 m_victim; - std::list m_assistants; - Unit& m_owner; + uint64 m_victim; + std::list m_assistants; + Unit& m_owner; }; class ForcedDespawnDelayEvent : public BasicEvent { - public: - ForcedDespawnDelayEvent(Creature& owner) : BasicEvent(), m_owner(owner) { } - bool Execute(uint64 e_time, uint32 p_time); +public: + ForcedDespawnDelayEvent(Creature& owner) : BasicEvent(), m_owner(owner) { } + bool Execute(uint64 e_time, uint32 p_time); - private: - Creature& m_owner; +private: + Creature& m_owner; }; #endif diff --git a/src/server/game/Entities/Creature/CreatureGroups.cpp b/src/server/game/Entities/Creature/CreatureGroups.cpp index 0b97ff41d..87a3ae8f5 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.cpp +++ b/src/server/game/Entities/Creature/CreatureGroups.cpp @@ -136,8 +136,7 @@ void FormationMgr::LoadCreatureFormations() CreatureGroupMap[memberGUID] = group_member; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creatures in formations in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -248,7 +247,7 @@ void CreatureGroup::LeaderMoveTo(float x, float y, float z, bool run) continue; // Xinef: this should be automatized, if turn angle is greater than PI/2 (90�) we should swap formation angle - if (M_PI - fabs(fabs(m_leader->GetOrientation() - pathAngle) - M_PI) > M_PI*0.50f) + if (M_PI - fabs(fabs(m_leader->GetOrientation() - pathAngle) - M_PI) > M_PI * 0.50f) { // pussywizard: in both cases should be 2*M_PI - follow_angle // pussywizard: also, GetCurrentWaypointID() returns 0..n-1, while point_1 must be > 0, so +1 diff --git a/src/server/game/Entities/Creature/CreatureGroups.h b/src/server/game/Entities/Creature/CreatureGroups.h index fe65ec3dc..11264e24c 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.h +++ b/src/server/game/Entities/Creature/CreatureGroups.h @@ -28,47 +28,47 @@ typedef std::unordered_map CreatureGro class FormationMgr { - public: - FormationMgr() { } - ~FormationMgr(); - - static FormationMgr* instance(); - - void AddCreatureToGroup(uint32 group_id, Creature* creature); - void RemoveCreatureFromGroup(CreatureGroup* group, Creature* creature); - void LoadCreatureFormations(); - CreatureGroupInfoType CreatureGroupMap; +public: + FormationMgr() { } + ~FormationMgr(); + + static FormationMgr* instance(); + + void AddCreatureToGroup(uint32 group_id, Creature* creature); + void RemoveCreatureFromGroup(CreatureGroup* group, Creature* creature); + void LoadCreatureFormations(); + CreatureGroupInfoType CreatureGroupMap; }; class CreatureGroup { - public: - // pussywizard: moved public to the top so it compiles and typedef is public - typedef std::map CreatureGroupMemberType; +public: + // pussywizard: moved public to the top so it compiles and typedef is public + typedef std::map CreatureGroupMemberType; - //Group cannot be created empty - explicit CreatureGroup(uint32 id) : m_leader(nullptr), m_groupID(id), m_Formed(false) {} - ~CreatureGroup() {} + //Group cannot be created empty + explicit CreatureGroup(uint32 id) : m_leader(nullptr), m_groupID(id), m_Formed(false) {} + ~CreatureGroup() {} - Creature* getLeader() const { return m_leader; } - uint32 GetId() const { return m_groupID; } - bool isEmpty() const { return m_members.empty(); } - bool isFormed() const { return m_Formed; } - const CreatureGroupMemberType& GetMembers() const { return m_members; } + Creature* getLeader() const { return m_leader; } + uint32 GetId() const { return m_groupID; } + bool isEmpty() const { return m_members.empty(); } + bool isFormed() const { return m_Formed; } + const CreatureGroupMemberType& GetMembers() const { return m_members; } - void AddMember(Creature* member); - void RemoveMember(Creature* member); - void FormationReset(bool dismiss); + void AddMember(Creature* member); + void RemoveMember(Creature* member); + void FormationReset(bool dismiss); - void LeaderMoveTo(float x, float y, float z, bool run); - void MemberAttackStart(Creature* member, Unit* target); + void LeaderMoveTo(float x, float y, float z, bool run); + void MemberAttackStart(Creature* member, Unit* target); - private: - Creature* m_leader; //Important do not forget sometimes to work with pointers instead synonims :D:D - CreatureGroupMemberType m_members; +private: + Creature* m_leader; //Important do not forget sometimes to work with pointers instead synonims :D:D + CreatureGroupMemberType m_members; - uint32 m_groupID; - bool m_Formed; + uint32 m_groupID; + bool m_Formed; }; #define sFormationMgr FormationMgr::instance() diff --git a/src/server/game/Entities/Creature/GossipDef.cpp b/src/server/game/Entities/Creature/GossipDef.cpp index 4703c31a5..29e1c2c82 100644 --- a/src/server/game/Entities/Creature/GossipDef.cpp +++ b/src/server/game/Entities/Creature/GossipDef.cpp @@ -160,7 +160,7 @@ void GossipMenu::ClearMenu() PlayerMenu::PlayerMenu(WorldSession* session) : _session(session) { - _gossipMenu.SetLocale(session->GetSessionDbLocaleIndex()); + _gossipMenu.SetLocale(session->GetSessionDbLocaleIndex()); } PlayerMenu::~PlayerMenu() @@ -179,7 +179,7 @@ void PlayerMenu::SendGossipMenu(uint32 titleTextId, uint64 objectGUID) const //ACE_Read_Guard lock1(_gossipMenu.GetLock()); //ACE_Read_Guard lock2(_questMenu.GetLock()); - WorldPacket data(SMSG_GOSSIP_MESSAGE, 24 + _gossipMenu.GetMenuItemCount()*100 + _questMenu.GetMenuItemCount()*75); // guess size + WorldPacket data(SMSG_GOSSIP_MESSAGE, 24 + _gossipMenu.GetMenuItemCount() * 100 + _questMenu.GetMenuItemCount() * 75); // guess size data << uint64(objectGUID); data << uint32(_gossipMenu.GetMenuId()); // new 2.4.0 data << uint32(titleTextId); @@ -198,7 +198,7 @@ void PlayerMenu::SendGossipMenu(uint32 titleTextId, uint64 objectGUID) const data << uint32(_questMenu.GetMenuItemCount()); // max count 0x20 uint32 count = 0; - + for (uint32 iI = 0; iI < _questMenu.GetMenuItemCount(); ++iI) { ++count; @@ -216,8 +216,8 @@ void PlayerMenu::SendGossipMenu(uint32 titleTextId, uint64 objectGUID) const int32 locale = _session->GetSessionDbLocaleIndex(); if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(questID)) ObjectMgr::GetLocaleString(localeData->Title, locale, title); - data << title; - } + data << title; + } } _session->SendPacket(&data); @@ -299,7 +299,7 @@ void QuestMenu::ClearMenu() void PlayerMenu::SendQuestGiverQuestList(QEmote const& eEmote, const std::string& Title, uint64 npcGUID) { - WorldPacket data(SMSG_QUESTGIVER_QUEST_LIST, 100 + _questMenu.GetMenuItemCount()*75); // guess size + WorldPacket data(SMSG_QUESTGIVER_QUEST_LIST, 100 + _questMenu.GetMenuItemCount() * 75); // guess size data << uint64(npcGUID); data << Title; data << uint32(eEmote._Delay); // player emote @@ -322,7 +322,7 @@ void PlayerMenu::SendQuestGiverQuestList(QEmote const& eEmote, const std::string int32 locale = _session->GetSessionDbLocaleIndex(); if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(questID)) ObjectMgr::GetLocaleString(localeData->Title, locale, title); - + data << uint32(questID); data << uint32(qmi.QuestIcon); data << int32(quest->GetQuestLevel()); @@ -353,12 +353,12 @@ void PlayerMenu::SendQuestGiverStatus(uint8 questStatus, uint64 npcGUID) const void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, bool activateAccept) const { - std::string questTitle = quest->GetTitle(); - std::string questDetails = quest->GetDetails(); - std::string questObjectives = quest->GetObjectives(); - std::string questAreaDescription = quest->GetAreaDescription(); + std::string questTitle = quest->GetTitle(); + std::string questDetails = quest->GetDetails(); + std::string questObjectives = quest->GetObjectives(); + std::string questAreaDescription = quest->GetAreaDescription(); - int32 locale = _session->GetSessionDbLocaleIndex(); + int32 locale = _session->GetSessionDbLocaleIndex(); if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle); @@ -366,7 +366,7 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, ObjectMgr::GetLocaleString(localeData->Objectives, locale, questObjectives); ObjectMgr::GetLocaleString(localeData->AreaDescription, locale, questAreaDescription); } - + WorldPacket data(SMSG_QUESTGIVER_QUEST_DETAILS, 500); // guess size data << uint64(npcGUID); data << uint64(_session->GetPlayer()->GetDivider()); @@ -389,7 +389,7 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, else { data << uint32(quest->GetRewChoiceItemsCount()); - for (uint32 i=0; i < QUEST_REWARD_CHOICES_COUNT; ++i) + for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i) { if (!quest->RewardChoiceItemId[i]) continue; @@ -405,7 +405,7 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, data << uint32(quest->GetRewItemsCount()); - for (uint32 i=0; i < QUEST_REWARDS_COUNT; ++i) + for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i) { if (!quest->RewardItemId[i]) continue; @@ -573,11 +573,11 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* quest) const data << uint32(0); // req source count? } - for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) - { - data << uint32(quest->RequiredItemId[i]); - data << uint32(quest->RequiredItemCount[i]); - } + for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) + { + data << uint32(quest->RequiredItemId[i]); + data << uint32(quest->RequiredItemCount[i]); + } for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) data << questObjectiveText[i]; @@ -590,16 +590,16 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* quest) const void PlayerMenu::SendQuestGiverOfferReward(Quest const* quest, uint64 npcGUID, bool enableNext) const { - std::string questTitle = quest->GetTitle(); + std::string questTitle = quest->GetTitle(); std::string RewardText = quest->GetOfferRewardText(); - int32 locale = _session->GetSessionDbLocaleIndex(); - if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) - ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle); + int32 locale = _session->GetSessionDbLocaleIndex(); + if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) + ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle); if (QuestOfferRewardLocale const* questOfferRewardLocale = sObjectMgr->GetQuestOfferRewardLocale(quest->GetQuestId())) ObjectMgr::GetLocaleString(questOfferRewardLocale->RewardText, locale, RewardText); - + WorldPacket data(SMSG_QUESTGIVER_OFFER_REWARD, 400); // guess size data << uint64(npcGUID); data << uint32(quest->GetQuestId()); @@ -626,7 +626,7 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* quest, uint64 npcGUID, b } data << uint32(quest->GetRewChoiceItemsCount()); - for (uint32 i=0; i < quest->GetRewChoiceItemsCount(); ++i) + for (uint32 i = 0; i < quest->GetRewChoiceItemsCount(); ++i) { data << uint32(quest->RewardChoiceItemId[i]); data << uint32(quest->RewardChoiceItemCount[i]); @@ -683,10 +683,10 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* quest, uint64 npcGUID, // We can always call to RequestItems, but this packet only goes out if there are actually // items. Otherwise, we'll skip straight to the OfferReward - std::string questTitle = quest->GetTitle(); - std::string requestItemsText = quest->GetRequestItemsText(); + std::string questTitle = quest->GetTitle(); + std::string requestItemsText = quest->GetRequestItemsText(); - int32 locale = _session->GetSessionDbLocaleIndex(); + int32 locale = _session->GetSessionDbLocaleIndex(); if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle); @@ -704,7 +704,7 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* quest, uint64 npcGUID, QuestStatusMap::iterator qsitr = _player->getQuestStatusMap().find(quest->GetQuestId()); if (qsitr != _player->getQuestStatusMap().end() && qsitr->second.Status == QUEST_STATUS_INCOMPLETE) { - for (uint8 i=0; i<6; ++i) + for (uint8 i = 0; i < 6; ++i) if (quest->RequiredItemId[i] && qsitr->second.ItemCount[i] < quest->RequiredItemCount[i]) if (_player->GetItemCount(quest->RequiredItemId[i], false) >= quest->RequiredItemCount[i]) qsitr->second.ItemCount[i] = quest->RequiredItemCount[i]; diff --git a/src/server/game/Entities/Creature/GossipDef.h b/src/server/game/Entities/Creature/GossipDef.h index fa4b71c42..5f940bdfe 100644 --- a/src/server/game/Entities/Creature/GossipDef.h +++ b/src/server/game/Entities/Creature/GossipDef.h @@ -147,132 +147,132 @@ typedef std::vector QuestMenuItemList; class GossipMenu { - public: - GossipMenu(); - ~GossipMenu(); +public: + GossipMenu(); + ~GossipMenu(); - void AddMenuItem(int32 menuItemId, uint8 icon, std::string const& message, uint32 sender, uint32 action, std::string const& boxMessage, uint32 boxMoney, bool coded = false); - void AddMenuItem(uint32 menuId, uint32 menuItemId, uint32 sender, uint32 action); - - void SetMenuId(uint32 menu_id) { _menuId = menu_id; } - uint32 GetMenuId() const { return _menuId; } - void SetLocale(LocaleConstant locale) { _locale = locale; } - LocaleConstant GetLocale() const { return _locale; } + void AddMenuItem(int32 menuItemId, uint8 icon, std::string const& message, uint32 sender, uint32 action, std::string const& boxMessage, uint32 boxMoney, bool coded = false); + void AddMenuItem(uint32 menuId, uint32 menuItemId, uint32 sender, uint32 action); - void AddGossipMenuItemData(uint32 menuItemId, uint32 gossipActionMenuId, uint32 gossipActionPoi); + void SetMenuId(uint32 menu_id) { _menuId = menu_id; } + uint32 GetMenuId() const { return _menuId; } + void SetLocale(LocaleConstant locale) { _locale = locale; } + LocaleConstant GetLocale() const { return _locale; } - uint32 GetMenuItemCount() const - { - return _menuItems.size(); - } + void AddGossipMenuItemData(uint32 menuItemId, uint32 gossipActionMenuId, uint32 gossipActionPoi); - bool Empty() const - { - return _menuItems.empty(); - } + uint32 GetMenuItemCount() const + { + return _menuItems.size(); + } - GossipMenuItem const* GetItem(uint32 id) const - { - GossipMenuItemContainer::const_iterator itr = _menuItems.find(id); - if (itr != _menuItems.end()) - return &itr->second; + bool Empty() const + { + return _menuItems.empty(); + } - return nullptr; - } + GossipMenuItem const* GetItem(uint32 id) const + { + GossipMenuItemContainer::const_iterator itr = _menuItems.find(id); + if (itr != _menuItems.end()) + return &itr->second; - GossipMenuItemData const* GetItemData(uint32 indexId) const - { - GossipMenuItemDataContainer::const_iterator itr = _menuItemData.find(indexId); - if (itr != _menuItemData.end()) - return &itr->second; + return nullptr; + } - return nullptr; - } + GossipMenuItemData const* GetItemData(uint32 indexId) const + { + GossipMenuItemDataContainer::const_iterator itr = _menuItemData.find(indexId); + if (itr != _menuItemData.end()) + return &itr->second; - uint32 GetMenuItemSender(uint32 menuItemId) const; - uint32 GetMenuItemAction(uint32 menuItemId) const; - bool IsMenuItemCoded(uint32 menuItemId) const; + return nullptr; + } - void ClearMenu(); + uint32 GetMenuItemSender(uint32 menuItemId) const; + uint32 GetMenuItemAction(uint32 menuItemId) const; + bool IsMenuItemCoded(uint32 menuItemId) const; - GossipMenuItemContainer const& GetMenuItems() const - { - return _menuItems; - } + void ClearMenu(); - private: - GossipMenuItemContainer _menuItems; - GossipMenuItemDataContainer _menuItemData; - uint32 _menuId; - LocaleConstant _locale; + GossipMenuItemContainer const& GetMenuItems() const + { + return _menuItems; + } + +private: + GossipMenuItemContainer _menuItems; + GossipMenuItemDataContainer _menuItemData; + uint32 _menuId; + LocaleConstant _locale; }; class QuestMenu { - public: - QuestMenu(); - ~QuestMenu(); +public: + QuestMenu(); + ~QuestMenu(); - void AddMenuItem(uint32 QuestId, uint8 Icon); - void ClearMenu(); + void AddMenuItem(uint32 QuestId, uint8 Icon); + void ClearMenu(); - uint8 GetMenuItemCount() const - { - return _questMenuItems.size(); - } + uint8 GetMenuItemCount() const + { + return _questMenuItems.size(); + } - bool Empty() const - { - return _questMenuItems.empty(); - } + bool Empty() const + { + return _questMenuItems.empty(); + } - bool HasItem(uint32 questId) const; + bool HasItem(uint32 questId) const; - QuestMenuItem const& GetItem(uint16 index) const - { - return _questMenuItems[index]; - } + QuestMenuItem const& GetItem(uint16 index) const + { + return _questMenuItems[index]; + } - private: - QuestMenuItemList _questMenuItems; +private: + QuestMenuItemList _questMenuItems; }; class PlayerMenu { - public: - explicit PlayerMenu(WorldSession* session); - ~PlayerMenu(); +public: + explicit PlayerMenu(WorldSession* session); + ~PlayerMenu(); - GossipMenu& GetGossipMenu() { return _gossipMenu; } - QuestMenu& GetQuestMenu() { return _questMenu; } + GossipMenu& GetGossipMenu() { return _gossipMenu; } + QuestMenu& GetQuestMenu() { return _questMenu; } - bool Empty() const { return _gossipMenu.Empty() && _questMenu.Empty(); } + bool Empty() const { return _gossipMenu.Empty() && _questMenu.Empty(); } - void ClearMenus(); - uint32 GetGossipOptionSender(uint32 selection) const { return _gossipMenu.GetMenuItemSender(selection); } - uint32 GetGossipOptionAction(uint32 selection) const { return _gossipMenu.GetMenuItemAction(selection); } - bool IsGossipOptionCoded(uint32 selection) const { return _gossipMenu.IsMenuItemCoded(selection); } + void ClearMenus(); + uint32 GetGossipOptionSender(uint32 selection) const { return _gossipMenu.GetMenuItemSender(selection); } + uint32 GetGossipOptionAction(uint32 selection) const { return _gossipMenu.GetMenuItemAction(selection); } + bool IsGossipOptionCoded(uint32 selection) const { return _gossipMenu.IsMenuItemCoded(selection); } - void SendGossipMenu(uint32 titleTextId, uint64 objectGUID) const; - void SendCloseGossip() const; - void SendPointOfInterest(uint32 poiId) const; + void SendGossipMenu(uint32 titleTextId, uint64 objectGUID) const; + void SendCloseGossip() const; + void SendPointOfInterest(uint32 poiId) const; - /*********************************************************/ - /*** QUEST SYSTEM ***/ - /*********************************************************/ - void SendQuestGiverStatus(uint8 questStatus, uint64 npcGUID) const; + /*********************************************************/ + /*** QUEST SYSTEM ***/ + /*********************************************************/ + void SendQuestGiverStatus(uint8 questStatus, uint64 npcGUID) const; - void SendQuestGiverQuestList(QEmote const& eEmote, const std::string& Title, uint64 npcGUID); + void SendQuestGiverQuestList(QEmote const& eEmote, const std::string& Title, uint64 npcGUID); - void SendQuestQueryResponse(Quest const* quest) const; - void SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, bool activateAccept) const; + void SendQuestQueryResponse(Quest const* quest) const; + void SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, bool activateAccept) const; - void SendQuestGiverOfferReward(Quest const* quest, uint64 npcGUID, bool enableNext) const; - void SendQuestGiverRequestItems(Quest const* quest, uint64 npcGUID, bool canComplete, bool closeOnCancel) const; + void SendQuestGiverOfferReward(Quest const* quest, uint64 npcGUID, bool enableNext) const; + void SendQuestGiverRequestItems(Quest const* quest, uint64 npcGUID, bool canComplete, bool closeOnCancel) const; - private: - GossipMenu _gossipMenu; - QuestMenu _questMenu; - WorldSession* _session; +private: + GossipMenu _gossipMenu; + QuestMenu _questMenu; + WorldSession* _session; }; #endif diff --git a/src/server/game/Entities/Creature/TemporarySummon.cpp b/src/server/game/Entities/Creature/TemporarySummon.cpp index 11dd0fa0e..9f4b0b4a5 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.cpp +++ b/src/server/game/Entities/Creature/TemporarySummon.cpp @@ -14,20 +14,20 @@ #include "ScriptMgr.h" TempSummon::TempSummon(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject) : -Creature(isWorldObject), m_Properties(properties), m_type(TEMPSUMMON_MANUAL_DESPAWN), -m_timer(0), m_lifetime(0) + Creature(isWorldObject), m_Properties(properties), m_type(TEMPSUMMON_MANUAL_DESPAWN), + m_timer(0), m_lifetime(0) { m_summonerGUID = owner; m_unitTypeMask |= UNIT_MASK_SUMMON; } Unit* TempSummon::GetSummoner() const -{ +{ return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : nullptr; } void TempSummon::Update(uint32 diff) -{ +{ Creature::Update(diff); if (m_deathState == DEAD) @@ -41,19 +41,6 @@ void TempSummon::Update(uint32 diff) case TEMPSUMMON_DESPAWNED: break; case TEMPSUMMON_TIMED_DESPAWN: - { - if (m_timer <= diff) - { - UnSummon(); - return; - } - - m_timer -= diff; - break; - } - case TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT: - { - if (!IsInCombat()) { if (m_timer <= diff) { @@ -62,81 +49,94 @@ void TempSummon::Update(uint32 diff) } m_timer -= diff; + break; } - else if (m_timer != m_lifetime) - m_timer = m_lifetime; + case TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT: + { + if (!IsInCombat()) + { + if (m_timer <= diff) + { + UnSummon(); + return; + } - break; - } + m_timer -= diff; + } + else if (m_timer != m_lifetime) + m_timer = m_lifetime; + + break; + } case TEMPSUMMON_CORPSE_TIMED_DESPAWN: - { - if (m_deathState == CORPSE) { - if (m_timer <= diff) + if (m_deathState == CORPSE) { - UnSummon(); - return; - } + if (m_timer <= diff) + { + UnSummon(); + return; + } - m_timer -= diff; + m_timer -= diff; + } + break; } - break; - } case TEMPSUMMON_CORPSE_DESPAWN: - { - // if m_deathState is DEAD, CORPSE was skipped - if (m_deathState == CORPSE) { - UnSummon(); - return; - } + // if m_deathState is DEAD, CORPSE was skipped + if (m_deathState == CORPSE) + { + UnSummon(); + return; + } - break; - } + break; + } case TEMPSUMMON_DEAD_DESPAWN: - { - break; - } + { + break; + } case TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN: - { - // if m_deathState is DEAD, CORPSE was skipped - if (m_deathState == CORPSE) { - UnSummon(); - return; - } + // if m_deathState is DEAD, CORPSE was skipped + if (m_deathState == CORPSE) + { + UnSummon(); + return; + } - if (!IsInCombat()) - { - if (m_timer <= diff) + if (!IsInCombat()) { - UnSummon(); - return; + if (m_timer <= diff) + { + UnSummon(); + return; + } + else + m_timer -= diff; } - else - m_timer -= diff; + else if (m_timer != m_lifetime) + m_timer = m_lifetime; + break; } - else if (m_timer != m_lifetime) - m_timer = m_lifetime; - break; - } case TEMPSUMMON_TIMED_OR_DEAD_DESPAWN: - { - if (!IsInCombat() && IsAlive()) { - if (m_timer <= diff) + if (!IsInCombat() && IsAlive()) { - UnSummon(); - return; + if (m_timer <= diff) + { + UnSummon(); + return; + } + else + m_timer -= diff; } - else - m_timer -= diff; + else if (m_timer != m_lifetime) + m_timer = m_lifetime; + break; } - else if (m_timer != m_lifetime) - m_timer = m_lifetime; - break; - } default: UnSummon(); sLog->outError("Temporary summoned creature (entry: %u) have unknown type %u of ", GetEntry(), m_type); @@ -145,7 +145,7 @@ void TempSummon::Update(uint32 diff) } void TempSummon::InitStats(uint32 duration) -{ +{ ASSERT(!IsPet()); Unit* owner = GetSummoner(); @@ -197,7 +197,7 @@ void TempSummon::InitStats(uint32 duration) } void TempSummon::InitSummon() -{ +{ Unit* owner = GetSummoner(); if (owner) { @@ -211,12 +211,12 @@ void TempSummon::InitSummon() } void TempSummon::SetTempSummonType(TempSummonType type) -{ +{ m_type = type; } void TempSummon::UnSummon(uint32 msTime) -{ +{ if (msTime) { ForcedUnsummonDelayEvent* pEvent = new ForcedUnsummonDelayEvent(*this); @@ -252,7 +252,7 @@ bool ForcedUnsummonDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) } void TempSummon::RemoveFromWorld() -{ +{ if (!IsInWorld()) return; @@ -269,7 +269,7 @@ void TempSummon::RemoveFromWorld() } Minion::Minion(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject) : TempSummon(properties, owner, isWorldObject) -, m_owner(owner) + , m_owner(owner) { ASSERT(m_owner); m_unitTypeMask |= UNIT_MASK_MINION; @@ -277,12 +277,12 @@ Minion::Minion(SummonPropertiesEntry const* properties, uint64 owner, bool isWor } void Minion::InitStats(uint32 duration) -{ +{ TempSummon::InitStats(duration); SetReactState(REACT_PASSIVE); - Unit *m_owner = GetOwner(); + Unit* m_owner = GetOwner(); SetCreatorGUID(m_owner->GetGUID()); setFaction(m_owner->getFaction()); @@ -290,11 +290,11 @@ void Minion::InitStats(uint32 duration) } void Minion::RemoveFromWorld() -{ +{ if (!IsInWorld()) return; - if (Unit *owner = GetOwner()) + if (Unit* owner = GetOwner()) owner->SetMinion(this, false); TempSummon::RemoveFromWorld(); @@ -306,12 +306,12 @@ Unit* Minion::GetOwner() const } bool Minion::IsGuardianPet() const -{ +{ return IsPet() || (m_Properties && m_Properties->Category == SUMMON_CATEGORY_PET); } void Minion::setDeathState(DeathState s, bool despawn) -{ +{ Creature::setDeathState(s, despawn); if (s == JUST_DIED && IsGuardianPet()) if (Unit* owner = GetOwner()) @@ -336,10 +336,10 @@ Guardian::Guardian(SummonPropertiesEntry const* properties, uint64 owner, bool i } void Guardian::InitStats(uint32 duration) -{ +{ Minion::InitStats(duration); - Unit *m_owner = GetOwner(); + Unit* m_owner = GetOwner(); InitStatsForLevel(m_owner->getLevel()); if (m_owner->GetTypeId() == TYPEID_PLAYER && HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN)) @@ -349,13 +349,13 @@ void Guardian::InitStats(uint32 duration) } void Guardian::InitSummon() -{ +{ TempSummon::InitSummon(); - Unit *m_owner = GetOwner(); + Unit* m_owner = GetOwner(); if (m_owner->GetTypeId() == TYPEID_PLAYER - && m_owner->GetMinionGUID() == GetGUID() - && !m_owner->GetCharmGUID()) + && m_owner->GetMinionGUID() == GetGUID() + && !m_owner->GetCharmGUID()) m_owner->ToPlayer()->CharmSpellInitialize(); } @@ -366,14 +366,14 @@ Puppet::Puppet(SummonPropertiesEntry const* properties, uint64 owner) : Minion(p } void Puppet::InitStats(uint32 duration) -{ +{ Minion::InitStats(duration); SetLevel(GetOwner()->getLevel()); SetReactState(REACT_PASSIVE); } void Puppet::InitSummon() -{ +{ Minion::InitSummon(); if (!SetCharmedBy(GetOwner(), CHARM_TYPE_POSSESS)) { @@ -388,7 +388,7 @@ void Puppet::InitSummon() } void Puppet::Update(uint32 time) -{ +{ Minion::Update(time); //check if caster is channelling? if (IsInWorld()) @@ -402,7 +402,7 @@ void Puppet::Update(uint32 time) } void Puppet::RemoveFromWorld() -{ +{ if (!IsInWorld()) return; diff --git a/src/server/game/Entities/Creature/TemporarySummon.h b/src/server/game/Entities/Creature/TemporarySummon.h index 555c1f2e0..a375248d7 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.h +++ b/src/server/game/Entities/Creature/TemporarySummon.h @@ -27,75 +27,75 @@ struct TempSummonData class TempSummon : public Creature { - public: - explicit TempSummon(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject); - virtual ~TempSummon() {} - void Update(uint32 time); - virtual void InitStats(uint32 lifetime); - virtual void InitSummon(); - virtual void UnSummon(uint32 msTime = 0); - void RemoveFromWorld(); - void SetTempSummonType(TempSummonType type); - void SaveToDB(uint32 /*mapid*/, uint8 /*spawnMask*/, uint32 /*phaseMask*/) {} - Unit* GetSummoner() const; - uint64 GetSummonerGUID() { return m_summonerGUID; } - TempSummonType const& GetSummonType() { return m_type; } - uint32 GetTimer() { return m_timer; } - void SetTimer(uint32 t) { m_timer = t; } +public: + explicit TempSummon(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject); + virtual ~TempSummon() {} + void Update(uint32 time); + virtual void InitStats(uint32 lifetime); + virtual void InitSummon(); + virtual void UnSummon(uint32 msTime = 0); + void RemoveFromWorld(); + void SetTempSummonType(TempSummonType type); + void SaveToDB(uint32 /*mapid*/, uint8 /*spawnMask*/, uint32 /*phaseMask*/) {} + Unit* GetSummoner() const; + uint64 GetSummonerGUID() { return m_summonerGUID; } + TempSummonType const& GetSummonType() { return m_type; } + uint32 GetTimer() { return m_timer; } + void SetTimer(uint32 t) { m_timer = t; } - const SummonPropertiesEntry* const m_Properties; - private: - TempSummonType m_type; - uint32 m_timer; - uint32 m_lifetime; - uint64 m_summonerGUID; + const SummonPropertiesEntry* const m_Properties; +private: + TempSummonType m_type; + uint32 m_timer; + uint32 m_lifetime; + uint64 m_summonerGUID; }; class Minion : public TempSummon { - public: - Minion(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject); - void InitStats(uint32 duration); - void RemoveFromWorld(); - Unit* GetOwner() const; - float GetFollowAngle() const { return m_followAngle; } - void SetFollowAngle(float angle) { m_followAngle = angle; } - bool IsPetGhoul() const {return GetEntry() == 26125 /*normal ghoul*/ || GetEntry() == 30230 /*Raise Ally ghoul*/;} // Ghoul may be guardian or pet - bool IsGuardianPet() const; - void setDeathState(DeathState s, bool despawn = false); // override virtual Unit::setDeathState - protected: - const uint64 m_owner; - float m_followAngle; +public: + Minion(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject); + void InitStats(uint32 duration); + void RemoveFromWorld(); + Unit* GetOwner() const; + float GetFollowAngle() const { return m_followAngle; } + void SetFollowAngle(float angle) { m_followAngle = angle; } + bool IsPetGhoul() const {return GetEntry() == 26125 /*normal ghoul*/ || GetEntry() == 30230 /*Raise Ally ghoul*/;} // Ghoul may be guardian or pet + bool IsGuardianPet() const; + void setDeathState(DeathState s, bool despawn = false); // override virtual Unit::setDeathState +protected: + const uint64 m_owner; + float m_followAngle; }; class Guardian : public Minion { - public: - Guardian(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject); - void InitStats(uint32 duration); - bool InitStatsForLevel(uint8 level); - void InitSummon(); +public: + Guardian(SummonPropertiesEntry const* properties, uint64 owner, bool isWorldObject); + void InitStats(uint32 duration); + bool InitStatsForLevel(uint8 level); + void InitSummon(); - bool UpdateStats(Stats stat); - bool UpdateAllStats(); - void UpdateArmor(); - void UpdateMaxHealth(); - void UpdateMaxPower(Powers power); - void UpdateAttackPowerAndDamage(bool ranged = false); - void UpdateDamagePhysical(WeaponAttackType attType); + bool UpdateStats(Stats stat); + bool UpdateAllStats(); + void UpdateArmor(); + void UpdateMaxHealth(); + void UpdateMaxPower(Powers power); + void UpdateAttackPowerAndDamage(bool ranged = false); + void UpdateDamagePhysical(WeaponAttackType attType); }; class Puppet : public Minion { - public: - Puppet(SummonPropertiesEntry const* properties, uint64 owner); - void InitStats(uint32 duration); - void InitSummon(); - void Update(uint32 time); - void RemoveFromWorld(); - protected: - Player* GetOwner() const; - const uint64 m_owner; +public: + Puppet(SummonPropertiesEntry const* properties, uint64 owner); + void InitStats(uint32 duration); + void InitSummon(); + void Update(uint32 time); + void RemoveFromWorld(); +protected: + Player* GetOwner() const; + const uint64 m_owner; }; class ForcedUnsummonDelayEvent : public BasicEvent diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.cpp b/src/server/game/Entities/DynamicObject/DynamicObject.cpp index 224568863..d1e6471fc 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.cpp +++ b/src/server/game/Entities/DynamicObject/DynamicObject.cpp @@ -35,7 +35,7 @@ DynamicObject::~DynamicObject() ASSERT(!_isViewpoint); delete _removedAura; } - + void DynamicObject::CleanupsBeforeDelete(bool finalCleanup /* = true */) { if (Transport* transport = GetTransport()) @@ -50,7 +50,7 @@ void DynamicObject::CleanupsBeforeDelete(bool finalCleanup /* = true */) } void DynamicObject::AddToWorld() -{ +{ ///- Register the dynamicObject for guid lookup and for caster if (!IsInWorld()) { @@ -61,7 +61,7 @@ void DynamicObject::AddToWorld() } void DynamicObject::RemoveFromWorld() -{ +{ ///- Remove the dynamicObject from the accessor and from all lists of objects in world if (IsInWorld()) { @@ -84,7 +84,7 @@ void DynamicObject::RemoveFromWorld() } bool DynamicObject::CreateDynamicObject(uint32 guidlow, Unit* caster, uint32 spellId, Position const& pos, float radius, DynamicObjectType type) -{ +{ SetMap(caster->GetMap()); Relocate(pos); if (!IsPositionValid()) @@ -122,7 +122,7 @@ bool DynamicObject::CreateDynamicObject(uint32 guidlow, Unit* caster, uint32 spe } void DynamicObject::Update(uint32 p_time) -{ +{ // caster has to be always available and in the same map ASSERT(_caster); ASSERT(_caster->GetMap() == GetMap()); @@ -153,7 +153,7 @@ void DynamicObject::Update(uint32 p_time) } void DynamicObject::Remove() -{ +{ if (IsInWorld()) { SendObjectDeSpawnAnim(GetGUID()); @@ -163,7 +163,7 @@ void DynamicObject::Remove() } int32 DynamicObject::GetDuration() const -{ +{ if (!_aura) return _duration; else @@ -171,7 +171,7 @@ int32 DynamicObject::GetDuration() const } void DynamicObject::SetDuration(int32 newDuration) -{ +{ if (!_aura) _duration = newDuration; else @@ -179,18 +179,18 @@ void DynamicObject::SetDuration(int32 newDuration) } void DynamicObject::Delay(int32 delaytime) -{ +{ SetDuration(GetDuration() - delaytime); } void DynamicObject::SetAura(Aura* aura) -{ +{ ASSERT(!_aura && aura); _aura = aura; } void DynamicObject::RemoveAura() -{ +{ ASSERT(_aura && !_removedAura); _removedAura = _aura; _aura = nullptr; @@ -199,7 +199,7 @@ void DynamicObject::RemoveAura() } void DynamicObject::SetCasterViewpoint() -{ +{ if (Player* caster = _caster->ToPlayer()) { caster->SetViewpoint(this, true); @@ -208,7 +208,7 @@ void DynamicObject::SetCasterViewpoint() } void DynamicObject::RemoveCasterViewpoint() -{ +{ if (Player* caster = _caster->ToPlayer()) { caster->SetViewpoint(this, false); @@ -217,7 +217,7 @@ void DynamicObject::RemoveCasterViewpoint() } void DynamicObject::BindToCaster() -{ +{ ASSERT(!_caster); _caster = ObjectAccessor::GetUnit(*this, GetCasterGUID()); ASSERT(_caster); @@ -226,7 +226,7 @@ void DynamicObject::BindToCaster() } void DynamicObject::UnbindFromCaster() -{ +{ ASSERT(_caster); _caster->_UnregisterDynObject(this); _caster = nullptr; diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.h b/src/server/game/Entities/DynamicObject/DynamicObject.h index 74dd471a5..6f5d6601e 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.h +++ b/src/server/game/Entities/DynamicObject/DynamicObject.h @@ -22,38 +22,38 @@ enum DynamicObjectType class DynamicObject : public WorldObject, public GridObject, public MovableMapObject { - public: - DynamicObject(bool isWorldObject); - ~DynamicObject(); +public: + DynamicObject(bool isWorldObject); + ~DynamicObject(); - void AddToWorld() override; - void RemoveFromWorld() override; - - void CleanupsBeforeDelete(bool finalCleanup = true) override; + void AddToWorld() override; + void RemoveFromWorld() override; - bool CreateDynamicObject(uint32 guidlow, Unit* caster, uint32 spellId, Position const& pos, float radius, DynamicObjectType type); - void Update(uint32 p_time) override; - void Remove(); - void SetDuration(int32 newDuration); - int32 GetDuration() const; - void Delay(int32 delaytime); - void SetAura(Aura* aura); - void RemoveAura(); - void SetCasterViewpoint(); - void RemoveCasterViewpoint(); - Unit* GetCaster() const { return _caster; } - void BindToCaster(); - void UnbindFromCaster(); - uint32 GetSpellId() const { return GetUInt32Value(DYNAMICOBJECT_SPELLID); } - uint64 GetCasterGUID() const { return GetUInt64Value(DYNAMICOBJECT_CASTER); } - float GetRadius() const { return GetFloatValue(DYNAMICOBJECT_RADIUS); } - bool IsViewpoint() const { return _isViewpoint; } + void CleanupsBeforeDelete(bool finalCleanup = true) override; - protected: - Aura* _aura; - Aura* _removedAura; - Unit* _caster; - int32 _duration; // for non-aura dynobjects - bool _isViewpoint; + bool CreateDynamicObject(uint32 guidlow, Unit* caster, uint32 spellId, Position const& pos, float radius, DynamicObjectType type); + void Update(uint32 p_time) override; + void Remove(); + void SetDuration(int32 newDuration); + int32 GetDuration() const; + void Delay(int32 delaytime); + void SetAura(Aura* aura); + void RemoveAura(); + void SetCasterViewpoint(); + void RemoveCasterViewpoint(); + Unit* GetCaster() const { return _caster; } + void BindToCaster(); + void UnbindFromCaster(); + uint32 GetSpellId() const { return GetUInt32Value(DYNAMICOBJECT_SPELLID); } + uint64 GetCasterGUID() const { return GetUInt64Value(DYNAMICOBJECT_CASTER); } + float GetRadius() const { return GetFloatValue(DYNAMICOBJECT_RADIUS); } + bool IsViewpoint() const { return _isViewpoint; } + +protected: + Aura* _aura; + Aura* _removedAura; + Unit* _caster; + int32 _duration; // for non-aura dynobjects + bool _isViewpoint; }; #endif diff --git a/src/server/game/Entities/GameObject/GameObject.cpp b/src/server/game/Entities/GameObject/GameObject.cpp index e1db5b910..a4f82ab1b 100644 --- a/src/server/game/Entities/GameObject/GameObject.cpp +++ b/src/server/game/Entities/GameObject/GameObject.cpp @@ -370,377 +370,377 @@ void GameObject::Update(uint32 diff) switch (m_lootState) { case GO_NOT_READY: - { - switch (GetGoType()) { - case GAMEOBJECT_TYPE_TRAP: + switch (GetGoType()) { - // Arming Time for GAMEOBJECT_TYPE_TRAP (6) - GameObjectTemplate const* goInfo = GetGOInfo(); - // Bombs - if (goInfo->trap.type == 2) - m_cooldownTime = World::GetGameTimeMS()+10*IN_MILLISECONDS; // Hardcoded tooltip value - else if (GetOwner()) - m_cooldownTime = World::GetGameTimeMS()+goInfo->trap.startDelay*IN_MILLISECONDS; - - m_lootState = GO_READY; - break; - } - case GAMEOBJECT_TYPE_FISHINGNODE: - { - // fishing code (bobber ready) - if (time(nullptr) > m_respawnTime - FISHING_BOBBER_READY_TIME) - { - // splash bobber (bobber ready now) - Unit* caster = GetOwner(); - if (caster && caster->GetTypeId() == TYPEID_PLAYER) + case GAMEOBJECT_TYPE_TRAP: { - SetGoState(GO_STATE_ACTIVE); - SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN); + // Arming Time for GAMEOBJECT_TYPE_TRAP (6) + GameObjectTemplate const* goInfo = GetGOInfo(); + // Bombs + if (goInfo->trap.type == 2) + m_cooldownTime = World::GetGameTimeMS() + 10 * IN_MILLISECONDS; // Hardcoded tooltip value + else if (GetOwner()) + m_cooldownTime = World::GetGameTimeMS() + goInfo->trap.startDelay * IN_MILLISECONDS; - UpdateData udata; - WorldPacket packet; - BuildValuesUpdateBlockForPlayer(&udata, caster->ToPlayer()); - udata.BuildPacket(&packet); - caster->ToPlayer()->GetSession()->SendPacket(&packet); - - SendCustomAnim(GetGoAnimProgress()); + m_lootState = GO_READY; + break; } - - m_lootState = GO_READY; // can be successfully open with some chance - } - return; - } - case GAMEOBJECT_TYPE_SUMMONING_RITUAL: - { - if (World::GetGameTimeMS() < m_cooldownTime) - return; - GameObjectTemplate const* info = GetGOInfo(); - if (info->summoningRitual.animSpell) - { - // xinef: if ritual requires animation, ensure that all users performs channel - CheckRitualList(); - } - if (GetUniqueUseCount() < info->summoningRitual.reqParticipants) - { - SetLootState(GO_READY); - return; - } - - bool triggered = info->summoningRitual.animSpell; - Unit* owner = GetOwner(); - Unit* spellCaster = owner ? owner : ObjectAccessor::GetPlayer(*this, MAKE_NEW_GUID(m_ritualOwnerGUIDLow, 0, HIGHGUID_PLAYER)); - if (!spellCaster) - { - SetLootState(GO_JUST_DEACTIVATED); - return; - } - - uint32 spellId = info->summoningRitual.spellId; - - if (spellId == 62330) // GO store nonexistent spell, replace by expected - { - // spell have reagent and mana cost but it not expected use its - // it triggered spell in fact casted at currently channeled GO - spellId = 61993; - triggered = true; - } - - // Cast casterTargetSpell at a random GO user - // on the current DB there is only one gameobject that uses this (Ritual of Doom) - // and its required target number is 1 (outter for loop will run once) - if (info->summoningRitual.casterTargetSpell && info->summoningRitual.casterTargetSpell != 1) // No idea why this field is a bool in some cases - for (uint32 i = 0; i < info->summoningRitual.casterTargetSpellTargets; i++) - // m_unique_users can contain only player GUIDs - if (Player* target = ObjectAccessor::GetPlayer(*this, acore::Containers::SelectRandomContainerElement(m_unique_users))) - spellCaster->CastSpell(target, info->summoningRitual.casterTargetSpell, true); - - // finish owners spell - // xinef: properly process event cooldowns - if (owner) - { - if (Spell* spell = owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) + case GAMEOBJECT_TYPE_FISHINGNODE: { - spell->SendChannelUpdate(0); - spell->finish(false); - } - } - - // can be deleted now - if (!info->summoningRitual.ritualPersistent) - SetLootState(GO_JUST_DEACTIVATED); - else - SetLootState(GO_READY); - - ClearRitualList(); - spellCaster->CastSpell(spellCaster, spellId, triggered); - return; - } - default: - m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY - break; - } - - // NO BREAK for switch (m_lootState) - [[fallthrough]]; - } - case GO_READY: - { - if (m_respawnTime > 0) // timer on - { - time_t now = time(nullptr); - if (m_respawnTime <= now) // timer expired - { - uint64 dbtableHighGuid = MAKE_NEW_GUID(m_DBTableGuid, GetEntry(), HIGHGUID_GAMEOBJECT); - time_t linkedRespawntime = GetMap()->GetLinkedRespawnTime(dbtableHighGuid); - if (linkedRespawntime) // Can't respawn, the master is dead - { - uint64 targetGuid = sObjectMgr->GetLinkedRespawnGuid(dbtableHighGuid); - if (targetGuid == dbtableHighGuid) // if linking self, never respawn (check delayed to next day) - SetRespawnTime(DAY); - else - m_respawnTime = (now > linkedRespawntime ? now : linkedRespawntime)+urand(5, MINUTE); // else copy time from master and add a little - SaveRespawnTime(); // also save to DB immediately - return; - } - - m_respawnTime = 0; - m_SkillupList.clear(); - m_usetimes = 0; - - switch (GetGoType()) - { - case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now - { - Unit* caster = GetOwner(); - if (caster && caster->GetTypeId() == TYPEID_PLAYER) + // fishing code (bobber ready) + if (time(nullptr) > m_respawnTime - FISHING_BOBBER_READY_TIME) { - caster->ToPlayer()->RemoveGameObject(this, false); + // splash bobber (bobber ready now) + Unit* caster = GetOwner(); + if (caster && caster->GetTypeId() == TYPEID_PLAYER) + { + SetGoState(GO_STATE_ACTIVE); + SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN); - WorldPacket data(SMSG_FISH_ESCAPED, 0); - caster->ToPlayer()->GetSession()->SendPacket(&data); + UpdateData udata; + WorldPacket packet; + BuildValuesUpdateBlockForPlayer(&udata, caster->ToPlayer()); + udata.BuildPacket(&packet); + caster->ToPlayer()->GetSession()->SendPacket(&packet); + + SendCustomAnim(GetGoAnimProgress()); + } + + m_lootState = GO_READY; // can be successfully open with some chance } - // can be delete - m_lootState = GO_JUST_DEACTIVATED; return; } - case GAMEOBJECT_TYPE_DOOR: - case GAMEOBJECT_TYPE_BUTTON: - //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds) - if (GetGoState() != GO_STATE_READY) - ResetDoorOrButton(); - break; - case GAMEOBJECT_TYPE_FISHINGHOLE: - // Initialize a new max fish count on respawn - m_goValue.FishingHole.MaxOpens = urand(GetGOInfo()->fishinghole.minSuccessOpens, GetGOInfo()->fishinghole.maxSuccessOpens); - break; - default: - break; - } - - if (!m_spawnedByDefault) // despawn timer - { - // can be despawned or destroyed - SetLootState(GO_JUST_DEACTIVATED); - return; - } - - // Xinef: Call AI Reset (required for example in SmartAI to clear one time events) - if (AI()) - AI()->Reset(); - - // respawn timer - uint32 poolid = GetDBTableGUIDLow() ? sPoolMgr->IsPartOfAPool(GetDBTableGUIDLow()) : 0; - if (poolid) - sPoolMgr->UpdatePool(poolid, GetDBTableGUIDLow()); - else - GetMap()->AddToMap(this); - } - } - - if (isSpawned()) - { - // traps can have time and can not have - GameObjectTemplate const* goInfo = GetGOInfo(); - if (goInfo->type == GAMEOBJECT_TYPE_TRAP) - { - if (World::GetGameTimeMS() < m_cooldownTime) - break; - - // Type 2 - Bomb (will go away after casting it's spell) - if (goInfo->trap.type == 2) - { - if (goInfo->trap.spellId) - CastSpell(nullptr, goInfo->trap.spellId); // FIXME: null target won't work for target type 1 - SetLootState(GO_JUST_DEACTIVATED); - break; - } - - // Type 0 despawns after being triggered, type 1 does not. - bool isBattlegroundTrap = false; - - /// @todo This is activation radius. Casting radius must be selected from spell data. - /// @todo Move activated state code to GO_ACTIVATED, in this place just check for activation and set state. - float radius = float(goInfo->trap.diameter) * 0.5f; - if (!goInfo->trap.diameter) - { - // Cast in other case (at some triggering/linked go/etc explicit call) - if (goInfo->trap.cooldown != 3 || m_respawnTime > 0) - break; - - // Battleground gameobjects have data2 == 0 && data5 == 3 - isBattlegroundTrap = true; - radius = 3.f; - } - - // Type 0 and 1 - trap (type 0 will not get removed after casting a spell) - Unit* owner = GetOwner(); - Unit* target = nullptr; // pointer to appropriate target if found any - - // Note: this hack with search required until GO casting not implemented - // search unfriendly creature - if (owner) // hunter trap - { - acore::AnyUnfriendlyNoTotemUnitInObjectRangeCheck checker(this, owner, radius); - acore::UnitSearcher searcher(this, target, checker); - VisitNearbyGridObject(radius, searcher); - if (!target) - VisitNearbyWorldObject(radius, searcher); - } - else // environmental trap - { - // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support - // affect only players - Player* player = nullptr; - acore::AnyPlayerInObjectRangeCheck checker(this, radius, true, true); - acore::PlayerSearcher searcher(this, player, checker); - VisitNearbyWorldObject(radius, searcher); - target = player; - } - - if (target) - { - // some traps do not have spell but should be triggered - if (goInfo->trap.spellId) - CastSpell(target, goInfo->trap.spellId); - - m_cooldownTime = World::GetGameTimeMS()+(goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4))*IN_MILLISECONDS; // template or 4 seconds - - if (goInfo->trap.type == 1) - SetLootState(GO_JUST_DEACTIVATED); - - if (isBattlegroundTrap && target->GetTypeId() == TYPEID_PLAYER) + case GAMEOBJECT_TYPE_SUMMONING_RITUAL: { - // battleground gameobjects case - if (target->ToPlayer()->InBattleground()) - if (Battleground* bg = target->ToPlayer()->GetBattleground()) - bg->HandleTriggerBuff(this); + if (World::GetGameTimeMS() < m_cooldownTime) + return; + GameObjectTemplate const* info = GetGOInfo(); + if (info->summoningRitual.animSpell) + { + // xinef: if ritual requires animation, ensure that all users performs channel + CheckRitualList(); + } + if (GetUniqueUseCount() < info->summoningRitual.reqParticipants) + { + SetLootState(GO_READY); + return; + } + + bool triggered = info->summoningRitual.animSpell; + Unit* owner = GetOwner(); + Unit* spellCaster = owner ? owner : ObjectAccessor::GetPlayer(*this, MAKE_NEW_GUID(m_ritualOwnerGUIDLow, 0, HIGHGUID_PLAYER)); + if (!spellCaster) + { + SetLootState(GO_JUST_DEACTIVATED); + return; + } + + uint32 spellId = info->summoningRitual.spellId; + + if (spellId == 62330) // GO store nonexistent spell, replace by expected + { + // spell have reagent and mana cost but it not expected use its + // it triggered spell in fact casted at currently channeled GO + spellId = 61993; + triggered = true; + } + + // Cast casterTargetSpell at a random GO user + // on the current DB there is only one gameobject that uses this (Ritual of Doom) + // and its required target number is 1 (outter for loop will run once) + if (info->summoningRitual.casterTargetSpell && info->summoningRitual.casterTargetSpell != 1) // No idea why this field is a bool in some cases + for (uint32 i = 0; i < info->summoningRitual.casterTargetSpellTargets; i++) + // m_unique_users can contain only player GUIDs + if (Player* target = ObjectAccessor::GetPlayer(*this, acore::Containers::SelectRandomContainerElement(m_unique_users))) + spellCaster->CastSpell(target, info->summoningRitual.casterTargetSpell, true); + + // finish owners spell + // xinef: properly process event cooldowns + if (owner) + { + if (Spell* spell = owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) + { + spell->SendChannelUpdate(0); + spell->finish(false); + } + } + + // can be deleted now + if (!info->summoningRitual.ritualPersistent) + SetLootState(GO_JUST_DEACTIVATED); + else + SetLootState(GO_READY); + + ClearRitualList(); + spellCaster->CastSpell(spellCaster, spellId, triggered); + return; } - } + default: + m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY + break; } - else if (uint32 max_charges = goInfo->GetCharges()) + + // NO BREAK for switch (m_lootState) + [[fallthrough]]; + } + case GO_READY: + { + if (m_respawnTime > 0) // timer on { - if (m_usetimes >= max_charges) + time_t now = time(nullptr); + if (m_respawnTime <= now) // timer expired { + uint64 dbtableHighGuid = MAKE_NEW_GUID(m_DBTableGuid, GetEntry(), HIGHGUID_GAMEOBJECT); + time_t linkedRespawntime = GetMap()->GetLinkedRespawnTime(dbtableHighGuid); + if (linkedRespawntime) // Can't respawn, the master is dead + { + uint64 targetGuid = sObjectMgr->GetLinkedRespawnGuid(dbtableHighGuid); + if (targetGuid == dbtableHighGuid) // if linking self, never respawn (check delayed to next day) + SetRespawnTime(DAY); + else + m_respawnTime = (now > linkedRespawntime ? now : linkedRespawntime) + urand(5, MINUTE); // else copy time from master and add a little + SaveRespawnTime(); // also save to DB immediately + return; + } + + m_respawnTime = 0; + m_SkillupList.clear(); m_usetimes = 0; - SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed + + switch (GetGoType()) + { + case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now + { + Unit* caster = GetOwner(); + if (caster && caster->GetTypeId() == TYPEID_PLAYER) + { + caster->ToPlayer()->RemoveGameObject(this, false); + + WorldPacket data(SMSG_FISH_ESCAPED, 0); + caster->ToPlayer()->GetSession()->SendPacket(&data); + } + // can be delete + m_lootState = GO_JUST_DEACTIVATED; + return; + } + case GAMEOBJECT_TYPE_DOOR: + case GAMEOBJECT_TYPE_BUTTON: + //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds) + if (GetGoState() != GO_STATE_READY) + ResetDoorOrButton(); + break; + case GAMEOBJECT_TYPE_FISHINGHOLE: + // Initialize a new max fish count on respawn + m_goValue.FishingHole.MaxOpens = urand(GetGOInfo()->fishinghole.minSuccessOpens, GetGOInfo()->fishinghole.maxSuccessOpens); + break; + default: + break; + } + + if (!m_spawnedByDefault) // despawn timer + { + // can be despawned or destroyed + SetLootState(GO_JUST_DEACTIVATED); + return; + } + + // Xinef: Call AI Reset (required for example in SmartAI to clear one time events) + if (AI()) + AI()->Reset(); + + // respawn timer + uint32 poolid = GetDBTableGUIDLow() ? sPoolMgr->IsPartOfAPool(GetDBTableGUIDLow()) : 0; + if (poolid) + sPoolMgr->UpdatePool(poolid, GetDBTableGUIDLow()); + else + GetMap()->AddToMap(this); } } - } - break; - } - case GO_ACTIVATED: - { - switch (GetGoType()) - { - case GAMEOBJECT_TYPE_DOOR: - case GAMEOBJECT_TYPE_BUTTON: - if (GetGOInfo()->GetAutoCloseTime() && World::GetGameTimeMS() >= m_cooldownTime) - ResetDoorOrButton(); - break; - case GAMEOBJECT_TYPE_GOOBER: - if (World::GetGameTimeMS() >= m_cooldownTime) + if (isSpawned()) + { + // traps can have time and can not have + GameObjectTemplate const* goInfo = GetGOInfo(); + if (goInfo->type == GAMEOBJECT_TYPE_TRAP) { - RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); + if (World::GetGameTimeMS() < m_cooldownTime) + break; - SetLootState(GO_JUST_DEACTIVATED); - } - break; - case GAMEOBJECT_TYPE_CHEST: - if (m_groupLootTimer) - { - if (m_groupLootTimer <= diff) + // Type 2 - Bomb (will go away after casting it's spell) + if (goInfo->trap.type == 2) { - Group* group = sGroupMgr->GetGroupByGUID(lootingGroupLowGUID); - if (group) - group->EndRoll(&loot, GetMap()); - m_groupLootTimer = 0; - lootingGroupLowGUID = 0; + if (goInfo->trap.spellId) + CastSpell(nullptr, goInfo->trap.spellId); // FIXME: null target won't work for target type 1 + SetLootState(GO_JUST_DEACTIVATED); + break; + } + + // Type 0 despawns after being triggered, type 1 does not. + bool isBattlegroundTrap = false; + + /// @todo This is activation radius. Casting radius must be selected from spell data. + /// @todo Move activated state code to GO_ACTIVATED, in this place just check for activation and set state. + float radius = float(goInfo->trap.diameter) * 0.5f; + if (!goInfo->trap.diameter) + { + // Cast in other case (at some triggering/linked go/etc explicit call) + if (goInfo->trap.cooldown != 3 || m_respawnTime > 0) + break; + + // Battleground gameobjects have data2 == 0 && data5 == 3 + isBattlegroundTrap = true; + radius = 3.f; + } + + // Type 0 and 1 - trap (type 0 will not get removed after casting a spell) + Unit* owner = GetOwner(); + Unit* target = nullptr; // pointer to appropriate target if found any + + // Note: this hack with search required until GO casting not implemented + // search unfriendly creature + if (owner) // hunter trap + { + acore::AnyUnfriendlyNoTotemUnitInObjectRangeCheck checker(this, owner, radius); + acore::UnitSearcher searcher(this, target, checker); + VisitNearbyGridObject(radius, searcher); + if (!target) + VisitNearbyWorldObject(radius, searcher); + } + else // environmental trap + { + // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support + // affect only players + Player* player = nullptr; + acore::AnyPlayerInObjectRangeCheck checker(this, radius, true, true); + acore::PlayerSearcher searcher(this, player, checker); + VisitNearbyWorldObject(radius, searcher); + target = player; + } + + if (target) + { + // some traps do not have spell but should be triggered + if (goInfo->trap.spellId) + CastSpell(target, goInfo->trap.spellId); + + m_cooldownTime = World::GetGameTimeMS() + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)) * IN_MILLISECONDS; // template or 4 seconds + + if (goInfo->trap.type == 1) + SetLootState(GO_JUST_DEACTIVATED); + + if (isBattlegroundTrap && target->GetTypeId() == TYPEID_PLAYER) + { + // battleground gameobjects case + if (target->ToPlayer()->InBattleground()) + if (Battleground* bg = target->ToPlayer()->GetBattleground()) + bg->HandleTriggerBuff(this); + } } - else m_groupLootTimer -= diff; } - default: - break; + else if (uint32 max_charges = goInfo->GetCharges()) + { + if (m_usetimes >= max_charges) + { + m_usetimes = 0; + SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed + } + } + } + + break; + } + case GO_ACTIVATED: + { + switch (GetGoType()) + { + case GAMEOBJECT_TYPE_DOOR: + case GAMEOBJECT_TYPE_BUTTON: + if (GetGOInfo()->GetAutoCloseTime() && World::GetGameTimeMS() >= m_cooldownTime) + ResetDoorOrButton(); + break; + case GAMEOBJECT_TYPE_GOOBER: + if (World::GetGameTimeMS() >= m_cooldownTime) + { + RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); + + SetLootState(GO_JUST_DEACTIVATED); + } + break; + case GAMEOBJECT_TYPE_CHEST: + if (m_groupLootTimer) + { + if (m_groupLootTimer <= diff) + { + Group* group = sGroupMgr->GetGroupByGUID(lootingGroupLowGUID); + if (group) + group->EndRoll(&loot, GetMap()); + m_groupLootTimer = 0; + lootingGroupLowGUID = 0; + } + else m_groupLootTimer -= diff; + } + default: + break; + } + break; } - break; - } case GO_JUST_DEACTIVATED: - { - //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed - if (GetGoType() == GAMEOBJECT_TYPE_GOOBER) { - SetGoState(GO_STATE_READY); + //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed + if (GetGoType() == GAMEOBJECT_TYPE_GOOBER) + { + SetGoState(GO_STATE_READY); - //any return here in case battleground traps - // Xinef: Do not return here for summoned gos that should be deleted few lines below - // Xinef: Battleground objects are treated as spawned by default - if (GameObjectTemplateAddon const* addon = GetTemplateAddon()) - if ((addon->flags & GO_FLAG_NODESPAWN) && isSpawnedByDefault()) - return; - } + //any return here in case battleground traps + // Xinef: Do not return here for summoned gos that should be deleted few lines below + // Xinef: Battleground objects are treated as spawned by default + if (GameObjectTemplateAddon const* addon = GetTemplateAddon()) + if ((addon->flags & GO_FLAG_NODESPAWN) && isSpawnedByDefault()) + return; + } - loot.clear(); + loot.clear(); - //! If this is summoned by a spell with ie. SPELL_EFFECT_SUMMON_OBJECT_WILD, with or without owner, we check respawn criteria based on spell - //! The GetOwnerGUID() check is mostly for compatibility with hacky scripts - 99% of the time summoning should be done trough spells. - if (GetSpellId() || GetOwnerGUID()) - { - SetRespawnTime(0); - Delete(); - return; - } + //! If this is summoned by a spell with ie. SPELL_EFFECT_SUMMON_OBJECT_WILD, with or without owner, we check respawn criteria based on spell + //! The GetOwnerGUID() check is mostly for compatibility with hacky scripts - 99% of the time summoning should be done trough spells. + if (GetSpellId() || GetOwnerGUID()) + { + SetRespawnTime(0); + Delete(); + return; + } - SetLootState(GO_READY); + SetLootState(GO_READY); - //burning flags in some battlegrounds, if you find better condition, just add it - if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0) - { - SendObjectDeSpawnAnim(GetGUID()); - //reset flags - if (GameObjectTemplateAddon const* addon = GetTemplateAddon()) - SetUInt32Value(GAMEOBJECT_FLAGS, addon->flags); - } + //burning flags in some battlegrounds, if you find better condition, just add it + if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0) + { + SendObjectDeSpawnAnim(GetGUID()); + //reset flags + if (GameObjectTemplateAddon const* addon = GetTemplateAddon()) + SetUInt32Value(GAMEOBJECT_FLAGS, addon->flags); + } - if (!m_respawnDelayTime) - return; + if (!m_respawnDelayTime) + return; + + if (!m_spawnedByDefault) + { + m_respawnTime = 0; + DestroyForNearbyPlayers(); // xinef: old UpdateObjectVisibility(); + return; + } + + m_respawnTime = time(nullptr) + m_respawnDelayTime; + + // if option not set then object will be saved at grid unload + if (GetMap()->IsDungeon()) + SaveRespawnTime(); - if (!m_spawnedByDefault) - { - m_respawnTime = 0; DestroyForNearbyPlayers(); // xinef: old UpdateObjectVisibility(); - return; + break; } - - m_respawnTime = time(nullptr) + m_respawnDelayTime; - - // if option not set then object will be saved at grid unload - if (GetMap()->IsDungeon()) - SaveRespawnTime(); - - DestroyForNearbyPlayers(); // xinef: old UpdateObjectVisibility(); - break; - } } sScriptMgr->OnGameObjectUpdate(this, diff); } @@ -1028,7 +1028,7 @@ Unit* GameObject::GetOwner() const } void GameObject::SaveRespawnTime() -{ +{ if (m_goData && m_goData->dbData && m_respawnTime > time(nullptr) && m_spawnedByDefault) GetMap()->SaveGORespawnTime(m_DBTableGuid, m_respawnTime); } @@ -1104,46 +1104,46 @@ bool GameObject::ActivateToQuest(Player* target) const switch (GetGoType()) { case GAMEOBJECT_TYPE_QUESTGIVER: - { - GameObject* go = const_cast(this); - QuestGiverStatus questStatus = target->GetQuestDialogStatus(go); - if (questStatus > DIALOG_STATUS_UNAVAILABLE) - return true; - break; - } - case GAMEOBJECT_TYPE_CHEST: - { - // scan GO chest with loot including quest items - if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), target)) { - //TODO: fix this hack - //look for battlegroundAV for some objects which are only activated after mine gots captured by own team - if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S) - if (Battleground* bg = target->GetBattleground()) - if (bg->GetBgTypeID(true) == BATTLEGROUND_AV && !bg->ToBattlegroundAV()->PlayerCanDoMineQuest(GetEntry(), target->GetTeamId())) - return false; - return true; + GameObject* go = const_cast(this); + QuestGiverStatus questStatus = target->GetQuestDialogStatus(go); + if (questStatus > DIALOG_STATUS_UNAVAILABLE) + return true; + break; + } + case GAMEOBJECT_TYPE_CHEST: + { + // scan GO chest with loot including quest items + if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), target)) + { + //TODO: fix this hack + //look for battlegroundAV for some objects which are only activated after mine gots captured by own team + if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S) + if (Battleground* bg = target->GetBattleground()) + if (bg->GetBgTypeID(true) == BATTLEGROUND_AV && !bg->ToBattlegroundAV()->PlayerCanDoMineQuest(GetEntry(), target->GetTeamId())) + return false; + return true; + } + break; } - break; - } case GAMEOBJECT_TYPE_GENERIC: - { - if (GetGOInfo()->_generic.questID == -1 || target->GetQuestStatus(GetGOInfo()->_generic.questID) == QUEST_STATUS_INCOMPLETE) - return true; - break; - } + { + if (GetGOInfo()->_generic.questID == -1 || target->GetQuestStatus(GetGOInfo()->_generic.questID) == QUEST_STATUS_INCOMPLETE) + return true; + break; + } case GAMEOBJECT_TYPE_SPELL_FOCUS: - { - if (GetGOInfo()->spellFocus.questID > 0 && target->GetQuestStatus(GetGOInfo()->spellFocus.questID) == QUEST_STATUS_INCOMPLETE) - return true; - break; - } + { + if (GetGOInfo()->spellFocus.questID > 0 && target->GetQuestStatus(GetGOInfo()->spellFocus.questID) == QUEST_STATUS_INCOMPLETE) + return true; + break; + } case GAMEOBJECT_TYPE_GOOBER: - { - if (GetGOInfo()->goober.questId == -1 || target->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE) - return true; - break; - } + { + if (GetGOInfo()->goober.questId == -1 || target->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE) + return true; + break; + } default: break; } @@ -1187,7 +1187,7 @@ void GameObject::TriggeringLinkedGameObject(uint32 trapEntry, Unit* target) } GameObject* GameObject::LookupFishingHoleAround(float range) -{ +{ GameObject* ok = nullptr; @@ -1223,7 +1223,7 @@ void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = f SwitchDoorOrButton(true, alternative); SetLootState(GO_ACTIVATED, user); - m_cooldownTime = World::GetGameTimeMS()+time_to_restore; + m_cooldownTime = World::GetGameTimeMS() + time_to_restore; } void GameObject::SetGoArtKit(uint8 kit) @@ -1293,7 +1293,7 @@ void GameObject::Use(Unit* user) if (World::GetGameTimeMS() < m_cooldownTime) return; - m_cooldownTime = World::GetGameTimeMS()+cooldown*IN_MILLISECONDS; + m_cooldownTime = World::GetGameTimeMS() + cooldown * IN_MILLISECONDS; } switch (GetGoType()) @@ -1311,526 +1311,526 @@ void GameObject::Use(Unit* user) TriggeringLinkedGameObject(trapEntry, user); return; case GAMEOBJECT_TYPE_QUESTGIVER: //2 - { - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - Player* player = user->ToPlayer(); - - player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID, true); - player->SendPreparedGossip(this); - return; - } - case GAMEOBJECT_TYPE_TRAP: //6 - { - GameObjectTemplate const* goInfo = GetGOInfo(); - if (goInfo->trap.spellId) - CastSpell(user, goInfo->trap.spellId); - - m_cooldownTime = World::GetGameTimeMS()+(goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4))*IN_MILLISECONDS; // template or 4 seconds - - if (goInfo->trap.type == 1) // Deactivate after trigger - SetLootState(GO_JUST_DEACTIVATED); - - return; - } - //Sitting: Wooden bench, chairs enzz - case GAMEOBJECT_TYPE_CHAIR: //7 - { - GameObjectTemplate const* info = GetGOInfo(); - if (!info) - return; - - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - if (ChairListSlots.empty()) // this is called once at first chair use to make list of available slots { - if (info->chair.slots > 0) // sometimes chairs in DB have error in fields and we dont know number of slots - for (uint32 i = 0; i < info->chair.slots; ++i) - ChairListSlots[i] = 0; // Last user of current slot set to 0 (none sit here yet) - else - ChairListSlots[0] = 0; // error in DB, make one default slot - } - - Player* player = user->ToPlayer(); - - // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one - - float lowestDist = DEFAULT_VISIBILITY_DISTANCE; - - uint32 nearest_slot = 0; - float x_lowest = GetPositionX(); - float y_lowest = GetPositionY(); - - // the object orientation + 1/2 pi - // every slot will be on that straight line - float orthogonalOrientation = GetOrientation()+M_PI*0.5f; - // find nearest slot - bool found_free_slot = false; - for (ChairSlotAndUser::iterator itr = ChairListSlots.begin(); itr != ChairListSlots.end(); ++itr) - { - // the distance between this slot and the center of the go - imagine a 1D space - float relativeDistance = (info->size*itr->first)-(info->size*(info->chair.slots-1)/2.0f); - - float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation); - float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation); - - if (itr->second) - { - if (Player* ChairUser = ObjectAccessor::GetPlayer(*this, itr->second)) - { - if (ChairUser->IsSitState() && ChairUser->getStandState() != UNIT_STAND_STATE_SIT && ChairUser->GetExactDist2d(x_i, y_i) < 0.1f) - continue; // This seat is already occupied by ChairUser. NOTE: Not sure if the ChairUser->getStandState() != UNIT_STAND_STATE_SIT check is required. - else - itr->second = 0; // This seat is unoccupied. - } - else - itr->second = 0; // The seat may of had an occupant, but they're offline. - } - - found_free_slot = true; - - // calculate the distance between the player and this slot - float thisDistance = player->GetDistance2d(x_i, y_i); - - if (thisDistance <= lowestDist) - { - nearest_slot = itr->first; - lowestDist = thisDistance; - x_lowest = x_i; - y_lowest = y_i; - } - } - - if (found_free_slot) - { - ChairSlotAndUser::iterator itr = ChairListSlots.find(nearest_slot); - if (itr != ChairListSlots.end()) - { - itr->second = player->GetGUID(); //this slot in now used by player - player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); - player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->chair.height); + if (user->GetTypeId() != TYPEID_PLAYER) return; - } - } - return; - } - //big gun, its a spell/aura - case GAMEOBJECT_TYPE_GOOBER: //10 - { - GameObjectTemplate const* info = GetGOInfo(); - - // xinef: Goober cannot be used with this flag, skip - if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE)) - return; - - if (user->GetTypeId() == TYPEID_PLAYER) - { Player* player = user->ToPlayer(); - if (info->goober.pageId) // show page... - { - WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8); - data << GetGUID(); - player->GetSession()->SendPacket(&data); - } - else if (info->goober.gossipID) - { - player->PrepareGossipMenu(this, info->goober.gossipID); - player->SendPreparedGossip(this); - } - - if (info->goober.eventId) - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_MAPSCRIPTS, "Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetDBTableGUIDLow()); -#endif - GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player, this); - EventInform(info->goober.eventId); - } - - // possible quest objective for active quests - if (info->goober.questId && sObjectMgr->GetQuestTemplate(info->goober.questId)) - { - //Quest require to be active for GO using - if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE) - break; - } - - if (Battleground* bg = player->GetBattleground()) - bg->EventPlayerUsedGO(player, this); - - player->KillCreditGO(info->entry, GetGUID()); + player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID, true); + player->SendPreparedGossip(this); + return; } - - if (uint32 trapEntry = info->goober.linkedTrapId) - TriggeringLinkedGameObject(trapEntry, user); - - if (info->GetAutoCloseTime()) + case GAMEOBJECT_TYPE_TRAP: //6 { - SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); - SetLootState(GO_ACTIVATED, user); - if (!info->goober.customAnim) - SetGoState(GO_STATE_ACTIVE); - } + GameObjectTemplate const* goInfo = GetGOInfo(); + if (goInfo->trap.spellId) + CastSpell(user, goInfo->trap.spellId); - // this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389) - if (info->goober.customAnim) - SendCustomAnim(GetGoAnimProgress()); + m_cooldownTime = World::GetGameTimeMS() + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)) * IN_MILLISECONDS; // template or 4 seconds - m_cooldownTime = World::GetGameTimeMS()+info->GetAutoCloseTime(); - - // cast this spell later if provided - spellId = info->goober.spellId; - spellCaster = user; - tmpfish = true; - - break; - } - case GAMEOBJECT_TYPE_CAMERA: //13 - { - GameObjectTemplate const* info = GetGOInfo(); - if (!info) - return; - - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - Player* player = user->ToPlayer(); - - if (info->camera.cinematicId) - player->SendCinematicStart(info->camera.cinematicId); - - if (info->camera.eventID) - GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player, this); - - return; - } - //fishing bobber - case GAMEOBJECT_TYPE_FISHINGNODE: //17 - { - Player* player = user->ToPlayer(); - if (!player) - return; - - if (player->GetGUID() != GetOwnerGUID()) - return; - - switch (getLootState()) - { - case GO_READY: // ready for loot - { - uint32 zone, subzone; - GetZoneAndAreaId(zone, subzone); - - int32 zone_skill = sObjectMgr->GetFishingBaseSkillLevel(subzone); - if (!zone_skill) - zone_skill = sObjectMgr->GetFishingBaseSkillLevel(zone); - - //provide error, no fishable zone or area should be 0 - if (!zone_skill) - sLog->outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.", subzone); - - int32 skill = player->GetSkillValue(SKILL_FISHING); - - int32 chance; - if (skill < zone_skill) - { - chance = int32(pow((double)skill/zone_skill, 2) * 100); - if (chance < 1) - chance = 1; - } - else - chance = 100; - - int32 roll = irand(1, 100); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug("Fishing check (skill: %i zone min skill: %i chance %i roll: %i", skill, zone_skill, chance, roll); -#endif - - // but you will likely cause junk in areas that require a high fishing skill (not yet implemented) - if (chance >= roll) - { - player->UpdateFishingSkill(); - - //TODO: I do not understand this hack. Need some explanation. - // prevent removing GO at spell cancel - RemoveFromOwner(); - SetOwnerGUID(player->GetGUID()); - SetSpellId(0); // prevent removing unintended auras at Unit::RemoveGameObject - - //TODO: find reasonable value for fishing hole search - GameObject* ok = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); - if (ok) - { - ok->Use(player); - SetLootState(GO_JUST_DEACTIVATED); - } - else - player->SendLoot(GetGUID(), LOOT_FISHING); - } - else // else: junk - player->SendLoot(GetGUID(), LOOT_FISHING_JUNK); - - tmpfish = true; - break; - } - case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update - break; - default: - { + if (goInfo->trap.type == 1) // Deactivate after trigger SetLootState(GO_JUST_DEACTIVATED); - WorldPacket data(SMSG_FISH_NOT_HOOKED, 0); - player->GetSession()->SendPacket(&data); - break; - } + return; } + //Sitting: Wooden bench, chairs enzz + case GAMEOBJECT_TYPE_CHAIR: //7 + { + GameObjectTemplate const* info = GetGOInfo(); + if (!info) + return; - if(tmpfish) - player->FinishSpell(CURRENT_CHANNELED_SPELL, true); - else - player->InterruptSpell(CURRENT_CHANNELED_SPELL, true, true, true); - return; - } + if (user->GetTypeId() != TYPEID_PLAYER) + return; + + if (ChairListSlots.empty()) // this is called once at first chair use to make list of available slots + { + if (info->chair.slots > 0) // sometimes chairs in DB have error in fields and we dont know number of slots + for (uint32 i = 0; i < info->chair.slots; ++i) + ChairListSlots[i] = 0; // Last user of current slot set to 0 (none sit here yet) + else + ChairListSlots[0] = 0; // error in DB, make one default slot + } + + Player* player = user->ToPlayer(); + + // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one + + float lowestDist = DEFAULT_VISIBILITY_DISTANCE; + + uint32 nearest_slot = 0; + float x_lowest = GetPositionX(); + float y_lowest = GetPositionY(); + + // the object orientation + 1/2 pi + // every slot will be on that straight line + float orthogonalOrientation = GetOrientation() + M_PI * 0.5f; + // find nearest slot + bool found_free_slot = false; + for (ChairSlotAndUser::iterator itr = ChairListSlots.begin(); itr != ChairListSlots.end(); ++itr) + { + // the distance between this slot and the center of the go - imagine a 1D space + float relativeDistance = (info->size * itr->first) - (info->size * (info->chair.slots - 1) / 2.0f); + + float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation); + float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation); + + if (itr->second) + { + if (Player* ChairUser = ObjectAccessor::GetPlayer(*this, itr->second)) + { + if (ChairUser->IsSitState() && ChairUser->getStandState() != UNIT_STAND_STATE_SIT && ChairUser->GetExactDist2d(x_i, y_i) < 0.1f) + continue; // This seat is already occupied by ChairUser. NOTE: Not sure if the ChairUser->getStandState() != UNIT_STAND_STATE_SIT check is required. + else + itr->second = 0; // This seat is unoccupied. + } + else + itr->second = 0; // The seat may of had an occupant, but they're offline. + } + + found_free_slot = true; + + // calculate the distance between the player and this slot + float thisDistance = player->GetDistance2d(x_i, y_i); + + if (thisDistance <= lowestDist) + { + nearest_slot = itr->first; + lowestDist = thisDistance; + x_lowest = x_i; + y_lowest = y_i; + } + } + + if (found_free_slot) + { + ChairSlotAndUser::iterator itr = ChairListSlots.find(nearest_slot); + if (itr != ChairListSlots.end()) + { + itr->second = player->GetGUID(); //this slot in now used by player + player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); + player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR + info->chair.height); + return; + } + } + + return; + } + //big gun, its a spell/aura + case GAMEOBJECT_TYPE_GOOBER: //10 + { + GameObjectTemplate const* info = GetGOInfo(); + + // xinef: Goober cannot be used with this flag, skip + if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE)) + return; + + if (user->GetTypeId() == TYPEID_PLAYER) + { + Player* player = user->ToPlayer(); + + if (info->goober.pageId) // show page... + { + WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8); + data << GetGUID(); + player->GetSession()->SendPacket(&data); + } + else if (info->goober.gossipID) + { + player->PrepareGossipMenu(this, info->goober.gossipID); + player->SendPreparedGossip(this); + } + + if (info->goober.eventId) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_MAPSCRIPTS, "Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetDBTableGUIDLow()); +#endif + GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player, this); + EventInform(info->goober.eventId); + } + + // possible quest objective for active quests + if (info->goober.questId && sObjectMgr->GetQuestTemplate(info->goober.questId)) + { + //Quest require to be active for GO using + if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE) + break; + } + + if (Battleground* bg = player->GetBattleground()) + bg->EventPlayerUsedGO(player, this); + + player->KillCreditGO(info->entry, GetGUID()); + } + + if (uint32 trapEntry = info->goober.linkedTrapId) + TriggeringLinkedGameObject(trapEntry, user); + + if (info->GetAutoCloseTime()) + { + SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); + SetLootState(GO_ACTIVATED, user); + if (!info->goober.customAnim) + SetGoState(GO_STATE_ACTIVE); + } + + // this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389) + if (info->goober.customAnim) + SendCustomAnim(GetGoAnimProgress()); + + m_cooldownTime = World::GetGameTimeMS() + info->GetAutoCloseTime(); + + // cast this spell later if provided + spellId = info->goober.spellId; + spellCaster = user; + tmpfish = true; + + break; + } + case GAMEOBJECT_TYPE_CAMERA: //13 + { + GameObjectTemplate const* info = GetGOInfo(); + if (!info) + return; + + if (user->GetTypeId() != TYPEID_PLAYER) + return; + + Player* player = user->ToPlayer(); + + if (info->camera.cinematicId) + player->SendCinematicStart(info->camera.cinematicId); + + if (info->camera.eventID) + GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player, this); + + return; + } + //fishing bobber + case GAMEOBJECT_TYPE_FISHINGNODE: //17 + { + Player* player = user->ToPlayer(); + if (!player) + return; + + if (player->GetGUID() != GetOwnerGUID()) + return; + + switch (getLootState()) + { + case GO_READY: // ready for loot + { + uint32 zone, subzone; + GetZoneAndAreaId(zone, subzone); + + int32 zone_skill = sObjectMgr->GetFishingBaseSkillLevel(subzone); + if (!zone_skill) + zone_skill = sObjectMgr->GetFishingBaseSkillLevel(zone); + + //provide error, no fishable zone or area should be 0 + if (!zone_skill) + sLog->outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.", subzone); + + int32 skill = player->GetSkillValue(SKILL_FISHING); + + int32 chance; + if (skill < zone_skill) + { + chance = int32(pow((double)skill / zone_skill, 2) * 100); + if (chance < 1) + chance = 1; + } + else + chance = 100; + + int32 roll = irand(1, 100); + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outStaticDebug("Fishing check (skill: %i zone min skill: %i chance %i roll: %i", skill, zone_skill, chance, roll); +#endif + + // but you will likely cause junk in areas that require a high fishing skill (not yet implemented) + if (chance >= roll) + { + player->UpdateFishingSkill(); + + //TODO: I do not understand this hack. Need some explanation. + // prevent removing GO at spell cancel + RemoveFromOwner(); + SetOwnerGUID(player->GetGUID()); + SetSpellId(0); // prevent removing unintended auras at Unit::RemoveGameObject + + //TODO: find reasonable value for fishing hole search + GameObject* ok = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); + if (ok) + { + ok->Use(player); + SetLootState(GO_JUST_DEACTIVATED); + } + else + player->SendLoot(GetGUID(), LOOT_FISHING); + } + else // else: junk + player->SendLoot(GetGUID(), LOOT_FISHING_JUNK); + + tmpfish = true; + break; + } + case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update + break; + default: + { + SetLootState(GO_JUST_DEACTIVATED); + + WorldPacket data(SMSG_FISH_NOT_HOOKED, 0); + player->GetSession()->SendPacket(&data); + break; + } + } + + if(tmpfish) + player->FinishSpell(CURRENT_CHANNELED_SPELL, true); + else + player->InterruptSpell(CURRENT_CHANNELED_SPELL, true, true, true); + return; + } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18 - { - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - Player* player = user->ToPlayer(); - Unit* owner = GetOwner(); - GameObjectTemplate const* info = GetGOInfo(); - - // ritual owner is set for GO's without owner (not summoned) - if (m_ritualOwnerGUIDLow == 0 && !owner) - m_ritualOwnerGUIDLow = player->GetGUIDLow(); - - if (owner) { - if (owner->GetTypeId() != TYPEID_PLAYER) + if (user->GetTypeId() != TYPEID_PLAYER) return; - // accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect) - if (player == owner->ToPlayer() || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(owner->ToPlayer()))) - return; + Player* player = user->ToPlayer(); + Unit* owner = GetOwner(); + GameObjectTemplate const* info = GetGOInfo(); - // expect owner to already be channeling, so if not... - if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) - return; - } - else - { - Player* ritualOwner = ObjectAccessor::GetPlayer(*this, MAKE_NEW_GUID(m_ritualOwnerGUIDLow, 0, HIGHGUID_PLAYER)); - if (!ritualOwner) - return; - if (player != ritualOwner && (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(ritualOwner))) - return; - } + // ritual owner is set for GO's without owner (not summoned) + if (m_ritualOwnerGUIDLow == 0 && !owner) + m_ritualOwnerGUIDLow = player->GetGUIDLow(); - if (info->summoningRitual.animSpell) - { - // xinef: if ritual requires animation, ensure that all users performs channel - CheckRitualList(); + if (owner) + { + if (owner->GetTypeId() != TYPEID_PLAYER) + return; - // xinef: all participants found + // accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect) + if (player == owner->ToPlayer() || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(owner->ToPlayer()))) + return; + + // expect owner to already be channeling, so if not... + if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) + return; + } + else + { + Player* ritualOwner = ObjectAccessor::GetPlayer(*this, MAKE_NEW_GUID(m_ritualOwnerGUIDLow, 0, HIGHGUID_PLAYER)); + if (!ritualOwner) + return; + if (player != ritualOwner && (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(ritualOwner))) + return; + } + + if (info->summoningRitual.animSpell) + { + // xinef: if ritual requires animation, ensure that all users performs channel + CheckRitualList(); + + // xinef: all participants found + if (GetUniqueUseCount() == info->summoningRitual.reqParticipants) + return; + + player->CastSpell(player, info->summoningRitual.animSpell, true); + } + + AddUniqueUse(player); + + // full amount unique participants including original summoner if (GetUniqueUseCount() == info->summoningRitual.reqParticipants) - return; + { + SetLootState(GO_NOT_READY); + // can be deleted now, if + if (!info->summoningRitual.animSpell) + m_cooldownTime = 0; + else // channel ready, maintain this + m_cooldownTime = World::GetGameTimeMS() + 5 * IN_MILLISECONDS; + } - player->CastSpell(player, info->summoningRitual.animSpell, true); + return; } - - AddUniqueUse(player); - - // full amount unique participants including original summoner - if (GetUniqueUseCount() == info->summoningRitual.reqParticipants) - { - SetLootState(GO_NOT_READY); - // can be deleted now, if - if (!info->summoningRitual.animSpell) - m_cooldownTime = 0; - else // channel ready, maintain this - m_cooldownTime = World::GetGameTimeMS()+5*IN_MILLISECONDS; - } - - return; - } case GAMEOBJECT_TYPE_SPELLCASTER: //22 - { - GameObjectTemplate const* info = GetGOInfo(); - if (!info) - return; - - if (info->spellcaster.partyOnly) { - Player const* caster = ObjectAccessor::GetObjectInOrOutOfWorld(GetOwnerGUID(), (Player*)NULL); - if (!caster || user->GetTypeId() != TYPEID_PLAYER || !user->ToPlayer()->IsInSameRaidWith(caster)) + GameObjectTemplate const* info = GetGOInfo(); + if (!info) return; + + if (info->spellcaster.partyOnly) + { + Player const* caster = ObjectAccessor::GetObjectInOrOutOfWorld(GetOwnerGUID(), (Player*)NULL); + if (!caster || user->GetTypeId() != TYPEID_PLAYER || !user->ToPlayer()->IsInSameRaidWith(caster)) + return; + } + + user->RemoveAurasByType(SPELL_AURA_MOUNTED); + spellId = info->spellcaster.spellId; + + AddUse(); + break; } - - user->RemoveAurasByType(SPELL_AURA_MOUNTED); - spellId = info->spellcaster.spellId; - - AddUse(); - break; - } case GAMEOBJECT_TYPE_MEETINGSTONE: //23 - { - GameObjectTemplate const* info = GetGOInfo(); + { + GameObjectTemplate const* info = GetGOInfo(); - if (user->GetTypeId() != TYPEID_PLAYER) - return; + if (user->GetTypeId() != TYPEID_PLAYER) + return; - Player* player = user->ToPlayer(); + Player* player = user->ToPlayer(); - Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetTarget()); + Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetTarget()); - // accept only use by player from same raid as caster, except caster itself - if (!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameRaidWith(player)) - return; + // accept only use by player from same raid as caster, except caster itself + if (!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameRaidWith(player)) + return; - //required lvl checks! - uint8 level = player->getLevel(); - if (level < info->meetingstone.minLevel) - return; - level = targetPlayer->getLevel(); - if (level < info->meetingstone.minLevel) - return; + //required lvl checks! + uint8 level = player->getLevel(); + if (level < info->meetingstone.minLevel) + return; + level = targetPlayer->getLevel(); + if (level < info->meetingstone.minLevel) + return; - if (info->entry == 194097) - spellId = 61994; // Ritual of Summoning - else - spellId = 59782; // Summoning Stone Effect + if (info->entry == 194097) + spellId = 61994; // Ritual of Summoning + else + spellId = 59782; // Summoning Stone Effect - break; - } + break; + } case GAMEOBJECT_TYPE_FLAGSTAND: // 24 - { - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - Player* player = user->ToPlayer(); - - if (player->CanUseBattlegroundObject(this)) { - // in battleground check - Battleground* bg = player->GetBattleground(); - if (!bg) + if (user->GetTypeId() != TYPEID_PLAYER) return; - if (player->GetVehicle()) - return; + Player* player = user->ToPlayer(); - player->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); - player->RemoveAurasByType(SPELL_AURA_MOD_INVISIBILITY); - // BG flag click - // AB: - // 15001 - // 15002 - // 15003 - // 15004 - // 15005 - bg->EventPlayerClickedOnFlag(player, this); - return; //we don;t need to delete flag ... it is despawned! + if (player->CanUseBattlegroundObject(this)) + { + // in battleground check + Battleground* bg = player->GetBattleground(); + if (!bg) + return; + + if (player->GetVehicle()) + return; + + player->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); + player->RemoveAurasByType(SPELL_AURA_MOD_INVISIBILITY); + // BG flag click + // AB: + // 15001 + // 15002 + // 15003 + // 15004 + // 15005 + bg->EventPlayerClickedOnFlag(player, this); + return; //we don;t need to delete flag ... it is despawned! + } + break; } - break; - } case GAMEOBJECT_TYPE_FISHINGHOLE: // 25 - { - if (user->GetTypeId() != TYPEID_PLAYER) + { + if (user->GetTypeId() != TYPEID_PLAYER) + return; + + Player* player = user->ToPlayer(); + + player->SendLoot(GetGUID(), LOOT_FISHINGHOLE); + player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, GetGOInfo()->entry); return; - - Player* player = user->ToPlayer(); - - player->SendLoot(GetGUID(), LOOT_FISHINGHOLE); - player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, GetGOInfo()->entry); - return; - } + } case GAMEOBJECT_TYPE_FLAGDROP: // 26 - { - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - Player* player = user->ToPlayer(); - - if (player->CanUseBattlegroundObject(this)) { - // in battleground check - Battleground* bg = player->GetBattleground(); - if (!bg) + if (user->GetTypeId() != TYPEID_PLAYER) return; - if (player->GetVehicle()) - return; + Player* player = user->ToPlayer(); - player->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); - player->RemoveAurasByType(SPELL_AURA_MOD_INVISIBILITY); - // BG flag dropped - // WS: - // 179785 - Silverwing Flag - // 179786 - Warsong Flag - // EotS: - // 184142 - Netherstorm Flag - GameObjectTemplate const* info = GetGOInfo(); - if (info) + if (player->CanUseBattlegroundObject(this)) { - if (GameObject::gameObjectToEventFlag.find(info->entry) != GameObject::gameObjectToEventFlag.end()) + // in battleground check + Battleground* bg = player->GetBattleground(); + if (!bg) + return; + + if (player->GetVehicle()) + return; + + player->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); + player->RemoveAurasByType(SPELL_AURA_MOD_INVISIBILITY); + // BG flag dropped + // WS: + // 179785 - Silverwing Flag + // 179786 - Warsong Flag + // EotS: + // 184142 - Netherstorm Flag + GameObjectTemplate const* info = GetGOInfo(); + if (info) { - GameObject::gameObjectToEventFlag[info->entry](player, this, bg); - } - else - { - switch (info->entry) + if (GameObject::gameObjectToEventFlag.find(info->entry) != GameObject::gameObjectToEventFlag.end()) { - case 179785: // Silverwing Flag - case 179786: // Warsong Flag - if (bg->GetBgTypeID(true) == BATTLEGROUND_WS) - bg->EventPlayerClickedOnFlag(player, this); - break; - case 184142: // Netherstorm Flag - if (bg->GetBgTypeID(true) == BATTLEGROUND_EY) - bg->EventPlayerClickedOnFlag(player, this); - break; + GameObject::gameObjectToEventFlag[info->entry](player, this, bg); + } + else + { + switch (info->entry) + { + case 179785: // Silverwing Flag + case 179786: // Warsong Flag + if (bg->GetBgTypeID(true) == BATTLEGROUND_WS) + bg->EventPlayerClickedOnFlag(player, this); + break; + case 184142: // Netherstorm Flag + if (bg->GetBgTypeID(true) == BATTLEGROUND_EY) + bg->EventPlayerClickedOnFlag(player, this); + break; + } } } + //this cause to call return, all flags must be deleted here!! + spellId = 0; + Delete(); } - //this cause to call return, all flags must be deleted here!! - spellId = 0; - Delete(); + break; } - break; - } case GAMEOBJECT_TYPE_BARBER_CHAIR: //32 - { - GameObjectTemplate const* info = GetGOInfo(); - if (!info) + { + GameObjectTemplate const* info = GetGOInfo(); + if (!info) + return; + + if (user->GetTypeId() != TYPEID_PLAYER) + return; + + Player* player = user->ToPlayer(); + + // fallback, will always work + player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); + + WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0); + player->GetSession()->SendPacket(&data); + + player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR + info->barberChair.chairheight); return; - - if (user->GetTypeId() != TYPEID_PLAYER) - return; - - Player* player = user->ToPlayer(); - - // fallback, will always work - player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(), TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); - - WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0); - player->GetSession()->SendPacket(&data); - - player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight); - return; - } + } default: if (GetGoType() >= MAX_GAMEOBJECT_TYPE) sLog->outError("GameObject::Use(): unit (type: %u, guid: %u, name: %s) tries to use object (guid: %u, entry: %u, name: %s) of unknown type (%u)", - user->GetTypeId(), user->GetGUIDLow(), user->GetName().c_str(), GetGUIDLow(), GetEntry(), GetGOInfo()->name.c_str(), GetGoType()); + user->GetTypeId(), user->GetGUIDLow(), user->GetName().c_str(), GetGUIDLow(), GetEntry(), GetGOInfo()->name.c_str(), GetGoType()); break; } @@ -1920,7 +1920,7 @@ void GameObject::CastSpell(Unit* target, uint32 spellId) void GameObject::SendCustomAnim(uint32 anim) { - WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM, 8+4); + WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM, 8 + 4); data << GetGUID(); data << uint32(anim); SendMessageToSet(&data, true); @@ -1937,7 +1937,7 @@ bool GameObject::IsInRange(float x, float y, float z, float radius) const float dx = x - GetPositionX(); float dy = y - GetPositionY(); float dz = z - GetPositionZ(); - float dist = sqrt(dx*dx + dy*dy); + float dist = sqrt(dx * dx + dy * dy); //! Check if the distance between the 2 objects is 0, can happen if both objects are on the same position. //! The code below this check wont crash if dist is 0 because 0/0 in float operations is valid, and returns infinite if (G3D::fuzzyEq(dist, 0.0f)) @@ -1948,9 +1948,9 @@ bool GameObject::IsInRange(float x, float y, float z, float radius) const float cosB = dy / dist; dx = dist * (cosA * cosB + sinA * sinB); dy = dist * (cosA * sinB - sinA * cosB); - return dx < (info->maxX*scale) + radius && dx > (info->minX*scale) - radius - && dy < (info->maxY*scale) + radius && dy > (info->minY*scale) - radius - && dz < (info->maxZ*scale) + radius && dz > (info->minZ*scale) - radius; + return dx < (info->maxX * scale) + radius && dx > (info->minX * scale) - radius + && dy < (info->maxY * scale) + radius && dy > (info->minY * scale) - radius + && dz < (info->maxZ * scale) + radius && dz > (info->minZ * scale) - radius; } // pussywizard! @@ -2065,7 +2065,7 @@ void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= NULL*/, u data.appendPackGUID(attackerOrHealer->GetGUID()); data.appendPackGUID(player->GetGUID()); data << uint32(-change); // change < 0 triggers SPELL_BUILDING_HEAL combat log event - // change >= 0 triggers SPELL_BUILDING_DAMAGE event + // change >= 0 triggers SPELL_BUILDING_DAMAGE event data << uint32(spellId); player->GetSession()->SendPacket(&data); } @@ -2103,89 +2103,89 @@ void GameObject::SetDestructibleState(GameObjectDestructibleState state, Player* EnableCollision(true); break; case GO_DESTRUCTIBLE_DAMAGED: - { -#ifdef ELUNA - sEluna->OnDamaged(this, eventInvoker); -#endif - EventInform(m_goInfo->building.damagedEvent); - sScriptMgr->OnGameObjectDamaged(this, eventInvoker); - if (BattlegroundMap* bgMap = GetMap()->ToBattlegroundMap()) - if (Battleground* bg = bgMap->GetBG()) - bg->EventPlayerDamagedGO(eventInvoker, this, m_goInfo->building.damagedEvent); - - RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); - SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); - - uint32 modelId = m_goInfo->building.damagedDisplayId; - if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) - if (modelData->DamagedDisplayId) - modelId = modelData->DamagedDisplayId; - SetDisplayId(modelId); - - if (setHealth) { - m_goValue.Building.Health = m_goInfo->building.damagedNumHits; - uint32 maxHealth = m_goValue.Building.MaxHealth; - // in this case current health is 0 anyway so just prevent crashing here - if (!maxHealth) - maxHealth = 1; - SetGoAnimProgress(m_goValue.Building.Health * 255 / maxHealth); - } - break; - } - case GO_DESTRUCTIBLE_DESTROYED: - { #ifdef ELUNA - sEluna->OnDestroyed(this, eventInvoker); + sEluna->OnDamaged(this, eventInvoker); #endif - sScriptMgr->OnGameObjectDestroyed(this, eventInvoker); - EventInform(m_goInfo->building.destroyedEvent); - if (BattlegroundMap* bgMap = GetMap()->ToBattlegroundMap()) - { - if (Battleground* bg = bgMap->GetBG()) + EventInform(m_goInfo->building.damagedEvent); + sScriptMgr->OnGameObjectDamaged(this, eventInvoker); + if (BattlegroundMap* bgMap = GetMap()->ToBattlegroundMap()) + if (Battleground* bg = bgMap->GetBG()) + bg->EventPlayerDamagedGO(eventInvoker, this, m_goInfo->building.damagedEvent); + + RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); + SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); + + uint32 modelId = m_goInfo->building.damagedDisplayId; + if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) + if (modelData->DamagedDisplayId) + modelId = modelData->DamagedDisplayId; + SetDisplayId(modelId); + + if (setHealth) { - bg->EventPlayerDamagedGO(eventInvoker, this, m_goInfo->building.destroyedEvent); - bg->DestroyGate(eventInvoker, this); + m_goValue.Building.Health = m_goInfo->building.damagedNumHits; + uint32 maxHealth = m_goValue.Building.MaxHealth; + // in this case current health is 0 anyway so just prevent crashing here + if (!maxHealth) + maxHealth = 1; + SetGoAnimProgress(m_goValue.Building.Health * 255 / maxHealth); } + break; } - - RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); - SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); - - uint32 modelId = m_goInfo->building.destroyedDisplayId; - if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) - if (modelData->DestroyedDisplayId) - modelId = modelData->DestroyedDisplayId; - SetDisplayId(modelId); - - if (setHealth) + case GO_DESTRUCTIBLE_DESTROYED: { - m_goValue.Building.Health = 0; - SetGoAnimProgress(0); +#ifdef ELUNA + sEluna->OnDestroyed(this, eventInvoker); +#endif + sScriptMgr->OnGameObjectDestroyed(this, eventInvoker); + EventInform(m_goInfo->building.destroyedEvent); + if (BattlegroundMap* bgMap = GetMap()->ToBattlegroundMap()) + { + if (Battleground* bg = bgMap->GetBG()) + { + bg->EventPlayerDamagedGO(eventInvoker, this, m_goInfo->building.destroyedEvent); + bg->DestroyGate(eventInvoker, this); + } + } + + RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); + SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); + + uint32 modelId = m_goInfo->building.destroyedDisplayId; + if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) + if (modelData->DestroyedDisplayId) + modelId = modelData->DestroyedDisplayId; + SetDisplayId(modelId); + + if (setHealth) + { + m_goValue.Building.Health = 0; + SetGoAnimProgress(0); + } + EnableCollision(false); + break; } - EnableCollision(false); - break; - } case GO_DESTRUCTIBLE_REBUILDING: - { - EventInform(m_goInfo->building.rebuildingEvent); - RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED | GO_FLAG_DESTROYED); - - uint32 modelId = m_goInfo->displayId; - if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) - if (modelData->RebuildingDisplayId) - modelId = modelData->RebuildingDisplayId; - SetDisplayId(modelId); - - // restores to full health - if (setHealth) { - m_goValue.Building.Health = m_goValue.Building.MaxHealth; - SetGoAnimProgress(255); + EventInform(m_goInfo->building.rebuildingEvent); + RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED | GO_FLAG_DESTROYED); + + uint32 modelId = m_goInfo->displayId; + if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) + if (modelData->RebuildingDisplayId) + modelId = modelData->RebuildingDisplayId; + SetDisplayId(modelId); + + // restores to full health + if (setHealth) + { + m_goValue.Building.Health = m_goValue.Building.MaxHealth; + SetGoAnimProgress(255); + } + EnableCollision(true); + break; } - EnableCollision(true); - break; - } } } @@ -2363,8 +2363,8 @@ void GameObject::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* t for (uint16 index = 0; index < m_valuesCount; ++index) { if (_fieldNotifyFlags & flags[index] || - ((updateType == UPDATETYPE_VALUES ? _changesMask.GetBit(index) : m_uint32Values[index]) && (flags[index] & visibleFlag)) || - (index == GAMEOBJECT_FLAGS && forcedFlags)) + ((updateType == UPDATETYPE_VALUES ? _changesMask.GetBit(index) : m_uint32Values[index]) && (flags[index] & visibleFlag)) || + (index == GAMEOBJECT_FLAGS && forcedFlags)) { updateMask.SetBit(index); @@ -2405,7 +2405,7 @@ void GameObject::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* t pathProgress = int16(float(t->GetPathProgress()) / float(t->GetPauseTime()) * 65535.0f); } } - // else it's ignored + // else it's ignored break; case GAMEOBJECT_TYPE_MO_TRANSPORT: if (const MotionTransport* t = ToMotionTransport()) @@ -2437,7 +2437,7 @@ void GameObject::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* t data->append(fieldBuffer); } -void GameObject::GetRespawnPosition(float &x, float &y, float &z, float* ori /* = NULL*/) const +void GameObject::GetRespawnPosition(float& x, float& y, float& z, float* ori /* = NULL*/) const { if (m_DBTableGuid) { diff --git a/src/server/game/Entities/GameObject/GameObject.h b/src/server/game/Entities/GameObject/GameObject.h index f80ef82b2..ca12d0870 100644 --- a/src/server/game/Entities/GameObject/GameObject.h +++ b/src/server/game/Entities/GameObject/GameObject.h @@ -396,9 +396,12 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_CHEST: return chest.consumable; - case GAMEOBJECT_TYPE_GOOBER: return goober.consumable; - default: return false; + case GAMEOBJECT_TYPE_CHEST: + return chest.consumable; + case GAMEOBJECT_TYPE_GOOBER: + return goober.consumable; + default: + return false; } } @@ -406,11 +409,16 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.allowMounted; - case GAMEOBJECT_TYPE_TEXT: return text.allowMounted; - case GAMEOBJECT_TYPE_GOOBER: return goober.allowMounted; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.allowMounted; - default: return false; + case GAMEOBJECT_TYPE_QUESTGIVER: + return questgiver.allowMounted; + case GAMEOBJECT_TYPE_TEXT: + return text.allowMounted; + case GAMEOBJECT_TYPE_GOOBER: + return goober.allowMounted; + case GAMEOBJECT_TYPE_SPELLCASTER: + return spellcaster.allowMounted; + default: + return false; } } @@ -418,18 +426,30 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_DOOR: return door.lockId; - case GAMEOBJECT_TYPE_BUTTON: return button.lockId; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.lockId; - case GAMEOBJECT_TYPE_CHEST: return chest.lockId; - case GAMEOBJECT_TYPE_TRAP: return trap.lockId; - case GAMEOBJECT_TYPE_GOOBER: return goober.lockId; - case GAMEOBJECT_TYPE_AREADAMAGE: return areadamage.lockId; - case GAMEOBJECT_TYPE_CAMERA: return camera.lockId; - case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.lockId; - case GAMEOBJECT_TYPE_FISHINGHOLE:return fishinghole.lockId; - case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.lockId; - default: return 0; + case GAMEOBJECT_TYPE_DOOR: + return door.lockId; + case GAMEOBJECT_TYPE_BUTTON: + return button.lockId; + case GAMEOBJECT_TYPE_QUESTGIVER: + return questgiver.lockId; + case GAMEOBJECT_TYPE_CHEST: + return chest.lockId; + case GAMEOBJECT_TYPE_TRAP: + return trap.lockId; + case GAMEOBJECT_TYPE_GOOBER: + return goober.lockId; + case GAMEOBJECT_TYPE_AREADAMAGE: + return areadamage.lockId; + case GAMEOBJECT_TYPE_CAMERA: + return camera.lockId; + case GAMEOBJECT_TYPE_FLAGSTAND: + return flagstand.lockId; + case GAMEOBJECT_TYPE_FISHINGHOLE: + return fishinghole.lockId; + case GAMEOBJECT_TYPE_FLAGDROP: + return flagdrop.lockId; + default: + return 0; } } @@ -437,13 +457,20 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_DOOR: return door.noDamageImmune; - case GAMEOBJECT_TYPE_BUTTON: return button.noDamageImmune; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.noDamageImmune; - case GAMEOBJECT_TYPE_GOOBER: return goober.noDamageImmune; - case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.noDamageImmune; - case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.noDamageImmune; - default: return true; + case GAMEOBJECT_TYPE_DOOR: + return door.noDamageImmune; + case GAMEOBJECT_TYPE_BUTTON: + return button.noDamageImmune; + case GAMEOBJECT_TYPE_QUESTGIVER: + return questgiver.noDamageImmune; + case GAMEOBJECT_TYPE_GOOBER: + return goober.noDamageImmune; + case GAMEOBJECT_TYPE_FLAGSTAND: + return flagstand.noDamageImmune; + case GAMEOBJECT_TYPE_FLAGDROP: + return flagdrop.noDamageImmune; + default: + return true; } } @@ -452,9 +479,12 @@ struct GameObjectTemplate switch (type) { //case GAMEOBJECT_TYPE_TRAP: return trap.charges; - case GAMEOBJECT_TYPE_GUARDPOST: return guardpost.charges; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.charges; - default: return 0; + case GAMEOBJECT_TYPE_GUARDPOST: + return guardpost.charges; + case GAMEOBJECT_TYPE_SPELLCASTER: + return spellcaster.charges; + default: + return 0; } } @@ -462,10 +492,14 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_CHEST: return chest.linkedTrapId; - case GAMEOBJECT_TYPE_SPELL_FOCUS: return spellFocus.linkedTrapId; - case GAMEOBJECT_TYPE_GOOBER: return goober.linkedTrapId; - default: return 0; + case GAMEOBJECT_TYPE_CHEST: + return chest.linkedTrapId; + case GAMEOBJECT_TYPE_SPELL_FOCUS: + return spellFocus.linkedTrapId; + case GAMEOBJECT_TYPE_GOOBER: + return goober.linkedTrapId; + default: + return 0; } } @@ -474,13 +508,26 @@ struct GameObjectTemplate uint32 autoCloseTime = 0; switch (type) { - case GAMEOBJECT_TYPE_DOOR: autoCloseTime = door.autoCloseTime; break; - case GAMEOBJECT_TYPE_BUTTON: autoCloseTime = button.autoCloseTime; break; - case GAMEOBJECT_TYPE_TRAP: autoCloseTime = trap.autoCloseTime; break; - case GAMEOBJECT_TYPE_GOOBER: autoCloseTime = goober.autoCloseTime; break; - case GAMEOBJECT_TYPE_TRANSPORT: autoCloseTime = transport.autoCloseTime; break; - case GAMEOBJECT_TYPE_AREADAMAGE: autoCloseTime = areadamage.autoCloseTime; break; - default: break; + case GAMEOBJECT_TYPE_DOOR: + autoCloseTime = door.autoCloseTime; + break; + case GAMEOBJECT_TYPE_BUTTON: + autoCloseTime = button.autoCloseTime; + break; + case GAMEOBJECT_TYPE_TRAP: + autoCloseTime = trap.autoCloseTime; + break; + case GAMEOBJECT_TYPE_GOOBER: + autoCloseTime = goober.autoCloseTime; + break; + case GAMEOBJECT_TYPE_TRANSPORT: + autoCloseTime = transport.autoCloseTime; + break; + case GAMEOBJECT_TYPE_AREADAMAGE: + autoCloseTime = areadamage.autoCloseTime; + break; + default: + break; } return autoCloseTime /* xinef: changed to milliseconds/ IN_MILLISECONDS*/; // prior to 3.0.3, conversion was / 0x10000; } @@ -489,9 +536,12 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_CHEST: return chest.lootId; - case GAMEOBJECT_TYPE_FISHINGHOLE: return fishinghole.lootId; - default: return 0; + case GAMEOBJECT_TYPE_CHEST: + return chest.lootId; + case GAMEOBJECT_TYPE_FISHINGHOLE: + return fishinghole.lootId; + default: + return 0; } } @@ -499,9 +549,12 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.gossipID; - case GAMEOBJECT_TYPE_GOOBER: return goober.gossipID; - default: return 0; + case GAMEOBJECT_TYPE_QUESTGIVER: + return questgiver.gossipID; + case GAMEOBJECT_TYPE_GOOBER: + return goober.gossipID; + default: + return 0; } } @@ -509,10 +562,14 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_GOOBER: return goober.eventId; - case GAMEOBJECT_TYPE_CHEST: return chest.eventId; - case GAMEOBJECT_TYPE_CAMERA: return camera.eventID; - default: return 0; + case GAMEOBJECT_TYPE_GOOBER: + return goober.eventId; + case GAMEOBJECT_TYPE_CHEST: + return chest.eventId; + case GAMEOBJECT_TYPE_CAMERA: + return camera.eventID; + default: + return 0; } } @@ -520,9 +577,12 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_TRAP: return trap.cooldown; - case GAMEOBJECT_TYPE_GOOBER: return goober.cooldown; - default: return 0; + case GAMEOBJECT_TYPE_TRAP: + return trap.cooldown; + case GAMEOBJECT_TYPE_GOOBER: + return goober.cooldown; + default: + return 0; } } @@ -530,15 +590,24 @@ struct GameObjectTemplate { switch (type) { - case GAMEOBJECT_TYPE_BUTTON: return button.large != 0; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.large != 0; - case GAMEOBJECT_TYPE_GENERIC: return _generic.large != 0; - case GAMEOBJECT_TYPE_TRAP: return trap.large != 0; - case GAMEOBJECT_TYPE_SPELL_FOCUS: return spellFocus.large != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.large != 0; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.large != 0; - case GAMEOBJECT_TYPE_CAPTURE_POINT: return capturePoint.large != 0; - default: return false; + case GAMEOBJECT_TYPE_BUTTON: + return button.large != 0; + case GAMEOBJECT_TYPE_QUESTGIVER: + return questgiver.large != 0; + case GAMEOBJECT_TYPE_GENERIC: + return _generic.large != 0; + case GAMEOBJECT_TYPE_TRAP: + return trap.large != 0; + case GAMEOBJECT_TYPE_SPELL_FOCUS: + return spellFocus.large != 0; + case GAMEOBJECT_TYPE_GOOBER: + return goober.large != 0; + case GAMEOBJECT_TYPE_SPELLCASTER: + return spellcaster.large != 0; + case GAMEOBJECT_TYPE_CAPTURE_POINT: + return capturePoint.large != 0; + default: + return false; } } @@ -581,7 +650,7 @@ union GameObjectValue //29 GAMEOBJECT_TYPE_CAPTURE_POINT struct { - OPvPCapturePoint *OPvPObj; + OPvPCapturePoint* OPvPObj; } CapturePoint; //33 GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING struct @@ -620,7 +689,7 @@ enum GOState struct GameObjectData { explicit GameObjectData() : id(0), mapid(0), phaseMask(0), posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), - animprogress(0), go_state(GO_STATE_ACTIVE), spawnMask(0), artKit(0), dbData(true) { } + animprogress(0), go_state(GO_STATE_ACTIVE), spawnMask(0), artKit(0), dbData(true) { } uint32 id; // entry in gamobject_template uint16 mapid; uint32 phaseMask; @@ -660,276 +729,276 @@ class GameObjectModel; class GameObject : public WorldObject, public GridObject, public MovableMapObject { - public: - explicit GameObject(); - ~GameObject(); +public: + explicit GameObject(); + ~GameObject(); - void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const override; + void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const override; - void AddToWorld() override; - void RemoveFromWorld() override; - void CleanupsBeforeDelete(bool finalCleanup = true) override; + void AddToWorld() override; + void RemoveFromWorld() override; + void CleanupsBeforeDelete(bool finalCleanup = true) override; - virtual bool Create(uint32 guidlow, uint32 name_id, Map* map, uint32 phaseMask, float x, float y, float z, float ang, G3D::Quat const& rotation, uint32 animprogress, GOState go_state, uint32 artKit = 0); - void Update(uint32 p_time) override; - GameObjectTemplate const* GetGOInfo() const { return m_goInfo; } - GameObjectTemplateAddon const* GetTemplateAddon() const; - GameObjectData const* GetGOData() const { return m_goData; } - GameObjectValue const* GetGOValue() const { return &m_goValue; } + virtual bool Create(uint32 guidlow, uint32 name_id, Map* map, uint32 phaseMask, float x, float y, float z, float ang, G3D::Quat const& rotation, uint32 animprogress, GOState go_state, uint32 artKit = 0); + void Update(uint32 p_time) override; + GameObjectTemplate const* GetGOInfo() const { return m_goInfo; } + GameObjectTemplateAddon const* GetTemplateAddon() const; + GameObjectData const* GetGOData() const { return m_goData; } + GameObjectValue const* GetGOValue() const { return &m_goValue; } - bool IsTransport() const; - bool IsDestructibleBuilding() const; + bool IsTransport() const; + bool IsDestructibleBuilding() const; - uint32 GetDBTableGUIDLow() const { return m_DBTableGuid; } + uint32 GetDBTableGUIDLow() const { return m_DBTableGuid; } - // z_rot, y_rot, x_rot - rotation angles around z, y and x axes - void SetWorldRotationAngles(float z_rot, float y_rot, float x_rot); - void SetWorldRotation(G3D::Quat const& rot); - void SetTransportPathRotation(float qx, float qy, float qz, float qw); - int64 GetPackedWorldRotation() const { return m_packedRotation; } + // z_rot, y_rot, x_rot - rotation angles around z, y and x axes + void SetWorldRotationAngles(float z_rot, float y_rot, float x_rot); + void SetWorldRotation(G3D::Quat const& rot); + void SetTransportPathRotation(float qx, float qy, float qz, float qw); + int64 GetPackedWorldRotation() const { return m_packedRotation; } - // overwrite WorldObject function for proper name localization - std::string const& GetNameForLocaleIdx(LocaleConstant locale_idx) const override; + // overwrite WorldObject function for proper name localization + std::string const& GetNameForLocaleIdx(LocaleConstant locale_idx) const override; - void SaveToDB(); - void SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask); - bool LoadFromDB(uint32 guid, Map* map) { return LoadGameObjectFromDB(guid, map, false); } - bool LoadGameObjectFromDB(uint32 guid, Map* map, bool addToMap = true); - void DeleteFromDB(); + void SaveToDB(); + void SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask); + bool LoadFromDB(uint32 guid, Map* map) { return LoadGameObjectFromDB(guid, map, false); } + bool LoadGameObjectFromDB(uint32 guid, Map* map, bool addToMap = true); + void DeleteFromDB(); - void SetOwnerGUID(uint64 owner) + void SetOwnerGUID(uint64 owner) + { + // Owner already found and different than expected owner - remove object from old owner + if (owner && GetOwnerGUID() && GetOwnerGUID() != owner) { - // Owner already found and different than expected owner - remove object from old owner - if (owner && GetOwnerGUID() && GetOwnerGUID() != owner) - { - ABORT(); - } - m_spawnedByDefault = false; // all object with owner is despawned after delay - SetUInt64Value(OBJECT_FIELD_CREATED_BY, owner); + ABORT(); } - uint64 GetOwnerGUID() const { return GetUInt64Value(OBJECT_FIELD_CREATED_BY); } - Unit* GetOwner() const; + m_spawnedByDefault = false; // all object with owner is despawned after delay + SetUInt64Value(OBJECT_FIELD_CREATED_BY, owner); + } + uint64 GetOwnerGUID() const { return GetUInt64Value(OBJECT_FIELD_CREATED_BY); } + Unit* GetOwner() const; - void SetSpellId(uint32 id) - { - m_spawnedByDefault = false; // all summoned object is despawned after delay - m_spellId = id; - } - uint32 GetSpellId() const { return m_spellId;} + void SetSpellId(uint32 id) + { + m_spawnedByDefault = false; // all summoned object is despawned after delay + m_spellId = id; + } + uint32 GetSpellId() const { return m_spellId;} - time_t GetRespawnTime() const { return m_respawnTime; } - time_t GetRespawnTimeEx() const - { - time_t now = time(nullptr); - if (m_respawnTime > now) - return m_respawnTime; - else - return now; - } + time_t GetRespawnTime() const { return m_respawnTime; } + time_t GetRespawnTimeEx() const + { + time_t now = time(nullptr); + if (m_respawnTime > now) + return m_respawnTime; + else + return now; + } - void SetRespawnTime(int32 respawn) - { - m_respawnTime = respawn > 0 ? time(nullptr) + respawn : 0; - m_respawnDelayTime = respawn > 0 ? respawn : 0; - } - void Respawn(); - bool isSpawned() const - { - return m_respawnDelayTime == 0 || - (m_respawnTime > 0 && !m_spawnedByDefault) || - (m_respawnTime == 0 && m_spawnedByDefault); - } - bool isSpawnedByDefault() const { return m_spawnedByDefault; } - void SetSpawnedByDefault(bool b) { m_spawnedByDefault = b; } - uint32 GetRespawnDelay() const { return m_respawnDelayTime; } - void Refresh(); - void Delete(); - void getFishLoot(Loot* loot, Player* loot_owner); - void getFishLootJunk(Loot* loot, Player* loot_owner); - GameobjectTypes GetGoType() const { return GameobjectTypes(GetByteValue(GAMEOBJECT_BYTES_1, 1)); } - void SetGoType(GameobjectTypes type) { SetByteValue(GAMEOBJECT_BYTES_1, 1, type); } - GOState GetGoState() const { return GOState(GetByteValue(GAMEOBJECT_BYTES_1, 0)); } - void SetGoState(GOState state); - uint8 GetGoArtKit() const { return GetByteValue(GAMEOBJECT_BYTES_1, 2); } - void SetGoArtKit(uint8 artkit); - uint8 GetGoAnimProgress() const { return GetByteValue(GAMEOBJECT_BYTES_1, 3); } - void SetGoAnimProgress(uint8 animprogress) { SetByteValue(GAMEOBJECT_BYTES_1, 3, animprogress); } - static void SetGoArtKit(uint8 artkit, GameObject* go, uint32 lowguid = 0); + void SetRespawnTime(int32 respawn) + { + m_respawnTime = respawn > 0 ? time(nullptr) + respawn : 0; + m_respawnDelayTime = respawn > 0 ? respawn : 0; + } + void Respawn(); + bool isSpawned() const + { + return m_respawnDelayTime == 0 || + (m_respawnTime > 0 && !m_spawnedByDefault) || + (m_respawnTime == 0 && m_spawnedByDefault); + } + bool isSpawnedByDefault() const { return m_spawnedByDefault; } + void SetSpawnedByDefault(bool b) { m_spawnedByDefault = b; } + uint32 GetRespawnDelay() const { return m_respawnDelayTime; } + void Refresh(); + void Delete(); + void getFishLoot(Loot* loot, Player* loot_owner); + void getFishLootJunk(Loot* loot, Player* loot_owner); + GameobjectTypes GetGoType() const { return GameobjectTypes(GetByteValue(GAMEOBJECT_BYTES_1, 1)); } + void SetGoType(GameobjectTypes type) { SetByteValue(GAMEOBJECT_BYTES_1, 1, type); } + GOState GetGoState() const { return GOState(GetByteValue(GAMEOBJECT_BYTES_1, 0)); } + void SetGoState(GOState state); + uint8 GetGoArtKit() const { return GetByteValue(GAMEOBJECT_BYTES_1, 2); } + void SetGoArtKit(uint8 artkit); + uint8 GetGoAnimProgress() const { return GetByteValue(GAMEOBJECT_BYTES_1, 3); } + void SetGoAnimProgress(uint8 animprogress) { SetByteValue(GAMEOBJECT_BYTES_1, 3, animprogress); } + static void SetGoArtKit(uint8 artkit, GameObject* go, uint32 lowguid = 0); - void SetPhaseMask(uint32 newPhaseMask, bool update) override; - void EnableCollision(bool enable); + void SetPhaseMask(uint32 newPhaseMask, bool update) override; + void EnableCollision(bool enable); - void Use(Unit* user); + void Use(Unit* user); - LootState getLootState() const { return m_lootState; } - // Note: unit is only used when s = GO_ACTIVATED - void SetLootState(LootState s, Unit* unit = nullptr); + LootState getLootState() const { return m_lootState; } + // Note: unit is only used when s = GO_ACTIVATED + void SetLootState(LootState s, Unit* unit = nullptr); - uint16 GetLootMode() const { return m_LootMode; } - bool HasLootMode(uint16 lootMode) const { return m_LootMode & lootMode; } - void SetLootMode(uint16 lootMode) { m_LootMode = lootMode; } - void AddLootMode(uint16 lootMode) { m_LootMode |= lootMode; } - void RemoveLootMode(uint16 lootMode) { m_LootMode &= ~lootMode; } - void ResetLootMode() { m_LootMode = LOOT_MODE_DEFAULT; } + uint16 GetLootMode() const { return m_LootMode; } + bool HasLootMode(uint16 lootMode) const { return m_LootMode & lootMode; } + void SetLootMode(uint16 lootMode) { m_LootMode = lootMode; } + void AddLootMode(uint16 lootMode) { m_LootMode |= lootMode; } + void RemoveLootMode(uint16 lootMode) { m_LootMode &= ~lootMode; } + void ResetLootMode() { m_LootMode = LOOT_MODE_DEFAULT; } - void AddToSkillupList(uint32 PlayerGuidLow) { m_SkillupList.push_back(PlayerGuidLow); } - bool IsInSkillupList(uint32 PlayerGuidLow) const - { - for (std::list::const_iterator i = m_SkillupList.begin(); i != m_SkillupList.end(); ++i) - if (*i == PlayerGuidLow) - return true; + void AddToSkillupList(uint32 PlayerGuidLow) { m_SkillupList.push_back(PlayerGuidLow); } + bool IsInSkillupList(uint32 PlayerGuidLow) const + { + for (std::list::const_iterator i = m_SkillupList.begin(); i != m_SkillupList.end(); ++i) + if (*i == PlayerGuidLow) + return true; - return false; - } - void ClearSkillupList() { m_SkillupList.clear(); } + return false; + } + void ClearSkillupList() { m_SkillupList.clear(); } - void AddUniqueUse(Player* player); - void AddUse() { ++m_usetimes; } + void AddUniqueUse(Player* player); + void AddUse() { ++m_usetimes; } - uint32 GetUseCount() const { return m_usetimes; } - uint32 GetUniqueUseCount() const { return m_unique_users.size(); } + uint32 GetUseCount() const { return m_usetimes; } + uint32 GetUniqueUseCount() const { return m_unique_users.size(); } - void SaveRespawnTime() override; + void SaveRespawnTime() override; - Loot loot; + Loot loot; - Player* GetLootRecipient() const; - Group* GetLootRecipientGroup() const; - void SetLootRecipient(Unit* unit); - bool IsLootAllowedFor(Player const* player) const; - bool HasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; } - uint32 m_groupLootTimer; // (msecs)timer used for group loot - uint32 lootingGroupLowGUID; // used to find group which is looting - void SetLootGenerationTime() { m_lootGenerationTime = time(nullptr); } - uint32 GetLootGenerationTime() const { return m_lootGenerationTime; } + Player* GetLootRecipient() const; + Group* GetLootRecipientGroup() const; + void SetLootRecipient(Unit* unit); + bool IsLootAllowedFor(Player const* player) const; + bool HasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; } + uint32 m_groupLootTimer; // (msecs)timer used for group loot + uint32 lootingGroupLowGUID; // used to find group which is looting + void SetLootGenerationTime() { m_lootGenerationTime = time(nullptr); } + uint32 GetLootGenerationTime() const { return m_lootGenerationTime; } - bool hasQuest(uint32 quest_id) const override; - bool hasInvolvedQuest(uint32 quest_id) const override; - bool ActivateToQuest(Player* target) const; - void UseDoorOrButton(uint32 time_to_restore = 0, bool alternative = false, Unit* user = nullptr); - // 0 = use `gameobject`.`spawntimesecs` - void ResetDoorOrButton(); + bool hasQuest(uint32 quest_id) const override; + bool hasInvolvedQuest(uint32 quest_id) const override; + bool ActivateToQuest(Player* target) const; + void UseDoorOrButton(uint32 time_to_restore = 0, bool alternative = false, Unit* user = nullptr); + // 0 = use `gameobject`.`spawntimesecs` + void ResetDoorOrButton(); - void TriggeringLinkedGameObject(uint32 trapEntry, Unit* target); + void TriggeringLinkedGameObject(uint32 trapEntry, Unit* target); - bool IsNeverVisible() const override; - bool IsAlwaysVisibleFor(WorldObject const* seer) const override; - bool IsInvisibleDueToDespawn() const override; + bool IsNeverVisible() const override; + bool IsAlwaysVisibleFor(WorldObject const* seer) const override; + bool IsInvisibleDueToDespawn() const override; - uint8 getLevelForTarget(WorldObject const* target) const override - { - if (Unit* owner = GetOwner()) - return owner->getLevelForTarget(target); + uint8 getLevelForTarget(WorldObject const* target) const override + { + if (Unit* owner = GetOwner()) + return owner->getLevelForTarget(target); - return 1; - } + return 1; + } - GameObject* LookupFishingHoleAround(float range); + GameObject* LookupFishingHoleAround(float range); - void CastSpell(Unit* target, uint32 spell); - void SendCustomAnim(uint32 anim); - bool IsInRange(float x, float y, float z, float radius) const; + void CastSpell(Unit* target, uint32 spell); + void SendCustomAnim(uint32 anim); + bool IsInRange(float x, float y, float z, float radius) const; - void SendMessageToSetInRange(WorldPacket* data, float dist, bool /*self*/, bool includeMargin = false, Player const* skipped_rcvr = nullptr) override; // pussywizard! + void SendMessageToSetInRange(WorldPacket* data, float dist, bool /*self*/, bool includeMargin = false, Player const* skipped_rcvr = nullptr) override; // pussywizard! - void ModifyHealth(int32 change, Unit* attackerOrHealer = NULL, uint32 spellId = 0); - void SetDestructibleBuildingModifyState(bool allow) { m_allowModifyDestructibleBuilding = allow; } - // sets GameObject type 33 destruction flags and optionally default health for that state - void SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker = NULL, bool setHealth = false); - GameObjectDestructibleState GetDestructibleState() const - { - if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED)) - return GO_DESTRUCTIBLE_DESTROYED; - if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED)) - return GO_DESTRUCTIBLE_DAMAGED; - return GO_DESTRUCTIBLE_INTACT; - } + void ModifyHealth(int32 change, Unit* attackerOrHealer = NULL, uint32 spellId = 0); + void SetDestructibleBuildingModifyState(bool allow) { m_allowModifyDestructibleBuilding = allow; } + // sets GameObject type 33 destruction flags and optionally default health for that state + void SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker = NULL, bool setHealth = false); + GameObjectDestructibleState GetDestructibleState() const + { + if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED)) + return GO_DESTRUCTIBLE_DESTROYED; + if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED)) + return GO_DESTRUCTIBLE_DAMAGED; + return GO_DESTRUCTIBLE_INTACT; + } - void EventInform(uint32 eventId); + void EventInform(uint32 eventId); - virtual uint32 GetScriptId() const { return GetGOInfo()->ScriptId; } - GameObjectAI* AI() const { return m_AI; } + virtual uint32 GetScriptId() const { return GetGOInfo()->ScriptId; } + GameObjectAI* AI() const { return m_AI; } - std::string GetAIName() const; - void SetDisplayId(uint32 displayid); - uint32 GetDisplayId() const { return GetUInt32Value(GAMEOBJECT_DISPLAYID); } + std::string GetAIName() const; + void SetDisplayId(uint32 displayid); + uint32 GetDisplayId() const { return GetUInt32Value(GAMEOBJECT_DISPLAYID); } - GameObjectModel* m_model; - void GetRespawnPosition(float &x, float &y, float &z, float* ori = nullptr) const; + GameObjectModel* m_model; + void GetRespawnPosition(float& x, float& y, float& z, float* ori = nullptr) const; - void SetPosition(float x, float y, float z, float o); - void SetPosition(const Position &pos) { SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation()); } + void SetPosition(float x, float y, float z, float o); + void SetPosition(const Position& pos) { SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation()); } - bool IsStaticTransport() const { return GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT; } - bool IsMotionTransport() const { return GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT; } + bool IsStaticTransport() const { return GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT; } + bool IsMotionTransport() const { return GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT; } - Transport* ToTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT || GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } - Transport const* ToTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT || GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + Transport* ToTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT || GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + Transport const* ToTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT || GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } - StaticTransport* ToStaticTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } - StaticTransport const* ToStaticTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + StaticTransport* ToStaticTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + StaticTransport const* ToStaticTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) return reinterpret_cast(this); else return nullptr; } - MotionTransport* ToMotionTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } - MotionTransport const* ToMotionTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + MotionTransport* ToMotionTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + MotionTransport const* ToMotionTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } - float GetStationaryX() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionX(); return GetPositionX(); } - float GetStationaryY() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionY(); return GetPositionY(); } - float GetStationaryZ() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionZ(); return GetPositionZ(); } - float GetStationaryO() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetOrientation(); return GetOrientation(); } + float GetStationaryX() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionX(); return GetPositionX(); } + float GetStationaryY() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionY(); return GetPositionY(); } + float GetStationaryZ() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionZ(); return GetPositionZ(); } + float GetStationaryO() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetOrientation(); return GetOrientation(); } - float GetInteractionDistance(); - - void UpdateModelPosition(); + float GetInteractionDistance(); - static std::unordered_map gameObjectToEventFlag; // Gameobject -> event flag + void UpdateModelPosition(); - protected: - bool AIM_Initialize(); - void UpdateModel(); // updates model in case displayId were changed - uint32 m_spellId; - time_t m_respawnTime; // (secs) time of next respawn (or despawn if GO have owner()), - uint32 m_respawnDelayTime; // (secs) if 0 then current GO state no dependent from timer - LootState m_lootState; - bool m_spawnedByDefault; - uint32 m_cooldownTime; // used as internal reaction delay time store (not state change reaction). - // For traps this: spell casting cooldown, for doors/buttons: reset time. - std::list m_SkillupList; + static std::unordered_map gameObjectToEventFlag; // Gameobject -> event flag - uint32 m_ritualOwnerGUIDLow; // used for GAMEOBJECT_TYPE_SUMMONING_RITUAL where GO is not summoned (no owner) - std::set m_unique_users; - uint32 m_usetimes; +protected: + bool AIM_Initialize(); + void UpdateModel(); // updates model in case displayId were changed + uint32 m_spellId; + time_t m_respawnTime; // (secs) time of next respawn (or despawn if GO have owner()), + uint32 m_respawnDelayTime; // (secs) if 0 then current GO state no dependent from timer + LootState m_lootState; + bool m_spawnedByDefault; + uint32 m_cooldownTime; // used as internal reaction delay time store (not state change reaction). + // For traps this: spell casting cooldown, for doors/buttons: reset time. + std::list m_SkillupList; - typedef std::map ChairSlotAndUser; - ChairSlotAndUser ChairListSlots; + uint32 m_ritualOwnerGUIDLow; // used for GAMEOBJECT_TYPE_SUMMONING_RITUAL where GO is not summoned (no owner) + std::set m_unique_users; + uint32 m_usetimes; - uint32 m_DBTableGuid; ///< For new or temporary gameobjects is 0 for saved it is lowguid - GameObjectTemplate const* m_goInfo; - GameObjectData const* m_goData; - GameObjectValue m_goValue; - bool m_allowModifyDestructibleBuilding; + typedef std::map ChairSlotAndUser; + ChairSlotAndUser ChairListSlots; - int64 m_packedRotation; - G3D::Quat m_worldRotation; - Position m_stationaryPosition; + uint32 m_DBTableGuid; ///< For new or temporary gameobjects is 0 for saved it is lowguid + GameObjectTemplate const* m_goInfo; + GameObjectData const* m_goData; + GameObjectValue m_goValue; + bool m_allowModifyDestructibleBuilding; - uint64 m_lootRecipient; - uint32 m_lootRecipientGroup; - uint16 m_LootMode; // bitmask, default LOOT_MODE_DEFAULT, determines what loot will be lootable - uint32 m_lootGenerationTime; - private: - void CheckRitualList(); - void ClearRitualList(); - void RemoveFromOwner(); - void SwitchDoorOrButton(bool activate, bool alternative = false); - void UpdatePackedRotation(); + int64 m_packedRotation; + G3D::Quat m_worldRotation; + Position m_stationaryPosition; - //! Object distance/size - overridden from Object::_IsWithinDist. Needs to take in account proper GO size. - bool _IsWithinDist(WorldObject const* obj, float dist2compare, bool /*is3D*/) const override - { - //! Following check does check 3d distance - dist2compare += obj->GetObjectSize(); - return IsInRange(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), dist2compare); - } - GameObjectAI* m_AI; + uint64 m_lootRecipient; + uint32 m_lootRecipientGroup; + uint16 m_LootMode; // bitmask, default LOOT_MODE_DEFAULT, determines what loot will be lootable + uint32 m_lootGenerationTime; +private: + void CheckRitualList(); + void ClearRitualList(); + void RemoveFromOwner(); + void SwitchDoorOrButton(bool activate, bool alternative = false); + void UpdatePackedRotation(); + + //! Object distance/size - overridden from Object::_IsWithinDist. Needs to take in account proper GO size. + bool _IsWithinDist(WorldObject const* obj, float dist2compare, bool /*is3D*/) const override + { + //! Following check does check 3d distance + dist2compare += obj->GetObjectSize(); + return IsInRange(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), dist2compare); + } + GameObjectAI* m_AI; }; #endif diff --git a/src/server/game/Entities/Item/Container/Bag.cpp b/src/server/game/Entities/Item/Container/Bag.cpp index 385d3efbb..d073758a7 100644 --- a/src/server/game/Entities/Item/Container/Bag.cpp +++ b/src/server/game/Entities/Item/Container/Bag.cpp @@ -31,8 +31,8 @@ Bag::~Bag() if (item->IsInWorld()) { sLog->outCrash("Item %u (slot %u, bag slot %u) in bag %u (slot %u, bag slot %u, m_bagslot %u) is to be deleted but is still in world.", - item->GetEntry(), (uint32)item->GetSlot(), (uint32)item->GetBagSlot(), - GetEntry(), (uint32)GetSlot(), (uint32)GetBagSlot(), (uint32)i); + item->GetEntry(), (uint32)item->GetSlot(), (uint32)item->GetBagSlot(), + GetEntry(), (uint32)GetSlot(), (uint32)GetBagSlot(), (uint32)i); item->RemoveFromWorld(); } delete m_bagslot[i]; @@ -82,7 +82,7 @@ bool Bag::Create(uint32 guidlow, uint32 itemid, Player const* owner) // Cleaning 20 slots for (uint8 i = 0; i < MAX_BAG_SIZE; ++i) { - SetUInt64Value(CONTAINER_FIELD_SLOT_1 + (i*2), 0); + SetUInt64Value(CONTAINER_FIELD_SLOT_1 + (i * 2), 0); m_bagslot[i] = nullptr; } @@ -104,7 +104,7 @@ bool Bag::LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entry // cleanup bag content related item value fields (its will be filled correctly from `character_inventory`) for (uint8 i = 0; i < MAX_BAG_SIZE; ++i) { - SetUInt64Value(CONTAINER_FIELD_SLOT_1 + (i*2), 0); + SetUInt64Value(CONTAINER_FIELD_SLOT_1 + (i * 2), 0); delete m_bagslot[i]; m_bagslot[i] = nullptr; } @@ -124,7 +124,7 @@ void Bag::DeleteFromDB(SQLTransaction& trans) uint32 Bag::GetFreeSlots() const { uint32 slots = 0; - for (uint32 i=0; i < GetBagSize(); ++i) + for (uint32 i = 0; i < GetBagSize(); ++i) if (!m_bagslot[i]) ++slots; @@ -180,7 +180,7 @@ uint32 Bag::GetItemCount(uint32 item, Item* eItem) const { Item* pItem; uint32 count = 0; - for (uint32 i=0; i < GetBagSize(); ++i) + for (uint32 i = 0; i < GetBagSize(); ++i) { pItem = m_bagslot[i]; if (pItem && pItem != eItem && pItem->GetEntry() == item) @@ -189,7 +189,7 @@ uint32 Bag::GetItemCount(uint32 item, Item* eItem) const if (eItem && eItem->GetTemplate()->GemProperties) { - for (uint32 i=0; i < GetBagSize(); ++i) + for (uint32 i = 0; i < GetBagSize(); ++i) { pItem = m_bagslot[i]; if (pItem && pItem != eItem && pItem->GetTemplate()->Socket[0].Color) diff --git a/src/server/game/Entities/Item/Container/Bag.h b/src/server/game/Entities/Item/Container/Bag.h index 9398729ee..54484614d 100644 --- a/src/server/game/Entities/Item/Container/Bag.h +++ b/src/server/game/Entities/Item/Container/Bag.h @@ -15,43 +15,43 @@ class Bag : public Item { - public: +public: - Bag(); - ~Bag(); + Bag(); + ~Bag(); - void AddToWorld(); - void RemoveFromWorld(); + void AddToWorld(); + void RemoveFromWorld(); - bool Create(uint32 guidlow, uint32 itemid, Player const* owner); + bool Create(uint32 guidlow, uint32 itemid, Player const* owner); - void Clear(); - void StoreItem(uint8 slot, Item* pItem, bool update); - void RemoveItem(uint8 slot, bool update); + void Clear(); + void StoreItem(uint8 slot, Item* pItem, bool update); + void RemoveItem(uint8 slot, bool update); - Item* GetItemByPos(uint8 slot) const; - uint32 GetItemCount(uint32 item, Item* eItem = nullptr) const; - uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; + Item* GetItemByPos(uint8 slot) const; + uint32 GetItemCount(uint32 item, Item* eItem = nullptr) const; + uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; - uint8 GetSlotByItemGUID(uint64 guid) const; - bool IsEmpty() const; - uint32 GetFreeSlots() const; - uint32 GetBagSize() const { return GetUInt32Value(CONTAINER_FIELD_NUM_SLOTS); } + uint8 GetSlotByItemGUID(uint64 guid) const; + bool IsEmpty() const; + uint32 GetFreeSlots() const; + uint32 GetBagSize() const { return GetUInt32Value(CONTAINER_FIELD_NUM_SLOTS); } - // DB operations - // overwrite virtual Item::SaveToDB - void SaveToDB(SQLTransaction& trans); - // overwrite virtual Item::LoadFromDB - bool LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entry); - // overwrite virtual Item::DeleteFromDB - void DeleteFromDB(SQLTransaction& trans); + // DB operations + // overwrite virtual Item::SaveToDB + void SaveToDB(SQLTransaction& trans); + // overwrite virtual Item::LoadFromDB + bool LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entry); + // overwrite virtual Item::DeleteFromDB + void DeleteFromDB(SQLTransaction& trans); - void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const; + void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const; - protected: +protected: - // Bag Storage space - Item* m_bagslot[MAX_BAG_SIZE]; + // Bag Storage space + Item* m_bagslot[MAX_BAG_SIZE]; }; inline Item* NewItemOrBag(ItemTemplate const* proto) diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index 9c5e8d84c..18bc10eb8 100644 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -55,7 +55,7 @@ void AddItemsSetItem(Player* player, Item* item) break; if (x < player->ItemSetEff.size()) - player->ItemSetEff[x]=eff; + player->ItemSetEff[x] = eff; else player->ItemSetEff.push_back(eff); } @@ -99,7 +99,7 @@ void AddItemsSetItem(Player* player, Item* item) } } -void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) +void RemoveItemsSetItem(Player* player, ItemTemplate const* proto) { uint32 setid = proto->ItemSet; @@ -143,7 +143,7 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) { // spell can be not active if not fit form requirement player->ApplyEquipSpell(eff->spells[z], NULL, false); - eff->spells[z]=NULL; + eff->spells[z] = NULL; break; } } @@ -309,68 +309,68 @@ void Item::SaveToDB(SQLTransaction& trans) { case ITEM_NEW: case ITEM_CHANGED: - { - uint8 index = 0; - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_REP_ITEM_INSTANCE : CHAR_UPD_ITEM_INSTANCE); - stmt->setUInt32( index, GetEntry()); - stmt->setUInt32(++index, GUID_LOPART(GetOwnerGUID())); - stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_CREATOR))); - stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_GIFTCREATOR))); - stmt->setUInt32(++index, GetCount()); - stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURATION)); - - std::ostringstream ssSpells; - for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) - ssSpells << GetSpellCharges(i) << ' '; - stmt->setString(++index, ssSpells.str()); - - stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_FLAGS)); - - std::ostringstream ssEnchants; - for (uint8 i = 0; i < MAX_ENCHANTMENT_SLOT; ++i) { - ssEnchants << GetEnchantmentId(EnchantmentSlot(i)) << ' '; - ssEnchants << GetEnchantmentDuration(EnchantmentSlot(i)) << ' '; - ssEnchants << GetEnchantmentCharges(EnchantmentSlot(i)) << ' '; - } - stmt->setString(++index, ssEnchants.str()); + uint8 index = 0; + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_REP_ITEM_INSTANCE : CHAR_UPD_ITEM_INSTANCE); + stmt->setUInt32( index, GetEntry()); + stmt->setUInt32(++index, GUID_LOPART(GetOwnerGUID())); + stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_CREATOR))); + stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_GIFTCREATOR))); + stmt->setUInt32(++index, GetCount()); + stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURATION)); - stmt->setInt16 (++index, GetItemRandomPropertyId()); - stmt->setUInt16(++index, GetUInt32Value(ITEM_FIELD_DURABILITY)); - stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME)); - stmt->setString(++index, m_text); - stmt->setUInt32(++index, guid); + std::ostringstream ssSpells; + for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) + ssSpells << GetSpellCharges(i) << ' '; + stmt->setString(++index, ssSpells.str()); - trans->Append(stmt); + stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_FLAGS)); + + std::ostringstream ssEnchants; + for (uint8 i = 0; i < MAX_ENCHANTMENT_SLOT; ++i) + { + ssEnchants << GetEnchantmentId(EnchantmentSlot(i)) << ' '; + ssEnchants << GetEnchantmentDuration(EnchantmentSlot(i)) << ' '; + ssEnchants << GetEnchantmentCharges(EnchantmentSlot(i)) << ' '; + } + stmt->setString(++index, ssEnchants.str()); + + stmt->setInt16 (++index, GetItemRandomPropertyId()); + stmt->setUInt16(++index, GetUInt32Value(ITEM_FIELD_DURABILITY)); + stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME)); + stmt->setString(++index, m_text); + stmt->setUInt32(++index, guid); - if ((uState == ITEM_CHANGED) && HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) - { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GIFT_OWNER); - stmt->setUInt32(0, GUID_LOPART(GetOwnerGUID())); - stmt->setUInt32(1, guid); trans->Append(stmt); - } - break; - } - case ITEM_REMOVED: - { - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); - stmt->setUInt32(0, guid); - trans->Append(stmt); - if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) + if ((uState == ITEM_CHANGED) && HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GIFT_OWNER); + stmt->setUInt32(0, GUID_LOPART(GetOwnerGUID())); + stmt->setUInt32(1, guid); + trans->Append(stmt); + } + break; + } + case ITEM_REMOVED: { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->setUInt32(0, guid); trans->Append(stmt); + + if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); + stmt->setUInt32(0, guid); + trans->Append(stmt); + } + + if (!isInTransaction) + CharacterDatabase.CommitTransaction(trans); + + delete this; + return; } - - if (!isInTransaction) - CharacterDatabase.CommitTransaction(trans); - - delete this; - return; - } case ITEM_UNCHANGED: break; } @@ -467,7 +467,7 @@ bool Item::LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entr /*static*/ void Item::DeleteFromDB(SQLTransaction& trans, uint32 itemGuid) { - sScriptMgr->OnGlobalItemDelFromDB(trans,itemGuid); + sScriptMgr->OnGlobalItemDelFromDB(trans, itemGuid); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->setUInt32(0, itemGuid); trans->Append(stmt); @@ -516,32 +516,54 @@ uint32 Item::GetSpell() case ITEM_CLASS_WEAPON: switch (proto->SubClass) { - case ITEM_SUBCLASS_WEAPON_AXE: return 196; - case ITEM_SUBCLASS_WEAPON_AXE2: return 197; - case ITEM_SUBCLASS_WEAPON_BOW: return 264; - case ITEM_SUBCLASS_WEAPON_GUN: return 266; - case ITEM_SUBCLASS_WEAPON_MACE: return 198; - case ITEM_SUBCLASS_WEAPON_MACE2: return 199; - case ITEM_SUBCLASS_WEAPON_POLEARM: return 200; - case ITEM_SUBCLASS_WEAPON_SWORD: return 201; - case ITEM_SUBCLASS_WEAPON_SWORD2: return 202; - case ITEM_SUBCLASS_WEAPON_STAFF: return 227; - case ITEM_SUBCLASS_WEAPON_DAGGER: return 1180; - case ITEM_SUBCLASS_WEAPON_THROWN: return 2567; - case ITEM_SUBCLASS_WEAPON_SPEAR: return 3386; - case ITEM_SUBCLASS_WEAPON_CROSSBOW:return 5011; - case ITEM_SUBCLASS_WEAPON_WAND: return 5009; - default: return 0; + case ITEM_SUBCLASS_WEAPON_AXE: + return 196; + case ITEM_SUBCLASS_WEAPON_AXE2: + return 197; + case ITEM_SUBCLASS_WEAPON_BOW: + return 264; + case ITEM_SUBCLASS_WEAPON_GUN: + return 266; + case ITEM_SUBCLASS_WEAPON_MACE: + return 198; + case ITEM_SUBCLASS_WEAPON_MACE2: + return 199; + case ITEM_SUBCLASS_WEAPON_POLEARM: + return 200; + case ITEM_SUBCLASS_WEAPON_SWORD: + return 201; + case ITEM_SUBCLASS_WEAPON_SWORD2: + return 202; + case ITEM_SUBCLASS_WEAPON_STAFF: + return 227; + case ITEM_SUBCLASS_WEAPON_DAGGER: + return 1180; + case ITEM_SUBCLASS_WEAPON_THROWN: + return 2567; + case ITEM_SUBCLASS_WEAPON_SPEAR: + return 3386; + case ITEM_SUBCLASS_WEAPON_CROSSBOW: + return 5011; + case ITEM_SUBCLASS_WEAPON_WAND: + return 5009; + default: + return 0; } case ITEM_CLASS_ARMOR: switch (proto->SubClass) { - case ITEM_SUBCLASS_ARMOR_CLOTH: return 9078; - case ITEM_SUBCLASS_ARMOR_LEATHER: return 9077; - case ITEM_SUBCLASS_ARMOR_MAIL: return 8737; - case ITEM_SUBCLASS_ARMOR_PLATE: return 750; - case ITEM_SUBCLASS_ARMOR_SHIELD: return 9116; - default: return 0; + case ITEM_SUBCLASS_ARMOR_CLOTH: + return 9078; + case ITEM_SUBCLASS_ARMOR_LEATHER: + return 9077; + case ITEM_SUBCLASS_ARMOR_MAIL: + return 8737; + case ITEM_SUBCLASS_ARMOR_PLATE: + return 750; + case ITEM_SUBCLASS_ARMOR_SHIELD: + return 9116; + default: + return 0; } } return 0; @@ -618,7 +640,7 @@ void Item::SetItemRandomProperties(int32 randomPropId) if (item_rand) { if (GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID) != -int32(item_rand->ID) || - !GetItemSuffixFactor()) + !GetItemSuffixFactor()) { SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, -int32(item_rand->ID)); UpdateItemSuffixFactor(); @@ -688,7 +710,7 @@ void Item::AddToUpdateQueueOf(Player* player) return; player->m_itemUpdateQueue.push_back(this); - uQueuePos = player->m_itemUpdateQueue.size()-1; + uQueuePos = player->m_itemUpdateQueue.size() - 1; } void Item::RemoveFromUpdateQueueOf(Player* player) @@ -763,7 +785,7 @@ bool Item::HasEnchantRequiredSkill(const Player* player) const if (enchantEntry->requiredSkill && player->GetSkillValue(enchantEntry->requiredSkill) < enchantEntry->requiredSkillValue) return false; - return true; + return true; } uint32 Item::GetEnchantRequiredLevel() const @@ -825,7 +847,7 @@ bool Item::IsFitToSpellRequirements(SpellInfo const* spellInfo) const { // Special case - accept vellum for armor/weapon requirements if ((spellInfo->EquippedItemClass == ITEM_CLASS_ARMOR && proto->IsArmorVellum()) - ||(spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && proto->IsWeaponVellum())) + || (spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && proto->IsWeaponVellum())) if (spellInfo->IsAbilityOfSkillType(SKILL_ENCHANTING)) // only for enchanting spells return true; @@ -843,8 +865,8 @@ bool Item::IsFitToSpellRequirements(SpellInfo const* spellInfo) const { // Special case - accept weapon type for main and offhand requirements if (proto->InventoryType == INVTYPE_WEAPON && - (spellInfo->EquippedItemInventoryTypeMask & (1 << INVTYPE_WEAPONMAINHAND) || - spellInfo->EquippedItemInventoryTypeMask & (1 << INVTYPE_WEAPONOFFHAND))) + (spellInfo->EquippedItemInventoryTypeMask & (1 << INVTYPE_WEAPONMAINHAND) || + spellInfo->EquippedItemInventoryTypeMask & (1 << INVTYPE_WEAPONOFFHAND))) return true; else if ((spellInfo->EquippedItemInventoryTypeMask & (1 << proto->InventoryType)) == 0) return false; // inventory type not present in mask @@ -869,9 +891,9 @@ void Item::SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint owner->GetSession()->SendEnchantmentLog(GetOwnerGUID(), caster, GetEntry(), id); } - SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET, id); - SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET, duration); - SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET, charges); + SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET, id); + SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET, duration); + SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET, charges); SetState(ITEM_CHANGED, owner); } void Item::SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* owner) @@ -879,7 +901,7 @@ void Item::SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* if (GetEnchantmentDuration(slot) == duration) return; - SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET, duration); + SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET, duration); SetState(ITEM_CHANGED, owner); // Cannot use GetOwner() here, has to be passed as an argument to avoid freeze due to hashtable locking } @@ -889,7 +911,7 @@ void Item::SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges) if (GetEnchantmentCharges(slot) == charges) return; - SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET, charges); + SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET, charges); SetState(ITEM_CHANGED, GetOwner()); } @@ -899,15 +921,15 @@ void Item::ClearEnchantment(EnchantmentSlot slot) return; for (uint8 x = 0; x < MAX_SPELL_ITEM_ENCHANTMENT_EFFECTS; ++x) - SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + x, 0); + SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + x, 0); SetState(ITEM_CHANGED, GetOwner()); } bool Item::GemsFitSockets() const { - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) { - uint8 SocketColor = GetTemplate()->Socket[enchant_slot-SOCK_ENCHANTMENT_SLOT].Color; + uint8 SocketColor = GetTemplate()->Socket[enchant_slot - SOCK_ENCHANTMENT_SLOT].Color; if (!SocketColor) // no socket slot continue; @@ -943,7 +965,7 @@ bool Item::GemsFitSockets() const uint8 Item::GetGemCountWithID(uint32 GemID) const { uint8 count = 0; - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) { uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) @@ -962,7 +984,7 @@ uint8 Item::GetGemCountWithID(uint32 GemID) const uint8 Item::GetGemCountWithLimitCategory(uint32 limitCategory) const { uint8 count = 0; - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) { uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) @@ -990,7 +1012,7 @@ bool Item::IsLimitedToAnotherMapOrZone(uint32 cur_mapId, uint32 cur_zoneId) cons void Item::SendUpdateSockets() { - WorldPacket data(SMSG_SOCKET_GEMS_RESULT, 8+4+4+4+4); + WorldPacket data(SMSG_SOCKET_GEMS_RESULT, 8 + 4 + 4 + 4 + 4); data << uint64(GetGUID()); for (uint32 i = SOCK_ENCHANTMENT_SLOT; i <= BONUS_ENCHANTMENT_SLOT; ++i) data << uint32(GetEnchantmentId(EnchantmentSlot(i))); @@ -1007,7 +1029,7 @@ void Item::SendTimeUpdate(Player* owner) if (!duration) return; - WorldPacket data(SMSG_ITEM_TIME_UPDATE, (8+4)); + WorldPacket data(SMSG_ITEM_TIME_UPDATE, (8 + 4)); data << uint64(GetGUID()); data << uint32(duration); owner->GetSession()->SendPacket(&data); @@ -1024,7 +1046,7 @@ Item* Item::CreateItem(uint32 item, uint32 count, Player const* player, bool clo if (count > pProto->GetMaxStackSize()) count = pProto->GetMaxStackSize(); - ASSERT(count !=0 && "pProto->Stackable == 0 but checked at loading already"); + ASSERT(count != 0 && "pProto->Stackable == 0 but checked at loading already"); Item* pItem = NewItemOrBag(pProto); if (pItem->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_ITEM), item, player)) @@ -1032,9 +1054,8 @@ Item* Item::CreateItem(uint32 item, uint32 count, Player const* player, bool clo pItem->SetCount(count); if (!clone) pItem->SetItemRandomProperties(randomPropertyId ? randomPropertyId : Item::GenerateItemRandomPropertyId(item)); - else - if (randomPropertyId) - pItem->SetItemRandomProperties(randomPropertyId); + else if (randomPropertyId) + pItem->SetItemRandomProperties(randomPropertyId); return pItem; } else @@ -1048,7 +1069,7 @@ Item* Item::CreateItem(uint32 item, uint32 count, Player const* player, bool clo Item* Item::CloneItem(uint32 count, Player const* player) const { // player CAN be NULL in which case we must not update random properties because that accesses player's item update queue - Item * newItem = CreateItem(GetEntry(), count, player, true, player ? GetItemRandomPropertyId() : 0); + Item* newItem = CreateItem(GetEntry(), count, player, true, player ? GetItemRandomPropertyId() : 0); if (!newItem) return nullptr; @@ -1147,7 +1168,7 @@ void Item::UpdatePlayedTime(Player* owner) uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); uint32 new_playtime = current_playtime + elapsed; // Check if the refund timer has expired yet - if (new_playtime <= 2*HOUR) + if (new_playtime <= 2 * HOUR) { // No? Proceed. // Update the data field @@ -1171,7 +1192,7 @@ uint32 Item::GetPlayedTime() bool Item::IsRefundExpired() { - return (GetPlayedTime() > 2*HOUR); + return (GetPlayedTime() > 2 * HOUR); } void Item::SetSoulboundTradeable(AllowedLooterSet& allowedLooters) @@ -1196,7 +1217,7 @@ void Item::ClearSoulboundTradeable(Player* currentOwner) bool Item::CheckSoulboundTradeExpire() { // called from owner's update - GetOwner() MUST be valid - if (GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + 2*HOUR < GetOwner()->GetTotalPlayedTime()) + if (GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + 2 * HOUR < GetOwner()->GetTotalPlayedTime()) { ClearSoulboundTradeable(GetOwner()); return true; // remove from tradeable list diff --git a/src/server/game/Entities/Item/Item.h b/src/server/game/Entities/Item/Item.h index 4d07b4339..045b7c41e 100644 --- a/src/server/game/Entities/Item/Item.h +++ b/src/server/game/Entities/Item/Item.h @@ -195,154 +195,154 @@ bool ItemCanGoIntoBag(ItemTemplate const* proto, ItemTemplate const* pBagProto); class Item : public Object { - public: - static Item* CreateItem(uint32 item, uint32 count, Player const* player = NULL, bool clone = false, uint32 randomPropertyId = 0); - Item* CloneItem(uint32 count, Player const* player = nullptr) const; +public: + static Item* CreateItem(uint32 item, uint32 count, Player const* player = NULL, bool clone = false, uint32 randomPropertyId = 0); + Item* CloneItem(uint32 count, Player const* player = nullptr) const; - Item(); + Item(); - virtual bool Create(uint32 guidlow, uint32 itemid, Player const* owner); + virtual bool Create(uint32 guidlow, uint32 itemid, Player const* owner); - ItemTemplate const* GetTemplate() const; + ItemTemplate const* GetTemplate() const; - uint64 GetOwnerGUID() const { return GetUInt64Value(ITEM_FIELD_OWNER); } - void SetOwnerGUID(uint64 guid) { SetUInt64Value(ITEM_FIELD_OWNER, guid); } - Player* GetOwner() const; + uint64 GetOwnerGUID() const { return GetUInt64Value(ITEM_FIELD_OWNER); } + void SetOwnerGUID(uint64 guid) { SetUInt64Value(ITEM_FIELD_OWNER, guid); } + Player* GetOwner() const; - void SetBinding(bool val) { ApplyModFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_SOULBOUND, val); } - bool IsSoulBound() const { return HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_SOULBOUND); } - bool IsBoundAccountWide() const { return (GetTemplate()->Flags & ITEM_FLAG_IS_BOUND_TO_ACCOUNT) != 0; } - bool IsBindedNotWith(Player const* player) const; - bool IsBoundByEnchant() const; - bool IsBoundByTempEnchant() const; - virtual void SaveToDB(SQLTransaction& trans); - virtual bool LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entry); - static void DeleteFromDB(SQLTransaction& trans, uint32 itemGuid); - virtual void DeleteFromDB(SQLTransaction& trans); - static void DeleteFromInventoryDB(SQLTransaction& trans, uint32 itemGuid); - void DeleteFromInventoryDB(SQLTransaction& trans); - void SaveRefundDataToDB(); - void DeleteRefundDataFromDB(SQLTransaction* trans); + void SetBinding(bool val) { ApplyModFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_SOULBOUND, val); } + bool IsSoulBound() const { return HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_SOULBOUND); } + bool IsBoundAccountWide() const { return (GetTemplate()->Flags & ITEM_FLAG_IS_BOUND_TO_ACCOUNT) != 0; } + bool IsBindedNotWith(Player const* player) const; + bool IsBoundByEnchant() const; + bool IsBoundByTempEnchant() const; + virtual void SaveToDB(SQLTransaction& trans); + virtual bool LoadFromDB(uint32 guid, uint64 owner_guid, Field* fields, uint32 entry); + static void DeleteFromDB(SQLTransaction& trans, uint32 itemGuid); + virtual void DeleteFromDB(SQLTransaction& trans); + static void DeleteFromInventoryDB(SQLTransaction& trans, uint32 itemGuid); + void DeleteFromInventoryDB(SQLTransaction& trans); + void SaveRefundDataToDB(); + void DeleteRefundDataFromDB(SQLTransaction* trans); - Bag* ToBag() { if (IsBag()) return reinterpret_cast(this); else return nullptr; } - const Bag* ToBag() const { if (IsBag()) return reinterpret_cast(this); else return nullptr; } + Bag* ToBag() { if (IsBag()) return reinterpret_cast(this); else return nullptr; } + const Bag* ToBag() const { if (IsBag()) return reinterpret_cast(this); else return nullptr; } - bool IsLocked() const { return !HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_UNLOCKED); } - bool IsBag() const { return GetTemplate()->InventoryType == INVTYPE_BAG; } - bool IsCurrencyToken() const { return GetTemplate()->IsCurrencyToken(); } - bool IsNotEmptyBag() const; - bool IsBroken() const { return GetUInt32Value(ITEM_FIELD_MAXDURABILITY) > 0 && GetUInt32Value(ITEM_FIELD_DURABILITY) == 0; } - bool CanBeTraded(bool mail = false, bool trade = false) const; - void SetInTrade(bool b = true) { mb_in_trade = b; } - bool IsInTrade() const { return mb_in_trade; } + bool IsLocked() const { return !HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_UNLOCKED); } + bool IsBag() const { return GetTemplate()->InventoryType == INVTYPE_BAG; } + bool IsCurrencyToken() const { return GetTemplate()->IsCurrencyToken(); } + bool IsNotEmptyBag() const; + bool IsBroken() const { return GetUInt32Value(ITEM_FIELD_MAXDURABILITY) > 0 && GetUInt32Value(ITEM_FIELD_DURABILITY) == 0; } + bool CanBeTraded(bool mail = false, bool trade = false) const; + void SetInTrade(bool b = true) { mb_in_trade = b; } + bool IsInTrade() const { return mb_in_trade; } - bool HasEnchantRequiredSkill(const Player* player) const; - uint32 GetEnchantRequiredLevel() const; + bool HasEnchantRequiredSkill(const Player* player) const; + uint32 GetEnchantRequiredLevel() const; - bool IsFitToSpellRequirements(SpellInfo const* spellInfo) const; - bool IsLimitedToAnotherMapOrZone(uint32 cur_mapId, uint32 cur_zoneId) const; - bool GemsFitSockets() const; + bool IsFitToSpellRequirements(SpellInfo const* spellInfo) const; + bool IsLimitedToAnotherMapOrZone(uint32 cur_mapId, uint32 cur_zoneId) const; + bool GemsFitSockets() const; - uint32 GetCount() const { return GetUInt32Value(ITEM_FIELD_STACK_COUNT); } - void SetCount(uint32 value) { SetUInt32Value(ITEM_FIELD_STACK_COUNT, value); } - uint32 GetMaxStackCount() const { return GetTemplate()->GetMaxStackSize(); } - uint8 GetGemCountWithID(uint32 GemID) const; - uint8 GetGemCountWithLimitCategory(uint32 limitCategory) const; - InventoryResult CanBeMergedPartlyWith(ItemTemplate const* proto) const; + uint32 GetCount() const { return GetUInt32Value(ITEM_FIELD_STACK_COUNT); } + void SetCount(uint32 value) { SetUInt32Value(ITEM_FIELD_STACK_COUNT, value); } + uint32 GetMaxStackCount() const { return GetTemplate()->GetMaxStackSize(); } + uint8 GetGemCountWithID(uint32 GemID) const; + uint8 GetGemCountWithLimitCategory(uint32 limitCategory) const; + InventoryResult CanBeMergedPartlyWith(ItemTemplate const* proto) const; - uint8 GetSlot() const {return m_slot;} - Bag* GetContainer() { return m_container; } - uint8 GetBagSlot() const; - void SetSlot(uint8 slot) { m_slot = slot; } - uint16 GetPos() const { return uint16(GetBagSlot()) << 8 | GetSlot(); } - void SetContainer(Bag* container) { m_container = container; } + uint8 GetSlot() const {return m_slot;} + Bag* GetContainer() { return m_container; } + uint8 GetBagSlot() const; + void SetSlot(uint8 slot) { m_slot = slot; } + uint16 GetPos() const { return uint16(GetBagSlot()) << 8 | GetSlot(); } + void SetContainer(Bag* container) { m_container = container; } - bool IsInBag() const { return m_container != nullptr; } - bool IsEquipped() const; + bool IsInBag() const { return m_container != nullptr; } + bool IsEquipped() const; - uint32 GetSkill(); - uint32 GetSpell(); + uint32 GetSkill(); + uint32 GetSpell(); - // RandomPropertyId (signed but stored as unsigned) - int32 GetItemRandomPropertyId() const { return GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID); } - uint32 GetItemSuffixFactor() const { return GetUInt32Value(ITEM_FIELD_PROPERTY_SEED); } - void SetItemRandomProperties(int32 randomPropId); - void UpdateItemSuffixFactor(); - static int32 GenerateItemRandomPropertyId(uint32 item_id); - void SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint32 charges, uint64 caster = 0); - void SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* owner); - void SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges); - void ClearEnchantment(EnchantmentSlot slot); - uint32 GetEnchantmentId(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET);} - uint32 GetEnchantmentDuration(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET);} - uint32 GetEnchantmentCharges(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET);} + // RandomPropertyId (signed but stored as unsigned) + int32 GetItemRandomPropertyId() const { return GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID); } + uint32 GetItemSuffixFactor() const { return GetUInt32Value(ITEM_FIELD_PROPERTY_SEED); } + void SetItemRandomProperties(int32 randomPropId); + void UpdateItemSuffixFactor(); + static int32 GenerateItemRandomPropertyId(uint32 item_id); + void SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint32 charges, uint64 caster = 0); + void SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* owner); + void SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges); + void ClearEnchantment(EnchantmentSlot slot); + uint32 GetEnchantmentId(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET);} + uint32 GetEnchantmentDuration(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET);} + uint32 GetEnchantmentCharges(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET);} - std::string const& GetText() const { return m_text; } - void SetText(std::string const& text) { m_text = text; } + std::string const& GetText() const { return m_text; } + void SetText(std::string const& text) { m_text = text; } - void SendUpdateSockets(); + void SendUpdateSockets(); - void SendTimeUpdate(Player* owner); - void UpdateDuration(Player* owner, uint32 diff); + void SendTimeUpdate(Player* owner); + void UpdateDuration(Player* owner, uint32 diff); - // spell charges (signed but stored as unsigned) - int32 GetSpellCharges(uint8 index/*0..5*/ = 0) const { return GetInt32Value(ITEM_FIELD_SPELL_CHARGES + index); } - void SetSpellCharges(uint8 index/*0..5*/, int32 value) { SetInt32Value(ITEM_FIELD_SPELL_CHARGES + index, value); } + // spell charges (signed but stored as unsigned) + int32 GetSpellCharges(uint8 index/*0..5*/ = 0) const { return GetInt32Value(ITEM_FIELD_SPELL_CHARGES + index); } + void SetSpellCharges(uint8 index/*0..5*/, int32 value) { SetInt32Value(ITEM_FIELD_SPELL_CHARGES + index, value); } - Loot loot; - bool m_lootGenerated; + Loot loot; + bool m_lootGenerated; - // Update States - ItemUpdateState GetState() const { return uState; } - void SetState(ItemUpdateState state, Player* forplayer = nullptr); - void AddToUpdateQueueOf(Player* player); - void RemoveFromUpdateQueueOf(Player* player); - bool IsInUpdateQueue() const { return uQueuePos != -1; } - uint32 GetQueuePos() const { return uQueuePos; } - void FSetState(ItemUpdateState state) // forced - { - uState = state; - } + // Update States + ItemUpdateState GetState() const { return uState; } + void SetState(ItemUpdateState state, Player* forplayer = nullptr); + void AddToUpdateQueueOf(Player* player); + void RemoveFromUpdateQueueOf(Player* player); + bool IsInUpdateQueue() const { return uQueuePos != -1; } + uint32 GetQueuePos() const { return uQueuePos; } + void FSetState(ItemUpdateState state) // forced + { + uState = state; + } - bool hasQuest(uint32 quest_id) const { return GetTemplate()->StartQuest == quest_id; } - bool hasInvolvedQuest(uint32 /*quest_id*/) const { return false; } - bool IsPotion() const { return GetTemplate()->IsPotion(); } - bool IsWeaponVellum() const { return GetTemplate()->IsWeaponVellum(); } - bool IsArmorVellum() const { return GetTemplate()->IsArmorVellum(); } - bool IsConjuredConsumable() const { return GetTemplate()->IsConjuredConsumable(); } + bool hasQuest(uint32 quest_id) const { return GetTemplate()->StartQuest == quest_id; } + bool hasInvolvedQuest(uint32 /*quest_id*/) const { return false; } + bool IsPotion() const { return GetTemplate()->IsPotion(); } + bool IsWeaponVellum() const { return GetTemplate()->IsWeaponVellum(); } + bool IsArmorVellum() const { return GetTemplate()->IsArmorVellum(); } + bool IsConjuredConsumable() const { return GetTemplate()->IsConjuredConsumable(); } - // Item Refund system - void SetNotRefundable(Player* owner, bool changestate = true, SQLTransaction* trans = nullptr); - void SetRefundRecipient(uint32 pGuidLow) { m_refundRecipient = pGuidLow; } - void SetPaidMoney(uint32 money) { m_paidMoney = money; } - void SetPaidExtendedCost(uint32 iece) { m_paidExtendedCost = iece; } - uint32 GetRefundRecipient() { return m_refundRecipient; } - uint32 GetPaidMoney() { return m_paidMoney; } - uint32 GetPaidExtendedCost() { return m_paidExtendedCost; } + // Item Refund system + void SetNotRefundable(Player* owner, bool changestate = true, SQLTransaction* trans = nullptr); + void SetRefundRecipient(uint32 pGuidLow) { m_refundRecipient = pGuidLow; } + void SetPaidMoney(uint32 money) { m_paidMoney = money; } + void SetPaidExtendedCost(uint32 iece) { m_paidExtendedCost = iece; } + uint32 GetRefundRecipient() { return m_refundRecipient; } + uint32 GetPaidMoney() { return m_paidMoney; } + uint32 GetPaidExtendedCost() { return m_paidExtendedCost; } - void UpdatePlayedTime(Player* owner); - uint32 GetPlayedTime(); - bool IsRefundExpired(); + void UpdatePlayedTime(Player* owner); + uint32 GetPlayedTime(); + bool IsRefundExpired(); - // Soulbound trade system - void SetSoulboundTradeable(AllowedLooterSet& allowedLooters); - void ClearSoulboundTradeable(Player* currentOwner); - bool CheckSoulboundTradeExpire(); + // Soulbound trade system + void SetSoulboundTradeable(AllowedLooterSet& allowedLooters); + void ClearSoulboundTradeable(Player* currentOwner); + bool CheckSoulboundTradeExpire(); - void BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet&); + void BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet&); - uint32 GetScriptId() const { return GetTemplate()->ScriptId; } - private: - std::string m_text; - uint8 m_slot; - Bag* m_container; - ItemUpdateState uState; - int32 uQueuePos; - bool mb_in_trade; // true if item is currently in trade-window - time_t m_lastPlayedTimeUpdate; - uint32 m_refundRecipient; - uint32 m_paidMoney; - uint32 m_paidExtendedCost; - AllowedLooterSet allowedGUIDs; + uint32 GetScriptId() const { return GetTemplate()->ScriptId; } +private: + std::string m_text; + uint8 m_slot; + Bag* m_container; + ItemUpdateState uState; + int32 uQueuePos; + bool mb_in_trade; // true if item is currently in trade-window + time_t m_lastPlayedTimeUpdate; + uint32 m_refundRecipient; + uint32 m_paidMoney; + uint32 m_paidExtendedCost; + AllowedLooterSet allowedGUIDs; }; #endif diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp index 6a75dd287..34bfcb46a 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp @@ -134,7 +134,7 @@ uint32 GenerateEnchSuffixFactor(uint32 item_id) case INVTYPE_QUIVER: case INVTYPE_RELIC: return 0; - // Select point coefficient + // Select point coefficient case INVTYPE_HEAD: case INVTYPE_BODY: case INVTYPE_CHEST: diff --git a/src/server/game/Entities/Item/ItemTemplate.h b/src/server/game/Entities/Item/ItemTemplate.h index 124a69bc6..5608b99ba 100644 --- a/src/server/game/Entities/Item/ItemTemplate.h +++ b/src/server/game/Entities/Item/ItemTemplate.h @@ -555,9 +555,12 @@ inline uint8 ItemSubClassToDurabilityMultiplierId(uint32 ItemClass, uint32 ItemS { switch (ItemClass) { - case ITEM_CLASS_WEAPON: return ItemSubClass; - case ITEM_CLASS_ARMOR: return ItemSubClass + 21; - default: return 0; + case ITEM_CLASS_WEAPON: + return ItemSubClass; + case ITEM_CLASS_ARMOR: + return ItemSubClass + 21; + default: + return 0; } } @@ -692,10 +695,10 @@ struct ItemTemplate bool HasSignature() const { return GetMaxStackSize() == 1 && - Class != ITEM_CLASS_CONSUMABLE && - Class != ITEM_CLASS_QUEST && - (Flags & ITEM_FLAG_NO_CREATOR) == 0 && - ItemId != 6948; /*Hearthstone*/ + Class != ITEM_CLASS_CONSUMABLE && + Class != ITEM_CLASS_QUEST && + (Flags & ITEM_FLAG_NO_CREATOR) == 0 && + ItemId != 6948; /*Hearthstone*/ } bool CanChangeEquipStateInCombat() const @@ -722,7 +725,7 @@ struct ItemTemplate uint32 GetMaxStackSize() const { - return (Stackable == 2147483647 || Stackable <= 0) ? uint32(0x7FFFFFFF-1) : uint32(Stackable); + return (Stackable == 2147483647 || Stackable <= 0) ? uint32(0x7FFFFFFF - 1) : uint32(Stackable); } float getDPS() const @@ -731,16 +734,16 @@ struct ItemTemplate return 0; float temp = 0; for (auto i : Damage) - temp+=i.DamageMin + i.DamageMax; - return temp*500/Delay; + temp += i.DamageMin + i.DamageMax; + return temp * 500 / Delay; } int32 getFeralBonus(int32 extraDPS = 0) const { // 0x02A5F3 - is mask for Melee weapon from ItemSubClassMask.dbc - if (Class == ITEM_CLASS_WEAPON && (1<GetOwner()) - updatetype = UPDATETYPE_CREATE_OBJECT2; + updatetype = UPDATETYPE_CREATE_OBJECT2; break; } } @@ -328,7 +337,7 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 flags) const // 0x08000000 if (unit->m_movementInfo.GetMovementFlags() & MOVEMENTFLAG_SPLINE_ENABLED) { - const G3D::Vector3 * p = &unit->movespline->_Spline().getPoints(true)[0]; + const G3D::Vector3* p = &unit->movespline->_Spline().getPoints(true)[0]; if (unit->movespline->_Spline().getPoints(true).empty() || (!unit->movespline->_Spline().getPoints(true).empty() && !p)) const_cast(unit)->DisableSpline(); else @@ -469,7 +478,7 @@ void Object::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* targe for (uint16 index = 0; index < m_valuesCount; ++index) { if (_fieldNotifyFlags & flags[index] || - ((updateType == UPDATETYPE_VALUES ? _changesMask.GetBit(index) : m_uint32Values[index]) && (flags[index] & visibleFlag))) + ((updateType == UPDATETYPE_VALUES ? _changesMask.GetBit(index) : m_uint32Values[index]) && (flags[index] & visibleFlag))) { updateMask.SetBit(index); fieldBuffer << m_uint32Values[index]; @@ -524,20 +533,20 @@ uint32 Object::GetUpdateFieldData(Player const* target, uint32*& flags) const break; case TYPEID_UNIT: case TYPEID_PLAYER: - { - Player* plr = ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself(); - flags = UnitUpdateFieldFlags; - if (ToUnit()->GetOwnerGUID() == target->GetGUID()) - visibleFlag |= UF_FLAG_OWNER; + { + Player* plr = ToUnit()->GetCharmerOrOwnerPlayerOrPlayerItself(); + flags = UnitUpdateFieldFlags; + if (ToUnit()->GetOwnerGUID() == target->GetGUID()) + visibleFlag |= UF_FLAG_OWNER; - if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO)) - if (ToUnit()->HasAuraTypeWithCaster(SPELL_AURA_EMPATHY, target->GetGUID())) - visibleFlag |= UF_FLAG_SPECIAL_INFO; + if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO)) + if (ToUnit()->HasAuraTypeWithCaster(SPELL_AURA_EMPATHY, target->GetGUID())) + visibleFlag |= UF_FLAG_SPECIAL_INFO; - if (plr && plr->IsInSameRaidWith(target)) - visibleFlag |= UF_FLAG_PARTY_MEMBER; - break; - } + if (plr && plr->IsInSameRaidWith(target)) + visibleFlag |= UF_FLAG_PARTY_MEMBER; + break; + } case TYPEID_GAMEOBJECT: flags = GameObjectUpdateFieldFlags; if (ToGameObject()->GetOwnerGUID() == target->GetGUID()) @@ -622,7 +631,7 @@ void Object::UpdateUInt32Value(uint16 index, uint32 value) void Object::SetUInt64Value(uint16 index, uint64 value) { ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, true)); - if (*((uint64*)&(m_uint32Values[index])) != value) + if (*((uint64*) & (m_uint32Values[index])) != value) { m_uint32Values[index] = PAIR64_LOPART(value); m_uint32Values[index + 1] = PAIR64_HIPART(value); @@ -640,7 +649,7 @@ void Object::SetUInt64Value(uint16 index, uint64 value) bool Object::AddUInt64Value(uint16 index, uint64 value) { ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, true)); - if (value && !*((uint64*)&(m_uint32Values[index]))) + if (value && !*((uint64*) & (m_uint32Values[index]))) { m_uint32Values[index] = PAIR64_LOPART(value); m_uint32Values[index + 1] = PAIR64_HIPART(value); @@ -662,7 +671,7 @@ bool Object::AddUInt64Value(uint16 index, uint64 value) bool Object::RemoveUInt64Value(uint16 index, uint64 value) { ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, true)); - if (value && *((uint64*)&(m_uint32Values[index])) == value) + if (value && *((uint64*) & (m_uint32Values[index])) == value) { m_uint32Values[index] = 0; m_uint32Values[index + 1] = 0; @@ -976,11 +985,11 @@ void MovementInfo::OutDebug() WorldObject::WorldObject(bool isWorldObject) : WorldLocation(), #ifdef ELUNA -elunaEvents(nullptr), + elunaEvents(nullptr), #endif -LastUsedScriptID(0), m_name(""), m_isActive(false), m_isVisibilityDistanceOverride(false), m_isWorldObject(isWorldObject), m_zoneScript(nullptr), -m_transport(nullptr), m_currMap(nullptr), m_InstanceId(0), -m_phaseMask(PHASEMASK_NORMAL), m_useCombinedPhases(true), m_notifyflags(0), m_executed_notifies(0) + LastUsedScriptID(0), m_name(""), m_isActive(false), m_isVisibilityDistanceOverride(false), m_isWorldObject(isWorldObject), m_zoneScript(nullptr), + m_transport(nullptr), m_currMap(nullptr), m_InstanceId(0), + m_phaseMask(PHASEMASK_NORMAL), m_useCombinedPhases(true), m_notifyflags(0), m_executed_notifies(0) { m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE | GHOST_VISIBILITY_GHOST); m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); @@ -1118,11 +1127,11 @@ bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); - float distsq = dx*dx + dy*dy; + float distsq = dx * dx + dy * dy; if (is3D) { float dz = GetPositionZ() - obj->GetPositionZ(); - distsq += dz*dz; + distsq += dz * dz; } return distsq < maxdist * maxdist; @@ -1178,20 +1187,20 @@ bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* o { float dx1 = GetPositionX() - obj1->GetPositionX(); float dy1 = GetPositionY() - obj1->GetPositionY(); - float distsq1 = dx1*dx1 + dy1*dy1; + float distsq1 = dx1 * dx1 + dy1 * dy1; if (is3D) { float dz1 = GetPositionZ() - obj1->GetPositionZ(); - distsq1 += dz1*dz1; + distsq1 += dz1 * dz1; } float dx2 = GetPositionX() - obj2->GetPositionX(); float dy2 = GetPositionY() - obj2->GetPositionY(); - float distsq2 = dx2*dx2 + dy2*dy2; + float distsq2 = dx2 * dx2 + dy2 * dy2; if (is3D) { float dz2 = GetPositionZ() - obj2->GetPositionZ(); - distsq2 += dz2*dz2; + distsq2 += dz2 * dz2; } return distsq1 < distsq2; @@ -1201,11 +1210,11 @@ bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRan { float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); - float distsq = dx*dx + dy*dy; + float distsq = dx * dx + dy * dy; if (is3D) { float dz = GetPositionZ() - obj->GetPositionZ(); - distsq += dz*dz; + distsq += dz * dz; } float sizefactor = GetObjectSize() + obj->GetObjectSize(); @@ -1226,7 +1235,7 @@ bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) { float dx = GetPositionX() - x; float dy = GetPositionY() - y; - float distsq = dx*dx + dy*dy; + float distsq = dx * dx + dy * dy; float sizefactor = GetObjectSize(); @@ -1247,7 +1256,7 @@ bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float m float dx = GetPositionX() - x; float dy = GetPositionY() - y; float dz = GetPositionZ() - z; - float distsq = dx*dx + dy*dy + dz*dz; + float distsq = dx * dx + dy * dy + dz * dz; float sizefactor = GetObjectSize(); @@ -1263,7 +1272,7 @@ bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float m return distsq < maxdist * maxdist; } -void Position::RelocateOffset(const Position & offset) +void Position::RelocateOffset(const Position& offset) { m_positionX = GetPositionX() + (offset.GetPositionX() * cos(GetOrientation()) + offset.GetPositionY() * sin(GetOrientation() + M_PI)); m_positionY = GetPositionY() + (offset.GetPositionY() * cos(GetOrientation()) + offset.GetPositionX() * sin(GetOrientation())); @@ -1271,7 +1280,7 @@ void Position::RelocateOffset(const Position & offset) m_orientation = GetOrientation() + offset.GetOrientation(); } -void Position::GetPositionOffsetTo(const Position & endPos, Position & retOffset) const +void Position::GetPositionOffsetTo(const Position& endPos, Position& retOffset) const { float dx = endPos.GetPositionX() - GetPositionX(); float dy = endPos.GetPositionY() - GetPositionY(); @@ -1301,20 +1310,20 @@ float Position::GetAngle(const float x, const float y) const return ang; } -void Position::GetSinCos(const float x, const float y, float &vsin, float &vcos) const +void Position::GetSinCos(const float x, const float y, float& vsin, float& vcos) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; if (fabs(dx) < 0.001f && fabs(dy) < 0.001f) { - float angle = (float)rand_norm()*static_cast(2*M_PI); + float angle = (float)rand_norm() * static_cast(2 * M_PI); vcos = cos(angle); vsin = sin(angle); } else { - float dist = sqrt((dx*dx) + (dy*dy)); + float dist = sqrt((dx * dx) + (dy * dy)); vcos = dx / dist; vsin = dy / dist; } @@ -1333,16 +1342,16 @@ bool Position::IsWithinBox(const Position& center, float xradius, float yradius, float BoxDistX = GetPositionX() - center.GetPositionX(); float BoxDistY = GetPositionY() - center.GetPositionY(); - float rotX = float(center.GetPositionX() + BoxDistX * cosVal - BoxDistY*sinVal); - float rotY = float(center.GetPositionY() + BoxDistY * cosVal + BoxDistX*sinVal); + float rotX = float(center.GetPositionX() + BoxDistX * cosVal - BoxDistY * sinVal); + float rotY = float(center.GetPositionY() + BoxDistY * cosVal + BoxDistX * sinVal); // box edges are parallel to coordiante axis, so we can treat every dimension independently :D float dz = GetPositionZ() - center.GetPositionZ(); float dx = rotX - center.GetPositionX(); float dy = rotY - center.GetPositionY(); if ((std::fabs(dx) > xradius) || - (std::fabs(dy) > yradius) || - (std::fabs(dz) > zradius)) + (std::fabs(dy) > yradius) || + (std::fabs(dz) > zradius)) return false; return true; @@ -1363,17 +1372,17 @@ bool Position::HasInArc(float arc, const Position* obj, float targetRadius) cons // move angle to range -pi ... +pi angle = Position::NormalizeOrientation(angle); if (angle > M_PI) - angle -= 2.0f*M_PI; + angle -= 2.0f * M_PI; - float lborder = -1 * (arc/2.0f); // in range -pi..0 - float rborder = (arc/2.0f); // in range 0..pi + float lborder = -1 * (arc / 2.0f); // in range -pi..0 + float rborder = (arc / 2.0f); // in range 0..pi // pussywizard: take into consideration target size if (targetRadius > 0.0f) { float distSq = GetExactDist2dSq(obj); // pussywizard: at least a part of target's model is in every direction - if (distSq < targetRadius*targetRadius) + if (distSq < targetRadius * targetRadius) return true; float angularRadius = 2.0f * atan(targetRadius / (2.0f * sqrt(distSq))); lborder -= angularRadius; @@ -1396,12 +1405,12 @@ bool WorldObject::IsInBetween(const WorldObject* obj1, const WorldObject* obj2, return false; if (G3D::fuzzyEq(obj1->GetPositionX(), obj2->GetPositionX())) - return GetPositionX() >= obj1->GetPositionX()-size && GetPositionX() <= obj1->GetPositionX()+size; + return GetPositionX() >= obj1->GetPositionX() - size && GetPositionX() <= obj1->GetPositionX() + size; - float A = (obj2->GetPositionY()-obj1->GetPositionY())/(obj2->GetPositionX()-obj1->GetPositionX()); + float A = (obj2->GetPositionY() - obj1->GetPositionY()) / (obj2->GetPositionX() - obj1->GetPositionX()); float B = -1; - float C = obj1->GetPositionY() - A*obj1->GetPositionX(); - float dist = fabs(A*GetPositionX()+B*GetPositionY()+C)/sqrt(A*A+B*B); + float C = obj1->GetPositionY() - A * obj1->GetPositionX(); + float dist = fabs(A * GetPositionX() + B * GetPositionY() + C) / sqrt(A * A + B * B); return dist <= size; } @@ -1415,7 +1424,7 @@ bool WorldObject::isInBack(WorldObject const* target, float arc) const return !HasInArc(2 * M_PI - arc, target); } -void WorldObject::GetRandomPoint(const Position &pos, float distance, float &rand_x, float &rand_y, float &rand_z) const +void WorldObject::GetRandomPoint(const Position& pos, float distance, float& rand_x, float& rand_y, float& rand_z) const { if (!distance) { @@ -1424,8 +1433,8 @@ void WorldObject::GetRandomPoint(const Position &pos, float distance, float &ran } // angle to face `obj` to `this` - float angle = (float)rand_norm()*static_cast(2*M_PI); - float new_dist = (float)rand_norm()*static_cast(distance); + float angle = (float)rand_norm() * static_cast(2 * M_PI); + float new_dist = (float)rand_norm() * static_cast(distance); rand_x = pos.m_positionX + new_dist * cos(angle); rand_y = pos.m_positionY + new_dist * sin(angle); @@ -1436,14 +1445,14 @@ void WorldObject::GetRandomPoint(const Position &pos, float distance, float &ran UpdateGroundPositionZ(rand_x, rand_y, rand_z); // update to LOS height if available } -void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const +void WorldObject::UpdateGroundPositionZ(float x, float y, float& z) const { float new_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z /*+ 2.0f*/, true); // pussywizard: +2.0f is added in all inner functions if (new_z > INVALID_HEIGHT) z = new_z + 0.05f; // just to be sure that we are not a few pixel under the surface } -void WorldObject::UpdateAllowedPositionZ(float x, float y, float &z) const +void WorldObject::UpdateAllowedPositionZ(float x, float y, float& z) const { // TODO: Allow transports to be part of dynamic vmap tree //if (GetTransport()) @@ -1452,62 +1461,62 @@ void WorldObject::UpdateAllowedPositionZ(float x, float y, float &z) const switch (GetTypeId()) { case TYPEID_UNIT: - { - // non fly unit don't must be in air - // non swim unit must be at ground (mostly speedup, because it don't must be in water and water level check less fast - if (!ToCreature()->CanFly()) { - bool canSwim = ToCreature()->CanSwim(); - float ground_z = z; - float max_z = canSwim - ? GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)) - : ((ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true))); - if (max_z > INVALID_HEIGHT) + // non fly unit don't must be in air + // non swim unit must be at ground (mostly speedup, because it don't must be in water and water level check less fast + if (!ToCreature()->CanFly()) { - if (z > max_z) - z = max_z; - else if (z < ground_z) + bool canSwim = ToCreature()->CanSwim(); + float ground_z = z; + float max_z = canSwim + ? GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)) + : ((ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true))); + if (max_z > INVALID_HEIGHT) + { + if (z > max_z) + z = max_z; + else if (z < ground_z) + z = ground_z; + } + } + else + { + float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); + if (z < ground_z) z = ground_z; } + break; } - else - { - float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); - if (z < ground_z) - z = ground_z; - } - break; - } case TYPEID_PLAYER: - { - // for server controlled moves playr work same as creature (but it can always swim) - if (!ToPlayer()->CanFly()) { - float ground_z = z; - float max_z = GetMap()->GetWaterOrGroundLevel(GetPhaseMask(),x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)); - if (max_z > INVALID_HEIGHT) + // for server controlled moves playr work same as creature (but it can always swim) + if (!ToPlayer()->CanFly()) { - if (z > max_z) - z = max_z; - else if (z < ground_z) + float ground_z = z; + float max_z = GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)); + if (max_z > INVALID_HEIGHT) + { + if (z > max_z) + z = max_z; + else if (z < ground_z) + z = ground_z; + } + } + else + { + float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); + if (z < ground_z) z = ground_z; } + break; } - else + default: { float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); - if (z < ground_z) + if (ground_z > INVALID_HEIGHT) z = ground_z; + break; } - break; - } - default: - { - float ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true); - if (ground_z > INVALID_HEIGHT) - z = ground_z; - break; - } } } @@ -1535,11 +1544,11 @@ float WorldObject::GetVisibilityRange() const else if (GetTypeId() == TYPEID_GAMEOBJECT) { if (IsInWintergrasp()) - return VISIBILITY_DIST_WINTERGRASP+VISIBILITY_INC_FOR_GOBJECTS; + return VISIBILITY_DIST_WINTERGRASP + VISIBILITY_INC_FOR_GOBJECTS; else if (IsVisibilityOverridden()) return MAX_VISIBILITY_DISTANCE; else - return GetMap()->GetVisibilityRange()+VISIBILITY_INC_FOR_GOBJECTS; + return GetMap()->GetVisibilityRange() + VISIBILITY_INC_FOR_GOBJECTS; } else return IsInWintergrasp() ? VISIBILITY_DIST_WINTERGRASP : GetMap()->GetVisibilityRange(); @@ -1558,11 +1567,11 @@ float WorldObject::GetSightRange(const WorldObject* target) const else if (target->GetTypeId() == TYPEID_GAMEOBJECT) { if (IsInWintergrasp() && target->IsInWintergrasp()) - return VISIBILITY_DIST_WINTERGRASP+VISIBILITY_INC_FOR_GOBJECTS; + return VISIBILITY_DIST_WINTERGRASP + VISIBILITY_INC_FOR_GOBJECTS; else if (target->IsVisibilityOverridden()) return MAX_VISIBILITY_DISTANCE; else - return GetMap()->GetVisibilityRange()+VISIBILITY_INC_FOR_GOBJECTS; + return GetMap()->GetVisibilityRange() + VISIBILITY_INC_FOR_GOBJECTS; } return IsInWintergrasp() && target->IsInWintergrasp() ? VISIBILITY_DIST_WINTERGRASP : GetMap()->GetVisibilityRange(); @@ -1607,7 +1616,7 @@ bool WorldObject::CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth, boo if (Player const* thisPlayer = ToPlayer()) { if (thisPlayer->isDead() && thisPlayer->GetHealth() > 0 && // Cheap way to check for ghost state - !(obj->m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & GHOST_VISIBILITY_GHOST)) + !(obj->m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GHOST) & GHOST_VISIBILITY_GHOST)) { if (Corpse* corpse = thisPlayer->GetCorpse()) { @@ -1879,51 +1888,51 @@ void Object::ForceValuesUpdateAtIndex(uint32 i) namespace acore { - class MonsterChatBuilder + class MonsterChatBuilder { - public: - MonsterChatBuilder(WorldObject const* obj, ChatMsg msgtype, int32 textId, uint32 language, WorldObject const* target) - : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(Language(language)), i_target(target) { } - void operator()(WorldPacket& data, LocaleConstant loc_idx) + public: + MonsterChatBuilder(WorldObject const* obj, ChatMsg msgtype, int32 textId, uint32 language, WorldObject const* target) + : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(Language(language)), i_target(target) { } + void operator()(WorldPacket& data, LocaleConstant loc_idx) + { + if (BroadcastText const* broadcastText = sObjectMgr->GetBroadcastText(i_textId)) { - if (BroadcastText const* broadcastText = sObjectMgr->GetBroadcastText(i_textId)) - { - uint8 gender = GENDER_MALE; - if (Unit const* unit = i_object->ToUnit()) - gender = unit->getGender(); + uint8 gender = GENDER_MALE; + if (Unit const* unit = i_object->ToUnit()) + gender = unit->getGender(); - std::string text = broadcastText->GetText(loc_idx, gender); - ChatHandler::BuildChatPacket(data, i_msgtype, i_language, i_object, i_target, text, 0, "", loc_idx); - } - else - sLog->outError("MonsterChatBuilder: `broadcast_text` id %i missing", i_textId); + std::string text = broadcastText->GetText(loc_idx, gender); + ChatHandler::BuildChatPacket(data, i_msgtype, i_language, i_object, i_target, text, 0, "", loc_idx); } + else + sLog->outError("MonsterChatBuilder: `broadcast_text` id %i missing", i_textId); + } - private: - WorldObject const* i_object; - ChatMsg i_msgtype; - int32 i_textId; - Language i_language; - WorldObject const* i_target; + private: + WorldObject const* i_object; + ChatMsg i_msgtype; + int32 i_textId; + Language i_language; + WorldObject const* i_target; }; class MonsterCustomChatBuilder { - public: - MonsterCustomChatBuilder(WorldObject const* obj, ChatMsg msgtype, const char* text, uint32 language, WorldObject const* target) - : i_object(obj), i_msgtype(msgtype), i_text(text), i_language(Language(language)), i_target(target) - {} - void operator()(WorldPacket& data, LocaleConstant loc_idx) - { - ChatHandler::BuildChatPacket(data, i_msgtype, i_language, i_object, i_target, i_text, 0, "", loc_idx); - } + public: + MonsterCustomChatBuilder(WorldObject const* obj, ChatMsg msgtype, const char* text, uint32 language, WorldObject const* target) + : i_object(obj), i_msgtype(msgtype), i_text(text), i_language(Language(language)), i_target(target) + {} + void operator()(WorldPacket& data, LocaleConstant loc_idx) + { + ChatHandler::BuildChatPacket(data, i_msgtype, i_language, i_object, i_target, i_text, 0, "", loc_idx); + } - private: - WorldObject const* i_object; - ChatMsg i_msgtype; - const char* i_text; - Language i_language; - WorldObject const* i_target; + private: + WorldObject const* i_object; + ChatMsg i_msgtype; + const char* i_text; + Language i_language; + WorldObject const* i_target; }; } // namespace acore @@ -2142,33 +2151,33 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert case SUMMON_CATEGORY_WILD: case SUMMON_CATEGORY_ALLY: case SUMMON_CATEGORY_UNK: - { - switch (properties->Type) { - case SUMMON_TYPE_MINION: - case SUMMON_TYPE_GUARDIAN: - case SUMMON_TYPE_GUARDIAN2: - mask = UNIT_MASK_GUARDIAN; - break; - case SUMMON_TYPE_TOTEM: - case SUMMON_TYPE_LIGHTWELL: - mask = UNIT_MASK_TOTEM; - break; - case SUMMON_TYPE_VEHICLE: - case SUMMON_TYPE_VEHICLE2: - mask = UNIT_MASK_SUMMON; - break; - case SUMMON_TYPE_MINIPET: - case SUMMON_TYPE_JEEVES: - mask = UNIT_MASK_MINION; - break; - default: - if (properties->Flags & 512) // Mirror Image, Summon Gargoyle - mask = UNIT_MASK_GUARDIAN; + switch (properties->Type) + { + case SUMMON_TYPE_MINION: + case SUMMON_TYPE_GUARDIAN: + case SUMMON_TYPE_GUARDIAN2: + mask = UNIT_MASK_GUARDIAN; + break; + case SUMMON_TYPE_TOTEM: + case SUMMON_TYPE_LIGHTWELL: + mask = UNIT_MASK_TOTEM; + break; + case SUMMON_TYPE_VEHICLE: + case SUMMON_TYPE_VEHICLE2: + mask = UNIT_MASK_SUMMON; + break; + case SUMMON_TYPE_MINIPET: + case SUMMON_TYPE_JEEVES: + mask = UNIT_MASK_MINION; + break; + default: + if (properties->Flags & 512) // Mirror Image, Summon Gargoyle + mask = UNIT_MASK_GUARDIAN; + break; + } break; } - break; - } default: return nullptr; } @@ -2282,7 +2291,7 @@ void WorldObject::SetZoneScript() } } -TempSummon* WorldObject::SummonCreature(uint32 entry, const Position &pos, TempSummonType spwtype, uint32 duration, uint32 /*vehId*/, SummonPropertiesEntry const *properties) const +TempSummon* WorldObject::SummonCreature(uint32 entry, const Position& pos, TempSummonType spwtype, uint32 duration, uint32 /*vehId*/, SummonPropertiesEntry const* properties) const { if (Map* map = FindMap()) { @@ -2331,7 +2340,7 @@ GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float return go; } -Creature* WorldObject::SummonTrigger(float x, float y, float z, float ang, uint32 duration, bool setLevel, CreatureAI* (*GetAI)(Creature*)) +Creature* WorldObject::SummonTrigger(float x, float y, float z, float ang, uint32 duration, bool setLevel, CreatureAI * (*GetAI)(Creature*)) { TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; Creature* summon = SummonCreature(WORLD_TRIGGER, x, y, z, ang, summonType, duration); @@ -2512,7 +2521,7 @@ namespace acore //=================================================================================================== -void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle) const +void WorldObject::GetNearPoint2D(float& x, float& y, float distance2d, float absAngle) const { x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle); y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle); @@ -2521,9 +2530,9 @@ void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float abs acore::NormalizeMapCoord(y); } -void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle, float controlZ) const +void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, float& z, float searcher_size, float distance2d, float absAngle, float controlZ) const { - GetNearPoint2D(x, y, distance2d+searcher_size, absAngle); + GetNearPoint2D(x, y, distance2d + searcher_size, absAngle); z = GetPositionZ(); if (searcher) searcher->UpdateAllowedPositionZ(x, y, z); @@ -2568,12 +2577,12 @@ void WorldObject::GetVoidClosePoint(float& x, float& y, float& z, float size, fl GetNearPoint(nullptr, x, y, z, size, distance2d, GetOrientation() + relAngle, controlZ); } -bool WorldObject::GetClosePoint(float &x, float &y, float &z, float size, float distance2d, float angle, const WorldObject* forWho, bool force) const +bool WorldObject::GetClosePoint(float& x, float& y, float& z, float size, float distance2d, float angle, const WorldObject* forWho, bool force) const { // angle calculated from current orientation GetNearPoint(forWho, x, y, z, size, distance2d, GetOrientation() + angle); - if (fabs(this->GetPositionZ()-z) > 3.0f || !IsWithinLOS(x, y, z)) + if (fabs(this->GetPositionZ() - z) > 3.0f || !IsWithinLOS(x, y, z)) { x = this->GetPositionX(); y = this->GetPositionY(); @@ -2583,7 +2592,7 @@ bool WorldObject::GetClosePoint(float &x, float &y, float &z, float size, float u->UpdateAllowedPositionZ(x, y, z); } float maxDist = GetObjectSize() + size + distance2d + 1.0f; - if (GetExactDistSq(x, y, z) >= maxDist*maxDist) + if (GetExactDistSq(x, y, z) >= maxDist * maxDist) { if (force) { @@ -2597,12 +2606,12 @@ bool WorldObject::GetClosePoint(float &x, float &y, float &z, float size, float return true; } -void WorldObject::GetContactPoint(const WorldObject* obj, float &x, float &y, float &z, float distance2d) const +void WorldObject::GetContactPoint(const WorldObject* obj, float& x, float& y, float& z, float distance2d) const { // angle to face `obj` to `this` using distance includes size of `obj` GetNearPoint(obj, x, y, z, obj->GetObjectSize(), distance2d, GetAngle(obj)); - if (fabs(this->GetPositionZ()-z) > 3.0f || !IsWithinLOS(x, y, z)) + if (fabs(this->GetPositionZ() - z) > 3.0f || !IsWithinLOS(x, y, z)) { x = this->GetPositionX(); y = this->GetPositionY(); @@ -2612,12 +2621,12 @@ void WorldObject::GetContactPoint(const WorldObject* obj, float &x, float &y, fl } -void WorldObject::GetChargeContactPoint(const WorldObject* obj, float &x, float &y, float &z, float distance2d) const +void WorldObject::GetChargeContactPoint(const WorldObject* obj, float& x, float& y, float& z, float distance2d) const { // angle to face `obj` to `this` using distance includes size of `obj` GetNearPoint(obj, x, y, z, obj->GetObjectSize(), distance2d, GetAngle(obj)); - if (fabs(this->GetPositionZ()-z) > 3.0f || !IsWithinLOS(x, y, z)) + if (fabs(this->GetPositionZ() - z) > 3.0f || !IsWithinLOS(x, y, z)) { x = this->GetPositionX(); y = this->GetPositionY(); @@ -2626,7 +2635,7 @@ void WorldObject::GetChargeContactPoint(const WorldObject* obj, float &x, float } } -void WorldObject::MovePosition(Position &pos, float dist, float angle) +void WorldObject::MovePosition(Position& pos, float dist, float angle) { angle += m_orientation; float destx, desty, destz, ground, floor; @@ -2644,7 +2653,7 @@ void WorldObject::MovePosition(Position &pos, float dist, float angle) floor = GetMap()->GetHeight(GetPhaseMask(), destx, desty, pos.m_positionZ, true); destz = fabs(ground - pos.m_positionZ) <= fabs(floor - pos.m_positionZ) ? ground : floor; - float step = dist/10.0f; + float step = dist / 10.0f; for (uint8 j = 0; j < 10; ++j) { @@ -2670,14 +2679,14 @@ void WorldObject::MovePosition(Position &pos, float dist, float angle) pos.m_orientation = m_orientation; } -void WorldObject::MovePositionToFirstCollision(Position &pos, float dist, float angle) +void WorldObject::MovePositionToFirstCollision(Position& pos, float dist, float angle) { angle += m_orientation; float destx, desty, destz; destx = pos.m_positionX + dist * cos(angle); desty = pos.m_positionY + dist * sin(angle); destz = pos.m_positionZ; - if (isType(TYPEMASK_UNIT|TYPEMASK_PLAYER) && !ToUnit()->IsInWater()) + if (isType(TYPEMASK_UNIT | TYPEMASK_PLAYER) && !ToUnit()->IsInWater()) destz += 2.0f; // Prevent invalid coordinates here, position is unchanged @@ -2700,7 +2709,7 @@ void WorldObject::MovePositionToFirstCollision(Position &pos, float dist, float else UpdateAllowedPositionZ(destx, desty, destz); - bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), pos.m_positionX, pos.m_positionY, pos.m_positionZ+selfAddition, destx, desty, destz+0.5f, destx, desty, destz, -0.5f); + bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), pos.m_positionX, pos.m_positionY, pos.m_positionZ + selfAddition, destx, desty, destz + 0.5f, destx, desty, destz, -0.5f); // collision occured if (col) @@ -2712,11 +2721,11 @@ void WorldObject::MovePositionToFirstCollision(Position &pos, float dist, float desty -= CONTACT_DISTANCE * sin(angle); } - newDist = sqrt((pos.m_positionX - destx)*(pos.m_positionX - destx) + (pos.m_positionY - desty)*(pos.m_positionY - desty)); + newDist = sqrt((pos.m_positionX - destx) * (pos.m_positionX - destx) + (pos.m_positionY - desty) * (pos.m_positionY - desty)); } // check dynamic collision - col = GetMap()->getObjectHitPos(GetPhaseMask(), pos.m_positionX, pos.m_positionY, pos.m_positionZ+selfAddition, destx, desty, destz+0.5f, destx, desty, destz, -0.5f); + col = GetMap()->getObjectHitPos(GetPhaseMask(), pos.m_positionX, pos.m_positionY, pos.m_positionZ + selfAddition, destx, desty, destz + 0.5f, destx, desty, destz, -0.5f); // Collided with a gameobject if (col) @@ -2727,7 +2736,7 @@ void WorldObject::MovePositionToFirstCollision(Position &pos, float dist, float destx -= CONTACT_DISTANCE * cos(angle); desty -= CONTACT_DISTANCE * sin(angle); } - newDist = sqrt((pos.m_positionX - destx)*(pos.m_positionX - destx) + (pos.m_positionY - desty)*(pos.m_positionY - desty)); + newDist = sqrt((pos.m_positionX - destx) * (pos.m_positionX - destx) + (pos.m_positionY - desty) * (pos.m_positionY - desty)); } float step = newDist / 10.0f; @@ -2771,7 +2780,7 @@ void WorldObject::MovePositionToFirstCollision(Position &pos, float dist, float pos.m_orientation = m_orientation; } -void WorldObject::MovePositionToFirstCollisionForTotem(Position &pos, float dist, float angle, bool forGameObject) +void WorldObject::MovePositionToFirstCollisionForTotem(Position& pos, float dist, float angle, bool forGameObject) { angle += m_orientation; float destx, desty, destz, ground, floor; @@ -2799,11 +2808,11 @@ void WorldObject::MovePositionToFirstCollisionForTotem(Position &pos, float dist desty -= CONTACT_DISTANCE * sin(angle); } - dist = sqrt((pos.m_positionX - destx)*(pos.m_positionX - destx) + (pos.m_positionY - desty)*(pos.m_positionY - desty)); + dist = sqrt((pos.m_positionX - destx) * (pos.m_positionX - destx) + (pos.m_positionY - desty) * (pos.m_positionY - desty)); } // check dynamic collision - col = GetMap()->getObjectHitPos(GetPhaseMask(), pos.m_positionX, pos.m_positionY, pos.m_positionZ+0.5f, destx, desty, destz+0.5f, destx, desty, destz, -0.5f); + col = GetMap()->getObjectHitPos(GetPhaseMask(), pos.m_positionX, pos.m_positionY, pos.m_positionZ + 0.5f, destx, desty, destz + 0.5f, destx, desty, destz, -0.5f); // Collided with a gameobject if (col) @@ -2814,7 +2823,7 @@ void WorldObject::MovePositionToFirstCollisionForTotem(Position &pos, float dist destx -= CONTACT_DISTANCE * cos(angle); desty -= CONTACT_DISTANCE * sin(angle); } - dist = sqrt((pos.m_positionX - destx)*(pos.m_positionX - destx) + (pos.m_positionY - desty)*(pos.m_positionY - desty)); + dist = sqrt((pos.m_positionX - destx) * (pos.m_positionX - destx) + (pos.m_positionY - desty) * (pos.m_positionY - desty)); } float prevdx = destx, prevdy = desty, prevdz = destz; @@ -2829,7 +2838,7 @@ void WorldObject::MovePositionToFirstCollisionForTotem(Position &pos, float dist if (forGameObject) prevdz = destz; - float step = dist/10.0f; + float step = dist / 10.0f; for (uint8 j = 0; j < 10; ++j) { // do not allow too big z changes @@ -2875,7 +2884,7 @@ void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update) void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= NULL*/) { - WorldPacket data(SMSG_PLAY_OBJECT_SOUND, 4+8); + WorldPacket data(SMSG_PLAY_OBJECT_SOUND, 4 + 8); data << uint32(sound_id); data << uint64(GetGUID()); if (target) @@ -2915,9 +2924,9 @@ void WorldObject::DestroyForNearbyPlayers() return; std::list targets; - acore::AnyPlayerInObjectRangeCheck check(this, GetVisibilityRange()+VISIBILITY_COMPENSATION, false); + acore::AnyPlayerInObjectRangeCheck check(this, GetVisibilityRange() + VISIBILITY_COMPENSATION, false); acore::PlayerListSearcherWithSharedVision searcher(this, targets, check); - VisitNearbyWorldObject(GetVisibilityRange()+VISIBILITY_COMPENSATION, searcher); + VisitNearbyWorldObject(GetVisibilityRange() + VISIBILITY_COMPENSATION, searcher); for (std::list::const_iterator iter = targets.begin(); iter != targets.end(); ++iter) { Player* player = (*iter); @@ -2940,7 +2949,7 @@ void WorldObject::UpdateObjectVisibility(bool /*forced*/, bool /*fromUpdate*/) { //updates object's visibility for nearby players acore::VisibleChangesNotifier notifier(*this); - VisitNearbyWorldObject(GetVisibilityRange()+VISIBILITY_COMPENSATION, notifier); + VisitNearbyWorldObject(GetVisibilityRange() + VISIBILITY_COMPENSATION, notifier); } void WorldObject::AddToNotify(uint16 f) @@ -2953,12 +2962,12 @@ void WorldObject::AddToNotify(uint16 f) uint32 EVENT_VISIBILITY_DELAY = u->FindMap() ? DynamicVisibilityMgr::GetVisibilityNotifyDelay(u->FindMap()->GetEntry()->map_type) : 1000; uint32 diff = getMSTimeDiff(u->m_last_notify_mstime, World::GetGameTimeMS()); - if (diff >= EVENT_VISIBILITY_DELAY/2) + if (diff >= EVENT_VISIBILITY_DELAY / 2) EVENT_VISIBILITY_DELAY /= 2; else EVENT_VISIBILITY_DELAY -= diff; u->m_delayed_unit_relocation_timer = EVENT_VISIBILITY_DELAY; - u->m_last_notify_mstime = World::GetGameTimeMS()+EVENT_VISIBILITY_DELAY-1; + u->m_last_notify_mstime = World::GetGameTimeMS() + EVENT_VISIBILITY_DELAY - 1; } else if (f & NOTIFY_AI_RELOCATION) { @@ -2974,11 +2983,11 @@ struct WorldObjectChangeAccumulator UpdateDataMapType& i_updateDatas; UpdatePlayerSet& i_playerSet; WorldObject& i_object; - WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d, UpdatePlayerSet &p) : i_updateDatas(d), i_playerSet(p), i_object(obj) + WorldObjectChangeAccumulator(WorldObject& obj, UpdateDataMapType& d, UpdatePlayerSet& p) : i_updateDatas(d), i_playerSet(p), i_object(obj) { i_playerSet.clear(); } - void Visit(PlayerMapType &m) + void Visit(PlayerMapType& m) { Player* source = nullptr; for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) @@ -2996,7 +3005,7 @@ struct WorldObjectChangeAccumulator } } - void Visit(CreatureMapType &m) + void Visit(CreatureMapType& m) { Creature* source = nullptr; for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) @@ -3011,7 +3020,7 @@ struct WorldObjectChangeAccumulator } } - void Visit(DynamicObjectMapType &m) + void Visit(DynamicObjectMapType& m) { DynamicObject* source = nullptr; for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) @@ -3039,7 +3048,7 @@ struct WorldObjectChangeAccumulator } } - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; void WorldObject::BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet& player_set) @@ -3051,12 +3060,12 @@ void WorldObject::BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet& play TypeContainerVisitor player_notifier(notifier); Map& map = *GetMap(); //we must build packets for all visible players - cell.Visit(p, player_notifier, map, *this, GetVisibilityRange()+VISIBILITY_COMPENSATION); + cell.Visit(p, player_notifier, map, *this, GetVisibilityRange() + VISIBILITY_COMPENSATION); ClearUpdateMask(false); } -void WorldObject::GetCreaturesWithEntryInRange(std::list &creatureList, float radius, uint32 entry) +void WorldObject::GetCreaturesWithEntryInRange(std::list& creatureList, float radius, uint32 entry) { CellCoord pair(acore::ComputeCellCoord(this->GetPositionX(), this->GetPositionY())); Cell cell(pair); diff --git a/src/server/game/Entities/Object/Object.h b/src/server/game/Entities/Object/Object.h index 1f6a93e5d..e368ad564 100644 --- a/src/server/game/Entities/Object/Object.h +++ b/src/server/game/Entities/Object/Object.h @@ -122,252 +122,254 @@ typedef std::unordered_set UpdatePlayerSet; class Object { - public: - virtual ~Object(); +public: + virtual ~Object(); - bool IsInWorld() const { return m_inWorld; } + bool IsInWorld() const { return m_inWorld; } - virtual void AddToWorld(); - virtual void RemoveFromWorld(); + virtual void AddToWorld(); + virtual void RemoveFromWorld(); - uint64 GetGUID() const { return GetUInt64Value(0); } - uint32 GetGUIDLow() const { return GUID_LOPART(GetUInt64Value(0)); } - uint32 GetGUIDMid() const { return GUID_ENPART(GetUInt64Value(0)); } - uint32 GetGUIDHigh() const { return GUID_HIPART(GetUInt64Value(0)); } - const ByteBuffer& GetPackGUID() const { return m_PackGUID; } - uint32 GetEntry() const { return GetUInt32Value(OBJECT_FIELD_ENTRY); } - void SetEntry(uint32 entry) { SetUInt32Value(OBJECT_FIELD_ENTRY, entry); } + uint64 GetGUID() const { return GetUInt64Value(0); } + uint32 GetGUIDLow() const { return GUID_LOPART(GetUInt64Value(0)); } + uint32 GetGUIDMid() const { return GUID_ENPART(GetUInt64Value(0)); } + uint32 GetGUIDHigh() const { return GUID_HIPART(GetUInt64Value(0)); } + const ByteBuffer& GetPackGUID() const { return m_PackGUID; } + uint32 GetEntry() const { return GetUInt32Value(OBJECT_FIELD_ENTRY); } + void SetEntry(uint32 entry) { SetUInt32Value(OBJECT_FIELD_ENTRY, entry); } - virtual void SetObjectScale(float scale) { SetFloatValue(OBJECT_FIELD_SCALE_X, scale); } + virtual void SetObjectScale(float scale) { SetFloatValue(OBJECT_FIELD_SCALE_X, scale); } - TypeID GetTypeId() const { return m_objectTypeId; } - bool isType(uint16 mask) const { return (mask & m_objectType); } + TypeID GetTypeId() const { return m_objectTypeId; } + bool isType(uint16 mask) const { return (mask & m_objectType); } - virtual void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const; - void SendUpdateToPlayer(Player* player); + virtual void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const; + void SendUpdateToPlayer(Player* player); - void BuildValuesUpdateBlockForPlayer(UpdateData* data, Player* target) const; - void BuildOutOfRangeUpdateBlock(UpdateData* data) const; - void BuildMovementUpdateBlock(UpdateData* data, uint32 flags = 0) const; + void BuildValuesUpdateBlockForPlayer(UpdateData* data, Player* target) const; + void BuildOutOfRangeUpdateBlock(UpdateData* data) const; + void BuildMovementUpdateBlock(UpdateData* data, uint32 flags = 0) const; - virtual void DestroyForPlayer(Player* target, bool onDeath = false) const; + virtual void DestroyForPlayer(Player* target, bool onDeath = false) const; - int32 GetInt32Value(uint16 index) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - return m_int32Values[index]; - } + int32 GetInt32Value(uint16 index) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + return m_int32Values[index]; + } - uint32 GetUInt32Value(uint16 index) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - return m_uint32Values[index]; - } + uint32 GetUInt32Value(uint16 index) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + return m_uint32Values[index]; + } - uint64 GetUInt64Value(uint16 index) const - { - ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, false)); - return *((uint64*)&(m_uint32Values[index])); - } + uint64 GetUInt64Value(uint16 index) const + { + ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, false)); + return *((uint64*) & (m_uint32Values[index])); + } - float GetFloatValue(uint16 index) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - return m_floatValues[index]; - } + float GetFloatValue(uint16 index) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + return m_floatValues[index]; + } - uint8 GetByteValue(uint16 index, uint8 offset) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - ASSERT(offset < 4); - return *(((uint8*)&m_uint32Values[index])+offset); - } + uint8 GetByteValue(uint16 index, uint8 offset) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + ASSERT(offset < 4); + return *(((uint8*)&m_uint32Values[index]) + offset); + } - uint16 GetUInt16Value(uint16 index, uint8 offset) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - ASSERT(offset < 2); - return *(((uint16*)&m_uint32Values[index])+offset); - } + uint16 GetUInt16Value(uint16 index, uint8 offset) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + ASSERT(offset < 2); + return *(((uint16*)&m_uint32Values[index]) + offset); + } - void SetInt32Value(uint16 index, int32 value); - void SetUInt32Value(uint16 index, uint32 value); - void UpdateUInt32Value(uint16 index, uint32 value); - void SetUInt64Value(uint16 index, uint64 value); - void SetFloatValue(uint16 index, float value); - void SetByteValue(uint16 index, uint8 offset, uint8 value); - void SetUInt16Value(uint16 index, uint8 offset, uint16 value); - void SetInt16Value(uint16 index, uint8 offset, int16 value) { SetUInt16Value(index, offset, (uint16)value); } - void SetStatFloatValue(uint16 index, float value); - void SetStatInt32Value(uint16 index, int32 value); + void SetInt32Value(uint16 index, int32 value); + void SetUInt32Value(uint16 index, uint32 value); + void UpdateUInt32Value(uint16 index, uint32 value); + void SetUInt64Value(uint16 index, uint64 value); + void SetFloatValue(uint16 index, float value); + void SetByteValue(uint16 index, uint8 offset, uint8 value); + void SetUInt16Value(uint16 index, uint8 offset, uint16 value); + void SetInt16Value(uint16 index, uint8 offset, int16 value) { SetUInt16Value(index, offset, (uint16)value); } + void SetStatFloatValue(uint16 index, float value); + void SetStatInt32Value(uint16 index, int32 value); - bool AddUInt64Value(uint16 index, uint64 value); - bool RemoveUInt64Value(uint16 index, uint64 value); + bool AddUInt64Value(uint16 index, uint64 value); + bool RemoveUInt64Value(uint16 index, uint64 value); - void ApplyModUInt32Value(uint16 index, int32 val, bool apply); - void ApplyModInt32Value(uint16 index, int32 val, bool apply); - void ApplyModUInt64Value(uint16 index, int32 val, bool apply); - void ApplyModPositiveFloatValue(uint16 index, float val, bool apply); - void ApplyModSignedFloatValue(uint16 index, float val, bool apply); + void ApplyModUInt32Value(uint16 index, int32 val, bool apply); + void ApplyModInt32Value(uint16 index, int32 val, bool apply); + void ApplyModUInt64Value(uint16 index, int32 val, bool apply); + void ApplyModPositiveFloatValue(uint16 index, float val, bool apply); + void ApplyModSignedFloatValue(uint16 index, float val, bool apply); - void ApplyPercentModFloatValue(uint16 index, float val, bool apply) - { - float value = GetFloatValue(index); - ApplyPercentModFloatVar(value, val, apply); - SetFloatValue(index, value); - } + void ApplyPercentModFloatValue(uint16 index, float val, bool apply) + { + float value = GetFloatValue(index); + ApplyPercentModFloatVar(value, val, apply); + SetFloatValue(index, value); + } - void SetFlag(uint16 index, uint32 newFlag); - void RemoveFlag(uint16 index, uint32 oldFlag); + void SetFlag(uint16 index, uint32 newFlag); + void RemoveFlag(uint16 index, uint32 oldFlag); - void ToggleFlag(uint16 index, uint32 flag) - { - if (HasFlag(index, flag)) - RemoveFlag(index, flag); - else - SetFlag(index, flag); - } + void ToggleFlag(uint16 index, uint32 flag) + { + if (HasFlag(index, flag)) + RemoveFlag(index, flag); + else + SetFlag(index, flag); + } - bool HasFlag(uint16 index, uint32 flag) const - { - if (index >= m_valuesCount && !PrintIndexError(index, false)) - return false; + bool HasFlag(uint16 index, uint32 flag) const + { + if (index >= m_valuesCount && !PrintIndexError(index, false)) + return false; - return (m_uint32Values[index] & flag) != 0; - } + return (m_uint32Values[index] & flag) != 0; + } - void SetByteFlag(uint16 index, uint8 offset, uint8 newFlag); - void RemoveByteFlag(uint16 index, uint8 offset, uint8 newFlag); + void SetByteFlag(uint16 index, uint8 offset, uint8 newFlag); + void RemoveByteFlag(uint16 index, uint8 offset, uint8 newFlag); - void ToggleFlag(uint16 index, uint8 offset, uint8 flag) - { - if (HasByteFlag(index, offset, flag)) - RemoveByteFlag(index, offset, flag); - else - SetByteFlag(index, offset, flag); - } + void ToggleFlag(uint16 index, uint8 offset, uint8 flag) + { + if (HasByteFlag(index, offset, flag)) + RemoveByteFlag(index, offset, flag); + else + SetByteFlag(index, offset, flag); + } - bool HasByteFlag(uint16 index, uint8 offset, uint8 flag) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - ASSERT(offset < 4); - return (((uint8*)&m_uint32Values[index])[offset] & flag) != 0; - } + bool HasByteFlag(uint16 index, uint8 offset, uint8 flag) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + ASSERT(offset < 4); + return (((uint8*)&m_uint32Values[index])[offset] & flag) != 0; + } - void ApplyModFlag(uint16 index, uint32 flag, bool apply) - { - if (apply) SetFlag(index, flag); else RemoveFlag(index, flag); - } + void ApplyModFlag(uint16 index, uint32 flag, bool apply) + { + if (apply) SetFlag(index, flag); + else RemoveFlag(index, flag); + } - void SetFlag64(uint16 index, uint64 newFlag) - { - uint64 oldval = GetUInt64Value(index); - uint64 newval = oldval | newFlag; - SetUInt64Value(index, newval); - } + void SetFlag64(uint16 index, uint64 newFlag) + { + uint64 oldval = GetUInt64Value(index); + uint64 newval = oldval | newFlag; + SetUInt64Value(index, newval); + } - void RemoveFlag64(uint16 index, uint64 oldFlag) - { - uint64 oldval = GetUInt64Value(index); - uint64 newval = oldval & ~oldFlag; - SetUInt64Value(index, newval); - } + void RemoveFlag64(uint16 index, uint64 oldFlag) + { + uint64 oldval = GetUInt64Value(index); + uint64 newval = oldval & ~oldFlag; + SetUInt64Value(index, newval); + } - void ToggleFlag64(uint16 index, uint64 flag) - { - if (HasFlag64(index, flag)) - RemoveFlag64(index, flag); - else - SetFlag64(index, flag); - } + void ToggleFlag64(uint16 index, uint64 flag) + { + if (HasFlag64(index, flag)) + RemoveFlag64(index, flag); + else + SetFlag64(index, flag); + } - bool HasFlag64(uint16 index, uint64 flag) const - { - ASSERT(index < m_valuesCount || PrintIndexError(index, false)); - return (GetUInt64Value(index) & flag) != 0; - } + bool HasFlag64(uint16 index, uint64 flag) const + { + ASSERT(index < m_valuesCount || PrintIndexError(index, false)); + return (GetUInt64Value(index) & flag) != 0; + } - void ApplyModFlag64(uint16 index, uint64 flag, bool apply) - { - if (apply) SetFlag64(index, flag); else RemoveFlag64(index, flag); - } + void ApplyModFlag64(uint16 index, uint64 flag, bool apply) + { + if (apply) SetFlag64(index, flag); + else RemoveFlag64(index, flag); + } - void ClearUpdateMask(bool remove); + void ClearUpdateMask(bool remove); - uint16 GetValuesCount() const { return m_valuesCount; } + uint16 GetValuesCount() const { return m_valuesCount; } - virtual bool hasQuest(uint32 /* quest_id */) const { return false; } - virtual bool hasInvolvedQuest(uint32 /* quest_id */) const { return false; } - virtual void BuildUpdate(UpdateDataMapType&, UpdatePlayerSet&) {} - void BuildFieldsUpdate(Player*, UpdateDataMapType &) const; + virtual bool hasQuest(uint32 /* quest_id */) const { return false; } + virtual bool hasInvolvedQuest(uint32 /* quest_id */) const { return false; } + virtual void BuildUpdate(UpdateDataMapType&, UpdatePlayerSet&) {} + void BuildFieldsUpdate(Player*, UpdateDataMapType&) const; - void SetFieldNotifyFlag(uint16 flag) { _fieldNotifyFlags |= flag; } - void RemoveFieldNotifyFlag(uint16 flag) { _fieldNotifyFlags &= ~flag; } + void SetFieldNotifyFlag(uint16 flag) { _fieldNotifyFlags |= flag; } + void RemoveFieldNotifyFlag(uint16 flag) { _fieldNotifyFlags &= ~flag; } - // FG: some hacky helpers - void ForceValuesUpdateAtIndex(uint32); + // FG: some hacky helpers + void ForceValuesUpdateAtIndex(uint32); - Player* ToPlayer() { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } - Player const* ToPlayer() const { if (GetTypeId() == TYPEID_PLAYER) return (Player const*)((Player*)this); else return nullptr; } - Creature* ToCreature() { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return nullptr; } - Creature const* ToCreature() const { if (GetTypeId() == TYPEID_UNIT) return (Creature const*)((Creature*)this); else return nullptr; } + Player* ToPlayer() { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } + Player const* ToPlayer() const { if (GetTypeId() == TYPEID_PLAYER) return (Player const*)((Player*)this); else return nullptr; } + Creature* ToCreature() { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return nullptr; } + Creature const* ToCreature() const { if (GetTypeId() == TYPEID_UNIT) return (Creature const*)((Creature*)this); else return nullptr; } - Unit* ToUnit() { if (GetTypeId() == TYPEID_UNIT || GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } - Unit const* ToUnit() const { if (GetTypeId() == TYPEID_UNIT || GetTypeId() == TYPEID_PLAYER) return (const Unit*)((Unit*)this); else return nullptr; } - GameObject* ToGameObject() { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return nullptr; } - GameObject const* ToGameObject() const { if (GetTypeId() == TYPEID_GAMEOBJECT) return (const GameObject*)((GameObject*)this); else return nullptr; } + Unit* ToUnit() { if (GetTypeId() == TYPEID_UNIT || GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } + Unit const* ToUnit() const { if (GetTypeId() == TYPEID_UNIT || GetTypeId() == TYPEID_PLAYER) return (const Unit*)((Unit*)this); else return nullptr; } + GameObject* ToGameObject() { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return nullptr; } + GameObject const* ToGameObject() const { if (GetTypeId() == TYPEID_GAMEOBJECT) return (const GameObject*)((GameObject*)this); else return nullptr; } - Corpse* ToCorpse() { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return nullptr; } - Corpse const* ToCorpse() const { if (GetTypeId() == TYPEID_CORPSE) return (const Corpse*)((Corpse*)this); else return nullptr; } + Corpse* ToCorpse() { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return nullptr; } + Corpse const* ToCorpse() const { if (GetTypeId() == TYPEID_CORPSE) return (const Corpse*)((Corpse*)this); else return nullptr; } - DynamicObject* ToDynObject() { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } - DynamicObject const* ToDynObject() const { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } + DynamicObject* ToDynObject() { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } + DynamicObject const* ToDynObject() const { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } - DataMap CustomData; + DataMap CustomData; - protected: +protected: - Object(); + Object(); - void _InitValues(); - void _Create(uint32 guidlow, uint32 entry, HighGuid guidhigh); - std::string _ConcatFields(uint16 startIndex, uint16 size) const; - void _LoadIntoDataField(std::string const& data, uint32 startOffset, uint32 count); + void _InitValues(); + void _Create(uint32 guidlow, uint32 entry, HighGuid guidhigh); + std::string _ConcatFields(uint16 startIndex, uint16 size) const; + void _LoadIntoDataField(std::string const& data, uint32 startOffset, uint32 count); - uint32 GetUpdateFieldData(Player const* target, uint32*& flags) const; + uint32 GetUpdateFieldData(Player const* target, uint32*& flags) const; - void BuildMovementUpdate(ByteBuffer* data, uint16 flags) const; - virtual void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const; + void BuildMovementUpdate(ByteBuffer* data, uint16 flags) const; + virtual void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const; - uint16 m_objectType; + uint16 m_objectType; - TypeID m_objectTypeId; - uint16 m_updateFlag; + TypeID m_objectTypeId; + uint16 m_updateFlag; - union - { - int32 *m_int32Values; - uint32 *m_uint32Values; - float *m_floatValues; - }; + union + { + int32* m_int32Values; + uint32* m_uint32Values; + float* m_floatValues; + }; - UpdateMask _changesMask; + UpdateMask _changesMask; - uint16 m_valuesCount; + uint16 m_valuesCount; - uint16 _fieldNotifyFlags; + uint16 _fieldNotifyFlags; - bool m_objectUpdated; + bool m_objectUpdated; - private: - bool m_inWorld; +private: + bool m_inWorld; - ByteBuffer m_PackGUID; + ByteBuffer m_PackGUID; - // for output helpfull error messages from asserts - bool PrintIndexError(uint32 index, bool set) const; - Object(const Object&); // prevent generation copy constructor - Object& operator=(Object const&); // prevent generation assigment operator + // for output helpfull error messages from asserts + bool PrintIndexError(uint32 index, bool set) const; + Object(const Object&); // prevent generation copy constructor + Object& operator=(Object const&); // prevent generation assigment operator }; struct Position @@ -377,11 +379,11 @@ struct Position Position(Position const& loc) { Relocate(loc); } /* requried as of C++ 11 */ - #if __cplusplus >= 201103L +#if __cplusplus >= 201103L Position(Position&&) = default; Position& operator=(const Position&) = default; Position& operator=(Position&&) = default; - #endif +#endif struct PositionXYStreamer { @@ -406,35 +408,47 @@ struct Position float m_positionZ = 0; float m_orientation = 0; - bool operator==(Position const &a); + bool operator==(Position const& a); - inline bool operator!=(Position const &a) + inline bool operator!=(Position const& a) { return !(operator==(a)); } void Relocate(float x, float y) { - m_positionX = x; m_positionY = y; + m_positionX = x; + m_positionY = y; } void Relocate(float x, float y, float z) { - m_positionX = x; m_positionY = y; m_positionZ = z; + m_positionX = x; + m_positionY = y; + m_positionZ = z; } void Relocate(float x, float y, float z, float orientation) { - m_positionX = x; m_positionY = y; m_positionZ = z; m_orientation = orientation; + m_positionX = x; + m_positionY = y; + m_positionZ = z; + m_orientation = orientation; } - void Relocate(const Position &pos) + void Relocate(const Position& pos) { - m_positionX = pos.m_positionX; m_positionY = pos.m_positionY; m_positionZ = pos.m_positionZ; m_orientation = pos.m_orientation; + m_positionX = pos.m_positionX; + m_positionY = pos.m_positionY; + m_positionZ = pos.m_positionZ; + m_orientation = pos.m_orientation; } void Relocate(const Position* pos) { - m_positionX = pos->m_positionX; m_positionY = pos->m_positionY; m_positionZ = pos->m_positionZ; m_orientation = pos->m_orientation; + m_positionX = pos->m_positionX; + m_positionY = pos->m_positionY; + m_positionZ = pos->m_positionZ; + m_orientation = pos->m_orientation; } void RelocatePolarOffset(float angle, float dist, float z = 0.0f); - void RelocateOffset(const Position &offset); + void RelocateOffset(const Position& offset); void SetOrientation(float orientation) { m_orientation = orientation; @@ -445,17 +459,23 @@ struct Position float GetPositionZ() const { return m_positionZ; } float GetOrientation() const { return m_orientation; } - void GetPosition(float &x, float &y) const + void GetPosition(float& x, float& y) const { - x = m_positionX; y = m_positionY; + x = m_positionX; + y = m_positionY; } - void GetPosition(float &x, float &y, float &z) const + void GetPosition(float& x, float& y, float& z) const { - x = m_positionX; y = m_positionY; z = m_positionZ; + x = m_positionX; + y = m_positionY; + z = m_positionZ; } - void GetPosition(float &x, float &y, float &z, float &o) const + void GetPosition(float& x, float& y, float& z, float& o) const { - x = m_positionX; y = m_positionY; z = m_positionZ; o = m_orientation; + x = m_positionX; + y = m_positionY; + z = m_positionZ; + o = m_orientation; } void GetPosition(Position* pos) const { @@ -479,7 +499,9 @@ struct Position float GetExactDist2dSq(float x, float y) const { - float dx = m_positionX - x; float dy = m_positionY - y; return dx*dx + dy*dy; + float dx = m_positionX - x; + float dy = m_positionY - y; + return dx * dx + dy * dy; } float GetExactDist2d(const float x, const float y) const { @@ -487,7 +509,9 @@ struct Position } float GetExactDist2dSq(const Position* pos) const { - float dx = m_positionX - pos->m_positionX; float dy = m_positionY - pos->m_positionY; return dx*dx + dy*dy; + float dx = m_positionX - pos->m_positionX; + float dy = m_positionY - pos->m_positionY; + return dx * dx + dy * dy; } float GetExactDist2d(const Position* pos) const { @@ -495,7 +519,8 @@ struct Position } float GetExactDistSq(float x, float y, float z) const { - float dz = m_positionZ - z; return GetExactDist2dSq(x, y) + dz*dz; + float dz = m_positionZ - z; + return GetExactDist2dSq(x, y) + dz * dz; } float GetExactDist(float x, float y, float z) const { @@ -503,14 +528,17 @@ struct Position } float GetExactDistSq(const Position* pos) const { - float dx = m_positionX - pos->m_positionX; float dy = m_positionY - pos->m_positionY; float dz = m_positionZ - pos->m_positionZ; return dx*dx + dy*dy + dz*dz; + float dx = m_positionX - pos->m_positionX; + float dy = m_positionY - pos->m_positionY; + float dz = m_positionZ - pos->m_positionZ; + return dx * dx + dy * dy + dz * dz; } float GetExactDist(const Position* pos) const { return sqrt(GetExactDistSq(pos)); } - void GetPositionOffsetTo(const Position & endPos, Position & retOffset) const; + void GetPositionOffsetTo(const Position& endPos, Position& retOffset) const; float GetAngle(const Position* pos) const; float GetAngle(float x, float y) const; @@ -519,7 +547,7 @@ struct Position return GetAngle(pos) - m_orientation; } float GetRelativeAngle(float x, float y) const { return GetAngle(x, y) - m_orientation; } - void GetSinCos(float x, float y, float &vsin, float &vcos) const; + void GetSinCos(float x, float y, float& vsin, float& vcos) const; bool IsInDist2d(float x, float y, float dist) const { @@ -550,7 +578,7 @@ struct Position // to emulate negative numbers if (o < 0) { - float mod = o *-1; + float mod = o * -1; mod = fmod(mod, 2.0f * static_cast(M_PI)); mod = -mod + 2.0f * static_cast(M_PI); return mod; @@ -600,7 +628,7 @@ struct MovementInfo // falling uint32 fallTime; - // jumping + // jumping struct JumpInfo { void Reset() @@ -642,69 +670,69 @@ struct MovementInfo class WorldLocation : public Position { - public: - explicit WorldLocation(uint32 _mapid = MAPID_INVALID, float _x = 0, float _y = 0, float _z = 0, float _o = 0) - : m_mapId(_mapid) { Relocate(_x, _y, _z, _o); } - WorldLocation(const WorldLocation &loc) : Position () { WorldRelocate(loc); } - /* requried as of C++ 11 */ - #if __cplusplus >= 201103L - WorldLocation(WorldLocation&&) = default; - WorldLocation& operator=(const WorldLocation&) = default; - WorldLocation& operator=(WorldLocation&&) = default; - #endif +public: + explicit WorldLocation(uint32 _mapid = MAPID_INVALID, float _x = 0, float _y = 0, float _z = 0, float _o = 0) + : m_mapId(_mapid) { Relocate(_x, _y, _z, _o); } + WorldLocation(const WorldLocation& loc) : Position () { WorldRelocate(loc); } + /* requried as of C++ 11 */ +#if __cplusplus >= 201103L + WorldLocation(WorldLocation&&) = default; + WorldLocation& operator=(const WorldLocation&) = default; + WorldLocation& operator=(WorldLocation&&) = default; +#endif - void WorldRelocate(const WorldLocation &loc) - { - m_mapId = loc.GetMapId(); - Relocate(loc); - } + void WorldRelocate(const WorldLocation& loc) + { + m_mapId = loc.GetMapId(); + Relocate(loc); + } - uint32 GetMapId() const - { - return m_mapId; - } + uint32 GetMapId() const + { + return m_mapId; + } - WorldLocation GetWorldLocation() const - { - return *this; - } + WorldLocation GetWorldLocation() const + { + return *this; + } - uint32 m_mapId; + uint32 m_mapId; }; template class GridObject { - public: - bool IsInGrid() const { return _gridRef.isValid(); } - void AddToGrid(GridRefManager& m) { ASSERT(!IsInGrid()); _gridRef.link(&m, (T*)this); } - void RemoveFromGrid() { ASSERT(IsInGrid()); _gridRef.unlink(); } - private: - GridReference _gridRef; +public: + bool IsInGrid() const { return _gridRef.isValid(); } + void AddToGrid(GridRefManager& m) { ASSERT(!IsInGrid()); _gridRef.link(&m, (T*)this); } + void RemoveFromGrid() { ASSERT(IsInGrid()); _gridRef.unlink(); } +private: + GridReference _gridRef; }; template class FlaggedValuesArray32 { - public: - FlaggedValuesArray32() - { - memset(&m_values, 0x00, sizeof(T_VALUES) * ARRAY_SIZE); - m_flags = 0; - } +public: + FlaggedValuesArray32() + { + memset(&m_values, 0x00, sizeof(T_VALUES) * ARRAY_SIZE); + m_flags = 0; + } - T_FLAGS GetFlags() const { return m_flags; } - bool HasFlag(FLAG_TYPE flag) const { return m_flags & (1 << flag); } - void AddFlag(FLAG_TYPE flag) { m_flags |= (1 << flag); } - void DelFlag(FLAG_TYPE flag) { m_flags &= ~(1 << flag); } + T_FLAGS GetFlags() const { return m_flags; } + bool HasFlag(FLAG_TYPE flag) const { return m_flags & (1 << flag); } + void AddFlag(FLAG_TYPE flag) { m_flags |= (1 << flag); } + void DelFlag(FLAG_TYPE flag) { m_flags &= ~(1 << flag); } - T_VALUES GetValue(FLAG_TYPE flag) const { return m_values[flag]; } - void SetValue(FLAG_TYPE flag, T_VALUES value) { m_values[flag] = value; } - void AddValue(FLAG_TYPE flag, T_VALUES value) { m_values[flag] += value; } + T_VALUES GetValue(FLAG_TYPE flag) const { return m_values[flag]; } + void SetValue(FLAG_TYPE flag, T_VALUES value) { m_values[flag] = value; } + void AddValue(FLAG_TYPE flag, T_VALUES value) { m_values[flag] += value; } - private: - T_VALUES m_values[ARRAY_SIZE]; - T_FLAGS m_flags; +private: + T_VALUES m_values[ARRAY_SIZE]; + T_FLAGS m_flags; }; enum MapObjectCellMoveState @@ -716,366 +744,366 @@ enum MapObjectCellMoveState class MovableMapObject { - friend class Map; //map for moving creatures - friend class ObjectGridLoader; //grid loader for loading creatures - template friend class RandomMovementGenerator; + friend class Map; //map for moving creatures + friend class ObjectGridLoader; //grid loader for loading creatures + template friend class RandomMovementGenerator; - protected: - MovableMapObject() : _moveState(MAP_OBJECT_CELL_MOVE_NONE) {} +protected: + MovableMapObject() : _moveState(MAP_OBJECT_CELL_MOVE_NONE) {} - private: - Cell const& GetCurrentCell() const { return _currentCell; } - void SetCurrentCell(Cell const& cell) { _currentCell = cell; } +private: + Cell const& GetCurrentCell() const { return _currentCell; } + void SetCurrentCell(Cell const& cell) { _currentCell = cell; } - Cell _currentCell; - MapObjectCellMoveState _moveState; + Cell _currentCell; + MapObjectCellMoveState _moveState; }; class WorldObject : public Object, public WorldLocation { - protected: - explicit WorldObject(bool isWorldObject); //note: here it means if it is in grid object list or world object list - public: - virtual ~WorldObject(); +protected: + explicit WorldObject(bool isWorldObject); //note: here it means if it is in grid object list or world object list +public: + virtual ~WorldObject(); #ifdef ELUNA - virtual void Update(uint32 /*time_diff*/); + virtual void Update(uint32 /*time_diff*/); #else - virtual void Update(uint32 /*time_diff*/) { }; + virtual void Update(uint32 /*time_diff*/) { }; #endif - void _Create(uint32 guidlow, HighGuid guidhigh, uint32 phaseMask); + void _Create(uint32 guidlow, HighGuid guidhigh, uint32 phaseMask); - virtual void RemoveFromWorld() - { - if (!IsInWorld()) - return; + virtual void RemoveFromWorld() + { + if (!IsInWorld()) + return; - DestroyForNearbyPlayers(); + DestroyForNearbyPlayers(); - Object::RemoveFromWorld(); - } + Object::RemoveFromWorld(); + } #ifdef ELUNA - ElunaEventProcessor* elunaEvents; + ElunaEventProcessor* elunaEvents; #endif - void GetNearPoint2D(float &x, float &y, float distance, float absAngle) const; - void GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle, float controlZ = 0) const; - void GetVoidClosePoint(float& x, float& y, float& z, float size, float distance2d = 0, float relAngle = 0, float controlZ = 0) const; - bool GetClosePoint(float &x, float &y, float &z, float size, float distance2d = 0, float angle = 0, const WorldObject* forWho = NULL, bool force = false) const; - void MovePosition(Position &pos, float dist, float angle); - void GetNearPosition(Position &pos, float dist, float angle) + void GetNearPoint2D(float& x, float& y, float distance, float absAngle) const; + void GetNearPoint(WorldObject const* searcher, float& x, float& y, float& z, float searcher_size, float distance2d, float absAngle, float controlZ = 0) const; + void GetVoidClosePoint(float& x, float& y, float& z, float size, float distance2d = 0, float relAngle = 0, float controlZ = 0) const; + bool GetClosePoint(float& x, float& y, float& z, float size, float distance2d = 0, float angle = 0, const WorldObject* forWho = NULL, bool force = false) const; + void MovePosition(Position& pos, float dist, float angle); + void GetNearPosition(Position& pos, float dist, float angle) + { + GetPosition(&pos); + MovePosition(pos, dist, angle); + } + void MovePositionToFirstCollision(Position& pos, float dist, float angle); + void GetFirstCollisionPosition(Position& pos, float dist, float angle) + { + GetPosition(&pos); + MovePositionToFirstCollision(pos, dist, angle); + } + void MovePositionToFirstCollisionForTotem(Position& pos, float dist, float angle, bool forGameObject); + void GetFirstCollisionPositionForTotem(Position& pos, float dist, float angle, bool forGameObject) + { + GetPosition(&pos); + MovePositionToFirstCollisionForTotem(pos, dist, angle, forGameObject); + } + void GetRandomNearPosition(Position& pos, float radius) + { + GetPosition(&pos); + MovePosition(pos, radius * (float)rand_norm(), (float)rand_norm() * static_cast(2 * M_PI)); + } + + void GetContactPoint(const WorldObject* obj, float& x, float& y, float& z, float distance2d = CONTACT_DISTANCE) const; + void GetChargeContactPoint(const WorldObject* obj, float& x, float& y, float& z, float distance2d = CONTACT_DISTANCE) const; + + float GetObjectSize() const + { + return (m_valuesCount > UNIT_FIELD_COMBATREACH) ? m_floatValues[UNIT_FIELD_COMBATREACH] : DEFAULT_WORLD_OBJECT_SIZE; + } + + virtual float GetCombatReach() const { return 0.0f; } // overridden (only) in Unit + void UpdateGroundPositionZ(float x, float y, float& z) const; + void UpdateAllowedPositionZ(float x, float y, float& z) const; + + void GetRandomPoint(const Position& srcPos, float distance, float& rand_x, float& rand_y, float& rand_z) const; + void GetRandomPoint(const Position& srcPos, float distance, Position& pos) const + { + float x, y, z; + GetRandomPoint(srcPos, distance, x, y, z); + pos.Relocate(x, y, z, GetOrientation()); + } + + uint32 GetInstanceId() const { return m_InstanceId; } + + virtual void SetPhaseMask(uint32 newPhaseMask, bool update); + uint32 GetPhaseMask() const { return m_phaseMask; } + bool InSamePhase(WorldObject const* obj) const { return InSamePhase(obj->GetPhaseMask()); } + bool InSamePhase(uint32 phasemask) const { return m_useCombinedPhases ? GetPhaseMask() & phasemask : GetPhaseMask() == phasemask; } + + virtual uint32 GetZoneId(bool forceRecalc = false) const; + virtual uint32 GetAreaId(bool forceRecalc = false) const; + virtual void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc = false) const; + + InstanceScript* GetInstanceScript(); + + std::string const& GetName() const { return m_name; } + void SetName(std::string const& newname) { m_name = newname; } + + virtual std::string const& GetNameForLocaleIdx(LocaleConstant /*locale_idx*/) const { return m_name; } + + float GetDistance(const WorldObject* obj) const + { + float d = GetExactDist(obj) - GetObjectSize() - obj->GetObjectSize(); + return d > 0.0f ? d : 0.0f; + } + float GetDistance(const Position& pos) const + { + float d = GetExactDist(&pos) - GetObjectSize(); + return d > 0.0f ? d : 0.0f; + } + float GetDistance(float x, float y, float z) const + { + float d = GetExactDist(x, y, z) - GetObjectSize(); + return d > 0.0f ? d : 0.0f; + } + float GetDistance2d(const WorldObject* obj) const + { + float d = GetExactDist2d(obj) - GetObjectSize() - obj->GetObjectSize(); + return d > 0.0f ? d : 0.0f; + } + float GetDistance2d(float x, float y) const + { + float d = GetExactDist2d(x, y) - GetObjectSize(); + return d > 0.0f ? d : 0.0f; + } + float GetDistanceZ(const WorldObject* obj) const; + + bool IsSelfOrInSameMap(const WorldObject* obj) const + { + if (this == obj) + return true; + return IsInMap(obj); + } + bool IsInMap(const WorldObject* obj) const + { + if (obj) + return IsInWorld() && obj->IsInWorld() && (FindMap() == obj->FindMap()); + return false; + } + bool IsWithinDist3d(float x, float y, float z, float dist) const + { return IsInDist(x, y, z, dist + GetObjectSize()); } + bool IsWithinDist3d(const Position* pos, float dist) const + { return IsInDist(pos, dist + GetObjectSize()); } + bool IsWithinDist2d(float x, float y, float dist) const + { return IsInDist2d(x, y, dist + GetObjectSize()); } + bool IsWithinDist2d(const Position* pos, float dist) const + { return IsInDist2d(pos, dist + GetObjectSize()); } + // use only if you will sure about placing both object at same map + bool IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D = true) const + { + return obj && _IsWithinDist(obj, dist2compare, is3D); + } + bool IsWithinDistInMap(WorldObject const* obj, float dist2compare, bool is3D = true) const + { + return obj && IsInMap(obj) && InSamePhase(obj) && _IsWithinDist(obj, dist2compare, is3D); + } + bool IsWithinLOS(float x, float y, float z, LineOfSightChecks checks = LINEOFSIGHT_ALL_CHECKS) const; + bool IsWithinLOSInMap(WorldObject const* obj, LineOfSightChecks checks = LINEOFSIGHT_ALL_CHECKS) const; + Position GetHitSpherePointFor(Position const& dest) const; + void GetHitSpherePointFor(Position const& dest, float& x, float& y, float& z) const; + bool GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D = true) const; + bool IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D = true) const; + bool IsInRange2d(float x, float y, float minRange, float maxRange) const; + bool IsInRange3d(float x, float y, float z, float minRange, float maxRange) const; + bool isInFront(WorldObject const* target, float arc = M_PI) const; + bool isInBack(WorldObject const* target, float arc = M_PI) const; + + bool IsInBetween(const WorldObject* obj1, const WorldObject* obj2, float size = 0) const; + + virtual void CleanupsBeforeDelete(bool finalCleanup = true); // used in destructor or explicitly before mass creature delete to remove cross-references to already deleted units + + virtual void SendMessageToSet(WorldPacket* data, bool self) { if (IsInWorld()) SendMessageToSetInRange(data, GetVisibilityRange(), self, true); } // pussywizard! + virtual void SendMessageToSetInRange(WorldPacket* data, float dist, bool /*self*/, bool includeMargin = false, Player const* skipped_rcvr = nullptr); // pussywizard! + virtual void SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr) { if (IsInWorld()) SendMessageToSetInRange(data, GetVisibilityRange(), false, true, skipped_rcvr); } // pussywizard! + + virtual uint8 getLevelForTarget(WorldObject const* /*target*/) const { return 1; } + + void MonsterSay(const char* text, uint32 language, WorldObject const* target); + void MonsterYell(const char* text, uint32 language, WorldObject const* target); + void MonsterTextEmote(const char* text, WorldObject const* target, bool IsBossEmote = false); + void MonsterWhisper(const char* text, Player const* target, bool IsBossWhisper = false); + void MonsterSay(int32 textId, uint32 language, WorldObject const* target); + void MonsterYell(int32 textId, uint32 language, WorldObject const* target); + void MonsterTextEmote(int32 textId, WorldObject const* target, bool IsBossEmote = false); + void MonsterWhisper(int32 textId, Player const* target, bool IsBossWhisper = false); + + void PlayDistanceSound(uint32 sound_id, Player* target = nullptr); + void PlayDirectSound(uint32 sound_id, Player* target = nullptr); + void PlayDirectMusic(uint32 music_id, Player* target = nullptr); + + void SendObjectDeSpawnAnim(uint64 guid); + + virtual void SaveRespawnTime() {} + void AddObjectToRemoveList(); + + float GetGridActivationRange() const; + float GetVisibilityRange() const; + float GetSightRange(const WorldObject* target = nullptr) const; + //bool CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth = false, bool distanceCheck = false) const; + bool CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth = false, bool distanceCheck = false, bool checkAlert = false) const; + + FlaggedValuesArray32 m_stealth; + FlaggedValuesArray32 m_stealthDetect; + + FlaggedValuesArray32 m_invisibility; + FlaggedValuesArray32 m_invisibilityDetect; + + FlaggedValuesArray32 m_serverSideVisibility; + FlaggedValuesArray32 m_serverSideVisibilityDetect; + + // Low Level Packets + void SendPlaySound(uint32 Sound, bool OnlySelf); + void SendPlayMusic(uint32 Music, bool OnlySelf); + + virtual void SetMap(Map* map); + virtual void ResetMap(); + Map* GetMap() const { ASSERT(m_currMap); return m_currMap; } + Map* FindMap() const { return m_currMap; } + //used to check all object's GetMap() calls when object is not in world! + + //this function should be removed in nearest time... + Map const* GetBaseMap() const; + + void SetZoneScript(); + ZoneScript* GetZoneScript() const { return m_zoneScript; } + + TempSummon* SummonCreature(uint32 id, const Position& pos, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, uint32 vehId = 0, SummonPropertiesEntry const* properties = nullptr) const; + TempSummon* SummonCreature(uint32 id, float x, float y, float z, float ang = 0, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, SummonPropertiesEntry const* properties = nullptr) + { + if (!x && !y && !z) { - GetPosition(&pos); - MovePosition(pos, dist, angle); - } - void MovePositionToFirstCollision(Position &pos, float dist, float angle); - void GetFirstCollisionPosition(Position &pos, float dist, float angle) - { - GetPosition(&pos); - MovePositionToFirstCollision(pos, dist, angle); - } - void MovePositionToFirstCollisionForTotem(Position &pos, float dist, float angle, bool forGameObject); - void GetFirstCollisionPositionForTotem(Position &pos, float dist, float angle, bool forGameObject) - { - GetPosition(&pos); - MovePositionToFirstCollisionForTotem(pos, dist, angle, forGameObject); - } - void GetRandomNearPosition(Position &pos, float radius) - { - GetPosition(&pos); - MovePosition(pos, radius * (float)rand_norm(), (float)rand_norm() * static_cast(2 * M_PI)); + GetClosePoint(x, y, z, GetObjectSize()); + ang = GetOrientation(); } + Position pos; + pos.Relocate(x, y, z, ang); + return SummonCreature(id, pos, spwtype, despwtime, 0, properties); + } + GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime, bool checkTransport = true); + Creature* SummonTrigger(float x, float y, float z, float ang, uint32 dur, bool setLevel = false, CreatureAI * (*GetAI)(Creature*) = nullptr); + void SummonCreatureGroup(uint8 group, std::list* list = nullptr); - void GetContactPoint(const WorldObject* obj, float &x, float &y, float &z, float distance2d = CONTACT_DISTANCE) const; - void GetChargeContactPoint(const WorldObject* obj, float &x, float &y, float &z, float distance2d = CONTACT_DISTANCE) const; + Creature* FindNearestCreature(uint32 entry, float range, bool alive = true) const; + GameObject* FindNearestGameObject(uint32 entry, float range) const; + GameObject* FindNearestGameObjectOfType(GameobjectTypes type, float range) const; - float GetObjectSize() const - { - return (m_valuesCount > UNIT_FIELD_COMBATREACH) ? m_floatValues[UNIT_FIELD_COMBATREACH] : DEFAULT_WORLD_OBJECT_SIZE; - } + Player* SelectNearestPlayer(float distance = 0) const; + void GetGameObjectListWithEntryInGrid(std::list& lList, uint32 uiEntry, float fMaxSearchRange) const; + void GetCreatureListWithEntryInGrid(std::list& lList, uint32 uiEntry, float fMaxSearchRange) const; - virtual float GetCombatReach() const { return 0.0f; } // overridden (only) in Unit - void UpdateGroundPositionZ(float x, float y, float &z) const; - void UpdateAllowedPositionZ(float x, float y, float &z) const; + void DestroyForNearbyPlayers(); + virtual void UpdateObjectVisibility(bool forced = true, bool fromUpdate = false); + void BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet& player_set); + void GetCreaturesWithEntryInRange(std::list& creatureList, float radius, uint32 entry); - void GetRandomPoint(const Position &srcPos, float distance, float &rand_x, float &rand_y, float &rand_z) const; - void GetRandomPoint(const Position &srcPos, float distance, Position &pos) const - { - float x, y, z; - GetRandomPoint(srcPos, distance, x, y, z); - pos.Relocate(x, y, z, GetOrientation()); - } + //relocation and visibility system functions + void AddToNotify(uint16 f); + void RemoveFromNotify(uint16 f) { m_notifyflags &= ~f; } + bool isNeedNotify(uint16 f) const { return m_notifyflags & f;} + uint16 GetNotifyFlags() const { return m_notifyflags; } + bool NotifyExecuted(uint16 f) const { return m_executed_notifies & f;} + void SetNotified(uint16 f) { m_executed_notifies |= f;} + void ResetAllNotifies() { m_notifyflags = 0; m_executed_notifies = 0; } - uint32 GetInstanceId() const { return m_InstanceId; } + bool isActiveObject() const { return m_isActive; } + void setActive(bool isActiveObject); + bool IsVisibilityOverridden() const { return m_isVisibilityDistanceOverride; } + void SetVisibilityDistanceOverride(bool isVisibilityDistanceOverride); + void SetWorldObject(bool apply); + bool IsPermanentWorldObject() const { return m_isWorldObject; } + bool IsWorldObject() const; - virtual void SetPhaseMask(uint32 newPhaseMask, bool update); - uint32 GetPhaseMask() const { return m_phaseMask; } - bool InSamePhase(WorldObject const* obj) const { return InSamePhase(obj->GetPhaseMask()); } - bool InSamePhase(uint32 phasemask) const { return m_useCombinedPhases ? GetPhaseMask() & phasemask : GetPhaseMask() == phasemask; } + template void VisitNearbyObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitAll(GetPositionX(), GetPositionY(), radius, notifier); } + template void VisitNearbyGridObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitGrid(GetPositionX(), GetPositionY(), radius, notifier); } + template void VisitNearbyWorldObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitWorld(GetPositionX(), GetPositionY(), radius, notifier); } - virtual uint32 GetZoneId(bool forceRecalc = false) const; - virtual uint32 GetAreaId(bool forceRecalc = false) const; - virtual void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc = false) const; - - InstanceScript* GetInstanceScript(); - - std::string const& GetName() const { return m_name; } - void SetName(std::string const& newname) { m_name=newname; } - - virtual std::string const& GetNameForLocaleIdx(LocaleConstant /*locale_idx*/) const { return m_name; } - - float GetDistance(const WorldObject* obj) const - { - float d = GetExactDist(obj) - GetObjectSize() - obj->GetObjectSize(); - return d > 0.0f ? d : 0.0f; - } - float GetDistance(const Position &pos) const - { - float d = GetExactDist(&pos) - GetObjectSize(); - return d > 0.0f ? d : 0.0f; - } - float GetDistance(float x, float y, float z) const - { - float d = GetExactDist(x, y, z) - GetObjectSize(); - return d > 0.0f ? d : 0.0f; - } - float GetDistance2d(const WorldObject* obj) const - { - float d = GetExactDist2d(obj) - GetObjectSize() - obj->GetObjectSize(); - return d > 0.0f ? d : 0.0f; - } - float GetDistance2d(float x, float y) const - { - float d = GetExactDist2d(x, y) - GetObjectSize(); - return d > 0.0f ? d : 0.0f; - } - float GetDistanceZ(const WorldObject* obj) const; - - bool IsSelfOrInSameMap(const WorldObject* obj) const - { - if (this == obj) - return true; - return IsInMap(obj); - } - bool IsInMap(const WorldObject* obj) const - { - if (obj) - return IsInWorld() && obj->IsInWorld() && (FindMap() == obj->FindMap()); - return false; - } - bool IsWithinDist3d(float x, float y, float z, float dist) const - { return IsInDist(x, y, z, dist + GetObjectSize()); } - bool IsWithinDist3d(const Position* pos, float dist) const - { return IsInDist(pos, dist + GetObjectSize()); } - bool IsWithinDist2d(float x, float y, float dist) const - { return IsInDist2d(x, y, dist + GetObjectSize()); } - bool IsWithinDist2d(const Position* pos, float dist) const - { return IsInDist2d(pos, dist + GetObjectSize()); } - // use only if you will sure about placing both object at same map - bool IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D = true) const - { - return obj && _IsWithinDist(obj, dist2compare, is3D); - } - bool IsWithinDistInMap(WorldObject const* obj, float dist2compare, bool is3D = true) const - { - return obj && IsInMap(obj) && InSamePhase(obj) && _IsWithinDist(obj, dist2compare, is3D); - } - bool IsWithinLOS(float x, float y, float z, LineOfSightChecks checks = LINEOFSIGHT_ALL_CHECKS) const; - bool IsWithinLOSInMap(WorldObject const* obj, LineOfSightChecks checks = LINEOFSIGHT_ALL_CHECKS) const; - Position GetHitSpherePointFor(Position const& dest) const; - void GetHitSpherePointFor(Position const& dest, float& x, float& y, float& z) const; - bool GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D = true) const; - bool IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D = true) const; - bool IsInRange2d(float x, float y, float minRange, float maxRange) const; - bool IsInRange3d(float x, float y, float z, float minRange, float maxRange) const; - bool isInFront(WorldObject const* target, float arc = M_PI) const; - bool isInBack(WorldObject const* target, float arc = M_PI) const; - - bool IsInBetween(const WorldObject* obj1, const WorldObject* obj2, float size = 0) const; - - virtual void CleanupsBeforeDelete(bool finalCleanup = true); // used in destructor or explicitly before mass creature delete to remove cross-references to already deleted units - - virtual void SendMessageToSet(WorldPacket* data, bool self) { if (IsInWorld()) SendMessageToSetInRange(data, GetVisibilityRange(), self, true); } // pussywizard! - virtual void SendMessageToSetInRange(WorldPacket* data, float dist, bool /*self*/, bool includeMargin = false, Player const* skipped_rcvr = nullptr); // pussywizard! - virtual void SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr) { if (IsInWorld()) SendMessageToSetInRange(data, GetVisibilityRange(), false, true, skipped_rcvr); } // pussywizard! - - virtual uint8 getLevelForTarget(WorldObject const* /*target*/) const { return 1; } - - void MonsterSay(const char* text, uint32 language, WorldObject const* target); - void MonsterYell(const char* text, uint32 language, WorldObject const* target); - void MonsterTextEmote(const char* text, WorldObject const* target, bool IsBossEmote = false); - void MonsterWhisper(const char* text, Player const* target, bool IsBossWhisper = false); - void MonsterSay(int32 textId, uint32 language, WorldObject const* target); - void MonsterYell(int32 textId, uint32 language, WorldObject const* target); - void MonsterTextEmote(int32 textId, WorldObject const* target, bool IsBossEmote = false); - void MonsterWhisper(int32 textId, Player const* target, bool IsBossWhisper = false); - - void PlayDistanceSound(uint32 sound_id, Player* target = nullptr); - void PlayDirectSound(uint32 sound_id, Player* target = nullptr); - void PlayDirectMusic(uint32 music_id, Player* target = nullptr); - - void SendObjectDeSpawnAnim(uint64 guid); - - virtual void SaveRespawnTime() {} - void AddObjectToRemoveList(); - - float GetGridActivationRange() const; - float GetVisibilityRange() const; - float GetSightRange(const WorldObject* target = nullptr) const; - //bool CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth = false, bool distanceCheck = false) const; - bool CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth = false, bool distanceCheck = false, bool checkAlert = false) const; - - FlaggedValuesArray32 m_stealth; - FlaggedValuesArray32 m_stealthDetect; - - FlaggedValuesArray32 m_invisibility; - FlaggedValuesArray32 m_invisibilityDetect; - - FlaggedValuesArray32 m_serverSideVisibility; - FlaggedValuesArray32 m_serverSideVisibilityDetect; - - // Low Level Packets - void SendPlaySound(uint32 Sound, bool OnlySelf); - void SendPlayMusic(uint32 Music, bool OnlySelf); - - virtual void SetMap(Map* map); - virtual void ResetMap(); - Map* GetMap() const { ASSERT(m_currMap); return m_currMap; } - Map* FindMap() const { return m_currMap; } - //used to check all object's GetMap() calls when object is not in world! - - //this function should be removed in nearest time... - Map const* GetBaseMap() const; - - void SetZoneScript(); - ZoneScript* GetZoneScript() const { return m_zoneScript; } - - TempSummon* SummonCreature(uint32 id, const Position &pos, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, uint32 vehId = 0, SummonPropertiesEntry const *properties = nullptr) const; - TempSummon* SummonCreature(uint32 id, float x, float y, float z, float ang = 0, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, SummonPropertiesEntry const *properties = nullptr) - { - if (!x && !y && !z) - { - GetClosePoint(x, y, z, GetObjectSize()); - ang = GetOrientation(); - } - Position pos; - pos.Relocate(x, y, z, ang); - return SummonCreature(id, pos, spwtype, despwtime, 0, properties); - } - GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime, bool checkTransport = true); - Creature* SummonTrigger(float x, float y, float z, float ang, uint32 dur, bool setLevel = false, CreatureAI* (*GetAI)(Creature*) = nullptr); - void SummonCreatureGroup(uint8 group, std::list* list = nullptr); - - Creature* FindNearestCreature(uint32 entry, float range, bool alive = true) const; - GameObject* FindNearestGameObject(uint32 entry, float range) const; - GameObject* FindNearestGameObjectOfType(GameobjectTypes type, float range) const; - - Player* SelectNearestPlayer(float distance = 0) const; - void GetGameObjectListWithEntryInGrid(std::list& lList, uint32 uiEntry, float fMaxSearchRange) const; - void GetCreatureListWithEntryInGrid(std::list& lList, uint32 uiEntry, float fMaxSearchRange) const; - - void DestroyForNearbyPlayers(); - virtual void UpdateObjectVisibility(bool forced = true, bool fromUpdate = false); - void BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet& player_set); - void GetCreaturesWithEntryInRange(std::list &creatureList, float radius, uint32 entry); - - //relocation and visibility system functions - void AddToNotify(uint16 f); - void RemoveFromNotify(uint16 f) { m_notifyflags &= ~f; } - bool isNeedNotify(uint16 f) const { return m_notifyflags & f;} - uint16 GetNotifyFlags() const { return m_notifyflags; } - bool NotifyExecuted(uint16 f) const { return m_executed_notifies & f;} - void SetNotified(uint16 f) { m_executed_notifies |= f;} - void ResetAllNotifies() { m_notifyflags = 0; m_executed_notifies = 0; } - - bool isActiveObject() const { return m_isActive; } - void setActive(bool isActiveObject); - bool IsVisibilityOverridden() const { return m_isVisibilityDistanceOverride; } - void SetVisibilityDistanceOverride(bool isVisibilityDistanceOverride); - void SetWorldObject(bool apply); - bool IsPermanentWorldObject() const { return m_isWorldObject; } - bool IsWorldObject() const; - - template void VisitNearbyObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitAll(GetPositionX(), GetPositionY(), radius, notifier); } - template void VisitNearbyGridObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitGrid(GetPositionX(), GetPositionY(), radius, notifier); } - template void VisitNearbyWorldObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitWorld(GetPositionX(), GetPositionY(), radius, notifier); } - - bool IsInWintergrasp() const - { - return GetMapId() == 571 && GetPositionX() > 3733.33331f && GetPositionX() < 5866.66663f && GetPositionY() > 1599.99999f && GetPositionY() < 4799.99997f; - } + bool IsInWintergrasp() const + { + return GetMapId() == 571 && GetPositionX() > 3733.33331f && GetPositionX() < 5866.66663f && GetPositionY() > 1599.99999f && GetPositionY() < 4799.99997f; + } #ifdef MAP_BASED_RAND_GEN - int32 irand(int32 min, int32 max) const { return int32 (GetMap()->mtRand.randInt(max - min)) + min; } - uint32 urand(uint32 min, uint32 max) const { return GetMap()->mtRand.randInt(max - min) + min;} - int32 rand32() const { return GetMap()->mtRand.randInt();} - double rand_norm() const { return GetMap()->mtRand.randExc();} - double rand_chance() const { return GetMap()->mtRand.randExc(100.0);} + int32 irand(int32 min, int32 max) const { return int32 (GetMap()->mtRand.randInt(max - min)) + min; } + uint32 urand(uint32 min, uint32 max) const { return GetMap()->mtRand.randInt(max - min) + min;} + int32 rand32() const { return GetMap()->mtRand.randInt();} + double rand_norm() const { return GetMap()->mtRand.randExc();} + double rand_chance() const { return GetMap()->mtRand.randExc(100.0);} #endif - uint32 LastUsedScriptID; + uint32 LastUsedScriptID; - // Transports - Transport* GetTransport() const { return m_transport; } - float GetTransOffsetX() const { return m_movementInfo.transport.pos.GetPositionX(); } - float GetTransOffsetY() const { return m_movementInfo.transport.pos.GetPositionY(); } - float GetTransOffsetZ() const { return m_movementInfo.transport.pos.GetPositionZ(); } - float GetTransOffsetO() const { return m_movementInfo.transport.pos.GetOrientation(); } - uint32 GetTransTime() const { return m_movementInfo.transport.time; } - int8 GetTransSeat() const { return m_movementInfo.transport.seat; } - virtual uint64 GetTransGUID() const; - void SetTransport(Transport* t) { m_transport = t; } + // Transports + Transport* GetTransport() const { return m_transport; } + float GetTransOffsetX() const { return m_movementInfo.transport.pos.GetPositionX(); } + float GetTransOffsetY() const { return m_movementInfo.transport.pos.GetPositionY(); } + float GetTransOffsetZ() const { return m_movementInfo.transport.pos.GetPositionZ(); } + float GetTransOffsetO() const { return m_movementInfo.transport.pos.GetOrientation(); } + uint32 GetTransTime() const { return m_movementInfo.transport.time; } + int8 GetTransSeat() const { return m_movementInfo.transport.seat; } + virtual uint64 GetTransGUID() const; + void SetTransport(Transport* t) { m_transport = t; } - MovementInfo m_movementInfo; + MovementInfo m_movementInfo; - virtual float GetStationaryX() const { return GetPositionX(); } - virtual float GetStationaryY() const { return GetPositionY(); } - virtual float GetStationaryZ() const { return GetPositionZ(); } - virtual float GetStationaryO() const { return GetOrientation(); } + virtual float GetStationaryX() const { return GetPositionX(); } + virtual float GetStationaryY() const { return GetPositionY(); } + virtual float GetStationaryZ() const { return GetPositionZ(); } + virtual float GetStationaryO() const { return GetOrientation(); } - protected: - std::string m_name; - bool m_isActive; - bool m_isVisibilityDistanceOverride; - const bool m_isWorldObject; - ZoneScript* m_zoneScript; +protected: + std::string m_name; + bool m_isActive; + bool m_isVisibilityDistanceOverride; + const bool m_isWorldObject; + ZoneScript* m_zoneScript; - // transports - Transport* m_transport; + // transports + Transport* m_transport; - //these functions are used mostly for Relocate() and Corpse/Player specific stuff... - //use them ONLY in LoadFromDB()/Create() funcs and nowhere else! - //mapId/instanceId should be set in SetMap() function! - void SetLocationMapId(uint32 _mapId) { m_mapId = _mapId; } - void SetLocationInstanceId(uint32 _instanceId) { m_InstanceId = _instanceId; } + //these functions are used mostly for Relocate() and Corpse/Player specific stuff... + //use them ONLY in LoadFromDB()/Create() funcs and nowhere else! + //mapId/instanceId should be set in SetMap() function! + void SetLocationMapId(uint32 _mapId) { m_mapId = _mapId; } + void SetLocationInstanceId(uint32 _instanceId) { m_InstanceId = _instanceId; } - virtual bool IsNeverVisible() const { return !IsInWorld(); } - virtual bool IsAlwaysVisibleFor(WorldObject const* /*seer*/) const { return false; } - virtual bool IsInvisibleDueToDespawn() const { return false; } - //difference from IsAlwaysVisibleFor: 1. after distance check; 2. use owner or charmer as seer - virtual bool IsAlwaysDetectableFor(WorldObject const* /*seer*/) const { return false; } - private: - Map* m_currMap; //current object's Map location + virtual bool IsNeverVisible() const { return !IsInWorld(); } + virtual bool IsAlwaysVisibleFor(WorldObject const* /*seer*/) const { return false; } + virtual bool IsInvisibleDueToDespawn() const { return false; } + //difference from IsAlwaysVisibleFor: 1. after distance check; 2. use owner or charmer as seer + virtual bool IsAlwaysDetectableFor(WorldObject const* /*seer*/) const { return false; } +private: + Map* m_currMap; //current object's Map location - //uint32 m_mapId; // object at map with map_id - uint32 m_InstanceId; // in map copy with instance id - uint32 m_phaseMask; // in area phase state - bool m_useCombinedPhases; // true (default): use phaseMask as bit mask combining up to 32 phases - // false: use phaseMask to represent single phases only (up to 4294967295 phases) + //uint32 m_mapId; // object at map with map_id + uint32 m_InstanceId; // in map copy with instance id + uint32 m_phaseMask; // in area phase state + bool m_useCombinedPhases; // true (default): use phaseMask as bit mask combining up to 32 phases + // false: use phaseMask to represent single phases only (up to 4294967295 phases) - uint16 m_notifyflags; - uint16 m_executed_notifies; + uint16 m_notifyflags; + uint16 m_executed_notifies; - virtual bool _IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const; + virtual bool _IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const; - bool CanNeverSee(WorldObject const* obj) const; - virtual bool CanAlwaysSee(WorldObject const* /*obj*/) const { return false; } - //bool CanDetect(WorldObject const* obj, bool ignoreStealth, bool checkClient) const; - bool CanDetect(WorldObject const* obj, bool ignoreStealth, bool checkClient, bool checkAlert = false) const; - bool CanDetectInvisibilityOf(WorldObject const* obj) const; - //bool CanDetectStealthOf(WorldObject const* obj) const; - bool CanDetectStealthOf(WorldObject const* obj, bool checkAlert = false) const; + bool CanNeverSee(WorldObject const* obj) const; + virtual bool CanAlwaysSee(WorldObject const* /*obj*/) const { return false; } + //bool CanDetect(WorldObject const* obj, bool ignoreStealth, bool checkClient) const; + bool CanDetect(WorldObject const* obj, bool ignoreStealth, bool checkClient, bool checkAlert = false) const; + bool CanDetectInvisibilityOf(WorldObject const* obj) const; + //bool CanDetectStealthOf(WorldObject const* obj) const; + bool CanDetectStealthOf(WorldObject const* obj, bool checkAlert = false) const; }; namespace acore @@ -1083,15 +1111,15 @@ namespace acore // Binary predicate to sort WorldObjects based on the distance to a reference WorldObject class ObjectDistanceOrderPred { - public: - ObjectDistanceOrderPred(const WorldObject* pRefObj, bool ascending = true) : m_refObj(pRefObj), m_ascending(ascending) {} - bool operator()(const WorldObject* pLeft, const WorldObject* pRight) const - { - return m_ascending ? m_refObj->GetDistanceOrder(pLeft, pRight) : !m_refObj->GetDistanceOrder(pLeft, pRight); - } - private: - const WorldObject* m_refObj; - const bool m_ascending; + public: + ObjectDistanceOrderPred(const WorldObject* pRefObj, bool ascending = true) : m_refObj(pRefObj), m_ascending(ascending) {} + bool operator()(const WorldObject* pLeft, const WorldObject* pRight) const + { + return m_ascending ? m_refObj->GetDistanceOrder(pLeft, pRight) : !m_refObj->GetDistanceOrder(pLeft, pRight); + } + private: + const WorldObject* m_refObj; + const bool m_ascending; }; } diff --git a/src/server/game/Entities/Object/ObjectDefines.h b/src/server/game/Entities/Object/ObjectDefines.h index 1f2a98ced..a0c4700e4 100644 --- a/src/server/game/Entities/Object/ObjectDefines.h +++ b/src/server/game/Entities/Object/ObjectDefines.h @@ -187,15 +187,15 @@ uint32 GUID_HIPART(uint64 guid) uint32 GUID_ENPART(uint64 x) { return IsGuidHaveEnPart(x) - ? (uint32)((x >> 24) & UI64LIT(0x0000000000FFFFFF)) - : 0; + ? (uint32)((x >> 24) & UI64LIT(0x0000000000FFFFFF)) + : 0; } uint32 GUID_LOPART(uint64 x) { return IsGuidHaveEnPart(x) - ? (uint32)(x & UI64LIT(0x0000000000FFFFFF)) - : (uint32)(x & UI64LIT(0x00000000FFFFFFFF)); + ? (uint32)(x & UI64LIT(0x0000000000FFFFFF)) + : (uint32)(x & UI64LIT(0x00000000FFFFFFFF)); } bool IsGuidHaveEnPart(uint64 guid) @@ -223,17 +223,28 @@ char const* GetLogNameForGuid(uint64 guid) { switch (GUID_HIPART(guid)) { - case HIGHGUID_ITEM: return "item"; - case HIGHGUID_PLAYER: return guid ? "player" : "none"; - case HIGHGUID_GAMEOBJECT: return "gameobject"; - case HIGHGUID_TRANSPORT: return "transport"; - case HIGHGUID_UNIT: return "creature"; - case HIGHGUID_PET: return "pet"; - case HIGHGUID_VEHICLE: return "vehicle"; - case HIGHGUID_DYNAMICOBJECT:return "dynobject"; - case HIGHGUID_CORPSE: return "corpse"; - case HIGHGUID_MO_TRANSPORT: return "mo_transport"; - case HIGHGUID_GROUP: return "group"; + case HIGHGUID_ITEM: + return "item"; + case HIGHGUID_PLAYER: + return guid ? "player" : "none"; + case HIGHGUID_GAMEOBJECT: + return "gameobject"; + case HIGHGUID_TRANSPORT: + return "transport"; + case HIGHGUID_UNIT: + return "creature"; + case HIGHGUID_PET: + return "pet"; + case HIGHGUID_VEHICLE: + return "vehicle"; + case HIGHGUID_DYNAMICOBJECT: + return "dynobject"; + case HIGHGUID_CORPSE: + return "corpse"; + case HIGHGUID_MO_TRANSPORT: + return "mo_transport"; + case HIGHGUID_GROUP: + return "group"; default: return ""; } diff --git a/src/server/game/Entities/Object/ObjectPosSelector.cpp b/src/server/game/Entities/Object/ObjectPosSelector.cpp index 16aee5417..46fbb6b83 100644 --- a/src/server/game/Entities/Object/ObjectPosSelector.cpp +++ b/src/server/game/Entities/Object/ObjectPosSelector.cpp @@ -7,9 +7,9 @@ #include "ObjectPosSelector.h" ObjectPosSelector::ObjectPosSelector(float x, float y, float size, float dist) -: m_center_x(x), m_center_y(y), m_size(size), m_dist(dist) + : m_center_x(x), m_center_y(y), m_size(size), m_dist(dist) { - m_anglestep = acos(m_dist/(m_dist+2*m_size)); + m_anglestep = acos(m_dist / (m_dist + 2 * m_size)); m_nextUsedPos[USED_POS_PLUS] = m_UsedPosLists[USED_POS_PLUS].end(); m_nextUsedPos[USED_POS_MINUS] = m_UsedPosLists[USED_POS_MINUS].end(); @@ -27,10 +27,10 @@ ObjectPosSelector::ObjectPosSelector(float x, float y, float size, float dist) ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos(UsedPosType uptype) { UsedPosList::const_iterator itr = m_nextUsedPos[uptype]; - if (itr!=m_UsedPosLists[uptype].end()) + if (itr != m_UsedPosLists[uptype].end()) ++itr; - if (itr==m_UsedPosLists[uptype].end()) + if (itr == m_UsedPosLists[uptype].end()) { if (!m_UsedPosLists[~uptype].empty()) return &*m_UsedPosLists[~uptype].rbegin(); @@ -73,9 +73,9 @@ bool ObjectPosSelector::FirstAngle(float& angle) bool ObjectPosSelector::NextAngle(float& angle) { - while (m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() || - m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end() || - m_smallStepOk[USED_POS_PLUS] || m_smallStepOk[USED_POS_MINUS] ) + while (m_nextUsedPos[USED_POS_PLUS] != m_UsedPosLists[USED_POS_PLUS].end() || + m_nextUsedPos[USED_POS_MINUS] != m_UsedPosLists[USED_POS_MINUS].end() || + m_smallStepOk[USED_POS_PLUS] || m_smallStepOk[USED_POS_MINUS] ) { // calculate next possible angle if (NextPosibleAngle(angle)) @@ -87,8 +87,8 @@ bool ObjectPosSelector::NextAngle(float& angle) bool ObjectPosSelector::NextUsedAngle(float& angle) { - while (m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() || - m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end()) + while (m_nextUsedPos[USED_POS_PLUS] != m_UsedPosLists[USED_POS_PLUS].end() || + m_nextUsedPos[USED_POS_MINUS] != m_UsedPosLists[USED_POS_MINUS].end()) { // calculate next possible angle if (!NextPosibleAngle(angle)) @@ -101,8 +101,8 @@ bool ObjectPosSelector::NextUsedAngle(float& angle) bool ObjectPosSelector::NextPosibleAngle(float& angle) { // ++ direction less updated - if (m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() && - (m_nextUsedPos[USED_POS_MINUS]==m_UsedPosLists[USED_POS_MINUS].end() || m_nextUsedPos[USED_POS_PLUS]->first <= m_nextUsedPos[USED_POS_MINUS]->first)) + if (m_nextUsedPos[USED_POS_PLUS] != m_UsedPosLists[USED_POS_PLUS].end() && + (m_nextUsedPos[USED_POS_MINUS] == m_UsedPosLists[USED_POS_MINUS].end() || m_nextUsedPos[USED_POS_PLUS]->first <= m_nextUsedPos[USED_POS_MINUS]->first)) { bool ok; if (m_smallStepOk[USED_POS_PLUS]) @@ -115,7 +115,7 @@ bool ObjectPosSelector::NextPosibleAngle(float& angle) return ok; } // -- direction less updated - else if (m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end()) + else if (m_nextUsedPos[USED_POS_MINUS] != m_UsedPosLists[USED_POS_MINUS].end()) { bool ok; if (m_smallStepOk[USED_POS_MINUS]) diff --git a/src/server/game/Entities/Object/ObjectPosSelector.h b/src/server/game/Entities/Object/ObjectPosSelector.h index 3ffff5f86..fe8a7ba06 100644 --- a/src/server/game/Entities/Object/ObjectPosSelector.h +++ b/src/server/game/Entities/Object/ObjectPosSelector.h @@ -15,7 +15,7 @@ enum UsedPosType { USED_POS_PLUS, USED_POS_MINUS }; inline UsedPosType operator ~(UsedPosType uptype) { - return uptype==USED_POS_PLUS ? USED_POS_MINUS : USED_POS_PLUS; + return uptype == USED_POS_PLUS ? USED_POS_MINUS : USED_POS_PLUS; } struct ObjectPosSelector @@ -49,20 +49,20 @@ struct ObjectPosSelector float next_angle = nextUsedPos.first; if (nextUsedPos.second.sign * sign < 0) // last node from diff. list (-pi+alpha) - next_angle = 2*M_PI-next_angle; // move to positive + next_angle = 2 * M_PI - next_angle; // move to positive - return fabs(angle)+angle_step2 <= next_angle; + return fabs(angle) + angle_step2 <= next_angle; } bool CheckOriginal() const { return (m_UsedPosLists[USED_POS_PLUS].empty() || CheckAngle(*m_UsedPosLists[USED_POS_PLUS].begin(), 1.0f, 0)) && - (m_UsedPosLists[USED_POS_MINUS].empty() || CheckAngle(*m_UsedPosLists[USED_POS_MINUS].begin(), -1.0f, 0)); + (m_UsedPosLists[USED_POS_MINUS].empty() || CheckAngle(*m_UsedPosLists[USED_POS_MINUS].begin(), -1.0f, 0)); } bool IsNonBalanced() const { return m_UsedPosLists[USED_POS_PLUS].empty() != m_UsedPosLists[USED_POS_MINUS].empty(); } - bool NextAngleFor(UsedPosList::value_type const& usedPos, float sign, UsedPosType uptype, float &angle) + bool NextAngleFor(UsedPosList::value_type const& usedPos, float sign, UsedPosType uptype, float& angle) { float angle_step = GetAngle(usedPos.second); @@ -88,7 +88,7 @@ struct ObjectPosSelector return true; } - bool NextSmallStepAngle(float sign, UsedPosType uptype, float &angle) + bool NextSmallStepAngle(float sign, UsedPosType uptype, float& angle) { // next possible angle angle = m_smallStepAngle[uptype] + m_anglestep * sign; @@ -124,7 +124,7 @@ struct ObjectPosSelector UsedPosList::value_type const* nextUsedPos(UsedPosType uptype); // angle from used pos to next possible free pos - float GetAngle(UsedPos const& usedPos) const { return acos(m_dist/(usedPos.dist+usedPos.size+m_size)); } + float GetAngle(UsedPos const& usedPos) const { return acos(m_dist / (usedPos.dist + usedPos.size + m_size)); } float m_center_x; float m_center_y; diff --git a/src/server/game/Entities/Object/Updates/UpdateData.cpp b/src/server/game/Entities/Object/Updates/UpdateData.cpp index e3b0aaa1f..e70459c4f 100644 --- a/src/server/game/Entities/Object/Updates/UpdateData.cpp +++ b/src/server/game/Entities/Object/Updates/UpdateData.cpp @@ -23,19 +23,19 @@ void UpdateData::AddOutOfRangeGUID(uint64 guid) m_outOfRangeGUIDs.push_back(guid); } -void UpdateData::AddUpdateBlock(const ByteBuffer &block) +void UpdateData::AddUpdateBlock(const ByteBuffer& block) { m_data.append(block); ++m_blockCount; } -void UpdateData::AddUpdateBlock(const UpdateData &block) +void UpdateData::AddUpdateBlock(const UpdateData& block) { m_data.append(block.m_data); m_blockCount += block.m_blockCount; } -void UpdateData::Compress(void* dst, uint32 *dst_size, void* src, int src_size) +void UpdateData::Compress(void* dst, uint32* dst_size, void* src, int src_size) { z_stream c_stream; diff --git a/src/server/game/Entities/Object/Updates/UpdateData.h b/src/server/game/Entities/Object/Updates/UpdateData.h index 733df205f..fa5db8729 100644 --- a/src/server/game/Entities/Object/Updates/UpdateData.h +++ b/src/server/game/Entities/Object/Updates/UpdateData.h @@ -37,22 +37,22 @@ enum OBJECT_UPDATE_FLAGS class UpdateData { - public: - UpdateData(); +public: + UpdateData(); - void AddOutOfRangeGUID(uint64 guid); - void AddUpdateBlock(const ByteBuffer &block); - void AddUpdateBlock(const UpdateData &block); - bool BuildPacket(WorldPacket* packet); - bool HasData() const { return m_blockCount > 0 || !m_outOfRangeGUIDs.empty(); } - void Clear(); + void AddOutOfRangeGUID(uint64 guid); + void AddUpdateBlock(const ByteBuffer& block); + void AddUpdateBlock(const UpdateData& block); + bool BuildPacket(WorldPacket* packet); + bool HasData() const { return m_blockCount > 0 || !m_outOfRangeGUIDs.empty(); } + void Clear(); - protected: - uint32 m_blockCount; - std::vector m_outOfRangeGUIDs; - ByteBuffer m_data; +protected: + uint32 m_blockCount; + std::vector m_outOfRangeGUIDs; + ByteBuffer m_data; - void Compress(void* dst, uint32 *dst_size, void* src, int src_size); + void Compress(void* dst, uint32* dst_size, void* src, int src_size); }; #endif diff --git a/src/server/game/Entities/Object/Updates/UpdateMask.h b/src/server/game/Entities/Object/Updates/UpdateMask.h index f1f47d918..49262faa8 100644 --- a/src/server/game/Entities/Object/Updates/UpdateMask.h +++ b/src/server/game/Entities/Object/Updates/UpdateMask.h @@ -13,101 +13,101 @@ class UpdateMask { - public: - /// Type representing how client reads update mask - typedef uint32 ClientUpdateMaskType; +public: + /// Type representing how client reads update mask + typedef uint32 ClientUpdateMaskType; - enum UpdateMaskCount + enum UpdateMaskCount + { + CLIENT_UPDATE_MASK_BITS = sizeof(ClientUpdateMaskType) * 8, + }; + + UpdateMask() : _fieldCount(0), _blockCount(0), _bits(nullptr) { } + + UpdateMask(UpdateMask const& right) : _bits(nullptr) + { + SetCount(right.GetCount()); + memcpy(_bits, right._bits, sizeof(uint8) * _blockCount * 32); + } + + ~UpdateMask() { delete[] _bits; } + + void SetBit(uint32 index) { _bits[index] = 1; } + void UnsetBit(uint32 index) { _bits[index] = 0; } + bool GetBit(uint32 index) const { return _bits[index] != 0; } + + void AppendToPacket(ByteBuffer* data) + { + for (uint32 i = 0; i < GetBlockCount(); ++i) { - CLIENT_UPDATE_MASK_BITS = sizeof(ClientUpdateMaskType) * 8, - }; + ClientUpdateMaskType maskPart = 0; + for (uint32 j = 0; j < CLIENT_UPDATE_MASK_BITS; ++j) + if (_bits[CLIENT_UPDATE_MASK_BITS * i + j]) + maskPart |= 1 << j; - UpdateMask() : _fieldCount(0), _blockCount(0), _bits(nullptr) { } - - UpdateMask(UpdateMask const& right) : _bits(nullptr) - { - SetCount(right.GetCount()); - memcpy(_bits, right._bits, sizeof(uint8) * _blockCount * 32); + *data << maskPart; } + } - ~UpdateMask() { delete[] _bits; } + uint32 GetBlockCount() const { return _blockCount; } + uint32 GetCount() const { return _fieldCount; } - void SetBit(uint32 index) { _bits[index] = 1; } - void UnsetBit(uint32 index) { _bits[index] = 0; } - bool GetBit(uint32 index) const { return _bits[index] != 0; } + void SetCount(uint32 valuesCount) + { + delete[] _bits; - void AppendToPacket(ByteBuffer* data) - { - for (uint32 i = 0; i < GetBlockCount(); ++i) - { - ClientUpdateMaskType maskPart = 0; - for (uint32 j = 0; j < CLIENT_UPDATE_MASK_BITS; ++j) - if (_bits[CLIENT_UPDATE_MASK_BITS * i + j]) - maskPart |= 1 << j; + _fieldCount = valuesCount; + _blockCount = (valuesCount + CLIENT_UPDATE_MASK_BITS - 1) / CLIENT_UPDATE_MASK_BITS; - *data << maskPart; - } - } + _bits = new uint8[_blockCount * CLIENT_UPDATE_MASK_BITS]; + memset(_bits, 0, sizeof(uint8) * _blockCount * CLIENT_UPDATE_MASK_BITS); + } - uint32 GetBlockCount() const { return _blockCount; } - uint32 GetCount() const { return _fieldCount; } - - void SetCount(uint32 valuesCount) - { - delete[] _bits; - - _fieldCount = valuesCount; - _blockCount = (valuesCount + CLIENT_UPDATE_MASK_BITS - 1) / CLIENT_UPDATE_MASK_BITS; - - _bits = new uint8[_blockCount * CLIENT_UPDATE_MASK_BITS]; + void Clear() + { + if (_bits) memset(_bits, 0, sizeof(uint8) * _blockCount * CLIENT_UPDATE_MASK_BITS); - } + } - void Clear() - { - if (_bits) - memset(_bits, 0, sizeof(uint8) * _blockCount * CLIENT_UPDATE_MASK_BITS); - } - - UpdateMask& operator=(UpdateMask const& right) - { - if (this == &right) - return *this; - - SetCount(right.GetCount()); - memcpy(_bits, right._bits, sizeof(uint8) * _blockCount * CLIENT_UPDATE_MASK_BITS); + UpdateMask& operator=(UpdateMask const& right) + { + if (this == &right) return *this; - } - UpdateMask& operator&=(UpdateMask const& right) - { - ASSERT(right.GetCount() <= GetCount()); - for (uint32 i = 0; i < _fieldCount; ++i) - _bits[i] &= right._bits[i]; + SetCount(right.GetCount()); + memcpy(_bits, right._bits, sizeof(uint8) * _blockCount * CLIENT_UPDATE_MASK_BITS); + return *this; + } - return *this; - } + UpdateMask& operator&=(UpdateMask const& right) + { + ASSERT(right.GetCount() <= GetCount()); + for (uint32 i = 0; i < _fieldCount; ++i) + _bits[i] &= right._bits[i]; - UpdateMask& operator|=(UpdateMask const& right) - { - ASSERT(right.GetCount() <= GetCount()); - for (uint32 i = 0; i < _fieldCount; ++i) - _bits[i] |= right._bits[i]; + return *this; + } - return *this; - } + UpdateMask& operator|=(UpdateMask const& right) + { + ASSERT(right.GetCount() <= GetCount()); + for (uint32 i = 0; i < _fieldCount; ++i) + _bits[i] |= right._bits[i]; - UpdateMask operator|(UpdateMask const& right) - { - UpdateMask ret(*this); - ret |= right; - return ret; - } + return *this; + } - private: - uint32 _fieldCount; - uint32 _blockCount; - uint8* _bits; + UpdateMask operator|(UpdateMask const& right) + { + UpdateMask ret(*this); + ret |= right; + return ret; + } + +private: + uint32 _fieldCount; + uint32 _blockCount; + uint8* _bits; }; #endif diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index 345e80d5a..283a1d4d6 100644 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -26,9 +26,9 @@ #define PET_XP_FACTOR 0.05f Pet::Pet(Player* owner, PetType type) : Guardian(nullptr, owner ? owner->GetGUID() : 0, true), -m_usedTalentCount(0), m_removed(false), m_owner(owner), -m_happinessTimer(PET_LOSE_HAPPINES_INTERVAL), m_petType(type), m_duration(0), -m_auraRaidUpdateMask(0), m_loading(false), m_petRegenTimer(PET_FOCUS_REGEN_INTERVAL), m_declinedname(nullptr), m_tempspellTarget(nullptr), m_tempoldTarget(nullptr), m_tempspellIsPositive(false), m_tempspell(0), asynchLoadType(PET_LOAD_DEFAULT) + m_usedTalentCount(0), m_removed(false), m_owner(owner), + m_happinessTimer(PET_LOSE_HAPPINES_INTERVAL), m_petType(type), m_duration(0), + m_auraRaidUpdateMask(0), m_loading(false), m_petRegenTimer(PET_FOCUS_REGEN_INTERVAL), m_declinedname(nullptr), m_tempspellTarget(nullptr), m_tempoldTarget(nullptr), m_tempspellIsPositive(false), m_tempspell(0), asynchLoadType(PET_LOAD_DEFAULT) { m_unitTypeMask |= UNIT_MASK_PET; if (type == HUNTER_PET) @@ -49,7 +49,7 @@ Pet::~Pet() } void Pet::AddToWorld() -{ +{ ///- Register the pet for guid lookup if (!IsInWorld()) { @@ -87,7 +87,7 @@ void Pet::AddToWorld() } void Pet::RemoveFromWorld() -{ +{ ///- Remove the pet from the accessor if (IsInWorld()) { @@ -147,7 +147,7 @@ SpellCastResult Pet::TryLoadFromDB(Player* owner, bool current /*= false*/, PetT } bool Pet::LoadPetFromDB(Player* owner, uint8 asynchLoadType, uint32 petentry, uint32 petnumber, bool current, AsynchPetSummon* info) -{ +{ // we are loading pet at that moment if (owner->IsSpectator() || owner->GetPet() || !owner->IsInWorld() || !owner->FindMap()) return false; @@ -216,7 +216,7 @@ void Pet::SavePetToDB(PetSaveMode mode, bool logout) // not save pet as current if another pet temporary unsummoned if (mode == PET_SAVE_AS_CURRENT && owner->GetTemporaryUnsummonedPetNumber() && - owner->GetTemporaryUnsummonedPetNumber() != m_charmInfo->GetPetNumber()) + owner->GetTemporaryUnsummonedPetNumber() != m_charmInfo->GetPetNumber()) { // pet will lost anyway at restore temporary unsummoned if (getPetType() == HUNTER_PET) @@ -336,7 +336,7 @@ void Pet::DeleteFromDB(uint32 guidlow) } void Pet::setDeathState(DeathState s, bool /*despawn = false*/) // overwrite virtual Creature::setDeathState and Unit::setDeathState -{ +{ Creature::setDeathState(s); if (getDeathState() == CORPSE) { @@ -346,7 +346,7 @@ void Pet::setDeathState(DeathState s, bool /*despawn = false*/) SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE); RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); - //lose happiness when died and not in BG/Arena + //lose happiness when died and not in BG/Arena MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId()); if (!mapEntry || (mapEntry->map_type != MAP_ARENA && mapEntry->map_type != MAP_BATTLEGROUND)) ModifyPower(POWER_HAPPINESS, -HAPPINESS_LEVEL_SIZE); @@ -362,7 +362,7 @@ void Pet::setDeathState(DeathState s, bool /*despawn = false*/) } void Pet::Update(uint32 diff) -{ +{ if (m_removed) // pet already removed, just wait in remove queue, no updates return; @@ -372,181 +372,181 @@ void Pet::Update(uint32 diff) switch (m_deathState) { case CORPSE: - { - if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(nullptr)) { - Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER! - return; + if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(nullptr)) + { + Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER! + return; + } + break; } - break; - } case ALIVE: - { - // unsummon pet that lost owner - Player* owner = GetOwner(); - if (!owner || (!IsWithinDistInMap(owner, GetMap()->GetVisibilityRange()) && !isPossessed()) || (isControlled() && !owner->GetPetGUID())) - //if (!owner || (!IsWithinDistInMap(owner, GetMap()->GetVisibilityDistance()) && (owner->GetCharmGUID() && (owner->GetCharmGUID() != GetGUID()))) || (isControlled() && !owner->GetPetGUID())) { - Remove(PET_SAVE_NOT_IN_SLOT, true); - return; - } - - if (isControlled()) - { - if (owner->GetPetGUID() != GetGUID()) + // unsummon pet that lost owner + Player* owner = GetOwner(); + if (!owner || (!IsWithinDistInMap(owner, GetMap()->GetVisibilityRange()) && !isPossessed()) || (isControlled() && !owner->GetPetGUID())) + //if (!owner || (!IsWithinDistInMap(owner, GetMap()->GetVisibilityDistance()) && (owner->GetCharmGUID() && (owner->GetCharmGUID() != GetGUID()))) || (isControlled() && !owner->GetPetGUID())) { - sLog->outError("Pet %u is not pet of owner %s, removed", GetEntry(), m_owner->GetName().c_str()); - Remove(getPetType() == HUNTER_PET?PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT); + Remove(PET_SAVE_NOT_IN_SLOT, true); return; } - } - if (m_duration > 0) - { - if (uint32(m_duration) > diff) - m_duration -= diff; - else + if (isControlled()) { - Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED:PET_SAVE_NOT_IN_SLOT); - return; - } - } - - // xinef: m_regenTimer is decrased in Creature::Update() - // xinef: just check if we can update focus in current period - if (getPowerType() == POWER_FOCUS) - { - m_petRegenTimer -= diff; - if (m_petRegenTimer <= int32(0)) - { - m_petRegenTimer += PET_FOCUS_REGEN_INTERVAL; - Regenerate(POWER_FOCUS); - } - } - - if (m_tempspell != 0) - { - Unit* tempspellTarget = m_tempspellTarget; - Unit* tempoldTarget = m_tempoldTarget; - bool tempspellIsPositive = m_tempspellIsPositive; - uint32 tempspell = m_tempspell; - Unit* charmer = GetCharmerOrOwner(); - if (!charmer) - return; - - if (!GetCharmInfo()) - return; - - if (tempspellTarget && tempspellTarget->IsAlive()) - { - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(tempspell); - if (!spellInfo) - return; - float max_range = GetSpellMaxRangeForTarget(tempspellTarget, spellInfo); - if (spellInfo->RangeEntry->type == SPELL_RANGE_MELEE) - max_range -= 2*MIN_MELEE_REACH; - - if (IsWithinLOSInMap(tempspellTarget) && GetDistance(tempspellTarget) < max_range) + if (owner->GetPetGUID() != GetGUID()) { - if (!GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(spellInfo) && !HasSpellCooldown(tempspell)) + sLog->outError("Pet %u is not pet of owner %s, removed", GetEntry(), m_owner->GetName().c_str()); + Remove(getPetType() == HUNTER_PET ? PET_SAVE_AS_DELETED : PET_SAVE_NOT_IN_SLOT); + return; + } + } + + if (m_duration > 0) + { + if (uint32(m_duration) > diff) + m_duration -= diff; + else + { + Remove(getPetType() != SUMMON_PET ? PET_SAVE_AS_DELETED : PET_SAVE_NOT_IN_SLOT); + return; + } + } + + // xinef: m_regenTimer is decrased in Creature::Update() + // xinef: just check if we can update focus in current period + if (getPowerType() == POWER_FOCUS) + { + m_petRegenTimer -= diff; + if (m_petRegenTimer <= int32(0)) + { + m_petRegenTimer += PET_FOCUS_REGEN_INTERVAL; + Regenerate(POWER_FOCUS); + } + } + + if (m_tempspell != 0) + { + Unit* tempspellTarget = m_tempspellTarget; + Unit* tempoldTarget = m_tempoldTarget; + bool tempspellIsPositive = m_tempspellIsPositive; + uint32 tempspell = m_tempspell; + Unit* charmer = GetCharmerOrOwner(); + if (!charmer) + return; + + if (!GetCharmInfo()) + return; + + if (tempspellTarget && tempspellTarget->IsAlive()) + { + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(tempspell); + if (!spellInfo) + return; + float max_range = GetSpellMaxRangeForTarget(tempspellTarget, spellInfo); + if (spellInfo->RangeEntry->type == SPELL_RANGE_MELEE) + max_range -= 2 * MIN_MELEE_REACH; + + if (IsWithinLOSInMap(tempspellTarget) && GetDistance(tempspellTarget) < max_range) + { + if (!GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(spellInfo) && !HasSpellCooldown(tempspell)) + { + StopMoving(); + GetMotionMaster()->Clear(false); + GetMotionMaster()->MoveIdle(); + + GetCharmInfo()->SetIsCommandAttack(false); + GetCharmInfo()->SetIsAtStay(true); + GetCharmInfo()->SetIsCommandFollow(false); + GetCharmInfo()->SetIsFollowing(false); + GetCharmInfo()->SetIsReturning(false); + GetCharmInfo()->SaveStayPosition(true); + + CastSpell(tempspellTarget, tempspell, true); + m_tempspell = 0; + m_tempspellTarget = nullptr; + + if (tempspellIsPositive) + { + if (tempoldTarget && tempoldTarget->IsAlive()) + { + GetCharmInfo()->SetIsCommandAttack(true); + GetCharmInfo()->SetIsAtStay(false); + GetCharmInfo()->SetIsFollowing(false); + GetCharmInfo()->SetIsCommandFollow(false); + GetCharmInfo()->SetIsReturning(false); + + if (ToCreature() && ToCreature()->IsAIEnabled) + ToCreature()->AI()->AttackStart(tempoldTarget); + } + else + { + GetCharmInfo()->SetCommandState(COMMAND_FOLLOW); + GetCharmInfo()->SetIsCommandAttack(false); + GetCharmInfo()->SetIsAtStay(false); + GetCharmInfo()->SetIsReturning(true); + GetCharmInfo()->SetIsCommandFollow(true); + GetCharmInfo()->SetIsFollowing(false); + GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, GetFollowAngle()); + } + + m_tempoldTarget = nullptr; + m_tempspellIsPositive = false; + } + } + } + } + else + { + m_tempspell = 0; + m_tempspellTarget = nullptr; + m_tempoldTarget = nullptr; + m_tempspellIsPositive = false; + + Unit* victim = charmer->GetVictim(); + if (victim && victim->IsAlive()) { StopMoving(); GetMotionMaster()->Clear(false); GetMotionMaster()->MoveIdle(); - GetCharmInfo()->SetIsCommandAttack(false); - GetCharmInfo()->SetIsAtStay(true); - GetCharmInfo()->SetIsCommandFollow(false); + GetCharmInfo()->SetIsCommandAttack(true); + GetCharmInfo()->SetIsAtStay(false); GetCharmInfo()->SetIsFollowing(false); + GetCharmInfo()->SetIsCommandFollow(false); GetCharmInfo()->SetIsReturning(false); - GetCharmInfo()->SaveStayPosition(true); - CastSpell(tempspellTarget, tempspell, true); - m_tempspell = 0; - m_tempspellTarget = nullptr; + if (ToCreature() && ToCreature()->IsAIEnabled) + ToCreature()->AI()->AttackStart(victim); + } + else + { + StopMoving(); + GetMotionMaster()->Clear(false); + GetMotionMaster()->MoveIdle(); - if (tempspellIsPositive) - { - if (tempoldTarget && tempoldTarget->IsAlive()) - { - GetCharmInfo()->SetIsCommandAttack(true); - GetCharmInfo()->SetIsAtStay(false); - GetCharmInfo()->SetIsFollowing(false); - GetCharmInfo()->SetIsCommandFollow(false); - GetCharmInfo()->SetIsReturning(false); - - if (ToCreature() && ToCreature()->IsAIEnabled) - ToCreature()->AI()->AttackStart(tempoldTarget); - } - else - { - GetCharmInfo()->SetCommandState(COMMAND_FOLLOW); - GetCharmInfo()->SetIsCommandAttack(false); - GetCharmInfo()->SetIsAtStay(false); - GetCharmInfo()->SetIsReturning(true); - GetCharmInfo()->SetIsCommandFollow(true); - GetCharmInfo()->SetIsFollowing(false); - GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, GetFollowAngle()); - } - - m_tempoldTarget = nullptr; - m_tempspellIsPositive = false; - } + GetCharmInfo()->SetCommandState(COMMAND_FOLLOW); + GetCharmInfo()->SetIsCommandAttack(false); + GetCharmInfo()->SetIsAtStay(false); + GetCharmInfo()->SetIsReturning(true); + GetCharmInfo()->SetIsCommandFollow(true); + GetCharmInfo()->SetIsFollowing(false); + GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, GetFollowAngle()); } } } - else + + if (getPetType() == HUNTER_PET) { - m_tempspell = 0; - m_tempspellTarget = nullptr; - m_tempoldTarget = nullptr; - m_tempspellIsPositive = false; - - Unit* victim = charmer->GetVictim(); - if (victim && victim->IsAlive()) + m_happinessTimer -= diff; + if (m_happinessTimer <= int32(0)) { - StopMoving(); - GetMotionMaster()->Clear(false); - GetMotionMaster()->MoveIdle(); - - GetCharmInfo()->SetIsCommandAttack(true); - GetCharmInfo()->SetIsAtStay(false); - GetCharmInfo()->SetIsFollowing(false); - GetCharmInfo()->SetIsCommandFollow(false); - GetCharmInfo()->SetIsReturning(false); - - if (ToCreature() && ToCreature()->IsAIEnabled) - ToCreature()->AI()->AttackStart(victim); - } - else - { - StopMoving(); - GetMotionMaster()->Clear(false); - GetMotionMaster()->MoveIdle(); - - GetCharmInfo()->SetCommandState(COMMAND_FOLLOW); - GetCharmInfo()->SetIsCommandAttack(false); - GetCharmInfo()->SetIsAtStay(false); - GetCharmInfo()->SetIsReturning(true); - GetCharmInfo()->SetIsCommandFollow(true); - GetCharmInfo()->SetIsFollowing(false); - GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, GetFollowAngle()); + LoseHappiness(); + m_happinessTimer += PET_LOSE_HAPPINES_INTERVAL; } } - } - if (getPetType() == HUNTER_PET) - { - m_happinessTimer -= diff; - if (m_happinessTimer <= int32(0)) - { - LoseHappiness(); - m_happinessTimer += PET_LOSE_HAPPINES_INTERVAL; - } + break; } - - break; - } default: break; } @@ -555,7 +555,7 @@ void Pet::Update(uint32 diff) } void Pet::LoseHappiness() -{ +{ uint32 curValue = GetPower(POWER_HAPPINESS); if (curValue <= 0) return; @@ -566,7 +566,7 @@ void Pet::LoseHappiness() } HappinessState Pet::GetHappinessState() -{ +{ if (GetPower(POWER_HAPPINESS) < HAPPINESS_LEVEL_SIZE) return UNHAPPY; else if (GetPower(POWER_HAPPINESS) >= HAPPINESS_LEVEL_SIZE * 2) @@ -576,12 +576,12 @@ HappinessState Pet::GetHappinessState() } void Pet::Remove(PetSaveMode mode, bool returnreagent) -{ +{ m_owner->RemovePet(this, mode, returnreagent); } void Pet::GivePetXP(uint32 xp) -{ +{ if (getPetType() != HUNTER_PET) return; @@ -596,7 +596,7 @@ void Pet::GivePetXP(uint32 xp) // If pet is detected to be at, or above(?) the players level, don't hand out XP if (petlevel >= maxlevel) - return; + return; uint32 nextLvlXP = GetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP); uint32 curXP = GetUInt32Value(UNIT_FIELD_PETEXPERIENCE); @@ -618,11 +618,11 @@ void Pet::GivePetXP(uint32 xp) } void Pet::GivePetLevel(uint8 level) -{ +{ if (!level || level == getLevel()) return; - if (getPetType()==HUNTER_PET) + if (getPetType() == HUNTER_PET) { SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32(sObjectMgr->GetXPForLevel(level)*PET_XP_FACTOR)); @@ -634,7 +634,7 @@ void Pet::GivePetLevel(uint8 level) } bool Pet::CreateBaseAtCreature(Creature* creature) -{ +{ ASSERT(creature); if (!CreateBaseAtTamed(creature->GetCreatureTemplate(), creature->GetMap(), creature->GetPhaseMask())) @@ -645,7 +645,7 @@ bool Pet::CreateBaseAtCreature(Creature* creature) if (!IsPositionValid()) { sLog->outError("Pet (guidlow %d, entry %d) not created base at creature. Suggested coordinates isn't valid (X: %f Y: %f)", - GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY()); + GetGUIDLow(), GetEntry(), GetPositionX(), GetPositionY()); return false; } @@ -667,7 +667,7 @@ bool Pet::CreateBaseAtCreature(Creature* creature) } bool Pet::CreateBaseAtCreatureInfo(CreatureTemplate const* cinfo, Unit* owner) -{ +{ if (!CreateBaseAtTamed(cinfo, owner->GetMap(), owner->GetPhaseMask())) return false; @@ -680,11 +680,11 @@ bool Pet::CreateBaseAtCreatureInfo(CreatureTemplate const* cinfo, Unit* owner) } bool Pet::CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phaseMask) -{ +{ #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PETS, "Pet::CreateBaseForTamed"); #endif - uint32 guid=sObjectMgr->GenerateLowGuid(HIGHGUID_PET); + uint32 guid = sObjectMgr->GenerateLowGuid(HIGHGUID_PET); uint32 pet_number = sObjectMgr->GeneratePetNumber(); if (!Create(guid, map, phaseMask, cinfo->Entry, pet_number)) return false; @@ -694,7 +694,7 @@ bool Pet::CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phas setPowerType(POWER_FOCUS); SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, 0); SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); - SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32(sObjectMgr->GetXPForLevel(getLevel()+1)*PET_XP_FACTOR)); + SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32(sObjectMgr->GetXPForLevel(getLevel() + 1)*PET_XP_FACTOR)); SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); if (cinfo->type == CREATURE_TYPE_BEAST) @@ -709,14 +709,14 @@ bool Pet::CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phas // TODO: Move stat mods code to pet passive auras bool Guardian::InitStatsForLevel(uint8 petlevel) -{ +{ CreatureTemplate const* cinfo = GetCreatureTemplate(); ASSERT(cinfo); SetLevel(petlevel); SetCanModifyStats(true); - Unit *owner = GetOwner(); + Unit* owner = GetOwner(); if (!owner) // just to be sure, asynchronous now { DespawnOrUnsummon(1000); @@ -735,9 +735,9 @@ bool Guardian::InitStatsForLevel(uint8 petlevel) { // The petType was not overwritten by the hook, continue with default initialization if (owner->getClass() == CLASS_WARLOCK || - owner->getClass() == CLASS_SHAMAN || // Fire Elemental - owner->getClass() == CLASS_DEATH_KNIGHT || // Risen Ghoul - owner->getClass() == CLASS_MAGE) // Water Elemental with glyph + owner->getClass() == CLASS_SHAMAN || // Fire Elemental + owner->getClass() == CLASS_DEATH_KNIGHT || // Risen Ghoul + owner->getClass() == CLASS_MAGE) // Water Elemental with glyph petType = SUMMON_PET; else if (owner->getClass() == CLASS_HUNTER) { @@ -756,7 +756,7 @@ bool Guardian::InitStatsForLevel(uint8 petlevel) SetMeleeDamageSchool(SpellSchools(cinfo->dmgschool)); - SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel*50)); + SetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE, float(petlevel * 50)); uint32 attackTime = BASE_ATTACK_TIME; if (owner->getClass() != CLASS_HUNTER && cinfo->BaseAttackTime >= 1000) @@ -817,239 +817,239 @@ bool Guardian::InitStatsForLevel(uint8 petlevel) SetCreateHealth(std::max(1, stats->BaseHealth[cinfo->expansion]*factorHealth)); SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, GetCreateHealth()); - SetCreateMana(stats->BaseMana*factorMana); + SetCreateMana(stats->BaseMana * factorMana); SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, GetCreateMana()); // xinef: added some multipliers so debuffs can affect pets in any way... - SetCreateStat(STAT_STRENGTH, 22 + 2*petlevel); - SetCreateStat(STAT_AGILITY, 22 + 1.5f*petlevel); - SetCreateStat(STAT_STAMINA, 25 + 2*petlevel); - SetCreateStat(STAT_INTELLECT, 28 + 2*petlevel); - SetCreateStat(STAT_SPIRIT, 27 + 1.5f*petlevel); + SetCreateStat(STAT_STRENGTH, 22 + 2 * petlevel); + SetCreateStat(STAT_AGILITY, 22 + 1.5f * petlevel); + SetCreateStat(STAT_STAMINA, 25 + 2 * petlevel); + SetCreateStat(STAT_INTELLECT, 28 + 2 * petlevel); + SetCreateStat(STAT_SPIRIT, 27 + 1.5f * petlevel); } switch (petType) { case HUNTER_PET: - { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4))); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4))); - SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32(sObjectMgr->GetXPForLevel(petlevel)*PET_XP_FACTOR)); - break; - } - case SUMMON_PET: - { - - if (pInfo) - { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(pInfo->min_dmg)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(pInfo->max_dmg)); - } - else { SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4))); SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4))); + SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32(sObjectMgr->GetXPForLevel(petlevel)*PET_XP_FACTOR)); + break; } - - switch(GetEntry()) + case SUMMON_PET: { - case NPC_FELGUARD: - { - // xinef: Glyph of Felguard, so ugly im crying... no appropriate spell - if (AuraEffect* aurEff = owner->GetAuraEffectDummy(SPELL_GLYPH_OF_FELGUARD)) - SetModifierValue(UNIT_MOD_ATTACK_POWER, TOTAL_PCT, 1.0f + float(aurEff->GetAmount() / 100.0f)); - break; - } - case NPC_WATER_ELEMENTAL_PERM: + if (pInfo) { - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_MAGE_PET_SCALING_01, this); - AddAura(SPELL_MAGE_PET_SCALING_02, this); - AddAura(SPELL_MAGE_PET_SCALING_03, this); - AddAura(SPELL_MAGE_PET_SCALING_04, this); - ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, true); - break; + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(pInfo->min_dmg)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(pInfo->max_dmg)); } - } - break; - } - default: - { - switch (GetEntry()) - { - case NPC_FIRE_ELEMENTAL: + else { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 3.5f - petlevel)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 3.5f + petlevel)); - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_FIRE_ELEMENTAL_SCALING_01, this); - AddAura(SPELL_FIRE_ELEMENTAL_SCALING_02, this); - AddAura(SPELL_FIRE_ELEMENTAL_SCALING_03, this); - AddAura(SPELL_FIRE_ELEMENTAL_SCALING_04, this); - break; - } - case NPC_EARTH_ELEMENTAL: - { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 2.0f - petlevel)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 2.0f + petlevel)); - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_EARTH_ELEMENTAL_SCALING_01, this); - AddAura(SPELL_EARTH_ELEMENTAL_SCALING_02, this); - AddAura(SPELL_EARTH_ELEMENTAL_SCALING_03, this); - AddAura(SPELL_EARTH_ELEMENTAL_SCALING_04, this); - break; - } - case NPC_INFERNAL: - { - float highAmt = petlevel / 11.0f; - float lowAmt = petlevel / 12.0f; - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, lowAmt*lowAmt*lowAmt); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, highAmt*highAmt*highAmt); - - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_WARLOCK_PET_SCALING_05, this); - AddAura(SPELL_INFERNAL_SCALING_01, this); - AddAura(SPELL_INFERNAL_SCALING_02, this); - AddAura(SPELL_INFERNAL_SCALING_03, this); - AddAura(SPELL_INFERNAL_SCALING_04, this); - break; - } - case NPC_DOOMGUARD: - { - float highAmt = petlevel / 11.0f; - float lowAmt = petlevel / 12.0f; - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, lowAmt*lowAmt*lowAmt); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, highAmt*highAmt*highAmt); - - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_WARLOCK_PET_SCALING_01, this); - AddAura(SPELL_WARLOCK_PET_SCALING_02, this); - AddAura(SPELL_WARLOCK_PET_SCALING_03, this); - AddAura(SPELL_WARLOCK_PET_SCALING_04, this); - AddAura(SPELL_WARLOCK_PET_SCALING_05, this); - break; - } - case NPC_WATER_ELEMENTAL_TEMP: - { - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_MAGE_PET_SCALING_01, this); - AddAura(SPELL_MAGE_PET_SCALING_02, this); - AddAura(SPELL_MAGE_PET_SCALING_03, this); - AddAura(SPELL_MAGE_PET_SCALING_04, this); - ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, true); - break; - } - case NPC_TREANT: //force of nature - { - if (!pInfo) - SetCreateHealth(30 + 30*petlevel); - - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 2.5f - petlevel)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 2.5f + petlevel)); - - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_TREANT_SCALING_01, this); - AddAura(SPELL_TREANT_SCALING_02, this); - AddAura(SPELL_TREANT_SCALING_03, this); - AddAura(SPELL_TREANT_SCALING_04, this); - break; - } - case NPC_SHADOWFIEND: - { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 2.5f - petlevel)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 2.5f + petlevel)); - - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_SHADOWFIEND_SCALING_01, this); - AddAura(SPELL_SHADOWFIEND_SCALING_02, this); - AddAura(SPELL_SHADOWFIEND_SCALING_03, this); - AddAura(SPELL_SHADOWFIEND_SCALING_04, this); - break; - } - case NPC_FERAL_SPIRIT: - { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 4.0f - petlevel)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 4.0f + petlevel)); - - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_FERAL_SPIRIT_SPIRIT_HUNT, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_FERAL_SPIRIT_SCALING_01, this); - AddAura(SPELL_FERAL_SPIRIT_SCALING_02, this); - AddAura(SPELL_FERAL_SPIRIT_SCALING_03, this); - break; - } - case NPC_MIRROR_IMAGE: // Mirror Image - { - SetDisplayId(owner->GetDisplayId()); - if (!pInfo) - { - SetCreateMana(28 + 30*petlevel); - SetCreateHealth(28 + 10*petlevel); - } - - AddAura(SPELL_PET_AVOIDANCE, this); - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_MAGE_PET_SCALING_01, this); - AddAura(SPELL_MAGE_PET_SCALING_02, this); - AddAura(SPELL_MAGE_PET_SCALING_03, this); - AddAura(SPELL_MAGE_PET_SCALING_04, this); - break; - } - case NPC_EBON_GARGOYLE: // Ebon Gargoyle - { - if (!pInfo) - { - SetCreateMana(28 + 10*petlevel); - SetCreateHealth(28 + 30*petlevel); - } - - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_DK_PET_SCALING_01, this); - AddAura(SPELL_DK_PET_SCALING_02, this); - AddAura(SPELL_DK_PET_SCALING_03, this); - break; - } - case NPC_BLOODWORM: - { - // Xinef: Hit / Expertise scaling - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_PET_AVOIDANCE, this); - SetCreateHealth(4 * petlevel); - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - 30 - (petlevel / 4) + owner->GetTotalAttackPowerValue(BASE_ATTACK) * 0.006f)); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel - 30 + (petlevel / 4) + owner->GetTotalAttackPowerValue(BASE_ATTACK) * 0.006f)); - SetReactState(REACT_DEFENSIVE); - break; - } - case NPC_ARMY_OF_THE_DEAD: - { - AddAura(SPELL_HUNTER_PET_SCALING_04, this); - AddAura(SPELL_DK_PET_SCALING_01, this); - AddAura(SPELL_DK_PET_SCALING_02, this); - AddAura(SPELL_DK_PET_SCALING_03, this); - AddAura(SPELL_PET_AVOIDANCE, this); - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4))); SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4))); - break; } - case NPC_GENERIC_IMP: - case NPC_GENERIC_VOIDWALKER: - { - SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4))); - SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4))); - break; + + switch(GetEntry()) + { + case NPC_FELGUARD: + { + // xinef: Glyph of Felguard, so ugly im crying... no appropriate spell + if (AuraEffect* aurEff = owner->GetAuraEffectDummy(SPELL_GLYPH_OF_FELGUARD)) + SetModifierValue(UNIT_MOD_ATTACK_POWER, TOTAL_PCT, 1.0f + float(aurEff->GetAmount() / 100.0f)); + + break; + } + case NPC_WATER_ELEMENTAL_PERM: + { + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_MAGE_PET_SCALING_01, this); + AddAura(SPELL_MAGE_PET_SCALING_02, this); + AddAura(SPELL_MAGE_PET_SCALING_03, this); + AddAura(SPELL_MAGE_PET_SCALING_04, this); + ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, true); + break; + } } + break; + } + default: + { + switch (GetEntry()) + { + case NPC_FIRE_ELEMENTAL: + { + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 3.5f - petlevel)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 3.5f + petlevel)); + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_FIRE_ELEMENTAL_SCALING_01, this); + AddAura(SPELL_FIRE_ELEMENTAL_SCALING_02, this); + AddAura(SPELL_FIRE_ELEMENTAL_SCALING_03, this); + AddAura(SPELL_FIRE_ELEMENTAL_SCALING_04, this); + break; + } + case NPC_EARTH_ELEMENTAL: + { + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 2.0f - petlevel)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 2.0f + petlevel)); + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_EARTH_ELEMENTAL_SCALING_01, this); + AddAura(SPELL_EARTH_ELEMENTAL_SCALING_02, this); + AddAura(SPELL_EARTH_ELEMENTAL_SCALING_03, this); + AddAura(SPELL_EARTH_ELEMENTAL_SCALING_04, this); + break; + } + case NPC_INFERNAL: + { + float highAmt = petlevel / 11.0f; + float lowAmt = petlevel / 12.0f; + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, lowAmt * lowAmt * lowAmt); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, highAmt * highAmt * highAmt); + + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_WARLOCK_PET_SCALING_05, this); + AddAura(SPELL_INFERNAL_SCALING_01, this); + AddAura(SPELL_INFERNAL_SCALING_02, this); + AddAura(SPELL_INFERNAL_SCALING_03, this); + AddAura(SPELL_INFERNAL_SCALING_04, this); + break; + } + case NPC_DOOMGUARD: + { + float highAmt = petlevel / 11.0f; + float lowAmt = petlevel / 12.0f; + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, lowAmt * lowAmt * lowAmt); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, highAmt * highAmt * highAmt); + + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_WARLOCK_PET_SCALING_01, this); + AddAura(SPELL_WARLOCK_PET_SCALING_02, this); + AddAura(SPELL_WARLOCK_PET_SCALING_03, this); + AddAura(SPELL_WARLOCK_PET_SCALING_04, this); + AddAura(SPELL_WARLOCK_PET_SCALING_05, this); + break; + } + case NPC_WATER_ELEMENTAL_TEMP: + { + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_MAGE_PET_SCALING_01, this); + AddAura(SPELL_MAGE_PET_SCALING_02, this); + AddAura(SPELL_MAGE_PET_SCALING_03, this); + AddAura(SPELL_MAGE_PET_SCALING_04, this); + ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FROST, true); + break; + } + case NPC_TREANT: //force of nature + { + if (!pInfo) + SetCreateHealth(30 + 30 * petlevel); + + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 2.5f - petlevel)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 2.5f + petlevel)); + + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_TREANT_SCALING_01, this); + AddAura(SPELL_TREANT_SCALING_02, this); + AddAura(SPELL_TREANT_SCALING_03, this); + AddAura(SPELL_TREANT_SCALING_04, this); + break; + } + case NPC_SHADOWFIEND: + { + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 2.5f - petlevel)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 2.5f + petlevel)); + + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_SHADOWFIEND_SCALING_01, this); + AddAura(SPELL_SHADOWFIEND_SCALING_02, this); + AddAura(SPELL_SHADOWFIEND_SCALING_03, this); + AddAura(SPELL_SHADOWFIEND_SCALING_04, this); + break; + } + case NPC_FERAL_SPIRIT: + { + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel * 4.0f - petlevel)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel * 4.0f + petlevel)); + + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_FERAL_SPIRIT_SPIRIT_HUNT, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_FERAL_SPIRIT_SCALING_01, this); + AddAura(SPELL_FERAL_SPIRIT_SCALING_02, this); + AddAura(SPELL_FERAL_SPIRIT_SCALING_03, this); + break; + } + case NPC_MIRROR_IMAGE: // Mirror Image + { + SetDisplayId(owner->GetDisplayId()); + if (!pInfo) + { + SetCreateMana(28 + 30 * petlevel); + SetCreateHealth(28 + 10 * petlevel); + } + + AddAura(SPELL_PET_AVOIDANCE, this); + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_MAGE_PET_SCALING_01, this); + AddAura(SPELL_MAGE_PET_SCALING_02, this); + AddAura(SPELL_MAGE_PET_SCALING_03, this); + AddAura(SPELL_MAGE_PET_SCALING_04, this); + break; + } + case NPC_EBON_GARGOYLE: // Ebon Gargoyle + { + if (!pInfo) + { + SetCreateMana(28 + 10 * petlevel); + SetCreateHealth(28 + 30 * petlevel); + } + + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_DK_PET_SCALING_01, this); + AddAura(SPELL_DK_PET_SCALING_02, this); + AddAura(SPELL_DK_PET_SCALING_03, this); + break; + } + case NPC_BLOODWORM: + { + // Xinef: Hit / Expertise scaling + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_PET_AVOIDANCE, this); + SetCreateHealth(4 * petlevel); + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - 30 - (petlevel / 4) + owner->GetTotalAttackPowerValue(BASE_ATTACK) * 0.006f)); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel - 30 + (petlevel / 4) + owner->GetTotalAttackPowerValue(BASE_ATTACK) * 0.006f)); + SetReactState(REACT_DEFENSIVE); + break; + } + case NPC_ARMY_OF_THE_DEAD: + { + AddAura(SPELL_HUNTER_PET_SCALING_04, this); + AddAura(SPELL_DK_PET_SCALING_01, this); + AddAura(SPELL_DK_PET_SCALING_02, this); + AddAura(SPELL_DK_PET_SCALING_03, this); + AddAura(SPELL_PET_AVOIDANCE, this); + + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4))); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4))); + break; + } + case NPC_GENERIC_IMP: + case NPC_GENERIC_VOIDWALKER: + { + SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, float(petlevel - (petlevel / 4))); + SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, float(petlevel + (petlevel / 4))); + break; + } + } + break; } - break; - } } // Can be summon and guardian @@ -1063,8 +1063,8 @@ bool Guardian::InitStatsForLevel(uint8 petlevel) CastSpell(this, SPELL_ORC_RACIAL_COMMAND, true, nullptr, nullptr, owner->GetGUID()); // Avoidance, Night of the Dead - if (Aura *aur = AddAura(SPELL_NIGHT_OF_THE_DEAD_AVOIDANCE, this)) - if (AuraEffect *aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, 2718, 0)) + if (Aura* aur = AddAura(SPELL_NIGHT_OF_THE_DEAD_AVOIDANCE, this)) + if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, 2718, 0)) if (aur->GetEffect(0)) aur->GetEffect(0)->SetAmount(-aurEff->GetSpellInfo()->Effects[EFFECT_2].CalcValue()); @@ -1089,7 +1089,7 @@ bool Guardian::InitStatsForLevel(uint8 petlevel) } bool Pet::HaveInDiet(ItemTemplate const* item) const -{ +{ if (!item->FoodType) return false; @@ -1102,12 +1102,12 @@ bool Pet::HaveInDiet(ItemTemplate const* item) const return false; uint32 diet = cFamily->petFoodMask; - uint32 FoodMask = 1 << (item->FoodType-1); + uint32 FoodMask = 1 << (item->FoodType - 1); return diet & FoodMask; } uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel) const -{ +{ // -5 or greater food level if (getLevel() <= itemlevel + 5) //possible to feed level 60 pet with level 55 level food for full effect return 35000; @@ -1123,7 +1123,7 @@ uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel) const } void Pet::_LoadSpellCooldowns(PreparedQueryResult result) -{ +{ m_CreatureSpellCooldowns.clear(); if (result) @@ -1150,15 +1150,14 @@ void Pet::_LoadSpellCooldowns(PreparedQueryResult result) if (db_time <= curTime) continue; - uint32 cooldown = (db_time-curTime)*IN_MILLISECONDS; + uint32 cooldown = (db_time - curTime) * IN_MILLISECONDS; cooldowns[spell_id] = cooldown; _AddCreatureSpellCooldown(spell_id, cooldown); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PETS, "Pet (Number: %u) spell %u cooldown loaded (%u secs).", m_charmInfo->GetPetNumber(), spell_id, uint32(db_time-curTime)); + sLog->outDebug(LOG_FILTER_PETS, "Pet (Number: %u) spell %u cooldown loaded (%u secs).", m_charmInfo->GetPetNumber(), spell_id, uint32(db_time - curTime)); #endif - } - while (result->NextRow()); + } while (result->NextRow()); if (!cooldowns.empty() && GetOwner()) { @@ -1169,13 +1168,13 @@ void Pet::_LoadSpellCooldowns(PreparedQueryResult result) } void Pet::_SaveSpellCooldowns(SQLTransaction& trans, bool logout) -{ +{ PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PET_SPELL_COOLDOWNS); stmt->setUInt32(0, m_charmInfo->GetPetNumber()); trans->Append(stmt); time_t curTime = time(nullptr); - uint32 checkTime = World::GetGameTimeMS() + 30*IN_MILLISECONDS; + uint32 checkTime = World::GetGameTimeMS() + 30 * IN_MILLISECONDS; // remove oudated and save active CreatureSpellCooldowns::iterator itr, itr2; @@ -1183,11 +1182,11 @@ void Pet::_SaveSpellCooldowns(SQLTransaction& trans, bool logout) { itr2 = itr; ++itr; - if (itr2->second <= World::GetGameTimeMS()+1000) + if (itr2->second <= World::GetGameTimeMS() + 1000) m_CreatureSpellCooldowns.erase(itr2); else if (logout || itr2->second > checkTime) { - uint32 cooldown = ((itr2->second-World::GetGameTimeMS())/IN_MILLISECONDS) + curTime; + uint32 cooldown = ((itr2->second - World::GetGameTimeMS()) / IN_MILLISECONDS) + curTime; stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PET_SPELL_COOLDOWN); stmt->setUInt32(0, m_charmInfo->GetPetNumber()); stmt->setUInt32(1, itr2->first); @@ -1199,7 +1198,7 @@ void Pet::_SaveSpellCooldowns(SQLTransaction& trans, bool logout) } void Pet::_LoadSpells(PreparedQueryResult result) -{ +{ if (result) { do @@ -1207,13 +1206,12 @@ void Pet::_LoadSpells(PreparedQueryResult result) Field* fields = result->Fetch(); addSpell(fields[0].GetUInt32(), ActiveStates(fields[1].GetUInt8()), PETSPELL_UNCHANGED); - } - while (result->NextRow()); + } while (result->NextRow()); } } void Pet::_SaveSpells(SQLTransaction& trans) -{ +{ for (PetSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next) { ++next; @@ -1262,7 +1260,7 @@ void Pet::_SaveSpells(SQLTransaction& trans) } void Pet::_LoadAuras(PreparedQueryResult result, uint32 timediff) -{ +{ #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PETS, "Loading auras for pet %u", GetGUIDLow()); #endif @@ -1311,10 +1309,10 @@ void Pet::_LoadAuras(PreparedQueryResult result, uint32 timediff) // negative effects should continue counting down after logout if (remaintime != -1 && !spellInfo->IsPositive()) { - if (remaintime/IN_MILLISECONDS <= int32(timediff)) + if (remaintime / IN_MILLISECONDS <= int32(timediff)) continue; - remaintime -= timediff*IN_MILLISECONDS; + remaintime -= timediff * IN_MILLISECONDS; } // prevent wrong values of remaincharges @@ -1339,13 +1337,12 @@ void Pet::_LoadAuras(PreparedQueryResult result, uint32 timediff) sLog->outDetail("Added aura spellid %u, effectmask %u", spellInfo->Id, effmask); #endif } - } - while (result->NextRow()); + } while (result->NextRow()); } } void Pet::_SaveAuras(SQLTransaction& trans, bool logout) -{ +{ PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PET_AURAS); stmt->setUInt32(0, m_charmInfo->GetPetNumber()); trans->Append(stmt); @@ -1357,7 +1354,7 @@ void Pet::_SaveAuras(SQLTransaction& trans, bool logout) continue; Aura* aura = itr->second; - if (!logout && aura->GetDuration() < 60*IN_MILLISECONDS) + if (!logout && aura->GetDuration() < 60 * IN_MILLISECONDS) continue; // dont save infinite negative auras! (lavas, transformations etc) @@ -1390,9 +1387,9 @@ void Pet::_SaveAuras(SQLTransaction& trans, bool logout) { baseDamage[i] = aura->GetEffect(i)->GetBaseAmount(); damage[i] = aura->GetEffect(i)->GetAmount(); - effMask |= (1<GetEffect(i)->CanBeRecalculated()) - recalculateMask |= (1<GetSpellInfo(spellId); if (!spellInfo) { @@ -1547,8 +1544,8 @@ bool Pet::addSpell(uint32 spellId, ActiveStates active /*= ACT_DECIDE*/, PetSpel if (Aura* aura = GetAura(spellId)) { if (aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTHLESS_35_PERCENT || - aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTH_ABOVE_75_PERCENT || - aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTHLESS_20_PERCENT ) + aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTH_ABOVE_75_PERCENT || + aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTHLESS_20_PERCENT ) if (!HasAuraState((AuraStateType)aura->GetSpellInfo()->CasterAuraState)) aura->HandleAllEffects(aura->GetApplicationOfTarget(GetGUID()), AURA_EFFECT_HANDLE_REAL, false); } @@ -1561,14 +1558,14 @@ bool Pet::addSpell(uint32 spellId, ActiveStates active /*= ACT_DECIDE*/, PetSpel int32 free_points = GetMaxTalentPointsForLevel(getLevel()); m_usedTalentCount += talentCost; // update free talent points - free_points-=m_usedTalentCount; + free_points -= m_usedTalentCount; SetFreeTalentPoints(free_points > 0 ? free_points : 0); } return true; } bool Pet::learnSpell(uint32 spell_id) -{ +{ // prevent duplicated entires in spell book if (!addSpell(spell_id)) return false; @@ -1584,7 +1581,7 @@ bool Pet::learnSpell(uint32 spell_id) } void Pet::InitLevelupSpellsForLevel() -{ +{ uint8 level = getLevel(); if (PetLevelupSpellSet const* levelupSpells = GetCreatureTemplate()->family ? sSpellMgr->GetPetLevelupSpellList(GetCreatureTemplate()->family) : nullptr) @@ -1623,7 +1620,7 @@ void Pet::InitLevelupSpellsForLevel() } bool Pet::unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab) -{ +{ if (removeSpell(spell_id, learn_prev, clear_ab)) { if (!m_loading) @@ -1638,7 +1635,7 @@ bool Pet::unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab) } bool Pet::removeSpell(uint32 spell_id, bool learn_prev, bool clear_ab) -{ +{ PetSpellMap::iterator itr = m_spells.find(spell_id); if (itr == m_spells.end()) return false; @@ -1689,7 +1686,7 @@ bool Pet::removeSpell(uint32 spell_id, bool learn_prev, bool clear_ab) } void Pet::CleanupActionBar() -{ +{ for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) if (UnitActionBarEntry const* ab = m_charmInfo->GetActionBarEntry(i)) if (ab->GetAction() && ab->IsActionBarForSpell()) @@ -1702,7 +1699,7 @@ void Pet::CleanupActionBar() } void Pet::InitPetCreateSpells() -{ +{ m_charmInfo->InitPetActionBar(); m_spells.clear(); @@ -1713,7 +1710,7 @@ void Pet::InitPetCreateSpells() } bool Pet::resetTalents() -{ +{ Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return false; @@ -1857,8 +1854,7 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= NULL*/) ss << spell; need_execute = true; - } - while (result->NextRow()); + } while (result->NextRow()); if (!need_execute) return; @@ -1869,7 +1865,7 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= NULL*/) } void Pet::InitTalentForLevel() -{ +{ uint8 level = getLevel(); uint32 talentPointsForLevel = GetMaxTalentPointsForLevel(level); // Reset talents in case low level (on level down) or wrong points for level (hunter can unlearn TP increase talent) @@ -1887,16 +1883,16 @@ void Pet::InitTalentForLevel() } uint8 Pet::GetMaxTalentPointsForLevel(uint8 level) -{ +{ uint8 points = (level >= 20) ? ((level - 16) / 4) : 0; // Mod points from owner SPELL_AURA_MOD_PET_TALENT_POINTS if (Unit* owner = GetOwner()) - points+=owner->GetTotalAuraModifier(SPELL_AURA_MOD_PET_TALENT_POINTS); + points += owner->GetTotalAuraModifier(SPELL_AURA_MOD_PET_TALENT_POINTS); return points; } void Pet::ToggleAutocast(SpellInfo const* spellInfo, bool apply) -{ +{ if (!spellInfo->IsAutocastable()) return; @@ -1945,7 +1941,7 @@ void Pet::ToggleAutocast(SpellInfo const* spellInfo, bool apply) } bool Pet::IsPermanentPetFor(Player* owner) const -{ +{ switch (getPetType()) { case SUMMON_PET: @@ -1968,7 +1964,7 @@ bool Pet::IsPermanentPetFor(Player* owner) const } bool Pet::Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, uint32 pet_number) -{ +{ ASSERT(map); SetMap(map); @@ -1987,14 +1983,14 @@ bool Pet::Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, uint3 } bool Pet::HasSpell(uint32 spell) const -{ +{ PetSpellMap::const_iterator itr = m_spells.find(spell); return itr != m_spells.end() && itr->second.state != PETSPELL_REMOVED; } // Get all passive spells in our skill line void Pet::LearnPetPassives() -{ +{ CreatureTemplate const* cInfo = GetCreatureTemplate(); if (!cInfo) return; @@ -2015,7 +2011,7 @@ void Pet::LearnPetPassives() } void Pet::CastPetAuras(bool current) -{ +{ Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; @@ -2036,7 +2032,7 @@ void Pet::CastPetAuras(bool current) } void Pet::learnSpellHighRank(uint32 spellid) -{ +{ learnSpell(spellid); if (uint32 next = sSpellMgr->GetNextSpellInChain(spellid)) @@ -2044,7 +2040,7 @@ void Pet::learnSpellHighRank(uint32 spellid) } void Pet::SynchronizeLevelWithOwner() -{ +{ Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; @@ -2068,7 +2064,7 @@ void Pet::SynchronizeLevelWithOwner() } void Pet::HandleAsynchLoadSucceed() -{ +{ Player* owner = GetOwner(); if (!owner) return; @@ -2130,22 +2126,22 @@ void Pet::HandleAsynchLoadSucceed() // Fix aurastate auras, depending on health! // Set aurastate manualy, prevents aura switching if (HealthBelowPct(20)) - SetFlag(UNIT_FIELD_AURASTATE, 1<<(AURA_STATE_HEALTHLESS_20_PERCENT-1)); + SetFlag(UNIT_FIELD_AURASTATE, 1 << (AURA_STATE_HEALTHLESS_20_PERCENT - 1)); if (HealthBelowPct(35)) - SetFlag(UNIT_FIELD_AURASTATE, 1<<(AURA_STATE_HEALTHLESS_35_PERCENT-1)); + SetFlag(UNIT_FIELD_AURASTATE, 1 << (AURA_STATE_HEALTHLESS_35_PERCENT - 1)); if (HealthAbovePct(75)) - SetFlag(UNIT_FIELD_AURASTATE, 1<<(AURA_STATE_HEALTH_ABOVE_75_PERCENT-1)); - + SetFlag(UNIT_FIELD_AURASTATE, 1 << (AURA_STATE_HEALTH_ABOVE_75_PERCENT - 1)); + // unapply aura stats if dont meet requirements - AuraApplicationMap const& Auras = GetAppliedAuras(); + AuraApplicationMap const& Auras = GetAppliedAuras(); for (AuraApplicationMap::const_iterator itr = Auras.begin(); itr != Auras.end(); ++itr) { // we assume that all auras are applied now, aurastate was modfied MANUALY preventing any apply/unapply state switching Aura* aura = itr->second->GetBase(); SpellInfo const* m_spellInfo = aura->GetSpellInfo(); if (m_spellInfo->CasterAuraState != AURA_STATE_HEALTHLESS_20_PERCENT && - m_spellInfo->CasterAuraState != AURA_STATE_HEALTHLESS_35_PERCENT && - m_spellInfo->CasterAuraState != AURA_STATE_HEALTH_ABOVE_75_PERCENT) + m_spellInfo->CasterAuraState != AURA_STATE_HEALTHLESS_35_PERCENT && + m_spellInfo->CasterAuraState != AURA_STATE_HEALTH_ABOVE_75_PERCENT) continue; if (!HasAuraState((AuraStateType)m_spellInfo->CasterAuraState)) @@ -2272,7 +2268,7 @@ void Pet::HandleAsynchLoadFailed(AsynchPetSummon* info, Player* player, uint8 as pet->SetHealth(pet->GetMaxHealth()); // generate new name for summon pet - std::string new_name=sObjectMgr->GeneratePetName(info->m_entry); + std::string new_name = sObjectMgr->GeneratePetName(info->m_entry); if (!new_name.empty()) pet->SetName(new_name); } @@ -2292,7 +2288,7 @@ void Pet::HandleAsynchLoadFailed(AsynchPetSummon* info, Player* player, uint8 as } void Pet::SetDisplayId(uint32 modelId) -{ +{ Guardian::SetDisplayId(modelId); if (!isControlled()) @@ -2334,7 +2330,7 @@ void Pet::RemoveSpellCooldown(uint32 spell_id, bool update /* = false */) if (update) { - + if (Player* playerOwner = GetCharmerOrOwnerPlayerOrPlayerItself()) { WorldPacket data(SMSG_CLEAR_COOLDOWN, 4 + 8); diff --git a/src/server/game/Entities/Pet/Pet.h b/src/server/game/Entities/Pet/Pet.h index c09d0650e..d60d98036 100644 --- a/src/server/game/Entities/Pet/Pet.h +++ b/src/server/game/Entities/Pet/Pet.h @@ -24,16 +24,16 @@ struct PetSpell class AsynchPetSummon { - public: - AsynchPetSummon(uint32 entry, Position position, PetType petType, uint32 duration, uint32 createdBySpell, uint64 casterGUID) : - m_entry(entry), pos(position), m_petType(petType), - m_duration(duration), m_createdBySpell(createdBySpell), m_casterGUID(casterGUID) { } +public: + AsynchPetSummon(uint32 entry, Position position, PetType petType, uint32 duration, uint32 createdBySpell, uint64 casterGUID) : + m_entry(entry), pos(position), m_petType(petType), + m_duration(duration), m_createdBySpell(createdBySpell), m_casterGUID(casterGUID) { } - uint32 m_entry; - Position pos; - PetType m_petType; - uint32 m_duration, m_createdBySpell; - uint64 m_casterGUID; + uint32 m_entry; + Position pos; + PetType m_petType; + uint32 m_duration, m_createdBySpell; + uint64 m_casterGUID; }; typedef std::unordered_map PetSpellMap; @@ -43,148 +43,148 @@ class Player; class Pet : public Guardian { - public: - explicit Pet(Player* owner, PetType type = MAX_PET_TYPE); - virtual ~Pet(); +public: + explicit Pet(Player* owner, PetType type = MAX_PET_TYPE); + virtual ~Pet(); - void AddToWorld() override; - void RemoveFromWorld() override; + void AddToWorld() override; + void RemoveFromWorld() override; - void SetDisplayId(uint32 modelId) override; + void SetDisplayId(uint32 modelId) override; - PetType getPetType() const { return m_petType; } - void setPetType(PetType type) { m_petType = type; } - bool isControlled() const { return getPetType() == SUMMON_PET || getPetType() == HUNTER_PET; } - bool isTemporarySummoned() const { return m_duration > 0; } + PetType getPetType() const { return m_petType; } + void setPetType(PetType type) { m_petType = type; } + bool isControlled() const { return getPetType() == SUMMON_PET || getPetType() == HUNTER_PET; } + bool isTemporarySummoned() const { return m_duration > 0; } - bool IsPermanentPetFor(Player* owner) const; // pet have tab in character windows and set UNIT_FIELD_PETNUMBER + bool IsPermanentPetFor(Player* owner) const; // pet have tab in character windows and set UNIT_FIELD_PETNUMBER - bool Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, uint32 pet_number); - bool CreateBaseAtCreature(Creature* creature); - bool CreateBaseAtCreatureInfo(CreatureTemplate const* cinfo, Unit* owner); - bool CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phaseMask); - static SpellCastResult TryLoadFromDB(Player* owner, bool current = false, PetType mandatoryPetType = MAX_PET_TYPE); - static bool LoadPetFromDB(Player* owner, uint8 asynchLoadType, uint32 petentry = 0, uint32 petnumber = 0, bool current = false, AsynchPetSummon* info = nullptr); - bool isBeingLoaded() const override { return m_loading;} - void SavePetToDB(PetSaveMode mode, bool logout); - void Remove(PetSaveMode mode, bool returnreagent = false); - static void DeleteFromDB(uint32 guidlow); + bool Create(uint32 guidlow, Map* map, uint32 phaseMask, uint32 Entry, uint32 pet_number); + bool CreateBaseAtCreature(Creature* creature); + bool CreateBaseAtCreatureInfo(CreatureTemplate const* cinfo, Unit* owner); + bool CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phaseMask); + static SpellCastResult TryLoadFromDB(Player* owner, bool current = false, PetType mandatoryPetType = MAX_PET_TYPE); + static bool LoadPetFromDB(Player* owner, uint8 asynchLoadType, uint32 petentry = 0, uint32 petnumber = 0, bool current = false, AsynchPetSummon* info = nullptr); + bool isBeingLoaded() const override { return m_loading;} + void SavePetToDB(PetSaveMode mode, bool logout); + void Remove(PetSaveMode mode, bool returnreagent = false); + static void DeleteFromDB(uint32 guidlow); - void setDeathState(DeathState s, bool despawn = false) override; // overwrite virtual Creature::setDeathState and Unit::setDeathState - void Update(uint32 diff) override; // overwrite virtual Creature::Update and Unit::Update + void setDeathState(DeathState s, bool despawn = false) override; // overwrite virtual Creature::setDeathState and Unit::setDeathState + void Update(uint32 diff) override; // overwrite virtual Creature::Update and Unit::Update - uint8 GetPetAutoSpellSize() const override { return m_autospells.size(); } - uint32 GetPetAutoSpellOnPos(uint8 pos) const override - { - if (pos >= m_autospells.size()) - return 0; - else - return m_autospells[pos]; - } + uint8 GetPetAutoSpellSize() const override { return m_autospells.size(); } + uint32 GetPetAutoSpellOnPos(uint8 pos) const override + { + if (pos >= m_autospells.size()) + return 0; + else + return m_autospells[pos]; + } - void LoseHappiness(); - HappinessState GetHappinessState(); - void GivePetXP(uint32 xp); - void GivePetLevel(uint8 level); - void SynchronizeLevelWithOwner(); - bool HaveInDiet(ItemTemplate const* item) const; - uint32 GetCurrentFoodBenefitLevel(uint32 itemlevel) const; - void SetDuration(int32 dur) { m_duration = dur; } - int32 GetDuration() const { return m_duration; } + void LoseHappiness(); + HappinessState GetHappinessState(); + void GivePetXP(uint32 xp); + void GivePetLevel(uint8 level); + void SynchronizeLevelWithOwner(); + bool HaveInDiet(ItemTemplate const* item) const; + uint32 GetCurrentFoodBenefitLevel(uint32 itemlevel) const; + void SetDuration(int32 dur) { m_duration = dur; } + int32 GetDuration() const { return m_duration; } - /* - bool UpdateStats(Stats stat); - bool UpdateAllStats(); - void UpdateResistances(uint32 school); - void UpdateArmor(); - void UpdateMaxHealth(); - void UpdateMaxPower(Powers power); - void UpdateAttackPowerAndDamage(bool ranged = false); - void UpdateDamagePhysical(WeaponAttackType attType); - */ + /* + bool UpdateStats(Stats stat); + bool UpdateAllStats(); + void UpdateResistances(uint32 school); + void UpdateArmor(); + void UpdateMaxHealth(); + void UpdateMaxPower(Powers power); + void UpdateAttackPowerAndDamage(bool ranged = false); + void UpdateDamagePhysical(WeaponAttackType attType); + */ - void ToggleAutocast(SpellInfo const* spellInfo, bool apply); + void ToggleAutocast(SpellInfo const* spellInfo, bool apply); - bool HasSpell(uint32 spell) const override; + bool HasSpell(uint32 spell) const override; - void LearnPetPassives(); - void CastPetAuras(bool current); + void LearnPetPassives(); + void CastPetAuras(bool current); - void CastWhenWillAvailable(uint32 spellid, Unit* spellTarget, Unit* oldTarget, bool spellIsPositive = false); - void ClearCastWhenWillAvailable(); - void RemoveSpellCooldown(uint32 spell_id, bool update /* = false */); + void CastWhenWillAvailable(uint32 spellid, Unit* spellTarget, Unit* oldTarget, bool spellIsPositive = false); + void ClearCastWhenWillAvailable(); + void RemoveSpellCooldown(uint32 spell_id, bool update /* = false */); - void _SaveSpellCooldowns(SQLTransaction& trans, bool logout); - void _SaveAuras(SQLTransaction& trans, bool logout); - void _SaveSpells(SQLTransaction& trans); + void _SaveSpellCooldowns(SQLTransaction& trans, bool logout); + void _SaveAuras(SQLTransaction& trans, bool logout); + void _SaveSpells(SQLTransaction& trans); - void _LoadSpellCooldowns(PreparedQueryResult result); - void _LoadAuras(PreparedQueryResult result, uint32 timediff); - void _LoadSpells(PreparedQueryResult result); + void _LoadSpellCooldowns(PreparedQueryResult result); + void _LoadAuras(PreparedQueryResult result, uint32 timediff); + void _LoadSpells(PreparedQueryResult result); - bool addSpell(uint32 spellId, ActiveStates active = ACT_DECIDE, PetSpellState state = PETSPELL_NEW, PetSpellType type = PETSPELL_NORMAL); - bool learnSpell(uint32 spell_id); - void learnSpellHighRank(uint32 spellid); - void InitLevelupSpellsForLevel(); - bool unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab = true); - bool removeSpell(uint32 spell_id, bool learn_prev, bool clear_ab = true); - void CleanupActionBar(); + bool addSpell(uint32 spellId, ActiveStates active = ACT_DECIDE, PetSpellState state = PETSPELL_NEW, PetSpellType type = PETSPELL_NORMAL); + bool learnSpell(uint32 spell_id); + void learnSpellHighRank(uint32 spellid); + void InitLevelupSpellsForLevel(); + bool unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab = true); + bool removeSpell(uint32 spell_id, bool learn_prev, bool clear_ab = true); + void CleanupActionBar(); - PetSpellMap m_spells; - AutoSpellList m_autospells; + PetSpellMap m_spells; + AutoSpellList m_autospells; - void InitPetCreateSpells(); + void InitPetCreateSpells(); - bool resetTalents(); - static void resetTalentsForAllPetsOf(Player* owner, Pet* online_pet = nullptr); - void InitTalentForLevel(); + bool resetTalents(); + static void resetTalentsForAllPetsOf(Player* owner, Pet* online_pet = nullptr); + void InitTalentForLevel(); - uint8 GetMaxTalentPointsForLevel(uint8 level); - uint8 GetFreeTalentPoints() { return GetByteValue(UNIT_FIELD_BYTES_1, 1); } - void SetFreeTalentPoints(uint8 points) { SetByteValue(UNIT_FIELD_BYTES_1, 1, points); } + uint8 GetMaxTalentPointsForLevel(uint8 level); + uint8 GetFreeTalentPoints() { return GetByteValue(UNIT_FIELD_BYTES_1, 1); } + void SetFreeTalentPoints(uint8 points) { SetByteValue(UNIT_FIELD_BYTES_1, 1, points); } - uint32 m_usedTalentCount; + uint32 m_usedTalentCount; - uint64 GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; } - void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); } - void ResetAuraUpdateMaskForRaid() { m_auraRaidUpdateMask = 0; } + uint64 GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; } + void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); } + void ResetAuraUpdateMaskForRaid() { m_auraRaidUpdateMask = 0; } - DeclinedName const* GetDeclinedNames() const { return m_declinedname; } + DeclinedName const* GetDeclinedNames() const { return m_declinedname; } - bool m_removed; // prevent overwrite pet state in DB at next Pet::Update if pet already removed(saved) + bool m_removed; // prevent overwrite pet state in DB at next Pet::Update if pet already removed(saved) - Player* GetOwner() const { return m_owner; } - void SetLoading(bool load) { m_loading = load; } - void HandleAsynchLoadSucceed(); - static void HandleAsynchLoadFailed(AsynchPetSummon* info, Player* player, uint8 asynchLoadType, uint8 loadResult); - uint8 GetAsynchLoadType() const { return asynchLoadType; } - void SetAsynchLoadType(uint8 type) { asynchLoadType = type; } - protected: - Player* m_owner; - int32 m_happinessTimer; - PetType m_petType; - int32 m_duration; // time until unsummon (used mostly for summoned guardians and not used for controlled pets) - uint64 m_auraRaidUpdateMask; - bool m_loading; - int32 m_petRegenTimer; // xinef: used for focus regeneration + Player* GetOwner() const { return m_owner; } + void SetLoading(bool load) { m_loading = load; } + void HandleAsynchLoadSucceed(); + static void HandleAsynchLoadFailed(AsynchPetSummon* info, Player* player, uint8 asynchLoadType, uint8 loadResult); + uint8 GetAsynchLoadType() const { return asynchLoadType; } + void SetAsynchLoadType(uint8 type) { asynchLoadType = type; } +protected: + Player* m_owner; + int32 m_happinessTimer; + PetType m_petType; + int32 m_duration; // time until unsummon (used mostly for summoned guardians and not used for controlled pets) + uint64 m_auraRaidUpdateMask; + bool m_loading; + int32 m_petRegenTimer; // xinef: used for focus regeneration - DeclinedName *m_declinedname; + DeclinedName* m_declinedname; - Unit* m_tempspellTarget; - Unit* m_tempoldTarget; - bool m_tempspellIsPositive; - uint32 m_tempspell; + Unit* m_tempspellTarget; + Unit* m_tempoldTarget; + bool m_tempspellIsPositive; + uint32 m_tempspell; - uint8 asynchLoadType; + uint8 asynchLoadType; - private: - void SaveToDB(uint32, uint8, uint32) override // override of Creature::SaveToDB - must not be called - { - ABORT(); - } - void DeleteFromDB() override // override of Creature::DeleteFromDB - must not be called - { - ABORT(); - } +private: + void SaveToDB(uint32, uint8, uint32) override // override of Creature::SaveToDB - must not be called + { + ABORT(); + } + void DeleteFromDB() override // override of Creature::DeleteFromDB - must not be called + { + ABORT(); + } }; #endif diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 370331041..70402b0ac 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -160,35 +160,60 @@ void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level switch (chrClass) { case CLASS_DEATH_KNIGHT: - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - m_taximask[i] |= sOldContinentsNodesMask[i]; - break; - } + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + m_taximask[i] |= sOldContinentsNodesMask[i]; + break; + } } // race specific initial known nodes: capital and taxi hub masks switch (race) { - case RACE_HUMAN: SetTaximaskNode(2); break; // Human - case RACE_ORC: SetTaximaskNode(23); break; // Orc - case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf - case RACE_NIGHTELF: SetTaximaskNode(26); - SetTaximaskNode(27); break; // Night Elf - case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead - case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren - case RACE_GNOME: SetTaximaskNode(6); break; // Gnome - case RACE_TROLL: SetTaximaskNode(23); break; // Troll - case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf - case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei + case RACE_HUMAN: + SetTaximaskNode(2); + break; // Human + case RACE_ORC: + SetTaximaskNode(23); + break; // Orc + case RACE_DWARF: + SetTaximaskNode(6); + break; // Dwarf + case RACE_NIGHTELF: + SetTaximaskNode(26); + SetTaximaskNode(27); + break; // Night Elf + case RACE_UNDEAD_PLAYER: + SetTaximaskNode(11); + break;// Undead + case RACE_TAUREN: + SetTaximaskNode(22); + break; // Tauren + case RACE_GNOME: + SetTaximaskNode(6); + break; // Gnome + case RACE_TROLL: + SetTaximaskNode(23); + break; // Troll + case RACE_BLOODELF: + SetTaximaskNode(82); + break; // Blood Elf + case RACE_DRAENEI: + SetTaximaskNode(94); + break; // Draenei } // new continent starting masks (It will be accessible only at new map) switch (Player::TeamIdForRace(race)) { - case TEAM_ALLIANCE: SetTaximaskNode(100); break; - case TEAM_HORDE: SetTaximaskNode(99); break; - default: break; + case TEAM_ALLIANCE: + SetTaximaskNode(100); + break; + case TEAM_HORDE: + SetTaximaskNode(99); + break; + default: + break; } // level dependent taxi hubs if (level >= 68) @@ -202,7 +227,7 @@ void PlayerTaxi::LoadTaxiMask(std::string const& data) uint8 index; Tokenizer::const_iterator iter; for (iter = tokens.begin(), index = 0; - (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index) + (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index) { // load and set bits only for existed taxi nodes m_taximask[index] = sTaxiNodesMask[index] & uint32(atol(*iter)); @@ -213,12 +238,12 @@ void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) { if (all) { - for (uint8 i=0; iGetTaxiPath(m_TaxiDestinations[i], m_TaxiDestinations[i+1], path, cost); + sObjectMgr->GetTaxiPath(m_TaxiDestinations[i], m_TaxiDestinations[i + 1], path, cost); if (!path) return false; } @@ -275,13 +300,13 @@ std::string PlayerTaxi::SaveTaxiDestinationsToString() uint32 PlayerTaxi::GetCurrentTaxiPath() const { - if (m_TaxiDestinations.size() < 2 || m_TaxiDestinations.size() <= _taxiSegment+1) + if (m_TaxiDestinations.size() < 2 || m_TaxiDestinations.size() <= _taxiSegment + 1) return 0; uint32 path; uint32 cost; - sObjectMgr->GetTaxiPath(m_TaxiDestinations[_taxiSegment], m_TaxiDestinations[_taxiSegment+1], path, cost); + sObjectMgr->GetTaxiPath(m_TaxiDestinations[_taxiSegment], m_TaxiDestinations[_taxiSegment + 1], path, cost); return path; } @@ -527,10 +552,10 @@ inline void KillRewarder::_RewardXP(Player* player, float rate) // * set to 0 if player's level is more than maximum level of not gray member; // * cut XP in half if _isFullXP is false. if (_maxNotGrayMember && player->IsAlive() && - _maxNotGrayMember->getLevel() >= player->getLevel()) + _maxNotGrayMember->getLevel() >= player->getLevel()) xp = _isFullXP ? - uint32(xp * rate) : // Reward FULL XP if all group members are not gray. - uint32(xp * rate / 2) + 1; // Reward only HALF of XP if some of group members are gray. + uint32(xp * rate) : // Reward FULL XP if all group members are not gray. + uint32(xp * rate / 2) + 1; // Reward only HALF of XP if some of group members are gray. else xp = 0; } @@ -583,8 +608,8 @@ void KillRewarder::_RewardPlayer(Player* player, bool isDungeon) if (!_isPvP || _isBattleGround) { const float rate = _group ? - _groupRate * float(player->getLevel()) / _sumLevel : // Group rate depends on summary level. - 1.0f; // Personal rate is 100%. + _groupRate * float(player->getLevel()) / _sumLevel : // Group rate depends on summary level. + 1.0f; // Personal rate is 100%. if (_xp) // 4.2. Give XP. _RewardXP(player, rate); @@ -762,7 +787,7 @@ Player::Player(WorldSession* session): Unit(true), m_mover(this) m_DailyQuestChanged = false; m_lastDailyQuestTime = 0; - for (uint8 i=0; ioutError("Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid race/class pair (%u/%u) - refusing to do so.", - GetSession()->GetAccountId(), m_name.c_str(), createInfo->Race, createInfo->Class); + GetSession()->GetAccountId(), m_name.c_str(), createInfo->Race, createInfo->Class); return false; } @@ -1021,7 +1046,7 @@ bool Player::Create(uint32 guidlow, CharacterCreateInfo* createInfo) if (!cEntry) { sLog->outError("Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid character class (%u) - refusing to do so (wrong DBC-files?)", - GetSession()->GetAccountId(), m_name.c_str(), createInfo->Class); + GetSession()->GetAccountId(), m_name.c_str(), createInfo->Class); return false; } @@ -1039,7 +1064,7 @@ bool Player::Create(uint32 guidlow, CharacterCreateInfo* createInfo) if (!IsValidGender(createInfo->Gender)) { sLog->outError("Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid gender (%u) - refusing to do so", - GetSession()->GetAccountId(), m_name.c_str(), createInfo->Gender); + GetSession()->GetAccountId(), m_name.c_str(), createInfo->Gender); return false; } @@ -1056,14 +1081,14 @@ bool Player::Create(uint32 guidlow, CharacterCreateInfo* createInfo) SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3 - // -1 is default value + // -1 is default value SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1)); SetUInt32Value(PLAYER_BYTES, (createInfo->Skin | (createInfo->Face << 8) | (createInfo->HairStyle << 16) | (createInfo->HairColor << 24))); SetUInt32Value(PLAYER_BYTES_2, (createInfo->FacialHair | - (0x00 << 8) | - (0x00 << 16) | - (((GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED) << 24))); + (0x00 << 8) | + (0x00 << 16) | + (((GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED) << 24))); SetByteValue(PLAYER_BYTES_3, 0, createInfo->Gender); SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1) @@ -1082,8 +1107,8 @@ bool Player::Create(uint32 guidlow, CharacterCreateInfo* createInfo) // set starting level uint32 start_level = getClass() != CLASS_DEATH_KNIGHT - ? sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL) - : sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL); + ? sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL) + : sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL); if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity())) { @@ -1103,8 +1128,8 @@ bool Player::Create(uint32 guidlow, CharacterCreateInfo* createInfo) // start with every map explored if (sWorld->getBoolConfig(CONFIG_START_ALL_EXPLORED)) { - for (uint8 i=0; iGetSecurity() >= AccountTypes(sWorld->getIntConfig(CONFIG_DISABLE_BREATHING))) - return DISABLED_MIRROR_TIMER; - int32 UnderWaterTime = 3 * MINUTE * IN_MILLISECONDS; - AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING); - for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i) - AddPct(UnderWaterTime, (*i)->GetAmount()); - return UnderWaterTime; - } + { + if (!IsAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= AccountTypes(sWorld->getIntConfig(CONFIG_DISABLE_BREATHING))) + return DISABLED_MIRROR_TIMER; + int32 UnderWaterTime = 3 * MINUTE * IN_MILLISECONDS; + AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING); + for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i) + AddPct(UnderWaterTime, (*i)->GetAmount()); + return UnderWaterTime; + } case FIRE_TIMER: - { - if (!IsAlive()) - return DISABLED_MIRROR_TIMER; - return 1 * IN_MILLISECONDS; - } + { + if (!IsAlive()) + return DISABLED_MIRROR_TIMER; + return 1 * IN_MILLISECONDS; + } default: return 0; } @@ -1388,14 +1413,14 @@ void Player::HandleDrowning(uint32 time_diff) } else // If activated - do tick { - m_MirrorTimer[BREATH_TIMER]-=time_diff; + m_MirrorTimer[BREATH_TIMER] -= time_diff; // Timer limit - need deal damage if (m_MirrorTimer[BREATH_TIMER] < 0) { - m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[BREATH_TIMER] += 1 * IN_MILLISECONDS; // Calculate and deal damage // TODO: Check this formula - uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); + uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel() - 1); EnvironmentalDamage(DAMAGE_DROWNING, damage); } else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need @@ -1406,7 +1431,7 @@ void Player::HandleDrowning(uint32 time_diff) { int32 UnderWaterTime = getMaxTimer(BREATH_TIMER); // Need breath regen - m_MirrorTimer[BREATH_TIMER]+=10*time_diff; + m_MirrorTimer[BREATH_TIMER] += 10 * time_diff; if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !IsAlive()) StopMirrorTimer(BREATH_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER) @@ -1424,14 +1449,14 @@ void Player::HandleDrowning(uint32 time_diff) } else { - m_MirrorTimer[FATIGUE_TIMER]-=time_diff; + m_MirrorTimer[FATIGUE_TIMER] -= time_diff; // Timer limit - need deal damage or teleport ghost to graveyard if (m_MirrorTimer[FATIGUE_TIMER] < 0) { - m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[FATIGUE_TIMER] += 1 * IN_MILLISECONDS; if (IsAlive()) // Calculate and deal damage { - uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); + uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel() - 1); EnvironmentalDamage(DAMAGE_EXHAUSTED, damage); } else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard @@ -1444,7 +1469,7 @@ void Player::HandleDrowning(uint32 time_diff) else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer { int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER); - m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff; + m_MirrorTimer[FATIGUE_TIMER] += 10 * time_diff; if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !IsAlive()) StopMirrorTimer(FATIGUE_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER) @@ -1461,7 +1486,7 @@ void Player::HandleDrowning(uint32 time_diff) m_MirrorTimer[FIRE_TIMER] -= time_diff; if (m_MirrorTimer[FIRE_TIMER] < 0) { - m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[FIRE_TIMER] += 1 * IN_MILLISECONDS; // Calculate and deal damage // TODO: Check this formula uint32 damage = urand(600, 700); @@ -1478,11 +1503,11 @@ void Player::HandleDrowning(uint32 time_diff) m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER; // Recheck timers flag - m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS; - for (uint8 i = 0; i< MAX_TIMERS; ++i) + m_MirrorTimerFlags &= ~UNDERWATER_EXIST_TIMERS; + for (uint8 i = 0; i < MAX_TIMERS; ++i) if (m_MirrorTimer[i] != DISABLED_MIRROR_TIMER) { - m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS; + m_MirrorTimerFlags |= UNDERWATER_EXIST_TIMERS; break; } m_MirrorTimerFlagsLast = m_MirrorTimerFlags; @@ -1536,7 +1561,7 @@ void Player::SetDrunkValue(uint8 newDrunkValue, uint32 itemId /*= 0*/) if (newDrunkenState == oldDrunkenState) return; - WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4)); + WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8 + 4 + 4)); data << uint64(GetGUID()); data << uint32(newDrunkenState); data << uint32(itemId); @@ -1660,7 +1685,7 @@ void Player::Update(uint32 p_time) } } //120 degrees of radiant range - else if (!HasInArc(2*M_PI/3, victim)) + else if (!HasInArc(2 * M_PI / 3, victim)) { setAttackTimer(BASE_ATTACK, 100); if (m_swingErrorMsg != 2) // send single time (client auto repeat) @@ -1688,7 +1713,7 @@ void Player::Update(uint32 p_time) { if (!IsWithinMeleeRange(victim)) setAttackTimer(OFF_ATTACK, 100); - else if (!HasInArc(2*M_PI/3, victim)) + else if (!HasInArc(2 * M_PI / 3, victim)) setAttackTimer(OFF_ATTACK, 100); else { @@ -1873,7 +1898,7 @@ void Player::Update(uint32 p_time) Pet* pet = GetPet(); if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityRange()) && !pet->isPossessed()) - //if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID()))) + //if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID()))) RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true); // pussywizard: @@ -2170,12 +2195,12 @@ void Player::SendTeleportAckPacket() GetSession()->SendPacket(&data); } -bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options /*= 0*/, Unit *target /*= nullptr*/) +bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options /*= 0*/, Unit* target /*= nullptr*/) { if (!MapManager::IsValidMapCoord(mapid, x, y, z, orientation)) { sLog->outError("TeleportTo: invalid map (%d) or invalid coordinates (X: %f, Y: %f, Z: %f, O: %f) given when teleporting player (GUID: %u, name: %s, map: %d, X: %f, Y: %f, Z: %f, O: %f).", - mapid, x, y, z, orientation, GetGUIDLow(), GetName().c_str(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); + mapid, x, y, z, orientation, GetGUIDLow(), GetName().c_str(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); return false; } @@ -2505,7 +2530,7 @@ void Player::ProcessDelayedOperations() if (m_DelayedOperations & DELAYED_BG_GROUP_RESTORE) { - if (Group *g = GetGroup()) + if (Group* g = GetGroup()) g->SendUpdateToPlayer(GetGUID()); } @@ -2602,14 +2627,14 @@ void Player::RegenerateAll() SetRuneCooldown(i, (cd > m_regenTimer) ? cd - m_regenTimer : 0); // start grace counter, player must be in combat and rune has to go off cooldown if (IsInCombat() && cd <= m_regenTimer) - SetGracePeriod(i, m_regenTimer-cd+1); // added 1 because m_regenTimer-cd can be equal 0 + SetGracePeriod(i, m_regenTimer - cd + 1); // added 1 because m_regenTimer-cd can be equal 0 } // xinef: if grace is started, increase it but no more than cap else if (uint32 grace = GetGracePeriod(i)) { if (grace < RUNE_GRACE_PERIOD) - SetGracePeriod(i, std::min(grace+m_regenTimer, RUNE_GRACE_PERIOD)); + SetGracePeriod(i, std::min(grace + m_regenTimer, RUNE_GRACE_PERIOD)); } } @@ -2617,8 +2642,8 @@ void Player::RegenerateAll() { // Not in combat or they have regeneration if (!IsInCombat() || IsPolymorphed() || m_baseHealthRegen || - HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) || - HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT)) + HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) || + HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT)) { RegenerateHealth(); } @@ -2673,7 +2698,7 @@ void Player::Regenerate(Powers power) uint32 curValue = GetPower(power); // TODO: possible use of miscvalueb instead of amount - if (HasAuraTypeWithMiscvalue(SPELL_AURA_PREVENT_REGENERATE_POWER, power+1)) + if (HasAuraTypeWithMiscvalue(SPELL_AURA_PREVENT_REGENERATE_POWER, power + 1)) return; float addvalue = 0.0f; @@ -2681,37 +2706,40 @@ void Player::Regenerate(Powers power) switch (power) { case POWER_MANA: - { - bool recentCast = IsUnderLastManaUseEffect(); - float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA); - - if (getLevel() < 15) - ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA) * (2.066f - (getLevel() * 0.066f)); - - if (recentCast) // Trinity Updates Mana in intervals of 2s, which is correct - addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer; - else - addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer; - } break; - case POWER_RAGE: // Regenerate rage - { - if (!IsInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) { - float RageDecreaseRate = sWorld->getRate(RATE_POWER_RAGE_LOSS); - addvalue += -20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec) + bool recentCast = IsUnderLastManaUseEffect(); + float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA); + + if (getLevel() < 15) + ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA) * (2.066f - (getLevel() * 0.066f)); + + if (recentCast) // Trinity Updates Mana in intervals of 2s, which is correct + addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer; + else + addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 0.001f * m_regenTimer; } - } break; + break; + case POWER_RAGE: // Regenerate rage + { + if (!IsInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) + { + float RageDecreaseRate = sWorld->getRate(RATE_POWER_RAGE_LOSS); + addvalue += -20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec) + } + } + break; case POWER_ENERGY: // Regenerate energy (rogue) addvalue += 0.01f * m_regenTimer * sWorld->getRate(RATE_POWER_ENERGY); break; case POWER_RUNIC_POWER: - { - if (!IsInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) { - float RunicPowerDecreaseRate = sWorld->getRate(RATE_POWER_RUNICPOWER_LOSS); - addvalue += -30 * RunicPowerDecreaseRate; // 3 RunicPower by tick + if (!IsInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) + { + float RunicPowerDecreaseRate = sWorld->getRate(RATE_POWER_RUNICPOWER_LOSS); + addvalue += -30 * RunicPowerDecreaseRate; // 3 RunicPower by tick + } } - } break; + break; case POWER_RUNE: case POWER_FOCUS: case POWER_HAPPINESS: @@ -2799,7 +2827,7 @@ void Player::RegenerateHealth() // polymorphed case if (IsPolymorphed()) - addvalue = (float)GetMaxHealth()/3; + addvalue = (float)GetMaxHealth() / 3; // normal regen case (maybe partly in combat case) else if (!IsInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT)) { @@ -2949,14 +2977,15 @@ bool Player::IsInWater(bool allowAbove) const return m_isInWater; float distsq = GetExactDistSq(&m_last_environment_position); - if (distsq < 3.0f*3.0f) + if (distsq < 3.0f * 3.0f) return m_last_islittleabovewater_status; else { - LiquidData liqData; liqData.level = INVALID_HEIGHT; + LiquidData liqData; + liqData.level = INVALID_HEIGHT; const_cast(&m_last_environment_position)->Relocate(GetPositionX(), GetPositionY(), GetPositionZ()); bool inWater = GetBaseMap()->IsInWater(GetPositionX(), GetPositionY(), GetPositionZ(), &liqData); - *(const_cast(&m_last_islittleabovewater_status)) = inWater || (liqData.level > INVALID_HEIGHT && liqData.level > liqData.depth_level && liqData.level <= GetPositionZ()+3.0f && liqData.level > GetPositionZ()-1.0f); + *(const_cast(&m_last_islittleabovewater_status)) = inWater || (liqData.level > INVALID_HEIGHT && liqData.level > liqData.depth_level && liqData.level <= GetPositionZ() + 3.0f && liqData.level > GetPositionZ() - 1.0f); return m_last_islittleabovewater_status; } } @@ -2964,7 +2993,7 @@ bool Player::IsInWater(bool allowAbove) const bool Player::IsUnderWater() const { return IsInWater() && - GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(), GetPositionY())-2); + GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(), GetPositionY()) - 2); } bool Player::IsFalling() const @@ -3103,17 +3132,20 @@ bool Player::IsGroupVisibleFor(Player const* p) const { switch (sWorld->getIntConfig(CONFIG_GROUP_VISIBILITY)) { - default: return IsInSameGroupWith(p); - case 1: return IsInSameRaidWith(p); - case 2: return GetTeamId() == p->GetTeamId(); + default: + return IsInSameGroupWith(p); + case 1: + return IsInSameRaidWith(p); + case 2: + return GetTeamId() == p->GetTeamId(); } } bool Player::IsInSameGroupWith(Player const* p) const { return p == this || (GetGroup() != NULL && - GetGroup() == p->GetGroup() && - GetGroup()->SameSubGroup(this, p)); + GetGroup() == p->GetGroup() && + GetGroup()->SameSubGroup(this, p)); } ///- If the player is invited, remove him. If the group if then only 1 person, disband the group. @@ -3248,7 +3280,7 @@ void Player::GiveLevel(uint8 level) sObjectMgr->GetPlayerClassLevelInfo(getClass(), level, &classInfo); // send levelup info to client - WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4)); + WorldPacket data(SMSG_LEVELUP_INFO, (4 + 4 + MAX_POWERS * 4 + MAX_STATS * 4)); data << uint32(level); data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth())); // for (int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6) @@ -3383,7 +3415,7 @@ void Player::InitStatsForLevel(bool reapplyMods) //set create powers SetCreateMana(classInfo.basemana); - SetArmor(int32(m_createStats[STAT_AGILITY]*2)); + SetArmor(int32(m_createStats[STAT_AGILITY] * 2)); InitStatBuffMods(); @@ -3394,9 +3426,9 @@ void Player::InitStatsForLevel(bool reapplyMods) SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS, 0); for (uint8 i = 0; i < 7; ++i) { - SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0); - SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0); - SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f); + SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, 0); + SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, 0); + SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT + i, 1.00f); } //reset attack power, damage and attack speed fields @@ -3425,7 +3457,7 @@ void Player::InitStatsForLevel(bool reapplyMods) // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset for (uint8 i = 0; i < 7; ++i) - SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f); + SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + i, 0.0f); SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f); SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f); @@ -3435,7 +3467,7 @@ void Player::InitStatsForLevel(bool reapplyMods) SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f); // set armor (resistance 0) to original value (create_agility*2) - SetArmor(int32(m_createStats[STAT_AGILITY]*2)); + SetArmor(int32(m_createStats[STAT_AGILITY] * 2)); SetResistanceBuffMods(SpellSchools(0), true, 0.0f); SetResistanceBuffMods(SpellSchools(0), false, 0.0f); // set other resistance to original value (0) @@ -3450,8 +3482,8 @@ void Player::InitStatsForLevel(bool reapplyMods) SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, 0); for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i) { - SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i, 0); - SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i, 0.0f); + SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + i, 0); + SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, 0.0f); } // Reset no reagent cost field for (uint8 i = 0; i < 3; ++i) @@ -3470,12 +3502,12 @@ void Player::InitStatsForLevel(bool reapplyMods) // cleanup unit flags (will be re-applied if need at aura load). RemoveFlag(UNIT_FIELD_FLAGS, - UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 | - UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_LOOTING | - UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED | - UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED | - UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE | - UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT ); + UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 | + UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_LOOTING | + UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED | + UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED | + UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE | + UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT ); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); // must be set SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);// must be set @@ -3510,11 +3542,11 @@ void Player::InitStatsForLevel(bool reapplyMods) void Player::SendInitialSpells() { uint32 curTime = World::GetGameTimeMS(); - uint32 infTime = World::GetGameTimeMS()+infinityCooldownDelayCheck; + uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; uint16 spellCount = 0; - WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(4+2+2+4+4))); + WorldPacket data(SMSG_INITIAL_SPELLS, (1 + 2 + 4 * m_spells.size() + 2 + m_spellCooldowns.size() * (4 + 2 + 2 + 4 + 4))); data << uint8(0); size_t countPos = data.wpos(); @@ -3580,7 +3612,7 @@ void Player::SendInitialSpells() continue; } - uint32 cooldown = itr->second.end > curTime ? itr->second.end-curTime : 0; + uint32 cooldown = itr->second.end > curTime ? itr->second.end - curTime : 0; if (!sEntry->GetCategory() || (sEntry->CategoryRecoveryTime != sEntry->RecoveryTime && sEntry->RecoveryTime && sEntry->CategoryRecoveryTime)) // may be wrong, but anyway better than nothing... { @@ -3612,7 +3644,7 @@ void Player::RemoveMail(uint32 id) void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count) { - WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0)))); + WorldPacket data(SMSG_SEND_MAIL_RESULT, (4 + 4 + 4 + (mailError == MAIL_ERR_EQUIP_ERROR ? 4 : (mailAction == MAIL_ITEM_TAKEN ? 4 + 4 : 0)))); data << (uint32) mailId; data << (uint32) mailAction; data << (uint32) mailError; @@ -3684,9 +3716,9 @@ bool Player::addTalent(uint32 spellId, uint8 addSpecMask, uint8 oldTalentRank) // xinef: remove old talent rank if any if (oldTalentRank) { - _removeTalent(talentInfo->RankID[oldTalentRank-1], addSpecMask); - _removeTalentAurasAndSpells(talentInfo->RankID[oldTalentRank-1]); - SendLearnPacket(talentInfo->RankID[oldTalentRank-1], false); + _removeTalent(talentInfo->RankID[oldTalentRank - 1], addSpecMask); + _removeTalentAurasAndSpells(talentInfo->RankID[oldTalentRank - 1]); + SendLearnPacket(talentInfo->RankID[oldTalentRank - 1], false); } // xinef: add talent auras and spells @@ -3789,7 +3821,7 @@ void Player::_addTalentAurasAndSpells(uint32 spellId) SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL)) { - for (uint8 i=0; iEffects[i].Effect == SPELL_EFFECT_LEARN_SPELL && !sSpellMgr->IsAdditionalTalentSpell(spellInfo->Effects[i].TriggerSpell)) _addSpell(spellInfo->Effects[i].TriggerSpell, SPEC_MASK_ALL, true); } @@ -3938,7 +3970,7 @@ bool Player::_addSpell(uint32 spellId, uint8 addSpecMask, bool temporary) // pussywizard: return if spell not in current spec // pussywizard: return true to fix active for ranks, this condition is true only at loading, so no problems with learning packets - if (!((1<GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTHLESS_35_PERCENT || - aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTH_ABOVE_75_PERCENT || - aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTHLESS_20_PERCENT ) + aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTH_ABOVE_75_PERCENT || + aura->GetSpellInfo()->CasterAuraState == AURA_STATE_HEALTHLESS_20_PERCENT ) if (!HasAuraState((AuraStateType)aura->GetSpellInfo()->CasterAuraState)) aura->HandleAllEffects(aura->GetApplicationOfTarget(GetGUID()), AURA_EFFECT_HANDLE_REAL, false); } @@ -3978,7 +4010,7 @@ bool Player::_addSpell(uint32 spellId, uint8 addSpecMask, bool temporary) if (uint32 freeProfs = GetFreePrimaryProfessionPoints()) { if (spellInfo->IsPrimaryProfessionFirstRank()) - SetFreePrimaryProfessions(freeProfs-1); + SetFreePrimaryProfessions(freeProfs - 1); } // pussywizard: update 310 flyer speed @@ -4014,7 +4046,7 @@ bool Player::_addSpell(uint32 spellId, uint8 addSpecMask, bool temporary) continue; if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL || // pussywizard: learning autolearned spell from skill ensures having the skill - ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0)) // pussywizard: learning any spell from lockpicking or runeforging ensures having the skill + ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0)) // pussywizard: learning any spell from lockpicking or runeforging ensures having the skill { switch (GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0)) { @@ -4054,7 +4086,7 @@ bool Player::IsNeedCastPassiveSpellAtLearn(SpellInfo const* spellInfo) const // talent dependent passives activated at form apply have proper stance data ShapeshiftForm form = GetShapeshiftForm(); return (!spellInfo->Stances || (form && (spellInfo->Stances & (1 << (form - 1)))) || - (!form && spellInfo->HasAttribute(SPELL_ATTR2_NOT_NEED_SHAPESHIFT))); + (!form && spellInfo->HasAttribute(SPELL_ATTR2_NOT_NEED_SHAPESHIFT))); } @@ -4169,7 +4201,7 @@ void Player::removeSpell(uint32 spellId, uint8 removeSpecMask, bool onlyTemporar // pussywizard: update free primary prof points if (spellInfo->IsPrimaryProfessionFirstRank()) { - uint32 freeProfs = GetFreePrimaryProfessionPoints()+1; + uint32 freeProfs = GetFreePrimaryProfessionPoints() + 1; if (freeProfs <= sWorld->getIntConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL)) SetFreePrimaryProfessions(freeProfs); } @@ -4226,7 +4258,7 @@ void Player::removeSpell(uint32 spellId, uint8 removeSpecMask, bool onlyTemporar // pussywizard: don't understand why whole skill is removed when just single spell from it is removed if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL && pSkill->categoryId != SKILL_CATEGORY_CLASS) || // pussywizard: don't unlearn class skills - ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0)) + ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0)) { // not reset skills for professions and racial abilities if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) && (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0)) @@ -4272,7 +4304,7 @@ bool Player::Has310Flyer(bool checkAllSpells, uint32 excludeSpellId) spellInfo = sSpellMgr->GetSpellInfo(itr->first); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED && - spellInfo->Effects[i].CalcValue() == 310) + spellInfo->Effects[i].CalcValue() == 310) { SetHas310Flyer(true); return true; @@ -4304,7 +4336,7 @@ void Player::RemoveCategoryCooldown(uint32 cat) void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns) { // remove cooldowns on spells that have < 10 min CD - uint32 infTime = World::GetGameTimeMS()+infinityCooldownDelayCheck; + uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; SpellCooldowns::iterator itr, next; for (itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); itr = next) { @@ -4317,7 +4349,7 @@ void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns) if (spellInfo->HasAttribute(SPELL_ATTR4_USABLE_IN_ARENA)) RemoveSpellCooldown(itr->first, true); else if (spellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS && spellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS && itr->second.end < infTime// xinef: dont remove active cooldowns - bugz - && itr->second.maxduration < 10 * MINUTE * IN_MILLISECONDS) // xinef: dont clear cooldowns that have maxduration > 10 minutes (eg item cooldowns with no spell.dbc cooldown info) + && itr->second.maxduration < 10 * MINUTE * IN_MILLISECONDS) // xinef: dont clear cooldowns that have maxduration > 10 minutes (eg item cooldowns with no spell.dbc cooldown info) RemoveSpellCooldown(itr->first, true); } @@ -4336,7 +4368,7 @@ void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns) void Player::RemoveAllSpellCooldown() { - uint32 infTime = World::GetGameTimeMS()+infinityCooldownDelayCheck; + uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; if (!m_spellCooldowns.empty()) { for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr) @@ -4375,13 +4407,12 @@ void Player::_LoadSpellCooldowns(PreparedQueryResult result) if (db_time <= curTime) continue; - AddSpellCooldown(spell_id, item_id, (db_time-curTime)*IN_MILLISECONDS, needSend); + AddSpellCooldown(spell_id, item_id, (db_time - curTime)*IN_MILLISECONDS, needSend); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime)); + sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time - curTime)); #endif - } - while (result->NextRow()); + } while (result->NextRow()); } } @@ -4408,9 +4439,9 @@ void Player::_SaveSpellCooldowns(SQLTransaction& trans, bool logout) continue; } - if (itr->second.end <= curMSTime+1000) + if (itr->second.end <= curMSTime + 1000) m_spellCooldowns.erase(itr++); - else if (itr->second.end <= infTime && (logout || itr->second.end > (curMSTime + 5*MINUTE*IN_MILLISECONDS))) // not save locked cooldowns, it will be reset or set at reload + else if (itr->second.end <= infTime && (logout || itr->second.end > (curMSTime + 5 * MINUTE * IN_MILLISECONDS))) // not save locked cooldowns, it will be reset or set at reload { if (first_round) { @@ -4436,31 +4467,31 @@ void Player::_SaveSpellCooldowns(SQLTransaction& trans, bool logout) uint32 Player::resetTalentsCost() const { // The first time reset costs 1 gold - if (m_resetTalentsCost < 1*GOLD) - return 1*GOLD; + if (m_resetTalentsCost < 1 * GOLD) + return 1 * GOLD; // then 5 gold - else if (m_resetTalentsCost < 5*GOLD) - return 5*GOLD; + else if (m_resetTalentsCost < 5 * GOLD) + return 5 * GOLD; // After that it increases in increments of 5 gold - else if (m_resetTalentsCost < 10*GOLD) - return 10*GOLD; + else if (m_resetTalentsCost < 10 * GOLD) + return 10 * GOLD; else { - uint64 months = (sWorld->GetGameTime() - m_resetTalentsTime)/MONTH; + uint64 months = (sWorld->GetGameTime() - m_resetTalentsTime) / MONTH; if (months > 0) { // This cost will be reduced by a rate of 5 gold per month - int32 new_cost = int32(m_resetTalentsCost - 5*GOLD*months); + int32 new_cost = int32(m_resetTalentsCost - 5 * GOLD * months); // to a minimum of 10 gold. - return (new_cost < 10*GOLD ? 10*GOLD : new_cost); + return (new_cost < 10 * GOLD ? 10 * GOLD : new_cost); } else { // After that it increases in increments of 5 gold - int32 new_cost = m_resetTalentsCost + 5*GOLD; + int32 new_cost = m_resetTalentsCost + 5 * GOLD; // until it hits a cap of 50 gold. - if (new_cost > 50*GOLD) - new_cost = 50*GOLD; + if (new_cost > 50 * GOLD) + new_cost = 50 * GOLD; return new_cost; } } @@ -4780,293 +4811,291 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC { // Completely remove from the database case CHAR_DELETE_REMOVE: - { - SQLTransaction trans = CharacterDatabase.BeginTransaction(); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL); - stmt->setUInt32(0, guid); - PreparedQueryResult resultMail = CharacterDatabase.Query(stmt); - - if (resultMail) { - do + SQLTransaction trans = CharacterDatabase.BeginTransaction(); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL); + stmt->setUInt32(0, guid); + PreparedQueryResult resultMail = CharacterDatabase.Query(stmt); + + if (resultMail) { - Field* mailFields = resultMail->Fetch(); - - uint32 mail_id = mailFields[0].GetUInt32(); - uint8 mailType = mailFields[1].GetUInt8(); - uint16 mailTemplateId= mailFields[2].GetUInt16(); - uint32 sender = mailFields[3].GetUInt32(); - std::string subject = mailFields[4].GetString(); - std::string body = mailFields[5].GetString(); - uint32 money = mailFields[6].GetUInt32(); - bool has_items = mailFields[7].GetBool(); - - // We can return mail now - // So firstly delete the old one - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID); - stmt->setUInt32(0, mail_id); - trans->Append(stmt); - - // Mail is not from player - if (mailType != MAIL_NORMAL) + do { + Field* mailFields = resultMail->Fetch(); + + uint32 mail_id = mailFields[0].GetUInt32(); + uint8 mailType = mailFields[1].GetUInt8(); + uint16 mailTemplateId = mailFields[2].GetUInt16(); + uint32 sender = mailFields[3].GetUInt32(); + std::string subject = mailFields[4].GetString(); + std::string body = mailFields[5].GetString(); + uint32 money = mailFields[6].GetUInt32(); + bool has_items = mailFields[7].GetBool(); + + // We can return mail now + // So firstly delete the old one + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID); + stmt->setUInt32(0, mail_id); + trans->Append(stmt); + + // Mail is not from player + if (mailType != MAIL_NORMAL) + { + if (has_items) + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID); + stmt->setUInt32(0, mail_id); + trans->Append(stmt); + } + continue; + } + + MailDraft draft(subject, body); + if (mailTemplateId) + draft = MailDraft(mailTemplateId, false); // items are already included + if (has_items) { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID); + // Data needs to be at first place for Item::LoadFromDB + stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS); stmt->setUInt32(0, mail_id); - trans->Append(stmt); - } - continue; - } - - MailDraft draft(subject, body); - if (mailTemplateId) - draft = MailDraft(mailTemplateId, false); // items are already included - - if (has_items) - { - // Data needs to be at first place for Item::LoadFromDB - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS); - stmt->setUInt32(0, mail_id); - PreparedQueryResult resultItems = CharacterDatabase.Query(stmt); - if (resultItems) - { - do + PreparedQueryResult resultItems = CharacterDatabase.Query(stmt); + if (resultItems) { - Field* itemFields = resultItems->Fetch(); - uint32 item_guidlow = itemFields[11].GetUInt32(); - uint32 item_template = itemFields[12].GetUInt32(); - - ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_template); - if (!itemProto) + do { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); - stmt->setUInt32(0, item_guidlow); - trans->Append(stmt); - continue; - } + Field* itemFields = resultItems->Fetch(); + uint32 item_guidlow = itemFields[11].GetUInt32(); + uint32 item_template = itemFields[12].GetUInt32(); - Item* pItem = NewItemOrBag(itemProto); - if (!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER), itemFields, item_template)) - { - pItem->FSetState(ITEM_REMOVED); - pItem->SaveToDB(trans); // it also deletes item object! - continue; - } + ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_template); + if (!itemProto) + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); + stmt->setUInt32(0, item_guidlow); + trans->Append(stmt); + continue; + } - draft.AddItem(pItem); + Item* pItem = NewItemOrBag(itemProto); + if (!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER), itemFields, item_template)) + { + pItem->FSetState(ITEM_REMOVED); + pItem->SaveToDB(trans); // it also deletes item object! + continue; + } + + draft.AddItem(pItem); + } while (resultItems->NextRow()); } - while (resultItems->NextRow()); } - } - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID); - stmt->setUInt32(0, mail_id); - trans->Append(stmt); + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID); + stmt->setUInt32(0, mail_id); + trans->Append(stmt); - uint32 pl_account = sObjectMgr->GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)); + uint32 pl_account = sObjectMgr->GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)); - draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender, trans); + draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender, trans); + } while (resultMail->NextRow()); } - while (resultMail->NextRow()); - } - // Unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet. - // NOW we can finally clear other DB data related to character - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PETS); - stmt->setUInt32(0, guid); - PreparedQueryResult resultPets = CharacterDatabase.Query(stmt); + // Unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet. + // NOW we can finally clear other DB data related to character + stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PETS); + stmt->setUInt32(0, guid); + PreparedQueryResult resultPets = CharacterDatabase.Query(stmt); - if (resultPets) - { - do + if (resultPets) { - uint32 petguidlow = (*resultPets)[0].GetUInt32(); - Pet::DeleteFromDB(petguidlow); - } while (resultPets->NextRow()); - } - - // Delete char from social list of online chars - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_SOCIAL); - stmt->setUInt32(0, guid); - PreparedQueryResult resultFriends = CharacterDatabase.Query(stmt); - - if (resultFriends) - { - do - { - if (Player* pFriend = ObjectAccessor::FindPlayerInOrOutOfWorld(MAKE_NEW_GUID((*resultFriends)[0].GetUInt32(), 0, HIGHGUID_PLAYER))) + do { - pFriend->GetSocial()->RemoveFromSocialList(guid, false); - sSocialMgr->SendFriendStatus(pFriend, FRIEND_REMOVED, guid, false); - } - } while (resultFriends->NextRow()); - } + uint32 petguidlow = (*resultPets)[0].GetUInt32(); + Pet::DeleteFromDB(petguidlow); + } while (resultPets->NextRow()); + } - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER); - stmt->setUInt32(0, guid); - trans->Append(stmt); + // Delete char from social list of online chars + stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_SOCIAL); + stmt->setUInt32(0, guid); + PreparedQueryResult resultFriends = CharacterDatabase.Query(stmt); - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA); - stmt->setUInt32(0, guid); - trans->Append(stmt); + if (resultFriends) + { + do + { + if (Player* pFriend = ObjectAccessor::FindPlayerInOrOutOfWorld(MAKE_NEW_GUID((*resultFriends)[0].GetUInt32(), 0, HIGHGUID_PLAYER))) + { + pFriend->GetSocial()->RemoveFromSocialList(guid, false); + sSocialMgr->SendFriendStatus(pFriend, FRIEND_REMOVED, guid, false); + } + } while (resultFriends->NextRow()); + } - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GIFT); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REPUTATION); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - if (sWorld->getBoolConfig(CONFIG_DELETE_CHARACTER_TICKET_TRACE)) - { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_GM_TICKETS_ON_CHAR_DELETION); + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER); stmt->setUInt32(0, guid); trans->Append(stmt); - } - else - { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_GM_TICKETS); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA); stmt->setUInt32(0, guid); trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GIFT); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REPUTATION); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + if (sWorld->getBoolConfig(CONFIG_DELETE_CHARACTER_TICKET_TRACE)) + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_GM_TICKETS_ON_CHAR_DELETION); + stmt->setUInt32(0, guid); + trans->Append(stmt); + } + else + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_GM_TICKETS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + } + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE_BY_OWNER); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEMS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_OWNER); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENTS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_EQUIPMENTSETS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER); + stmt->setUInt32(0, guid); + stmt->setUInt32(1, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ENTRY_POINT); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILLS); + stmt->setUInt32(0, guid); + trans->Append(stmt); + + CharacterDatabase.CommitTransaction(trans); + break; } - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE_BY_OWNER); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEMS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_OWNER); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENTS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_EQUIPMENTSETS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER); - stmt->setUInt32(0, guid); - stmt->setUInt32(1, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ENTRY_POINT); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILLS); - stmt->setUInt32(0, guid); - trans->Append(stmt); - - CharacterDatabase.CommitTransaction(trans); - break; - } // The character gets unlinked from the account, the name gets freed up and appears as deleted ingame case CHAR_DELETE_UNLINK: - { - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_DELETE_INFO); + { + stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_DELETE_INFO); - stmt->setUInt32(0, guid); + stmt->setUInt32(0, guid); - CharacterDatabase.Execute(stmt); - break; - } + CharacterDatabase.Execute(stmt); + break; + } default: sLog->outError("Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method); return; @@ -5101,13 +5130,12 @@ void Player::DeleteOldCharacters(uint32 keepDays) if (result) { - sLog->outString("Player::DeleteOldChars: Found " UI64FMTD " character(s) to delete", result->GetRowCount()); - do - { + sLog->outString("Player::DeleteOldChars: Found " UI64FMTD " character(s) to delete", result->GetRowCount()); + do + { Field* fields = result->Fetch(); Player::DeleteFromDB(fields[0].GetUInt32(), fields[1].GetUInt32(), true, true); - } - while (result->NextRow()); + } while (result->NextRow()); } } @@ -5116,10 +5144,18 @@ void Player::SetMovement(PlayerMovementType pType) WorldPacket data; switch (pType) { - case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break; - case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break; - case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break; - case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break; + case MOVE_ROOT: + data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size() + 4); + break; + case MOVE_UNROOT: + data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size() + 4); + break; + case MOVE_WATER_WALK: + data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size() + 4); + break; + case MOVE_LAND_WALK: + data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size() + 4); + break; default: sLog->outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.", pType); return; @@ -5192,7 +5228,7 @@ void Player::BuildPlayerRepop() void Player::ResurrectPlayer(float restore_percent, bool applySickness) { - WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position + WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4 * 4); // remove spirit healer position data << uint32(-1); data << float(0); data << float(0); @@ -5256,13 +5292,13 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) CastSpell(this, 15007, true); // not full duration - if (int32(getLevel()) < startLevel+9) + if (int32(getLevel()) < startLevel + 9) { - int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE; + int32 delta = (int32(getLevel()) - startLevel + 1) * MINUTE; if (Aura* aur = GetAura(15007, GetGUID())) { - aur->SetDuration(delta*IN_MILLISECONDS); + aur->SetDuration(delta * IN_MILLISECONDS); } } } @@ -5434,7 +5470,7 @@ void Player::DurabilityLoss(Item* item, double percent) if (!pMaxDurability) return; - uint32 pDurabilityLoss = uint32(pMaxDurability*percent); + uint32 pDurabilityLoss = uint32(pMaxDurability * percent); if (pDurabilityLoss < 1) pDurabilityLoss = 1; @@ -5534,7 +5570,7 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g if (cost) { uint32 LostDurability = maxDurability - curDurability; - if (LostDurability>0) + if (LostDurability > 0) { ItemTemplate const* ditemProto = item->GetTemplate(); @@ -5545,7 +5581,7 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g return TotalCost; } - uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2; + uint32 dQualitymodEntryId = (ditemProto->Quality + 1) * 2; DurabilityQualityEntry const* dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId); if (!dQualitymodEntry) { @@ -5554,7 +5590,7 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g } uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class, ditemProto->SubClass)]; - uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod)); + uint32 costs = uint32(LostDurability * dmultiplier * double(dQualitymodEntry->quality_mod)); costs = uint32(costs * discountMod * sWorld->getRate(RATE_REPAIRCOST)); @@ -5639,7 +5675,7 @@ void Player::RepopAtGraveyard() TeleportTo(ClosestGrave->Map, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation()); if (isDead()) // not send if alive, because it used in TeleportTo() { - WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap + WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4 * 4); // show spirit healer position on minimap data << ClosestGrave->Map; data << ClosestGrave->x; data << ClosestGrave->y; @@ -5812,11 +5848,20 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa switch (modGroup) { - case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break; - case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break; - case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break; - case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break; - default: break; + case CRIT_PERCENTAGE: + UpdateCritPercentage(BASE_ATTACK); + break; + case RANGED_CRIT_PERCENTAGE: + UpdateCritPercentage(RANGED_ATTACK); + break; + case OFFHAND_CRIT_PERCENTAGE: + UpdateCritPercentage(OFF_ATTACK); + break; + case SHIELD_BLOCK_VALUE: + UpdateShieldBlockValue(); + break; + default: + break; } } @@ -5850,7 +5895,7 @@ float Player::GetTotalBaseModValue(BaseModGroup modGroup) const uint32 Player::GetShieldBlockValue() const { - float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD]; + float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10) * m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD]; value = (value < 0) ? 0 : value; @@ -5865,46 +5910,46 @@ float Player::GetMeleeCritFromAgility() if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; - GtChanceToMeleeCritBaseEntry const* critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1); - GtChanceToMeleeCritEntry const* critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); + GtChanceToMeleeCritBaseEntry const* critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass - 1); + GtChanceToMeleeCritEntry const* critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1); if (critBase == NULL || critRatio == nullptr) return 0.0f; - float crit = critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio; - return crit*100.0f; + float crit = critBase->base + GetStat(STAT_AGILITY) * critRatio->ratio; + return crit * 100.0f; } -void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) +void Player::GetDodgeFromAgility(float& diminishing, float& nondiminishing) { // Table for base dodge values const float dodge_base[MAX_CLASSES] = { - 0.036640f, // Warrior - 0.034943f, // Paladi + 0.036640f, // Warrior + 0.034943f, // Paladi -0.040873f, // Hunter - 0.020957f, // Rogue - 0.034178f, // Priest - 0.036640f, // DK - 0.021080f, // Shaman - 0.036587f, // Mage - 0.024211f, // Warlock - 0.0f, // ?? - 0.056097f // Druid + 0.020957f, // Rogue + 0.034178f, // Priest + 0.036640f, // DK + 0.021080f, // Shaman + 0.036587f, // Mage + 0.024211f, // Warlock + 0.0f, // ?? + 0.056097f // Druid }; // Crit/agility to dodge/agility coefficient multipliers; 3.2.0 increased required agility by 15% const float crit_to_dodge[MAX_CLASSES] = { - 0.85f/1.15f, // Warrior - 1.00f/1.15f, // Paladin - 1.11f/1.15f, // Hunter - 2.00f/1.15f, // Rogue - 1.00f/1.15f, // Priest - 0.85f/1.15f, // DK - 1.60f/1.15f, // Shaman - 1.00f/1.15f, // Mage - 0.97f/1.15f, // Warlock (?) - 0.0f, // ?? - 2.00f/1.15f // Druid + 0.85f / 1.15f, // Warrior + 1.00f / 1.15f, // Paladin + 1.11f / 1.15f, // Hunter + 2.00f / 1.15f, // Rogue + 1.00f / 1.15f, // Priest + 0.85f / 1.15f, // DK + 1.60f / 1.15f, // Shaman + 1.00f / 1.15f, // Mage + 0.97f / 1.15f, // Warlock (?) + 0.0f, // ?? + 2.00f / 1.15f // Druid }; uint8 level = getLevel(); @@ -5914,7 +5959,7 @@ void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) level = GT_MAX_LEVEL; // Dodge per agility is proportional to crit per agility, which is available from DBC files - GtChanceToMeleeCritEntry const* dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); + GtChanceToMeleeCritEntry const* dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1); if (dodgeRatio == NULL || pclass > MAX_CLASSES) return; @@ -5923,8 +5968,8 @@ void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) float bonus_agility = GetStat(STAT_AGILITY) - base_agility; // calculate diminishing (green in char screen) and non-diminishing (white) contribution - diminishing = 100.0f * bonus_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]; - nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]); + diminishing = 100.0f * bonus_agility * dodgeRatio->ratio * crit_to_dodge[pclass - 1]; + nondiminishing = 100.0f * (dodge_base[pclass - 1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass - 1]); } float Player::GetSpellCritFromIntellect() @@ -5935,13 +5980,13 @@ float Player::GetSpellCritFromIntellect() if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; - GtChanceToSpellCritBaseEntry const* critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1); - GtChanceToSpellCritEntry const* critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); + GtChanceToSpellCritBaseEntry const* critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass - 1); + GtChanceToSpellCritEntry const* critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1); if (critBase == NULL || critRatio == nullptr) return 0.0f; - float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio; - return crit*100.0f; + float crit = critBase->base + GetStat(STAT_INTELLECT) * critRatio->ratio; + return crit * 100.0f; } float Player::GetRatingMultiplier(CombatRating cr) const @@ -5951,9 +5996,9 @@ float Player::GetRatingMultiplier(CombatRating cr) const if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; - GtCombatRatingsEntry const* Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1); + GtCombatRatingsEntry const* Rating = sGtCombatRatingsStore.LookupEntry(cr * GT_MAX_LEVEL + level - 1); // gtOCTClassCombatRatingScalarStore.dbc starts with 1, CombatRating with zero, so cr+1 - GtOCTClassCombatRatingScalarEntry const* classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((getClass()-1)*GT_MAX_RATING+cr+1); + GtOCTClassCombatRatingScalarEntry const* classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((getClass() - 1) * GT_MAX_RATING + cr + 1); if (!Rating || !classRating) return 1.0f; // By default use minimum coefficient (not must be called) @@ -5987,8 +6032,8 @@ float Player::OCTRegenHPPerSpirit() if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; - GtOCTRegenHPEntry const* baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - GtRegenHPPerSptEntry const* moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); + GtOCTRegenHPEntry const* baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1); + GtRegenHPPerSptEntry const* moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1); if (baseRatio == NULL || moreRatio == nullptr) return 0.0f; @@ -6010,8 +6055,8 @@ float Player::OCTRegenMPPerSpirit() if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; -// GtOCTRegenMPEntry const* baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - GtRegenMPPerSptEntry const* moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); + // GtOCTRegenMPEntry const* baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); + GtRegenMPPerSptEntry const* moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1); if (moreRatio == nullptr) return 0.0f; @@ -6062,7 +6107,7 @@ void Player::UpdateRating(CombatRating cr) // stat used stored in miscValueB for this aura AuraEffectList const& modRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT); for (AuraEffectList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i) - if ((*i)->GetMiscValue() & (1<GetMiscValue() & (1 << cr)) amount += int32(CalculatePct(GetStat(Stats((*i)->GetMiscValueB())), (*i)->GetAmount())); if (amount < 0) amount = 0; @@ -6186,7 +6231,7 @@ bool Player::UpdateSkill(uint32 skill_id, uint32 step) if (value < max) { - uint32 new_value = value+step; + uint32 new_value = value + step; if (new_value > max) new_value = max; @@ -6204,12 +6249,12 @@ bool Player::UpdateSkill(uint32 skill_id, uint32 step) inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel) { if (SkillValue >= GrayLevel) - return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREY)*10; + return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREY) * 10; if (SkillValue >= GreenLevel) - return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREEN)*10; + return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREEN) * 10; if (SkillValue >= YellowLevel) - return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_YELLOW)*10; - return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_ORANGE)*10; + return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_YELLOW) * 10; + return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_ORANGE) * 10; } bool Player::UpdateCraftSkill(uint32 spellid) @@ -6237,10 +6282,10 @@ bool Player::UpdateCraftSkill(uint32 spellid) uint32 craft_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_CRAFTING); return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue, - _spell_idx->second->max_value, - (_spell_idx->second->max_value + _spell_idx->second->min_value)/2, - _spell_idx->second->min_value), - craft_skill_gain); + _spell_idx->second->max_value, + (_spell_idx->second->max_value + _spell_idx->second->min_value) / 2, + _spell_idx->second->min_value), + craft_skill_gain); } } return false; @@ -6261,17 +6306,17 @@ bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLeve case SKILL_LOCKPICKING: case SKILL_JEWELCRAFTING: case SKILL_INSCRIPTION: - return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain); + return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel + 100, RedLevel + 50, RedLevel + 25) * Multiplicator, gathering_skill_gain); case SKILL_SKINNING: if (sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS) == 0) - return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain); + return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel + 100, RedLevel + 50, RedLevel + 25) * Multiplicator, gathering_skill_gain); else - return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain); + return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel + 100, RedLevel + 50, RedLevel + 25) * Multiplicator) >> (SkillValue / sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain); case SKILL_MINING: if (sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS) == 0) - return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain); + return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel + 100, RedLevel + 50, RedLevel + 25) * Multiplicator, gathering_skill_gain); else - return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)), gathering_skill_gain); + return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel + 100, RedLevel + 50, RedLevel + 25) * Multiplicator) >> (SkillValue / sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)), gathering_skill_gain); } return false; } @@ -6284,11 +6329,11 @@ bool Player::UpdateFishingSkill() uint32 SkillValue = GetPureSkillValue(SKILL_FISHING); - int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50); + int32 chance = SkillValue < 75 ? 100 : 2500 / (SkillValue - 50); uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING); - return UpdateSkillPro(SKILL_FISHING, chance*10, gathering_skill_gain); + return UpdateSkillPro(SKILL_FISHING, chance * 10, gathering_skill_gain); } // levels sync. with spell requirement for skill levels to learn @@ -6330,7 +6375,7 @@ bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) if (Roll <= Chance) { - uint32 new_value = SkillValue+step; + uint32 new_value = SkillValue + step; if (new_value > MaxValue) new_value = MaxValue; @@ -6438,9 +6483,9 @@ void Player::ModifySkillBonus(uint32 skillid, int32 val, bool talent) int16 perm_bonus = SKILL_PERM_BONUS(bonus_val); if (talent) // permanent bonus stored in high part - SetUInt32Value(bonusIndex, MAKE_SKILL_BONUS(temp_bonus, perm_bonus+val)); + SetUInt32Value(bonusIndex, MAKE_SKILL_BONUS(temp_bonus, perm_bonus + val)); else // temporary/item bonus stored in low part - SetUInt32Value(bonusIndex, MAKE_SKILL_BONUS(temp_bonus+val, perm_bonus)); + SetUInt32Value(bonusIndex, MAKE_SKILL_BONUS(temp_bonus + val, perm_bonus)); } void Player::UpdateSkillsForLevel() @@ -6570,50 +6615,50 @@ void Player::SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal) else if (newVal) //add { currVal = 0; - for (int i=0; i < PLAYER_MAX_SKILLS; ++i) + for (int i = 0; i < PLAYER_MAX_SKILLS; ++i) if (!GetUInt32Value(PLAYER_SKILL_INDEX(i))) - { - SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(id); - if (!pSkill) { - sLog->outError("Skill not found in SkillLineStore: skill #%u", id); + SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(id); + if (!pSkill) + { + sLog->outError("Skill not found in SkillLineStore: skill #%u", id); + return; + } + + SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step)); + SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i), MAKE_SKILL_VALUE(newVal, maxVal)); + UpdateSkillEnchantments(id, currVal, newVal); + + // insert new entry or update if not deleted old entry yet + if (itr != mSkillStatus.end()) + { + itr->second.pos = i; + itr->second.uState = SKILL_CHANGED; + } + else + mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW))); + + // apply skill bonuses + SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i), 0); + + // temporary bonuses + AuraEffectList const& mModSkill = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL); + for (AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j) + if ((*j)->GetMiscValue() == int32(id)) + (*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true); + + // permanent bonuses + AuraEffectList const& mModSkillTalent = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL_TALENT); + for (AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j) + if ((*j)->GetMiscValue() == int32(id)) + (*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true); + + // Learn all spells for skill + learnSkillRewardedSpells(id, newVal); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id); return; } - - SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step)); - SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i), MAKE_SKILL_VALUE(newVal, maxVal)); - UpdateSkillEnchantments(id, currVal, newVal); - - // insert new entry or update if not deleted old entry yet - if (itr != mSkillStatus.end()) - { - itr->second.pos = i; - itr->second.uState = SKILL_CHANGED; - } - else - mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW))); - - // apply skill bonuses - SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i), 0); - - // temporary bonuses - AuraEffectList const& mModSkill = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL); - for (AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j) - if ((*j)->GetMiscValue() == int32(id)) - (*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true); - - // permanent bonuses - AuraEffectList const& mModSkillTalent = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL_TALENT); - for (AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j) - if ((*j)->GetMiscValue() == int32(id)) - (*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true); - - // Learn all spells for skill - learnSkillRewardedSpells(id, newVal); - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id); - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id); - return; - } } } @@ -6740,7 +6785,7 @@ void Player::SendActionButtons(uint32 state) const sLog->outDetail("Sending Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec); #endif - WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4)); + WorldPacket data(SMSG_ACTION_BUTTONS, 1 + (MAX_ACTION_BUTTONS * 4)); data << uint8(state); /* state can be 0, 1, 2 @@ -6940,8 +6985,8 @@ void Player::CheckAreaExploreAndOutdoor() if (!areaEntry) { - sLog->outError("Player '%s' (%u) discovered unknown area (x: %f y: %f z: %f map: %u)", - GetName().c_str(), GetGUIDLow(), GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId()); + sLog->outError("Player '%s' (%u) discovered unknown area (x: %f y: %f z: %f map: %u)", + GetName().c_str(), GetGUIDLow(), GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId()); return; } @@ -6976,21 +7021,21 @@ void Player::CheckAreaExploreAndOutdoor() uint32 XP = 0; if (diff < -5) { - XP = uint32(sObjectMgr->GetBaseXP(getLevel()+5)*sWorld->getRate(RATE_XP_EXPLORE)); + XP = uint32(sObjectMgr->GetBaseXP(getLevel() + 5) * sWorld->getRate(RATE_XP_EXPLORE)); } else if (diff > 5) { - int32 exploration_percent = (100-((diff-5)*5)); + int32 exploration_percent = (100 - ((diff - 5) * 5)); if (exploration_percent > 100) exploration_percent = 100; else if (exploration_percent < 0) exploration_percent = 0; - XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level)*exploration_percent/100*sWorld->getRate(RATE_XP_EXPLORE)); + XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level) * exploration_percent / 100 * sWorld->getRate(RATE_XP_EXPLORE)); } else { - XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level)*sWorld->getRate(RATE_XP_EXPLORE)); + XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level) * sWorld->getRate(RATE_XP_EXPLORE)); } GiveXP(XP, nullptr); @@ -7009,8 +7054,10 @@ TeamId Player::TeamIdForRace(uint8 race) { switch (rEntry->TeamID) { - case 1: return TEAM_HORDE; - case 7: return TEAM_ALLIANCE; + case 1: + return TEAM_HORDE; + case 7: + return TEAM_ALLIANCE; } sLog->outError("Race (%u) has wrong teamid (%u) in DBC: wrong DBC files?", uint32(race), rEntry->TeamID); } @@ -7370,7 +7417,7 @@ bool Player::RewardHonor(Unit* uVictim, uint32 groupsize, int32 honor, bool awar // victim_rank [1..4] HK: // victim_rank [5..19] HK: // victim_rank [0, 20+] HK: <> - WorldPacket data(SMSG_PVP_CREDIT, 4+8+4); + WorldPacket data(SMSG_PVP_CREDIT, 4 + 8 + 4); data << honor; data << victim_guid; data << victim_rank; @@ -7391,7 +7438,7 @@ bool Player::RewardHonor(Unit* uVictim, uint32 groupsize, int32 honor, bool awar bg->UpdatePlayerScore(this, SCORE_BONUS_HONOR, honor, false); //false: prevent looping // Xinef: Only for BG activities if (!uVictim) - GiveXP(uint32(honor*(3+getLevel()*0.30f)), nullptr); + GiveXP(uint32(honor * (3 + getLevel() * 0.30f)), nullptr); } if (sWorld->getBoolConfig(CONFIG_PVP_TOKEN_ENABLE)) @@ -7404,8 +7451,8 @@ bool Player::RewardHonor(Unit* uVictim, uint32 groupsize, int32 honor, bool awar // Check if allowed to receive it in current map uint8 MapType = sWorld->getIntConfig(CONFIG_PVP_TOKEN_MAP_TYPE); if ((MapType == 1 && !InBattleground() && !IsFFAPvP()) - || (MapType == 2 && !IsFFAPvP()) - || (MapType == 3 && !InBattleground())) + || (MapType == 2 && !IsFFAPvP()) + || (MapType == 3 && !InBattleground())) return true; uint32 itemID = sWorld->getIntConfig(CONFIG_PVP_TOKEN_ID); @@ -7785,7 +7832,7 @@ void Player::CheckDuelDistance(time_t currTime) WorldPacket data(SMSG_DUEL_INBOUNDS, 0); GetSession()->SendPacket(&data); } - else if (currTime >= (duel->outOfBound+10)) + else if (currTime >= (duel->outOfBound + 10)) DuelComplete(DUEL_FLED); } } @@ -7813,7 +7860,7 @@ void Player::DuelComplete(DuelCompleteType type) if (type != DUEL_INTERRUPTED) { - data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size + data.Initialize(SMSG_DUEL_WINNER, (1 + 20)); // we guess size data << uint8(type == DUEL_WON ? 0 : 1); // 0 = just won; 1 = fled data << duel->opponent->GetName(); data << GetName(); @@ -7867,7 +7914,7 @@ void Player::DuelComplete(DuelCompleteType type) duel->initiator->RemoveGameObject(obj, true); /* remove auras */ - AuraApplicationMap &itsAuras = duel->opponent->GetAppliedAuras(); + AuraApplicationMap& itsAuras = duel->opponent->GetAppliedAuras(); for (AuraApplicationMap::iterator i = itsAuras.begin(); i != itsAuras.end();) { Aura const* aura = i->second->GetBase(); @@ -7877,7 +7924,7 @@ void Player::DuelComplete(DuelCompleteType type) ++i; } - AuraApplicationMap &myAuras = GetAppliedAuras(); + AuraApplicationMap& myAuras = GetAppliedAuras(); for (AuraApplicationMap::iterator i = myAuras.begin(); i != myAuras.end();) { Aura const* aura = i->second->GetBase(); @@ -8113,9 +8160,9 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply case ITEM_MOD_RANGED_ATTACK_POWER: HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply); break; -// case ITEM_MOD_FERAL_ATTACK_POWER: -// ApplyFeralAPBonus(int32(val), apply); -// break; + // case ITEM_MOD_FERAL_ATTACK_POWER: + // ApplyFeralAPBonus(int32(val), apply); + // break; case ITEM_MOD_MANA_REGENERATION: ApplyManaRegenBonus(int32(val), apply); break; @@ -8169,7 +8216,7 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply case ITEM_SUBCLASS_ARMOR_PLATE: case ITEM_SUBCLASS_ARMOR_SHIELD: modType = BASE_VALUE; - break; + break; } } HandleStatModifier(UNIT_MOD_ARMOR, modType, float(armor), apply); @@ -8203,8 +8250,8 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply WeaponAttackType attType = BASE_ATTACK; if (slot == EQUIPMENT_SLOT_RANGED && ( - proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN || - proto->InventoryType == INVTYPE_RANGEDRIGHT)) + proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN || + proto->InventoryType == INVTYPE_RANGEDRIGHT)) { attType = RANGED_ATTACK; } @@ -8240,8 +8287,8 @@ void Player::_ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, ScalingSt float damage = 0.0f; if (slot == EQUIPMENT_SLOT_RANGED && ( - proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN || - proto->InventoryType == INVTYPE_RANGEDRIGHT)) + proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN || + proto->InventoryType == INVTYPE_RANGEDRIGHT)) { attType = RANGED_ATTACK; } @@ -8280,11 +8327,11 @@ void Player::_ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, ScalingSt if (proto->Delay && !IsInFeralForm()) { if (slot == EQUIPMENT_SLOT_RANGED) - SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); + SetAttackTime(RANGED_ATTACK, apply ? proto->Delay : BASE_ATTACK_TIME); else if (slot == EQUIPMENT_SLOT_MAINHAND) - SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); + SetAttackTime(BASE_ATTACK, apply ? proto->Delay : BASE_ATTACK_TIME); else if (slot == EQUIPMENT_SLOT_OFFHAND) - SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME); + SetAttackTime(OFF_ATTACK, apply ? proto->Delay : BASE_ATTACK_TIME); } // No need to modify any physical damage for ferals as it is calculated from stats only @@ -8323,10 +8370,17 @@ void Player::_ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attac BaseModGroup mod = BASEMOD_END; switch (attackType) { - case BASE_ATTACK: mod = CRIT_PERCENTAGE; break; - case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break; - case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break; - default: return; + case BASE_ATTACK: + mod = CRIT_PERCENTAGE; + break; + case OFF_ATTACK: + mod = OFFHAND_CRIT_PERCENTAGE; + break; + case RANGED_ATTACK: + mod = RANGED_CRIT_PERCENTAGE; + break; + default: + return; } if (item->IsFitToSpellRequirements(aura->GetSpellInfo())) @@ -8350,18 +8404,30 @@ void Player::_ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType att UnitMods unitMod = UNIT_MOD_END; switch (attackType) { - case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; - case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break; - case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break; - default: return; + case BASE_ATTACK: + unitMod = UNIT_MOD_DAMAGE_MAINHAND; + break; + case OFF_ATTACK: + unitMod = UNIT_MOD_DAMAGE_OFFHAND; + break; + case RANGED_ATTACK: + unitMod = UNIT_MOD_DAMAGE_RANGED; + break; + default: + return; } UnitModifierType unitModType = TOTAL_VALUE; switch (aura->GetAuraType()) { - case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break; - case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break; - default: return; + case SPELL_AURA_MOD_DAMAGE_DONE: + unitModType = TOTAL_VALUE; + break; + case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: + unitModType = TOTAL_PCT; + break; + default: + return; } if (item->IsFitToSpellRequirements(aura->GetSpellInfo())) @@ -8510,10 +8576,18 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 EquipmentSlots slot; switch (attType) { - case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break; - case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break; - case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break; - default: slot = EQUIPMENT_SLOT_END; break; + case BASE_ATTACK: + slot = EQUIPMENT_SLOT_MAINHAND; + break; + case OFF_ATTACK: + slot = EQUIPMENT_SLOT_OFFHAND; + break; + case RANGED_ATTACK: + slot = EQUIPMENT_SLOT_RANGED; + break; + default: + slot = EQUIPMENT_SLOT_END; + break; } if (slot != i) continue; @@ -8528,7 +8602,7 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 { // Can do effect if any damage done to target if (procVictim & PROC_FLAG_TAKEN_DAMAGE) - //if (damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE) + //if (damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE) { for (uint8 i = 0; i < MAX_ITEM_SPELLS; ++i) { @@ -8567,7 +8641,7 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 } if (roll_chance_f(chance) && sScriptMgr->OnCastItemCombatSpell(this, target, spellInfo, item)) - CastSpell(target, spellInfo->Id, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD), item); + CastSpell(target, spellInfo->Id, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD), item); } } @@ -8596,7 +8670,7 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 { // Can do effect if any damage done to target if (!(procVictim & PROC_FLAG_TAKEN_DAMAGE)) - //if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)) + //if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)) continue; } @@ -8604,7 +8678,7 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 if (!spellInfo) { sLog->outError("Player::CastItemCombatSpell(GUID: %u, name: %s, enchant: %i): unknown spell %i is casted, ignoring...", - GetGUIDLow(), GetName().c_str(), pEnchant->ID, pEnchant->spellid[s]); + GetGUIDLow(), GetName().c_str(), pEnchant->ID, pEnchant->spellid[s]); continue; } @@ -8640,9 +8714,9 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 } if (spellInfo->IsPositive()) - CastSpell(this, spellInfo, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD), item); + CastSpell(this, spellInfo, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD), item); else - CastSpell(target, spellInfo, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD), item); + CastSpell(target, spellInfo, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD), item); } } } @@ -8988,7 +9062,7 @@ void Player::RemovedInsignia(Player* looterPlr) void Player::SendLootRelease(uint64 guid) { - WorldPacket data(SMSG_LOOT_RELEASE_RESPONSE, (8+1)); + WorldPacket data(SMSG_LOOT_RELEASE_RESPONSE, (8 + 1)); data << uint64(guid) << uint8(1); SendDirectMessage(&data); } @@ -9024,7 +9098,7 @@ void Player::SendLoot(uint64 guid, LootType loot_type) // Xinef: loot was generated and respawntime has passed since then, allow to recreate loot // Xinef: to avoid bugs, this rule covers spawned gameobjects only - if (go->isSpawnedByDefault() && go->getLootState() == GO_ACTIVATED && !go->loot.isLooted() && go->GetLootGenerationTime()+go->GetRespawnDelay() < time(nullptr)) + if (go->isSpawnedByDefault() && go->getLootState() == GO_ACTIVATED && !go->loot.isLooted() && go->GetLootGenerationTime() + go->GetRespawnDelay() < time(nullptr)) go->SetLootState(GO_READY); if (go->getLootState() == GO_READY) @@ -9191,7 +9265,7 @@ void Player::SendLoot(uint64 guid, LootType loot_type) // It may need a better formula // Now it works like this: lvl10: ~6copper, lvl70: ~9silver - bones->loot.gold = uint32(urand(50, 150) * 0.016f * pow(float(pLevel)/5.76f, 2.5f) * sWorld->getRate(RATE_DROP_MONEY)); + bones->loot.gold = uint32(urand(50, 150) * 0.016f * pow(float(pLevel) / 5.76f, 2.5f) * sWorld->getRate(RATE_DROP_MONEY)); } if (bones->lootRecipient != this) @@ -9231,8 +9305,8 @@ void Player::SendLoot(uint64 guid, LootType loot_type) loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, true); // Generate extra money for pick pocket loot - const uint32 a = urand(0, creature->getLevel()/2); - const uint32 b = urand(0, getLevel()/2); + const uint32 a = urand(0, creature->getLevel() / 2); + const uint32 b = urand(0, getLevel() / 2); loot->gold = uint32(10 * (a + b) * sWorld->getRate(RATE_DROP_MONEY)); permission = OWNER_PERMISSION; } @@ -9340,10 +9414,17 @@ void Player::SendLoot(uint64 guid, LootType loot_type) // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client switch (loot_type) { - case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break; - case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break; - case LOOT_FISHING_JUNK: loot_type = LOOT_FISHING; break; - default: break; + case LOOT_INSIGNIA: + loot_type = LOOT_SKINNING; + break; + case LOOT_FISHINGHOLE: + loot_type = LOOT_FISHING; + break; + case LOOT_FISHING_JUNK: + loot_type = LOOT_FISHING; + break; + default: + break; } // need know merged fishing/corpse loot type for achievements @@ -9353,7 +9434,7 @@ void Player::SendLoot(uint64 guid, LootType loot_type) { SetLootGUID(guid); - WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size + WorldPacket data(SMSG_LOOT_RESPONSE, (9 + 50)); // we guess size data << uint64(guid); data << uint8(loot_type); data << LootView(*loot, this, permission); @@ -9413,7 +9494,7 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) sLog->outDebug(LOG_FILTER_NETWORKIO, "Sending SMSG_INIT_WORLD_STATES to Map: %u, Zone: %u", mapid, zoneid); #endif - WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(12*8))); + WorldPacket data(SMSG_INIT_WORLD_STATES, (4 + 4 + 4 + 2 + (12 * 8))); data << uint32(mapid); // mapid data << uint32(zoneid); // zone id data << uint32(areaid); // area id, new 2.1.0 @@ -9425,9 +9506,9 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) data << uint32(0x8d5) << uint32(0x0); // 4 data << uint32(0x8d4) << uint32(0x0); // 5 data << uint32(0x8d3) << uint32(0x0); // 6 - // 7 1 - Arena season in progress, 0 - end of season + // 7 1 - Arena season in progress, 0 - end of season data << uint32(0xC77) << uint32(sWorld->getBoolConfig(CONFIG_ARENA_SEASON_IN_PROGRESS)); - // 8 Arena season id + // 8 Arena season id data << uint32(0xF3D) << uint32(sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID)); if (mapid == 530) // Outland @@ -10084,7 +10165,7 @@ uint32 Player::GetXPRestBonus(uint32 xp) SetRestBonus(GetRestBonus() - rested_bonus); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f", xp+rested_bonus, rested_bonus, GetRestBonus()); + sLog->outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f", xp + rested_bonus, rested_bonus, GetRestBonus()); #endif return rested_bonus; } @@ -10098,7 +10179,7 @@ void Player::SetBindPoint(uint64 guid) void Player::SendTalentWipeConfirm(uint64 guid) { - WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4)); + WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8 + 4)); data << uint64(guid); uint32 cost = sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : resetTalentsCost(); data << cost; @@ -10139,7 +10220,7 @@ void Player::SetVirtualItemSlot(uint8 i, Item* item) if (charges == 0) return; if (charges > 1) - item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT, charges-1); + item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT, charges - 1); else if (charges <= 1) { ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false); @@ -10230,15 +10311,15 @@ uint8 Player::FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) c slots[0] = EQUIPMENT_SLOT_BACK; break; case INVTYPE_WEAPON: - { - slots[0] = EQUIPMENT_SLOT_MAINHAND; + { + slots[0] = EQUIPMENT_SLOT_MAINHAND; - // suggest offhand slot only if know dual wielding - // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ... - if (CanDualWield()) - slots[1] = EQUIPMENT_SLOT_OFFHAND; - break; - } + // suggest offhand slot only if know dual wielding + // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ... + if (CanDualWield()) + slots[1] = EQUIPMENT_SLOT_OFFHAND; + break; + } case INVTYPE_SHIELD: case INVTYPE_WEAPONOFFHAND: case INVTYPE_HOLDABLE: @@ -10287,32 +10368,32 @@ uint8 Player::FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) c slots[3] = INVENTORY_SLOT_BAG_START + 3; break; case INVTYPE_RELIC: - { - switch (proto->SubClass) { - case ITEM_SUBCLASS_ARMOR_LIBRAM: - if (playerClass == CLASS_PALADIN) - slots[0] = EQUIPMENT_SLOT_RANGED; - break; - case ITEM_SUBCLASS_ARMOR_IDOL: - if (playerClass == CLASS_DRUID) - slots[0] = EQUIPMENT_SLOT_RANGED; - break; - case ITEM_SUBCLASS_ARMOR_TOTEM: - if (playerClass == CLASS_SHAMAN) - slots[0] = EQUIPMENT_SLOT_RANGED; - break; - case ITEM_SUBCLASS_ARMOR_MISC: - if (playerClass == CLASS_WARLOCK) - slots[0] = EQUIPMENT_SLOT_RANGED; - break; - case ITEM_SUBCLASS_ARMOR_SIGIL: - if (playerClass == CLASS_DEATH_KNIGHT) - slots[0] = EQUIPMENT_SLOT_RANGED; - break; + switch (proto->SubClass) + { + case ITEM_SUBCLASS_ARMOR_LIBRAM: + if (playerClass == CLASS_PALADIN) + slots[0] = EQUIPMENT_SLOT_RANGED; + break; + case ITEM_SUBCLASS_ARMOR_IDOL: + if (playerClass == CLASS_DRUID) + slots[0] = EQUIPMENT_SLOT_RANGED; + break; + case ITEM_SUBCLASS_ARMOR_TOTEM: + if (playerClass == CLASS_SHAMAN) + slots[0] = EQUIPMENT_SLOT_RANGED; + break; + case ITEM_SUBCLASS_ARMOR_MISC: + if (playerClass == CLASS_WARLOCK) + slots[0] = EQUIPMENT_SLOT_RANGED; + break; + case ITEM_SUBCLASS_ARMOR_SIGIL: + if (playerClass == CLASS_DEATH_KNIGHT) + slots[0] = EQUIPMENT_SLOT_RANGED; + break; + } + break; } - break; - } default: return NULL_SLOT; } @@ -10530,7 +10611,7 @@ Item* Player::GetItemByPos(uint8 bag, uint8 slot) const Bag* Player::GetBagByPos(uint8 bag) const { if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END) - || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END)) + || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END)) if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, bag)) return item->ToBag(); return nullptr; @@ -10541,10 +10622,17 @@ Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= f uint8 slot; switch (attackType) { - case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break; - case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break; - case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break; - default: return nullptr; + case BASE_ATTACK: + slot = EQUIPMENT_SLOT_MAINHAND; + break; + case OFF_ATTACK: + slot = EQUIPMENT_SLOT_OFFHAND; + break; + case RANGED_ATTACK: + slot = EQUIPMENT_SLOT_RANGED; + break; + default: + return nullptr; } Item* item = nullptr; @@ -10587,10 +10675,14 @@ uint8 Player::GetAttackBySlot(uint8 slot) { switch (slot) { - case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK; - case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK; - case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK; - default: return MAX_ATTACK; + case EQUIPMENT_SLOT_MAINHAND: + return BASE_ATTACK; + case EQUIPMENT_SLOT_OFFHAND: + return OFF_ATTACK; + case EQUIPMENT_SLOT_RANGED: + return RANGED_ATTACK; + default: + return MAX_ATTACK; } } @@ -10949,7 +11041,7 @@ bool Player::IsTotemCategoryCompatiableWith(const ItemTemplate* pProto, uint32 r return true; } -InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const +InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const { Item* pItem2 = GetItemByPos(bag, slot); @@ -10968,7 +11060,7 @@ InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemP if (bag == INVENTORY_SLOT_BAG_0) { // keyring case - if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)) + if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START + GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // currencytoken case @@ -11023,7 +11115,7 @@ InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemP return EQUIP_ERR_OK; } -InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const +InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const { // skip specific bag already processed in first called CanStoreItem_InBag if (bag == skip_bag) @@ -11086,14 +11178,14 @@ InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, Ite dest.push_back(newPosition); count -= need_space; - if (count==0) + if (count == 0) return EQUIP_ERR_OK; } } return EQUIP_ERR_OK; } -InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const +InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const { //this is never called for non-bag slots so we can do this if (pSrcItem && pSrcItem->IsNotEmptyBag()) @@ -11137,14 +11229,14 @@ InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 sl dest.push_back(newPosition); count -= need_space; - if (count==0) + if (count == 0) return EQUIP_ERR_OK; } } return EQUIP_ERR_OK; } -InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item* pItem, bool swap, uint32* no_space_count) const +InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem, bool swap, uint32* no_space_count) const { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count); @@ -11155,7 +11247,7 @@ InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &des { if (no_space_count) *no_space_count = count; - return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND; + return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; } if (pItem) @@ -11296,7 +11388,7 @@ InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &des if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS) { uint32 keyringSize = GetMaxKeyringSize(); - res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, KEYRING_SLOT_START+keyringSize, dest, pProto, count, false, pItem, bag, slot); + res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, KEYRING_SLOT_START + keyringSize, dest, pProto, count, false, pItem, bag, slot); if (res != EQUIP_ERR_OK) { if (no_space_count) @@ -11481,7 +11573,7 @@ InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &des if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS) { uint32 keyringSize = GetMaxKeyringSize(); - res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, KEYRING_SLOT_START+keyringSize, dest, pProto, count, false, pItem, bag, slot); + res = CanStoreItem_InInventorySlots(KEYRING_SLOT_START, KEYRING_SLOT_START + keyringSize, dest, pProto, count, false, pItem, bag, slot); if (res != EQUIP_ERR_OK) { if (no_space_count) @@ -11670,9 +11762,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const for (uint8 t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t) { pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t); - if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) + if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t - KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) { - inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount(); + inv_keys[t - KEYRING_SLOT_START] += pItem->GetCount(); b_found = true; break; } @@ -11683,9 +11775,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const for (int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t) { pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t); - if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) + if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t - CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) { - inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount(); + inv_tokens[t - CURRENCYTOKEN_SLOT_START] += pItem->GetCount(); b_found = true; break; } @@ -11696,9 +11788,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t) { pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t); - if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) + if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t - INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize()) { - inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount(); + inv_slot_items[t - INVENTORY_SLOT_ITEM_START] += pItem->GetCount(); b_found = true; break; } @@ -11715,9 +11807,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const for (uint32 j = 0; j < bag->GetBagSize(); j++) { pItem2 = GetItemByPos(t, j); - if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize()) + if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t - INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize()) { - inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount(); + inv_bags[t - INVENTORY_SLOT_BAG_START][j] += pItem->GetCount(); b_found = true; break; } @@ -11736,11 +11828,11 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS) { uint32 keyringSize = GetMaxKeyringSize(); - for (uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t) + for (uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START + keyringSize; ++t) { - if (inv_keys[t-KEYRING_SLOT_START] == 0) + if (inv_keys[t - KEYRING_SLOT_START] == 0) { - inv_keys[t-KEYRING_SLOT_START] = 1; + inv_keys[t - KEYRING_SLOT_START] = 1; b_found = true; break; } @@ -11754,9 +11846,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const { for (uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t) { - if (inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0) + if (inv_tokens[t - CURRENCYTOKEN_SLOT_START] == 0) { - inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1; + inv_tokens[t - CURRENCYTOKEN_SLOT_START] = 1; b_found = true; break; } @@ -11774,13 +11866,13 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const // not plain container check if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) && - ItemCanGoIntoBag(pProto, pBagProto)) + ItemCanGoIntoBag(pProto, pBagProto)) { for (uint32 j = 0; j < bag->GetBagSize(); j++) { - if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0) + if (inv_bags[t - INVENTORY_SLOT_BAG_START][j] == 0) { - inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1; + inv_bags[t - INVENTORY_SLOT_BAG_START][j] = 1; b_found = true; break; } @@ -11796,9 +11888,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const bool b_found = false; for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t) { - if (inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0) + if (inv_slot_items[t - INVENTORY_SLOT_ITEM_START] == 0) { - inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1; + inv_slot_items[t - INVENTORY_SLOT_ITEM_START] = 1; b_found = true; break; } @@ -11819,9 +11911,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const for (uint32 j = 0; j < bag->GetBagSize(); j++) { - if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0) + if (inv_bags[t - INVENTORY_SLOT_BAG_START][j] == 0) { - inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1; + inv_bags[t - INVENTORY_SLOT_BAG_START][j] = 1; b_found = true; break; } @@ -11838,7 +11930,7 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const } ////////////////////////////////////////////////////////////////////////// -InventoryResult Player::CanEquipNewItem(uint8 slot, uint16 &dest, uint32 item, bool swap) const +InventoryResult Player::CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const { dest = 0; Item* pItem = Item::CreateItem(item, 1, this); @@ -11852,7 +11944,7 @@ InventoryResult Player::CanEquipNewItem(uint8 slot, uint16 &dest, uint32 item, b return EQUIP_ERR_ITEM_NOT_FOUND; } -InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool swap, bool not_loading) const +InventoryResult Player::CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool swap, bool not_loading) const { dest = 0; if (pItem) @@ -11896,7 +11988,7 @@ InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool return EQUIP_ERR_NOT_DURING_ARENA_MATCH; } - if (IsInCombat()&& (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer != 0) + if (IsInCombat() && (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer != 0) return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err if (IsNonMeleeSpellCast(false)) @@ -11965,8 +12057,8 @@ InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool if (ItemTemplate const* pBagProto = pBag->GetTemplate()) if (pBagProto->Class == pProto->Class && (!swap || pBag->GetSlot() != eslot)) return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH) - ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH - : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER; + ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH + : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER; uint32 type = pProto->InventoryType; @@ -12009,8 +12101,8 @@ InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); ItemPosCountVec off_dest; if (offItem && (!not_loading || - CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND, false) != EQUIP_ERR_OK || - CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false) != EQUIP_ERR_OK)) + CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND, false) != EQUIP_ERR_OK || + CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false) != EQUIP_ERR_OK)) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL; } } @@ -12069,7 +12161,7 @@ InventoryResult Player::CanUnequipItem(uint16 pos, bool swap) const return EQUIP_ERR_OK; } -InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, Item* pItem, bool swap, bool not_loading) const +InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap, bool not_loading) const { if (!pItem) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; @@ -12095,7 +12187,7 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest if (pItemslot >= CURRENCYTOKEN_SLOT_START && pItemslot < CURRENCYTOKEN_SLOT_END) { sLog->outError("Possible hacking attempt: Player %s [guid: %u] tried to move token [guid: %u, entry: %u] out of the currency bag!", - GetName().c_str(), GetGUIDLow(), pItem->GetGUIDLow(), pProto->ItemId); + GetName().c_str(), GetGUIDLow(), pItem->GetGUIDLow(), pProto->ItemId); return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED; } @@ -12374,7 +12466,7 @@ InventoryResult Player::CanRollForItemInLFG(ItemTemplate const* proto, WorldObje if (!proto) return EQUIP_ERR_ITEM_NOT_FOUND; - // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player + // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player const static uint32 item_weapon_skills[MAX_ITEM_SUBCLASS_WEAPON] = { @@ -12451,7 +12543,7 @@ InventoryResult Player::CanUseAmmo(uint32 item) const ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item); if (pProto) { - if (pProto->InventoryType!= INVTYPE_AMMO) + if (pProto->InventoryType != INVTYPE_AMMO) return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE; InventoryResult res = CanUseItem(pProto); @@ -12558,7 +12650,7 @@ Item* Player::StoreItem(ItemPosCountVec const& dest, Item* pItem, bool update) return nullptr; Item* lastItem = pItem; - const ItemTemplate *proto = pItem->GetTemplate(); + const ItemTemplate* proto = pItem->GetTemplate(); for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end();) { @@ -12612,8 +12704,8 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool return nullptr; if (pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP || - pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM || - (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) + pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM || + (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) pItem->SetBinding(true); Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? NULL : GetBagByPos(bag); @@ -12652,8 +12744,8 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool else { if (pItem2->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP || - pItem2->GetTemplate()->Bonding == BIND_QUEST_ITEM || - (pItem2->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) + pItem2->GetTemplate()->Bonding == BIND_QUEST_ITEM || + (pItem2->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) pItem2->SetBinding(true); pItem2->SetCount(pItem2->GetCount() + count); @@ -12756,7 +12848,7 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) ApplyEquipCooldown(pItem); - // update expertise and armor penetration - passive auras may need it + // update expertise and armor penetration - passive auras may need it if (slot == EQUIPMENT_SLOT_MAINHAND) UpdateExpertise(BASE_ATTACK); @@ -12974,7 +13066,7 @@ void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) it->DestroyForPlayer(this); } - sScriptMgr->OnAfterPlayerMoveItemFromInventory(this,it,bag,slot,update); + sScriptMgr->OnAfterPlayerMoveItemFromInventory(this, it, bag, slot, update); } } @@ -13388,7 +13480,7 @@ Item* Player::GetItemByEntry(uint32 entry) const return nullptr; } -void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update) +void Player::DestroyItemCount(Item* pItem, uint32& count, bool update) { if (!pItem) return; @@ -13794,7 +13886,7 @@ void Player::SwapItem(uint16 src, uint16 dst) uint32 count = 0; - for (uint32 i=0; i < fullBag->GetBagSize(); ++i) + for (uint32 i = 0; i < fullBag->GetBagSize(); ++i) { Item* bagItem = fullBag->GetItemByPos(i); if (!bagItem) @@ -13820,7 +13912,7 @@ void Player::SwapItem(uint16 src, uint16 dst) // Items swap count = 0; // will pos in new bag - for (uint32 i = 0; i< fullBag->GetBagSize(); ++i) + for (uint32 i = 0; i < fullBag->GetBagSize(); ++i) { Item* bagItem = fullBag->GetItemByPos(i); if (!bagItem) @@ -13915,7 +14007,7 @@ void Player::AddItemToBuyBackSlot(Item* pItem) uint32 oldest_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1); uint32 oldest_slot = BUYBACK_SLOT_START; - for (uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i) + for (uint32 i = BUYBACK_SLOT_START + 1; i < BUYBACK_SLOT_END; ++i) { // found empty if (!m_items[i]) @@ -14016,26 +14108,26 @@ void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint { case EQUIP_ERR_CANT_EQUIP_LEVEL_I: case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW: - { - ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid); - data << uint32(proto ? proto->RequiredLevel : 0); - break; - } + { + ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid); + data << uint32(proto ? proto->RequiredLevel : 0); + break; + } case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one... - { - data << uint64(0); // item guid - data << uint32(0); // slot - data << uint64(0); // container - break; - } + { + data << uint64(0); // item guid + data << uint32(0); // slot + data << uint64(0); // container + break; + } case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED: case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED: case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED: - { - ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid); - data << uint32(proto ? proto->ItemLimitCategory : 0); - break; - } + { + ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid); + data << uint32(proto ? proto->ItemLimitCategory : 0); + break; + } default: break; } @@ -14048,7 +14140,7 @@ void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_BUY_FAILED"); #endif - WorldPacket data(SMSG_BUY_FAILED, (8+4+4+1)); + WorldPacket data(SMSG_BUY_FAILED, (8 + 4 + 4 + 1)); data << uint64(creature ? creature->GetGUID() : 0); data << uint32(item); if (param > 0) @@ -14062,7 +14154,7 @@ void Player::SendSellError(SellResult msg, Creature* creature, uint64 guid, uint #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_SELL_ITEM"); #endif - WorldPacket data(SMSG_SELL_ITEM, (8+8+(param?4:0)+1)); // last check 2.0.10 + WorldPacket data(SMSG_SELL_ITEM, (8 + 8 + (param ? 4 : 0) + 1)); // last check 2.0.10 data << uint64(creature ? creature->GetGUID() : 0); data << uint64(guid); if (param > 0) @@ -14149,7 +14241,7 @@ void Player::UpdateItemDuration(uint32 time, bool realtimeonly) void Player::UpdateEnchantTime(uint32 time) { - for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr=next) + for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next) { ASSERT(itr->item); next = itr; @@ -14278,7 +14370,7 @@ void Player::AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 dur } if (item && duration > 0) { - GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000)); + GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration / 1000)); m_enchantDuration.push_back(EnchantDuration(item, slot, duration)); } } @@ -14317,12 +14409,12 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool // If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements // rather than the gem requirements itself. If the socket has no color it is a prismatic socket. if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3) - && !item->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color) + && !item->GetTemplate()->Socket[slot - SOCK_ENCHANTMENT_SLOT].Color) { // Check if the requirements for the prismatic socket are met before applying the gem stats - SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(item->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)); - if (!pPrismaticEnchant || (pPrismaticEnchant->requiredSkill > 0 && pPrismaticEnchant->requiredSkillValue > GetSkillValue(pPrismaticEnchant->requiredSkill))) - return; + SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(item->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)); + if (!pPrismaticEnchant || (pPrismaticEnchant->requiredSkill > 0 && pPrismaticEnchant->requiredSkillValue > GetSkillValue(pPrismaticEnchant->requiredSkill))) + return; } if (!item->IsBroken()) @@ -14401,293 +14493,293 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply); break; case ITEM_ENCHANTMENT_TYPE_STAT: - { - if (!enchant_amount) { - ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId())); - if (item_rand_suffix) + if (!enchant_amount) { - for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k) + ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId())); + if (item_rand_suffix) { - if (item_rand_suffix->enchant_id[k] == enchant_id) + for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k) { - enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000); - break; + if (item_rand_suffix->enchant_id[k] == enchant_id) + { + enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000); + break; + } } } } - } #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Adding %u to stat nb %u", enchant_amount, enchant_spell_id); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Adding %u to stat nb %u", enchant_amount, enchant_spell_id); #endif - switch (enchant_spell_id) - { - case ITEM_MOD_MANA: + switch (enchant_spell_id) + { + case ITEM_MOD_MANA: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply); - break; - case ITEM_MOD_HEALTH: + HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply); + break; + case ITEM_MOD_HEALTH: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply); - break; - case ITEM_MOD_AGILITY: + HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply); + break; + case ITEM_MOD_AGILITY: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u AGILITY", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u AGILITY", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply); - ApplyStatBuffMod(STAT_AGILITY, (float)enchant_amount, apply); - break; - case ITEM_MOD_STRENGTH: + HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply); + ApplyStatBuffMod(STAT_AGILITY, (float)enchant_amount, apply); + break; + case ITEM_MOD_STRENGTH: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STRENGTH", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STRENGTH", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply); - ApplyStatBuffMod(STAT_STRENGTH, (float)enchant_amount, apply); - break; - case ITEM_MOD_INTELLECT: + HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply); + ApplyStatBuffMod(STAT_STRENGTH, (float)enchant_amount, apply); + break; + case ITEM_MOD_INTELLECT: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u INTELLECT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u INTELLECT", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply); - ApplyStatBuffMod(STAT_INTELLECT, (float)enchant_amount, apply); - break; - case ITEM_MOD_SPIRIT: + HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply); + ApplyStatBuffMod(STAT_INTELLECT, (float)enchant_amount, apply); + break; + case ITEM_MOD_SPIRIT: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPIRIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPIRIT", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply); - ApplyStatBuffMod(STAT_SPIRIT, (float)enchant_amount, apply); - break; - case ITEM_MOD_STAMINA: + HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply); + ApplyStatBuffMod(STAT_SPIRIT, (float)enchant_amount, apply); + break; + case ITEM_MOD_STAMINA: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STAMINA", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STAMINA", enchant_amount); #endif - HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply); - ApplyStatBuffMod(STAT_STAMINA, (float)enchant_amount, apply); - break; - case ITEM_MOD_DEFENSE_SKILL_RATING: - ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply); + HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply); + ApplyStatBuffMod(STAT_STAMINA, (float)enchant_amount, apply); + break; + case ITEM_MOD_DEFENSE_SKILL_RATING: + ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DEFENCE", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DEFENCE", enchant_amount); #endif - break; - case ITEM_MOD_DODGE_RATING: - ApplyRatingMod(CR_DODGE, enchant_amount, apply); + break; + case ITEM_MOD_DODGE_RATING: + ApplyRatingMod(CR_DODGE, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DODGE", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DODGE", enchant_amount); #endif - break; - case ITEM_MOD_PARRY_RATING: - ApplyRatingMod(CR_PARRY, enchant_amount, apply); + break; + case ITEM_MOD_PARRY_RATING: + ApplyRatingMod(CR_PARRY, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u PARRY", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u PARRY", enchant_amount); #endif - break; - case ITEM_MOD_BLOCK_RATING: - ApplyRatingMod(CR_BLOCK, enchant_amount, apply); + break; + case ITEM_MOD_BLOCK_RATING: + ApplyRatingMod(CR_BLOCK, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SHIELD_BLOCK", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SHIELD_BLOCK", enchant_amount); #endif - break; - case ITEM_MOD_HIT_MELEE_RATING: - ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply); + break; + case ITEM_MOD_HIT_MELEE_RATING: + ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_HIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_HIT", enchant_amount); #endif - break; - case ITEM_MOD_HIT_RANGED_RATING: - ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply); + break; + case ITEM_MOD_HIT_RANGED_RATING: + ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_HIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_HIT", enchant_amount); #endif - break; - case ITEM_MOD_HIT_SPELL_RATING: - ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply); + break; + case ITEM_MOD_HIT_SPELL_RATING: + ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_HIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_HIT", enchant_amount); #endif - break; - case ITEM_MOD_CRIT_MELEE_RATING: - ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply); + break; + case ITEM_MOD_CRIT_MELEE_RATING: + ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_CRIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MELEE_CRIT", enchant_amount); #endif - break; - case ITEM_MOD_CRIT_RANGED_RATING: - ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply); + break; + case ITEM_MOD_CRIT_RANGED_RATING: + ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_CRIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_CRIT", enchant_amount); #endif - break; - case ITEM_MOD_CRIT_SPELL_RATING: - ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply); + break; + case ITEM_MOD_CRIT_SPELL_RATING: + ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_CRIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_CRIT", enchant_amount); #endif - break; -// Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used -// in Enchantments -// case ITEM_MOD_HIT_TAKEN_MELEE_RATING: -// ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply); -// break; -// case ITEM_MOD_HIT_TAKEN_RANGED_RATING: -// ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply); -// break; -// case ITEM_MOD_HIT_TAKEN_SPELL_RATING: -// ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply); -// break; -// case ITEM_MOD_CRIT_TAKEN_MELEE_RATING: -// ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); -// break; -// case ITEM_MOD_CRIT_TAKEN_RANGED_RATING: -// ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); -// break; -// case ITEM_MOD_CRIT_TAKEN_SPELL_RATING: -// ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); -// break; -// case ITEM_MOD_HASTE_MELEE_RATING: -// ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply); -// break; - case ITEM_MOD_HASTE_RANGED_RATING: - ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply); - break; - case ITEM_MOD_HASTE_SPELL_RATING: - ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply); - break; - case ITEM_MOD_HIT_RATING: - ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply); - ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply); - ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply); + break; + // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used + // in Enchantments + // case ITEM_MOD_HIT_TAKEN_MELEE_RATING: + // ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply); + // break; + // case ITEM_MOD_HIT_TAKEN_RANGED_RATING: + // ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply); + // break; + // case ITEM_MOD_HIT_TAKEN_SPELL_RATING: + // ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply); + // break; + // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING: + // ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); + // break; + // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING: + // ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); + // break; + // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING: + // ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); + // break; + // case ITEM_MOD_HASTE_MELEE_RATING: + // ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply); + // break; + case ITEM_MOD_HASTE_RANGED_RATING: + ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply); + break; + case ITEM_MOD_HASTE_SPELL_RATING: + ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply); + break; + case ITEM_MOD_HIT_RATING: + ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply); + ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply); + ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HIT", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HIT", enchant_amount); #endif - break; - case ITEM_MOD_CRIT_RATING: - ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply); - ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply); - ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply); + break; + case ITEM_MOD_CRIT_RATING: + ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply); + ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply); + ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u CRITICAL", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u CRITICAL", enchant_amount); #endif - break; -// Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment -// case ITEM_MOD_HIT_TAKEN_RATING: -// ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply); -// ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply); -// ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply); -// break; -// case ITEM_MOD_CRIT_TAKEN_RATING: -// ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); -// ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); -// ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); -// break; - case ITEM_MOD_RESILIENCE_RATING: - ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); - ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); - ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); + break; + // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment + // case ITEM_MOD_HIT_TAKEN_RATING: + // ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply); + // ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply); + // ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply); + // break; + // case ITEM_MOD_CRIT_TAKEN_RATING: + // ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); + // ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); + // ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); + // break; + case ITEM_MOD_RESILIENCE_RATING: + ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply); + ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply); + ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RESILIENCE", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RESILIENCE", enchant_amount); #endif - break; - case ITEM_MOD_HASTE_RATING: - ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply); - ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply); - ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply); + break; + case ITEM_MOD_HASTE_RATING: + ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply); + ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply); + ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HASTE", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HASTE", enchant_amount); #endif - break; - case ITEM_MOD_EXPERTISE_RATING: - ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply); + break; + case ITEM_MOD_EXPERTISE_RATING: + ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u EXPERTISE", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u EXPERTISE", enchant_amount); #endif - break; - case ITEM_MOD_ATTACK_POWER: - HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply); - HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply); + break; + case ITEM_MOD_ATTACK_POWER: + HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply); + HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ATTACK_POWER", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ATTACK_POWER", enchant_amount); #endif - break; - case ITEM_MOD_RANGED_ATTACK_POWER: - HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply); + break; + case ITEM_MOD_RANGED_ATTACK_POWER: + HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_ATTACK_POWER", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RANGED_ATTACK_POWER", enchant_amount); #endif - break; -// case ITEM_MOD_FERAL_ATTACK_POWER: -// ApplyFeralAPBonus(enchant_amount, apply); + break; + // case ITEM_MOD_FERAL_ATTACK_POWER: + // ApplyFeralAPBonus(enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) -// sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u FERAL_ATTACK_POWER", enchant_amount); + // sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u FERAL_ATTACK_POWER", enchant_amount); #endif -// break; - case ITEM_MOD_MANA_REGENERATION: - ApplyManaRegenBonus(enchant_amount, apply); + // break; + case ITEM_MOD_MANA_REGENERATION: + ApplyManaRegenBonus(enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA_REGENERATION", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA_REGENERATION", enchant_amount); #endif - break; - case ITEM_MOD_ARMOR_PENETRATION_RATING: - ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply); + break; + case ITEM_MOD_ARMOR_PENETRATION_RATING: + ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ARMOR PENETRATION", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ARMOR PENETRATION", enchant_amount); #endif - break; - case ITEM_MOD_SPELL_POWER: - ApplySpellPowerBonus(enchant_amount, apply); + break; + case ITEM_MOD_SPELL_POWER: + ApplySpellPowerBonus(enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_POWER", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_POWER", enchant_amount); #endif - break; - case ITEM_MOD_HEALTH_REGEN: - ApplyHealthRegenBonus(enchant_amount, apply); + break; + case ITEM_MOD_HEALTH_REGEN: + ApplyHealthRegenBonus(enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH_REGENERATION", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH_REGENERATION", enchant_amount); #endif - break; - case ITEM_MOD_SPELL_PENETRATION: - ApplySpellPenetrationBonus(enchant_amount, apply); + break; + case ITEM_MOD_SPELL_PENETRATION: + ApplySpellPenetrationBonus(enchant_amount, apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_PENETRATION", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_PENETRATION", enchant_amount); #endif - break; - case ITEM_MOD_BLOCK_VALUE: - HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply); + break; + case ITEM_MOD_BLOCK_VALUE: + HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u BLOCK_VALUE", enchant_amount); + sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u BLOCK_VALUE", enchant_amount); #endif - break; - case ITEM_MOD_SPELL_HEALING_DONE: // deprecated - case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated - default: - break; + break; + case ITEM_MOD_SPELL_HEALING_DONE: // deprecated + case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated + default: + break; + } + break; } - break; - } case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon - { - if (getClass() == CLASS_SHAMAN) { - float addValue = 0.0f; - if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND) + if (getClass() == CLASS_SHAMAN) { - addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f); - HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply); - } - else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND) - { - addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f); - HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply); + float addValue = 0.0f; + if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND) + { + addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f); + HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply); + } + else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND) + { + addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f); + HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply); + } } + break; } - break; - } case ITEM_ENCHANTMENT_TYPE_USE_SPELL: // processed in Player::CastItemUseSpell break; @@ -14753,7 +14845,7 @@ void Player::UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 // If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements // rather than the gem requirements itself. If the socket has no color it is a prismatic socket. if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3) - && !m_items[i]->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color) + && !m_items[i]->GetTemplate()->Socket[slot - SOCK_ENCHANTMENT_SLOT].Color) { SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(m_items[i]->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)); @@ -14791,14 +14883,14 @@ void Player::SendNewItem(Item* item, uint32 count, bool received, bool created, if (!item) // prevent crash return; - // last check 2.0.10 - WorldPacket data(SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4)); + // last check 2.0.10 + WorldPacket data(SMSG_ITEM_PUSH_RESULT, (8 + 4 + 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4)); data << uint64(GetGUID()); // player GUID data << uint32(received); // 0=looted, 1=from npc data << uint32(created); // 0=received, 1=created data << uint32(sendChatMessage); // bool print message to chat data << uint8(item->GetBagSlot()); // bagslot - // item slot, but when added to stack: 0xFFFFFFFF + // item slot, but when added to stack: 0xFFFFFFFF data << uint32((item->GetCount() == count) ? item->GetSlot() : -1); data << uint32(item->GetEntry()); // item id data << uint32(item->GetItemSuffixFactor()); // SuffixFactor @@ -14862,15 +14954,15 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool canTalk = false; break; case GOSSIP_OPTION_VENDOR: - { - VendorItemData const* vendorItems = itr->second.ActionMenuID ? sObjectMgr->GetNpcVendorItemList(itr->second.ActionMenuID) : creature->GetVendorItems(); - if (!vendorItems || vendorItems->Empty()) { - sLog->outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", creature->GetGUIDLow(), creature->GetEntry()); - canTalk = false; + VendorItemData const* vendorItems = itr->second.ActionMenuID ? sObjectMgr->GetNpcVendorItemList(itr->second.ActionMenuID) : creature->GetVendorItems(); + if (!vendorItems || vendorItems->Empty()) + { + sLog->outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", creature->GetGUIDLow(), creature->GetEntry()); + canTalk = false; + } + break; } - break; - } case GOSSIP_OPTION_LEARNDUALSPEC: case GOSSIP_OPTION_DUALSPEC_INFO: if (!(GetSpecsCount() == 1 && creature->isCanTrainingAndResetTalentsOf(this) && !(getLevel() < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL)))) @@ -15066,18 +15158,18 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men { case GOSSIP_OPTION_GOSSIP: case GOSSIP_OPTION_DUALSPEC_INFO: - { - if (menuItemData->GossipActionPoi) - PlayerTalkClass->SendPointOfInterest(menuItemData->GossipActionPoi); - - if (menuItemData->GossipActionMenuId) { - PrepareGossipMenu(source, menuItemData->GossipActionMenuId); - SendPreparedGossip(source); - } + if (menuItemData->GossipActionPoi) + PlayerTalkClass->SendPointOfInterest(menuItemData->GossipActionPoi); - break; - } + if (menuItemData->GossipActionMenuId) + { + PrepareGossipMenu(source, menuItemData->GossipActionMenuId); + SendPreparedGossip(source); + } + + break; + } case GOSSIP_OPTION_OUTDOORPVP: sOutdoorPvPMgr->HandleGossipOption(this, source->GetGUID(), gossipListId); break; @@ -15145,18 +15237,18 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men SendPreparedGossip(source); break; case GOSSIP_OPTION_BATTLEFIELD: - { - BattlegroundTypeId bgTypeId = sBattlegroundMgr->GetBattleMasterBG(source->GetEntry()); - - if (bgTypeId == BATTLEGROUND_TYPE_NONE) { - sLog->outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow()); - return; - } + BattlegroundTypeId bgTypeId = sBattlegroundMgr->GetBattleMasterBG(source->GetEntry()); - GetSession()->SendBattleGroundList(guid, bgTypeId); - break; - } + if (bgTypeId == BATTLEGROUND_TYPE_NONE) + { + sLog->outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow()); + return; + } + + GetSession()->SendBattleGroundList(guid, bgTypeId); + break; + } } ModifyMoney(-cost); @@ -15240,7 +15332,7 @@ void Player::PrepareQuestMenu(uint64 guid) return; } - QuestMenu &qm = PlayerTalkClass->GetQuestMenu(); + QuestMenu& qm = PlayerTalkClass->GetQuestMenu(); qm.ClearMenu(); for (QuestRelations::const_iterator i = objectQIR.first; i != objectQIR.second; ++i) @@ -15396,10 +15488,10 @@ Quest const* Player::GetNextQuest(uint64 guid, Quest const* quest) bool Player::CanSeeStartQuest(Quest const* quest) { if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this) && SatisfyQuestClass(quest, false) && SatisfyQuestRace(quest, false) && - SatisfyQuestSkill(quest, false) && SatisfyQuestExclusiveGroup(quest, false) && SatisfyQuestReputation(quest, false) && - SatisfyQuestPreviousQuest(quest, false) && SatisfyQuestNextChain(quest, false) && - SatisfyQuestPrevChain(quest, false) && SatisfyQuestDay(quest, false) && SatisfyQuestWeek(quest, false) && - SatisfyQuestMonth(quest, false) && SatisfyQuestSeasonal(quest, false)) + SatisfyQuestSkill(quest, false) && SatisfyQuestExclusiveGroup(quest, false) && SatisfyQuestReputation(quest, false) && + SatisfyQuestPreviousQuest(quest, false) && SatisfyQuestNextChain(quest, false) && + SatisfyQuestPrevChain(quest, false) && SatisfyQuestDay(quest, false) && SatisfyQuestWeek(quest, false) && + SatisfyQuestMonth(quest, false) && SatisfyQuestSeasonal(quest, false)) { return getLevel() + sWorld->getIntConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= quest->GetMinLevel(); } @@ -15410,14 +15502,14 @@ bool Player::CanSeeStartQuest(Quest const* quest) bool Player::CanTakeQuest(Quest const* quest, bool msg) { return !DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this) - && SatisfyQuestStatus(quest, msg) && SatisfyQuestExclusiveGroup(quest, msg) - && SatisfyQuestClass(quest, msg) && SatisfyQuestRace(quest, msg) && SatisfyQuestLevel(quest, msg) - && SatisfyQuestSkill(quest, msg) && SatisfyQuestReputation(quest, msg) - && SatisfyQuestPreviousQuest(quest, msg) && SatisfyQuestTimed(quest, msg) - && SatisfyQuestNextChain(quest, msg) && SatisfyQuestPrevChain(quest, msg) - && SatisfyQuestDay(quest, msg) && SatisfyQuestWeek(quest, msg) - && SatisfyQuestMonth(quest, msg) && SatisfyQuestSeasonal(quest, msg) - && SatisfyQuestConditions(quest, msg); + && SatisfyQuestStatus(quest, msg) && SatisfyQuestExclusiveGroup(quest, msg) + && SatisfyQuestClass(quest, msg) && SatisfyQuestRace(quest, msg) && SatisfyQuestLevel(quest, msg) + && SatisfyQuestSkill(quest, msg) && SatisfyQuestReputation(quest, msg) + && SatisfyQuestPreviousQuest(quest, msg) && SatisfyQuestTimed(quest, msg) + && SatisfyQuestNextChain(quest, msg) && SatisfyQuestPrevChain(quest, msg) + && SatisfyQuestDay(quest, msg) && SatisfyQuestWeek(quest, msg) + && SatisfyQuestMonth(quest, msg) && SatisfyQuestSeasonal(quest, msg) + && SatisfyQuestConditions(quest, msg); } bool Player::CanAddQuest(Quest const* quest, bool msg) @@ -15478,7 +15570,7 @@ bool Player::CanCompleteQuest(uint32 quest_id, const QuestStatusData* q_savedSta { for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++) { - if (qInfo->RequiredItemCount[i]!= 0 && q_status.ItemCount[i] < qInfo->RequiredItemCount[i]) + if (qInfo->RequiredItemCount[i] != 0 && q_status.ItemCount[i] < qInfo->RequiredItemCount[i]) return false; } } @@ -15559,8 +15651,8 @@ bool Player::CanRewardQuest(Quest const* quest, bool msg) { for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++) { - if (quest->RequiredItemCount[i]!= 0 && - GetItemCount(quest->RequiredItemId[i]) < quest->RequiredItemCount[i]) + if (quest->RequiredItemCount[i] != 0 && + GetItemCount(quest->RequiredItemId[i]) < quest->RequiredItemCount[i]) { if (msg) SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr, quest->RequiredItemId[i]); @@ -15597,26 +15689,26 @@ void Player::AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver) break; case TYPEID_ITEM: case TYPEID_CONTAINER: - { - Item* item = (Item*)questGiver; - sScriptMgr->OnQuestAccept(this, item, quest); - - // destroy not required for quest finish quest starting item - bool destroyItem = true; - for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { - if (quest->RequiredItemId[i] == item->GetEntry() && item->GetTemplate()->MaxCount > 0) + Item* item = (Item*)questGiver; + sScriptMgr->OnQuestAccept(this, item, quest); + + // destroy not required for quest finish quest starting item + bool destroyItem = true; + for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { - destroyItem = false; - break; + if (quest->RequiredItemId[i] == item->GetEntry() && item->GetTemplate()->MaxCount > 0) + { + destroyItem = false; + break; + } } + + if (destroyItem) + DestroyItem(item->GetBagSlot(), item->GetSlot(), true); + + break; } - - if (destroyItem) - DestroyItem(item->GetBagSlot(), item->GetSlot(), true); - - break; - } case TYPEID_GAMEOBJECT: #ifdef ELUNA sEluna->OnQuestAccept(this, questGiver->ToGameObject(), quest); @@ -15904,7 +15996,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool rewarded = IsQuestRewarded(quest_id) && !quest->IsDFQuest(); // Not give XP in case already completed once repeatable quest - uint32 XP = rewarded ? 0 : uint32(quest->XPValue(this)*sWorld->getRate(RATE_XP_QUEST)); + uint32 XP = rewarded ? 0 : uint32(quest->XPValue(this) * sWorld->getRate(RATE_XP_QUEST)); // handle SPELL_AURA_MOD_XP_QUEST_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT); @@ -15942,7 +16034,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, if (quest->GetBonusTalents()) { - m_questRewardTalentCount+=quest->GetBonusTalents(); + m_questRewardTalentCount += quest->GetBonusTalents(); InitTalentForLevel(); } @@ -16436,7 +16528,7 @@ bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const bool have_slot = false; for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) { - uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx); + uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx); if (qInfo->GetQuestId() == id) return false; @@ -16729,29 +16821,29 @@ QuestGiverStatus Player::GetQuestDialogStatus(Object* questgiver) switch (questgiver->GetTypeId()) { case TYPEID_GAMEOBJECT: - { + { #ifdef ELUNA - sEluna->GetDialogStatus(this, questgiver->ToGameObject()); + sEluna->GetDialogStatus(this, questgiver->ToGameObject()); #endif - QuestGiverStatus questStatus = QuestGiverStatus(sScriptMgr->GetDialogStatus(this, questgiver->ToGameObject())); - if (questStatus != DIALOG_STATUS_SCRIPTED_NO_STATUS) - return questStatus; - qr = sObjectMgr->GetGOQuestRelationBounds(questgiver->GetEntry()); - qir = sObjectMgr->GetGOQuestInvolvedRelationBounds(questgiver->GetEntry()); - break; - } + QuestGiverStatus questStatus = QuestGiverStatus(sScriptMgr->GetDialogStatus(this, questgiver->ToGameObject())); + if (questStatus != DIALOG_STATUS_SCRIPTED_NO_STATUS) + return questStatus; + qr = sObjectMgr->GetGOQuestRelationBounds(questgiver->GetEntry()); + qir = sObjectMgr->GetGOQuestInvolvedRelationBounds(questgiver->GetEntry()); + break; + } case TYPEID_UNIT: - { + { #ifdef ELUNA - sEluna->GetDialogStatus(this, questgiver->ToCreature()); + sEluna->GetDialogStatus(this, questgiver->ToCreature()); #endif - QuestGiverStatus questStatus = QuestGiverStatus(sScriptMgr->GetDialogStatus(this, questgiver->ToCreature())); - if (questStatus != DIALOG_STATUS_SCRIPTED_NO_STATUS) - return questStatus; - qr = sObjectMgr->GetCreatureQuestRelationBounds(questgiver->GetEntry()); - qir = sObjectMgr->GetCreatureQuestInvolvedRelationBounds(questgiver->GetEntry()); - break; - } + QuestGiverStatus questStatus = QuestGiverStatus(sScriptMgr->GetDialogStatus(this, questgiver->ToCreature())); + if (questStatus != DIALOG_STATUS_SCRIPTED_NO_STATUS) + return questStatus; + qr = sObjectMgr->GetCreatureQuestRelationBounds(questgiver->GetEntry()); + qir = sObjectMgr->GetCreatureQuestInvolvedRelationBounds(questgiver->GetEntry()); + break; + } default: // it's impossible, but check //TC_LOG_ERROR("entities.player.quest", "GetQuestDialogStatus called for unexpected type %u", questgiver->GetTypeId()); @@ -16774,7 +16866,7 @@ QuestGiverStatus Player::GetQuestDialogStatus(Object* questgiver) QuestStatus status = GetQuestStatus(questId); if ((status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(questId)) || - (quest->IsAutoComplete() && CanTakeQuest(quest, false))) + (quest->IsAutoComplete() && CanTakeQuest(quest, false))) { if (quest->IsAutoComplete() && quest->IsRepeatable() && !quest->IsDailyOrWeekly()) result2 = DIALOG_STATUS_REWARD_REP; @@ -16805,23 +16897,28 @@ QuestGiverStatus Player::GetQuestDialogStatus(Object* questgiver) { if (CanSeeStartQuest(quest)) { - if (SatisfyQuestLevel(quest, false)) { + if (SatisfyQuestLevel(quest, false)) + { bool isLowLevel = (getLevel() > (GetQuestLevel(quest) + sWorld->getIntConfig(CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF))); - if (quest->IsAutoComplete()) { + if (quest->IsAutoComplete()) + { if (isLowLevel) result2 = DIALOG_STATUS_LOW_LEVEL_REWARD_REP; else result2 = DIALOG_STATUS_REWARD_REP; } - else { - if (quest->IsDaily()) { + else + { + if (quest->IsDaily()) + { if (isLowLevel) result2 = DIALOG_STATUS_LOW_LEVEL_AVAILABLE_REP; else result2 = DIALOG_STATUS_AVAILABLE_REP; } - else { + else + { if (isLowLevel) result2 = DIALOG_STATUS_LOW_LEVEL_AVAILABLE; else @@ -17049,7 +17146,7 @@ void Player::KilledMonsterCredit(uint32 entry, uint64 guid) // xinef: or is pvp quest, and player in BG/BF group QuestStatusData& q_status = m_QuestStatus[questid]; if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid(GetMap()->GetDifficulty()) || - (qInfo->IsPVPQuest() && (GetGroup()->isBFGroup() || GetGroup()->isBGGroup())))) + (qInfo->IsPVPQuest() && (GetGroup()->isBFGroup() || GetGroup()->isBGGroup())))) { if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_KILL) /*&& !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_CAST)*/) { @@ -17205,14 +17302,14 @@ void Player::TalkedToCreature(uint32 entry, uint64 guid) { for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { - // skip Gameobject objectives + // skip Gameobject objectives if (qInfo->RequiredNpcOrGo[j] < 0) continue; uint32 reqTarget = 0; if (qInfo->RequiredNpcOrGo[j] > 0) // creature activate objectives - // checked at quest_template loading + // checked at quest_template loading reqTarget = qInfo->RequiredNpcOrGo[j]; else continue; @@ -17408,7 +17505,7 @@ void Player::SendQuestReward(Quest const* quest, uint32 XP) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid); #endif sGameEventMgr->HandleQuestComplete(questid); - WorldPacket data(SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4)); + WorldPacket data(SMSG_QUESTGIVER_QUEST_COMPLETE, (4 + 4 + 4 + 4 + 4)); data << uint32(questid); if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) @@ -17493,7 +17590,7 @@ void Player::SendPushToPartyResponse(Player* player, uint8 msg) { if (player) { - WorldPacket data(MSG_QUEST_PUSH_RESULT, (8+1)); + WorldPacket data(MSG_QUEST_PUSH_RESULT, (8 + 1)); data << uint64(player->GetGUID()); data << uint8(msg); // valid values: 0-8 GetSession()->SendPacket(&data); @@ -17523,7 +17620,7 @@ void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, uint64 guid, uin // client expected gameobject template id in form (id|0x80000000) entry = (-entry) | 0x80000000; - WorldPacket data(SMSG_QUESTUPDATE_ADD_KILL, (4*4+8)); + WorldPacket data(SMSG_QUESTUPDATE_ADD_KILL, (4 * 4 + 8)); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL"); #endif @@ -17536,14 +17633,14 @@ void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, uint64 guid, uin uint16 log_slot = FindQuestSlot(quest->GetQuestId()); if (log_slot < MAX_QUEST_LOG_SIZE) - SetQuestSlotCounter(log_slot, creatureOrGO_idx, GetQuestSlotCounter(log_slot, creatureOrGO_idx)+add_count); + SetQuestSlotCounter(log_slot, creatureOrGO_idx, GetQuestSlotCounter(log_slot, creatureOrGO_idx) + add_count); } void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint16 add_count) { ASSERT(old_count + add_count < 65536 && "player count store in 16 bits"); - WorldPacket data(SMSG_QUESTUPDATE_ADD_PVP_KILL, (3*4)); + WorldPacket data(SMSG_QUESTUPDATE_ADD_PVP_KILL, (3 * 4)); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTUPDATE_ADD_PVP_KILL"); #endif @@ -17640,7 +17737,7 @@ void Player::_LoadEquipmentSets(PreparedQueryResult result) eqSet.state = EQUIPMENT_SET_UNCHANGED; for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) - eqSet.Items[i] = fields[5+i].GetUInt32(); + eqSet.Items[i] = fields[5 + i].GetUInt32(); m_EquipmentSets[index] = eqSet; @@ -17648,8 +17745,7 @@ void Player::_LoadEquipmentSets(PreparedQueryResult result) if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit break; - } - while (result->NextRow()); + } while (result->NextRow()); } void Player::_LoadEntryPointData(PreparedQueryResult result) @@ -17659,10 +17755,10 @@ void Player::_LoadEntryPointData(PreparedQueryResult result) Field* fields = result->Fetch(); m_entryPointData.joinPos = WorldLocation(fields[4].GetUInt32(), // Map - fields[0].GetFloat(), // X - fields[1].GetFloat(), // Y - fields[2].GetFloat(), // Z - fields[3].GetFloat()); // Orientation + fields[0].GetFloat(), // X + fields[1].GetFloat(), // Y + fields[2].GetFloat(), // Z + fields[3].GetFloat()); // Orientation std::string taxi = fields[5].GetString(); if (!taxi.empty()) @@ -17742,11 +17838,11 @@ bool Player::isBeingLoaded() const return GetSession()->PlayerLoading(); } -bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) +bool Player::LoadFromDB(uint32 guid, SQLQueryHolder* holder) { //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //QueryResult* result = CharacterDatabase.PQuery("SELECT guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, " - // 17 18 19 20 21 22 23 24 25 26 27 28 29 + // 17 18 19 20 21 22 23 24 25 26 27 28 29 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, " // 30 31 32 33 34 35 36 37 38 39 40 41 42 43 //"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, " @@ -17786,7 +17882,7 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) // check name limitations if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS || - (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()) && sObjectMgr->IsReservedName(m_name))) + (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()) && sObjectMgr->IsReservedName(m_name))) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->setUInt16(0, uint16(AT_LOGIN_RENAME)); @@ -17819,7 +17915,7 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) SetUInt32Value(PLAYER_XP, fields[7].GetUInt32()); _LoadIntoDataField(fields[66].GetCString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE); - _LoadIntoDataField(fields[69].GetCString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2); + _LoadIntoDataField(fields[69].GetCString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE * 2); SetObjectScale(1.0f); SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); @@ -18209,10 +18305,10 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour) float bubble1 = 0.125f; float bubble = fields[28].GetUInt8() > 0 - ? bubble1*sWorld->getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY) - : bubble0*sWorld->getRate(RATE_REST_OFFLINE_IN_WILDERNESS); + ? bubble1 * sWorld->getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY) + : bubble0 * sWorld->getRate(RATE_REST_OFFLINE_IN_WILDERNESS); - SetRestBonus(GetRestBonus() + time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) / 72000)*bubble); + SetRestBonus(GetRestBonus() + time_diff * ((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) / 72000)*bubble); } // load skills after InitStatsForLevel because it triggering aura apply also @@ -18319,8 +18415,11 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) switch (sWorld->getIntConfig(CONFIG_GM_LOGIN_STATE)) { default: - case 0: break; // disable - case 1: SetGameMaster(true); break; // enable + case 0: + break; // disable + case 1: + SetGameMaster(true); + break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_ON) SetGameMaster(true); @@ -18330,8 +18429,11 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) switch (sWorld->getIntConfig(CONFIG_GM_VISIBLE_STATE)) { default: - case 0: SetGMVisible(false); break; // invisible - case 1: break; // visible + case 0: + SetGMVisible(false); + break; // invisible + case 1: + break; // visible case 2: // save state if (extraflags & PLAYER_EXTRA_GM_INVISIBLE) SetGMVisible(false); @@ -18341,8 +18443,11 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) switch (sWorld->getIntConfig(CONFIG_GM_CHAT)) { default: - case 0: break; // disable - case 1: SetGMChat(true); break; // enable + case 0: + break; // disable + case 1: + SetGMChat(true); + break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_CHAT) SetGMChat(true); @@ -18352,8 +18457,11 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) switch (sWorld->getIntConfig(CONFIG_GM_WHISPERING_TO)) { default: - case 0: break; // disable - case 1: SetAcceptWhispers(true); break; // enable + case 0: + break; // disable + case 1: + SetAcceptWhispers(true); + break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS) SetAcceptWhispers(true); @@ -18387,22 +18495,22 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) // Fix aurastate auras, depending on health! // Set aurastate manualy, prevents aura switching if (HealthBelowPct(20)) - SetFlag(UNIT_FIELD_AURASTATE, 1<<(AURA_STATE_HEALTHLESS_20_PERCENT-1)); + SetFlag(UNIT_FIELD_AURASTATE, 1 << (AURA_STATE_HEALTHLESS_20_PERCENT - 1)); if (HealthBelowPct(35)) - SetFlag(UNIT_FIELD_AURASTATE, 1<<(AURA_STATE_HEALTHLESS_35_PERCENT-1)); + SetFlag(UNIT_FIELD_AURASTATE, 1 << (AURA_STATE_HEALTHLESS_35_PERCENT - 1)); if (HealthAbovePct(75)) - SetFlag(UNIT_FIELD_AURASTATE, 1<<(AURA_STATE_HEALTH_ABOVE_75_PERCENT-1)); + SetFlag(UNIT_FIELD_AURASTATE, 1 << (AURA_STATE_HEALTH_ABOVE_75_PERCENT - 1)); // unapply aura stats if dont meet requirements - AuraApplicationMap const& Auras = GetAppliedAuras(); + AuraApplicationMap const& Auras = GetAppliedAuras(); for (AuraApplicationMap::const_iterator itr = Auras.begin(); itr != Auras.end(); ++itr) { // we assume that all auras are applied now, aurastate was modfied MANUALY preventing any apply/unapply state switching Aura* aura = itr->second->GetBase(); SpellInfo const* m_spellInfo = aura->GetSpellInfo(); if (m_spellInfo->CasterAuraState != AURA_STATE_HEALTHLESS_20_PERCENT && - m_spellInfo->CasterAuraState != AURA_STATE_HEALTHLESS_35_PERCENT && - m_spellInfo->CasterAuraState != AURA_STATE_HEALTH_ABOVE_75_PERCENT) + m_spellInfo->CasterAuraState != AURA_STATE_HEALTHLESS_35_PERCENT && + m_spellInfo->CasterAuraState != AURA_STATE_HEALTH_ABOVE_75_PERCENT) continue; if (!HasAuraState((AuraStateType)m_spellInfo->CasterAuraState)) @@ -18537,10 +18645,10 @@ void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) // negative effects should continue counting down after logout if (remaintime != -1 && ((!spellInfo->IsPositive() && spellInfo->Id != 15007) || spellInfo->HasAttribute(SPELL_ATTR4_FADES_WHILE_LOGGED_OUT))) // Xinef: resurrection sickness should not tick when logged off { - if (remaintime/IN_MILLISECONDS <= int32(timediff)) + if (remaintime / IN_MILLISECONDS <= int32(timediff)) continue; - remaintime -= timediff*IN_MILLISECONDS; + remaintime -= timediff * IN_MILLISECONDS; } // prevent wrong values of remaincharges @@ -18568,8 +18676,7 @@ void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) sLog->outDetail("Added aura spellid %u, effectmask %u", spellInfo->Id, effmask); #endif } - } - while (result->NextRow()); + } while (result->NextRow()); } } @@ -18587,7 +18694,7 @@ void Player::_LoadGlyphAuras() if (glyphEntry->TypeFlags == glyphSlotEntry->TypeFlags) { if (!spellInfo->Stances) - CastSpell(this, glyphEntry->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK&~(TRIGGERED_IGNORE_SHAPESHIFT|TRIGGERED_IGNORE_CASTER_AURASTATE))); + CastSpell(this, glyphEntry->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK & ~(TRIGGERED_IGNORE_SHAPESHIFT | TRIGGERED_IGNORE_CASTER_AURASTATE))); continue; } else @@ -18682,10 +18789,9 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) if (Bag* pBag = item->ToBag()) bagMap[item->GetGUIDLow()] = pBag; } - else - if (IsBagPos(item->GetPos())) - if (item->IsBag()) - invalidBagMap[item->GetGUIDLow()] = item; + else if (IsBagPos(item->GetPos())) + if (item->IsBag()) + invalidBagMap[item->GetGUIDLow()] = item; } else { @@ -18702,13 +18808,13 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) else if (invalidBagMap.find(bagGuid) != invalidBagMap.end()) { std::map::iterator itr = invalidBagMap.find(bagGuid); - if (std::find(problematicItems.begin(), problematicItems.end(),itr->second) != problematicItems.end()) + if (std::find(problematicItems.begin(), problematicItems.end(), itr->second) != problematicItems.end()) err = EQUIP_ERR_INT_BAG_ERROR; } else { sLog->outError("Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which doesnt have a valid bag (Bag GUID: %u, slot: %u). Possible cheat?", - GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot); + GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot); item->DeleteFromInventoryDB(trans); delete item; continue; @@ -18722,7 +18828,7 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) else { sLog->outError("Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which can't be loaded into inventory (Bag GUID: %u, slot: %u) by reason %u. Item will be sent by mail.", - GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot, err); + GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot, err); item->DeleteFromInventoryDB(trans); problematicItems.push_back(item); } @@ -18768,7 +18874,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', map: %u) has item (GUID: %u, entry: %u) limited to another map (%u). Deleting item.", - GetGUIDLow(), GetName().c_str(), GetMapId(), item->GetGUIDLow(), item->GetEntry(), zoneId); + GetGUIDLow(), GetName().c_str(), GetMapId(), item->GetGUIDLow(), item->GetEntry(), zoneId); #endif remove = true; } @@ -18777,7 +18883,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', diff: %u) has conjured item (GUID: %u, entry: %u) with expired lifetime (15 minutes). Deleting item.", - GetGUIDLow(), GetName().c_str(), timeDiff, item->GetGUIDLow(), item->GetEntry()); + GetGUIDLow(), GetName().c_str(), timeDiff, item->GetGUIDLow(), item->GetEntry()); #endif remove = true; } @@ -18787,7 +18893,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with expired refund time (%u). Deleting refund data and removing refundable flag.", - GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), item->GetPlayedTime()); + GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry(), item->GetPlayedTime()); #endif stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE); stmt->setUInt32(0, item->GetGUIDLow()); @@ -18812,7 +18918,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with refundable flags, but without data in item_refund_instance. Removing flag.", - GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry()); + GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry()); #endif item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE); } @@ -18842,7 +18948,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with ITEM_FIELD_FLAG_BOP_TRADEABLE flag, but without data in item_soulbound_trade_data. Removing flag.", - GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry()); + GetGUIDLow(), GetName().c_str(), item->GetGUIDLow(), item->GetEntry()); #endif item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE); } @@ -18865,7 +18971,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F else { sLog->outError("Player::_LoadInventory: player (GUID: %u, name: '%s') has broken item (GUID: %u, entry: %u) in inventory. Deleting item.", - GetGUIDLow(), GetName().c_str(), itemGuid, itemEntry); + GetGUIDLow(), GetName().c_str(), itemGuid, itemEntry); remove = true; } // Remove item from inventory if necessary @@ -18880,7 +18986,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F else { sLog->outError("Player::_LoadInventory: player (GUID: %u, name: '%s') has unknown item (entry: %u) in inventory. Deleting item.", - GetGUIDLow(), GetName().c_str(), itemEntry); + GetGUIDLow(), GetName().c_str(), itemEntry); Item::DeleteFromInventoryDB(trans, itemGuid); Item::DeleteFromDB(trans, itemGuid); } @@ -18940,8 +19046,7 @@ void Player::_LoadMailedItems(Mail* mail) } AddMItem(item); - } - while (result->NextRow()); + } while (result->NextRow()); } void Player::_LoadMailInit(PreparedQueryResult resultUnread, PreparedQueryResult resultDelivery) @@ -18980,7 +19085,7 @@ void Player::_LoadMailAsynch(PreparedQueryResult result) m->receiver = fields[17].GetUInt32(); m->subject = fields[18].GetString(); m->body = fields[19].GetString(); -// has_items = fields[20].GetBool(); + // has_items = fields[20].GetBool(); m->expire_time = time_t(fields[21].GetUInt32()); m->deliver_time = time_t(fields[22].GetUInt32()); m->money = fields[23].GetUInt32(); @@ -19042,8 +19147,7 @@ void Player::_LoadMailAsynch(PreparedQueryResult result) } prevMailID = fields[14].GetUInt32(); - } - while (result->NextRow()); + } while (result->NextRow()); m_mail.push_back(m); } @@ -19094,8 +19198,7 @@ void Player::_LoadMail() _LoadMailedItems(m); m_mail.push_back(m); - } - while (result->NextRow()); + } while (result->NextRow()); } m_mailsLoaded = true; } @@ -19126,7 +19229,7 @@ void Player::_LoadQuestStatus(PreparedQueryResult result) Field* fields = result->Fetch(); uint32 quest_id = fields[0].GetUInt32(); - // used to be new, no delete? + // used to be new, no delete? Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id); if (quest) { @@ -19140,7 +19243,7 @@ void Player::_LoadQuestStatus(PreparedQueryResult result) { questStatusData.Status = QUEST_STATUS_INCOMPLETE; sLog->outError("Player %s (GUID: %u) has invalid quest %d status (%u), replaced by QUEST_STATUS_INCOMPLETE(3).", - GetName().c_str(), GetGUIDLow(), quest_id, qstatus); + GetName().c_str(), GetGUIDLow(), quest_id, qstatus); } questStatusData.Explored = (fields[2].GetUInt8() > 0); @@ -19191,8 +19294,7 @@ void Player::_LoadQuestStatus(PreparedQueryResult result) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.Status, quest_id, GetGUIDLow()); #endif } - } - while (result->NextRow()); + } while (result->NextRow()); } // clear quest log tail @@ -19212,7 +19314,7 @@ void Player::_LoadQuestStatusRewarded(PreparedQueryResult result) Field* fields = result->Fetch(); uint32 quest_id = fields[0].GetUInt32(); - // used to be new, no delete? + // used to be new, no delete? Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id); if (quest) { @@ -19231,15 +19333,14 @@ void Player::_LoadQuestStatusRewarded(PreparedQueryResult result) } m_RewardedQuests.insert(quest_id); - } - while (result->NextRow()); + } while (result->NextRow()); } } void Player::_LoadDailyQuestStatus(PreparedQueryResult result) { for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) - SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, 0); + SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx, 0); m_DFQuests.clear(); @@ -19277,14 +19378,13 @@ void Player::_LoadDailyQuestStatus(PreparedQueryResult result) if (!quest) continue; - SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id); + SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx, quest_id); ++quest_daily_idx; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Daily quest (%u) cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); #endif - } - while (result->NextRow()); + } while (result->NextRow()); } m_DailyQuestChanged = false; @@ -19308,8 +19408,7 @@ void Player::_LoadWeeklyQuestStatus(PreparedQueryResult result) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); #endif - } - while (result->NextRow()); + } while (result->NextRow()); } m_WeeklyQuestChanged = false; @@ -19334,8 +19433,7 @@ void Player::_LoadSeasonalQuestStatus(PreparedQueryResult result) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Seasonal quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); #endif - } - while (result->NextRow()); + } while (result->NextRow()); } m_SeasonalQuestChanged = false; @@ -19357,8 +19455,7 @@ void Player::_LoadMonthlyQuestStatus(PreparedQueryResult result) m_monthlyquests.insert(quest_id); sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow()); - } - while (result->NextRow()); + } while (result->NextRow()); } m_MonthlyQuestChanged = false; @@ -19435,7 +19532,7 @@ void Player::SendRaidInfo() data << uint64(MAKE_NEW_GUID(save->GetInstanceId(), 0, HIGHGUID_INSTANCE)); // instance id data << uint8(1); // expired = 0 data << uint8(itr->second.extended ? 1 : 0);// extended = 1 - data << uint32(resetTime >= now ? resetTime-now : 0); // reset time + data << uint32(resetTime >= now ? resetTime - now : 0); // reset time ++counter; } } @@ -19511,7 +19608,7 @@ bool Player::Satisfy(AccessRequirement const* ar, uint32 target_map, bool report if (ar->item) { if (!HasItemCount(ar->item, 1) && - (!ar->item2 || !HasItemCount(ar->item2))) + (!ar->item2 || !HasItemCount(ar->item2))) missingItem = ar->item; } else if (ar->item2 && !HasItemCount(ar->item2)) @@ -19621,7 +19718,7 @@ bool Player::_LoadHomeBind(PreparedQueryResult result) // accept saved data only for valid position (and non instanceable), and accessable if (MapManager::IsValidMapCoord(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ) && - !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion()) + !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion()) ok = true; else { @@ -19651,7 +19748,7 @@ bool Player::_LoadHomeBind(PreparedQueryResult result) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Setting player home position - mapid: %u, areaid: %u, X: %f, Y: %f, Z: %f", - m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ); + m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ); #endif return true; } @@ -19811,7 +19908,7 @@ void Player::_SaveAuras(SQLTransaction& trans, bool logout) continue; Aura* aura = itr->second; - if( !logout && aura->GetDuration() < 60*IN_MILLISECONDS ) + if( !logout && aura->GetDuration() < 60 * IN_MILLISECONDS ) continue; int32 damage[MAX_SPELL_EFFECTS]; @@ -19895,7 +19992,7 @@ void Player::_SaveInventory(SQLTransaction& trans) // SMSG_ITEM_REFUND_INFO_RESPONSE packet. // Item::UpdatePlayedTime is only called when needed, which is in DB saves, and item refund info requests. RefundableItemsSet::iterator i_next; - for (RefundableItemsSet::iterator itr = m_refundableItems.begin(); itr!= m_refundableItems.end(); itr = i_next) + for (RefundableItemsSet::iterator itr = m_refundableItems.begin(); itr != m_refundableItems.end(); itr = i_next) { // use copy iterator because itr may be invalid after operations in this loop i_next = itr; @@ -20092,7 +20189,7 @@ void Player::_SaveQuestStatus(SQLTransaction& trans) stmt->setUInt32(index++, statusItr->first); stmt->setUInt8(index++, uint8(statusItr->second.Status)); stmt->setBool(index++, statusItr->second.Explored); - stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS+ sWorld->GetGameTime())); + stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS + sWorld->GetGameTime())); for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++) stmt->setUInt16(index++, statusItr->second.CreatureOrGOCount[i]); @@ -20148,11 +20245,11 @@ void Player::_SaveDailyQuestStatus(SQLTransaction& trans) trans->Append(stmt); for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) { - if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx)) + if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx)) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS); stmt->setUInt32(0, GetGUIDLow()); - stmt->setUInt32(1, GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx)); + stmt->setUInt32(1, GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx)); stmt->setUInt64(2, uint64(m_lastDailyQuestTime)); trans->Append(stmt); } @@ -20712,13 +20809,13 @@ void Player::UpdateAfkReport(time_t currTime) if (m_bgData.bgAfkReportedTimer <= currTime) { m_bgData.bgAfkReportedCount = 0; - m_bgData.bgAfkReportedTimer = currTime+5*MINUTE; + m_bgData.bgAfkReportedTimer = currTime + 5 * MINUTE; } } void Player::UpdateContestedPvP(uint32 diff) { - if (!m_contestedPvPTimer||IsInCombat()) + if (!m_contestedPvPTimer || IsInCombat()) return; if (m_contestedPvPTimer <= diff) { @@ -21004,7 +21101,7 @@ void Player::PetSpellInitialize() CharmInfo* charmInfo = pet->GetCharmInfo(); - WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1); + WorldPacket data(SMSG_PET_SPELLS, 8 + 2 + 4 + 4 + 4 * MAX_UNIT_ACTION_BAR_INDEX + 1 + 1); data << uint64(pet->GetGUID()); data << uint16(pet->GetCreatureTemplate()->family); // creature family (required for pet talents) data << uint32(pet->GetDuration()); @@ -21068,7 +21165,7 @@ void Player::PossessSpellInitialize() return; } - WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1); + WorldPacket data(SMSG_PET_SPELLS, 8 + 2 + 4 + 4 + 4 * MAX_UNIT_ACTION_BAR_INDEX + 1 + 1); data << uint64(charm->GetGUID()); data << uint16(0); data << uint32(0); @@ -21105,7 +21202,7 @@ void Player::VehicleSpellInitialize() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) { - data << uint16(0) << uint8(0) << uint8(i+8); + data << uint16(0) << uint8(0) << uint8(i + 8); continue; } @@ -21115,14 +21212,14 @@ void Player::VehicleSpellInitialize() #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CONDITIONSYS, "VehicleSpellInitialize: conditions not met for Vehicle entry %u spell %u", vehicle->ToCreature()->GetEntry(), spellId); #endif - data << uint16(0) << uint8(0) << uint8(i+8); + data << uint16(0) << uint8(0) << uint8(i + 8); continue; } if (spellInfo->IsPassive()) vehicle->CastSpell(vehicle, spellId, true); - data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId, i+8)); + data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId, i + 8)); } for (uint32 i = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i) @@ -21172,7 +21269,7 @@ void Player::CharmSpellInitialize() } } - WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1); + WorldPacket data(SMSG_PET_SPELLS, 8 + 2 + 4 + 4 + 4 * MAX_UNIT_ACTION_BAR_INDEX + 1 + 4 * addlist + 1); data << uint64(charm->GetGUID()); data << uint16(0); data << uint32(0); @@ -21235,29 +21332,29 @@ bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod // Binary predicate for sorting SpellModifiers class SpellModPred { - public: - SpellModPred() {} - bool operator() (const SpellModifier* a, const SpellModifier* b) const - { - if (a->type != b->type) - return a->type == SPELLMOD_FLAT; - return a->value < b->value; - } +public: + SpellModPred() {} + bool operator() (const SpellModifier* a, const SpellModifier* b) const + { + if (a->type != b->type) + return a->type == SPELLMOD_FLAT; + return a->value < b->value; + } }; class MageSpellModPred { - public: - MageSpellModPred() {} - bool operator() (const SpellModifier* a, const SpellModifier* b) const - { - if (a->type != b->type) - return a->type == SPELLMOD_FLAT; - if (a->spellId == 44401) - return true; - if (b->spellId == 44401) - return false; - return a->value < b->value; - } +public: + MageSpellModPred() {} + bool operator() (const SpellModifier* a, const SpellModifier* b) const + { + if (a->type != b->type) + return a->type == SPELLMOD_FLAT; + if (a->spellId == 44401) + return true; + if (b->spellId == 44401) + return false; + return a->value < b->value; + } }; void Player::AddSpellMod(SpellModifier* mod, bool apply) @@ -21271,10 +21368,10 @@ void Player::AddSpellMod(SpellModifier* mod, bool apply) flag96 _mask = 0; for (int eff = 0; eff < 96; ++eff) { - if (eff != 0 && eff%32 == 0) + if (eff != 0 && eff % 32 == 0) _mask[i++] = 0; - _mask[i] = uint32(1) << (eff-(32*i)); + _mask[i] = uint32(1) << (eff - (32 * i)); if (mod->mask & _mask) { int32 val = 0; @@ -21284,7 +21381,7 @@ void Player::AddSpellMod(SpellModifier* mod, bool apply) val += (*itr)->value; } val += apply ? mod->value : -(mod->value); - WorldPacket data(Opcode, (1+1+4)); + WorldPacket data(Opcode, (1 + 1 + 4)); data << uint8(eff); data << uint8(mod->op); data << int32(val); @@ -21317,7 +21414,7 @@ void Player::RestoreSpellMods(Spell* spell, uint32 ownerAuraId, Aura* aura) std::list aurasQueue; - for (uint8 i=0; im_appliedMods.empty()) return; - const SpellInfo *const spellInfo = spell->m_spellInfo; + const SpellInfo* const spellInfo = spell->m_spellInfo; - for (uint8 i=0; iSpellFamilyName == SPELLFAMILY_MAGE ) { - const SpellInfo *sp = mod->ownerAura->GetSpellInfo(); + const SpellInfo* sp = mod->ownerAura->GetSpellInfo(); // Missile Barrage, Hot Streak, Brain Freeze (trigger spell - Fireball!) if( sp->SpellIconID == 3261 || sp->SpellIconID == 2999 || sp->SpellIconID == 2938 ) - if( AuraEffect *aurEff = GetAuraEffectDummy(64869) ) + if( AuraEffect* aurEff = GetAuraEffectDummy(64869) ) if( roll_chance_i(aurEff->GetAmount()) ) { mod->charges = 1; @@ -21574,8 +21671,7 @@ void Player::LeaveAllArenaTeams(uint64 guid) if (arenaTeam) arenaTeam->DelMember(guid, true); } - } - while (result->NextRow()); + } while (result->NextRow()); } void Player::SetRestBonus(float rest_bonus_new) @@ -21587,7 +21683,7 @@ void Player::SetRestBonus(float rest_bonus_new) if (rest_bonus_new < 0) rest_bonus_new = 0; - float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2; + float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) * 1.5f / 2; if (rest_bonus_new > rest_bonus_max) _restBonus = rest_bonus_max; @@ -21680,10 +21776,10 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f) { if (node->map_id != GetMapId() || - (node->x - GetPositionX())*(node->x - GetPositionX())+ - (node->y - GetPositionY())*(node->y - GetPositionY())+ - (node->z - GetPositionZ())*(node->z - GetPositionZ()) > - (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)) + (node->x - GetPositionX()) * (node->x - GetPositionX()) + + (node->y - GetPositionY()) * (node->y - GetPositionY()) + + (node->z - GetPositionZ()) * (node->z - GetPositionZ()) > + (2 * INTERACTION_DISTANCE) * (2 * INTERACTION_DISTANCE) * (2 * INTERACTION_DISTANCE)) { GetSession()->SendActivateTaxiReply(ERR_TAXITOOFARAWAY); return false; @@ -21763,7 +21859,7 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc uint32 money = GetMoney(); if (npc) - totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc)); + totalcost = (uint32)ceil(totalcost * GetReputationPriceDiscount(npc)); if (money < totalcost) { @@ -21783,7 +21879,7 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc // Xinef: dont use instant flight paths if spellid is present (custom calls use spellid = 1) if ((sWorld->getIntConfig(CONFIG_INSTANT_TAXI) == 1 || (sWorld->getIntConfig(CONFIG_INSTANT_TAXI) == 2 && m_isInstantFlightOn)) && !spellid) { - TaxiNodesEntry const* lastPathNode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]); + TaxiNodesEntry const* lastPathNode = sTaxiNodesStore.LookupEntry(nodes[nodes.size() - 1]); m_taxi.ClearTaxiDestinations(); TeleportTo(lastPathNode->map_id, lastPathNode->x, lastPathNode->y, lastPathNode->z, GetOrientation()); return false; @@ -21840,20 +21936,20 @@ void Player::ContinueTaxiFlight() TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path]; - float bestDist = SIZE_OF_GRIDS*SIZE_OF_GRIDS; // xinef: large value + float bestDist = SIZE_OF_GRIDS * SIZE_OF_GRIDS; // xinef: large value float currDist = 0.0f; // xinef: changed to -1, we dont want to catch last node for (uint32 i = 0; i < nodeList.size() - 1; ++i) { TaxiPathNodeEntry const* node = nodeList[i]; - TaxiPathNodeEntry const* nextNode = nodeList[i+1]; + TaxiPathNodeEntry const* nextNode = nodeList[i + 1]; // xinef: skip nodes at another map, get last valid node on current map if (nextNode->mapid != GetMapId() || node->mapid != GetMapId()) continue; - currDist = (node->x - GetPositionX())*(node->x - GetPositionX())+(node->y - GetPositionY())*(node->y - GetPositionY())+(node->z - GetPositionZ())*(node->z - GetPositionZ()); + currDist = (node->x - GetPositionX()) * (node->x - GetPositionX()) + (node->y - GetPositionY()) * (node->y - GetPositionY()) + (node->z - GetPositionZ()) * (node->z - GetPositionZ()); if (currDist < bestDist) { startNode = i; @@ -21927,25 +22023,25 @@ void Player::InitDataForForm(bool reapplyMods) { case FORM_GHOUL: case FORM_CAT: - { - if (getPowerType() != POWER_ENERGY) - setPowerType(POWER_ENERGY); - break; - } + { + if (getPowerType() != POWER_ENERGY) + setPowerType(POWER_ENERGY); + break; + } case FORM_BEAR: case FORM_DIREBEAR: - { - if (getPowerType() != POWER_RAGE) - setPowerType(POWER_RAGE); - break; - } + { + if (getPowerType() != POWER_RAGE) + setPowerType(POWER_RAGE); + break; + } default: // 0, for example - { - ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass()); - if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType) - setPowerType(Powers(cEntry->powerType)); - break; - } + { + ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass()); + if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType) + setPowerType(Powers(cEntry->powerType)); + break; + } } // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change. @@ -21987,8 +22083,8 @@ inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 c ItemPosCountVec vDest; uint16 uiDest = 0; InventoryResult msg = bStore ? - CanStoreNewItem(bag, slot, vDest, item, pProto->BuyCount * count) : - CanEquipNewItem(slot, uiDest, item, false); + CanStoreNewItem(bag, slot, vDest, item, pProto->BuyCount * count) : + CanEquipNewItem(slot, uiDest, item, false); if (msg != EQUIP_ERR_OK) { SendEquipError(msg, nullptr, nullptr, item); @@ -22014,13 +22110,13 @@ inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 c } Item* it = bStore ? - StoreNewItem(vDest, item, true) : - EquipNewItem(uiDest, item, true); + StoreNewItem(vDest, item, true) : + EquipNewItem(uiDest, item, true); if (it) { uint32 new_count = pVendor->UpdateVendorItemCurrentCount(crItem, pProto->BuyCount * count); - WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4)); + WorldPacket data(SMSG_BUY_ITEM, (8 + 4 + 4 + 4)); data << uint64(pVendor->GetGUID()); data << uint32(vendorslot + 1); // numbered from 1 at client data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF); @@ -22047,7 +22143,7 @@ inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 c // Return true is the bought item has a max count to force refresh of window by caller bool Player::BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot) { - sScriptMgr->OnBeforeBuyItemFromVendor(this, vendorguid,vendorslot,item,count,bag,slot); + sScriptMgr->OnBeforeBuyItemFromVendor(this, vendorguid, vendorslot, item, count, bag, slot); // this check can be used from the hook to implement a custom vendor process if (item == 0) @@ -22057,7 +22153,7 @@ bool Player::BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 if (count < 1) count = 1; // cheating attempt - if (slot > MAX_BAG_SIZE && slot !=NULL_SLOT) + if (slot > MAX_BAG_SIZE && slot != NULL_SLOT) return false; if (!IsAlive()) @@ -22249,7 +22345,7 @@ void Player::UpdateHomebindTime(uint32 time) if (m_HomebindTimer) // instance valid, but timer not reset { // hide reminder - WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); + WorldPacket data(SMSG_RAID_GROUP_ONLY, 4 + 4); data << uint32(0); data << uint32(0); GetSession()->SendPacket(&data); @@ -22272,7 +22368,7 @@ void Player::UpdateHomebindTime(uint32 time) // instance is invalid, start homebind timer m_HomebindTimer = 60000; // send message to player - WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); + WorldPacket data(SMSG_RAID_GROUP_ONLY, 4 + 4); data << uint32(m_HomebindTimer); data << uint32(1); GetSession()->SendPacket(&data); @@ -22287,7 +22383,7 @@ void Player::UpdatePvPState(bool onlyFFA) // TODO: should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled? // no, we shouldn't, those are checked for affecting player by client if (!pvpInfo.IsInNoPvPArea && !IsGameMaster() - && (pvpInfo.IsInFFAPvPArea || sWorld->IsFFAPvPRealm())) + && (pvpInfo.IsInFFAPvPArea || sWorld->IsFFAPvPRealm())) { if (!IsFFAPvP()) { @@ -22451,17 +22547,17 @@ void Player::AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 ite void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, uint32 end_time, bool needSendToClient, bool forceSendToSpectator) { SpellCooldown sc; - sc.end = World::GetGameTimeMS()+end_time; + sc.end = World::GetGameTimeMS() + end_time; sc.itemid = itemid; sc.maxduration = end_time; sc.sendToSpectator = false; sc.needSendToClient = needSendToClient; - if (end_time >= SPECTATOR_COOLDOWN_MIN*IN_MILLISECONDS && end_time <= SPECTATOR_COOLDOWN_MAX*IN_MILLISECONDS) + if (end_time >= SPECTATOR_COOLDOWN_MIN * IN_MILLISECONDS && end_time <= SPECTATOR_COOLDOWN_MAX * IN_MILLISECONDS) if (NeedSendSpectatorData() && forceSendToSpectator && (itemid || HasActiveSpell(spellid))) { sc.sendToSpectator = true; - ArenaSpectator::SendCommand_Cooldown(FindMap(), GetGUID(), "ACD", spellid, end_time/IN_MILLISECONDS, end_time/IN_MILLISECONDS); + ArenaSpectator::SendCommand_Cooldown(FindMap(), GetGUID(), "ACD", spellid, end_time / IN_MILLISECONDS, end_time / IN_MILLISECONDS); } m_spellCooldowns[spellid] = sc; } @@ -22510,7 +22606,7 @@ void Player::UpdatePotionCooldown() SetLastPotionId(0); } - //slot to be excluded while counting +//slot to be excluded while counting bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) { if (!enchantmentcondition) @@ -22577,7 +22673,7 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) uint32 _cur_gem = curcount[Condition->Color[i] - 1]; // if have use them as count, else use from Condition - uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i]; + uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1] : Condition->Value[i]; switch (Condition->Comparator[i]) { @@ -22602,7 +22698,7 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) { - //cycle all equipped items + //cycle all equipped items for (uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) { //enchants for the slot being socketed are handled by Player::ApplyItemMods @@ -22614,7 +22710,7 @@ void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) if (!pItem || !pItem->GetTemplate()->Socket[0].Color) continue; - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + 3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) @@ -22627,13 +22723,13 @@ void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) uint32 condition = enchantEntry->EnchantmentCondition; if (condition) { - //was enchant active with/without item? + //was enchant active with/without item? bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1); - //should it now be? + //should it now be? if (wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot)) { // ignore item gem conditions - //if state changed, (dis)apply enchant + //if state changed, (dis)apply enchant ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true); } } @@ -22641,7 +22737,7 @@ void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) } } - //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements +//if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) { //cycle all equipped items @@ -22657,7 +22753,7 @@ void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) continue; //cycle all (gem)enchants - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + 3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) //if no enchant go to next enchant(slot) @@ -22725,7 +22821,7 @@ void Player::LeaveBattleground(Battleground* bg) // Deserter tracker - leave BG if (bg->isBattleground() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS) - && (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)) + && (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->setUInt32(0, GetGUIDLow()); @@ -23020,7 +23116,7 @@ void Player::UpdateObjectVisibility(bool forced, bool fromUpdate) void Player::UpdateVisibilityForPlayer(bool mapChange) { acore::VisibleNotifier notifierNoLarge(*this, mapChange, false); // visit only objects which are not large; default distance - m_seer->VisitNearbyObject(GetSightRange()+VISIBILITY_INC_FOR_GOBJECTS, notifierNoLarge); + m_seer->VisitNearbyObject(GetSightRange() + VISIBILITY_INC_FOR_GOBJECTS, notifierNoLarge); notifierNoLarge.SendToSelf(); acore::VisibleNotifier notifierLarge(*this, mapChange, true); // visit only large objects; maximum distance m_seer->VisitNearbyObject(MAX_VISIBILITY_DISTANCE, notifierLarge); @@ -23089,11 +23185,11 @@ void Player::SendComboPoints() WorldPacket data; if (m_mover != this) { - data.Initialize(SMSG_PET_UPDATE_COMBO_POINTS, m_mover->GetPackGUID().size()+combotarget->GetPackGUID().size()+1); + data.Initialize(SMSG_PET_UPDATE_COMBO_POINTS, m_mover->GetPackGUID().size() + combotarget->GetPackGUID().size() + 1); data.append(m_mover->GetPackGUID()); } else - data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1); + data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size() + 1); data.append(combotarget->GetPackGUID()); data << uint8(m_comboPoints); GetSession()->SendPacket(&data); @@ -23105,7 +23201,7 @@ void Player::AddComboPoints(Unit* target, int8 count) if (!count) return; - int8 * comboPoints = &m_comboPoints; + int8* comboPoints = &m_comboPoints; // without combo points lost (duration checked in aura) RemoveAurasByType(SPELL_AURA_RETAIN_COMBO_POINTS); @@ -23174,7 +23270,7 @@ void Player::SendInitialPacketsBeforeAddToMap() // guild bank list wtf? // Homebind - WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4); + WorldPacket data(SMSG_BINDPOINTUPDATE, 5 * 4); data << m_homebindX << m_homebindY << m_homebindZ; data << (uint32) m_homebindMapId; data << (uint32) m_homebindAreaId; @@ -23188,7 +23284,7 @@ void Player::SendInitialPacketsBeforeAddToMap() SendTalentsInfoData(false); // SMSG_INSTANCE_DIFFICULTY - data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4); + data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4 + 4); data << uint32(GetMap()->GetDifficulty()); data << uint32(GetMap()->GetEntry()->IsDynamicDifficultyMap() && GetMap()->IsHeroic()); // Raid dynamic difficulty GetSession()->SendPacket(&data); @@ -23304,7 +23400,7 @@ void Player::SendUpdateToOutOfRangeGroupMembers() void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg) { - WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2); + WorldPacket data(SMSG_TRANSFER_ABORTED, 4 + 2); data << uint32(mapid); data << uint8(reason); // transfer abort reason switch (reason) @@ -23343,7 +23439,7 @@ void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint3 else type = RAID_INSTANCE_WARNING_MIN_SOON; - WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4); + WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4 + 4 + 4 + 4); data << uint32(type); data << uint32(mapid); data << uint32(difficulty); // difficulty @@ -23373,7 +23469,7 @@ void Player::ApplyEquipCooldown(Item* pItem) if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_EQUIP) { // xinef: uint32(-1) special marker for proc cooldowns - AddSpellCooldown(spellData.SpellId, uint32(-1), 30*IN_MILLISECONDS); + AddSpellCooldown(spellData.SpellId, uint32(-1), 30 * IN_MILLISECONDS); continue; } @@ -23395,7 +23491,7 @@ void Player::ApplyEquipCooldown(Item* pItem) if (spellInfo && spellInfo->HasAttribute(SPELL_ATTR0_CANT_USED_IN_COMBAT)) continue; - AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), 30*IN_MILLISECONDS, true, true); + AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), 30 * IN_MILLISECONDS, true, true); WorldPacket data(SMSG_ITEM_COOLDOWN, 12); data << pItem->GetGUID(); @@ -23478,7 +23574,7 @@ void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value) { uint32 raceMask = getRaceMask(); uint32 classMask = getClassMask(); - for (uint32 j=0; jskillId != skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL) @@ -23542,7 +23638,7 @@ void Player::GetAurasForTarget(Unit* target) // pussywizard: contact before chan Unit::VisibleAuraMap const* visibleAuras = target->GetVisibleAuras(); for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr) { - AuraApplication * auraApp = itr->second; + AuraApplication* auraApp = itr->second; auraApp->BuildUpdatePacket(data, false); } @@ -23557,15 +23653,16 @@ void Player::SetDailyQuestStatus(uint32 quest_id) { for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) { - if (!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx)) + if (!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx)) { - SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id); + SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx, quest_id); m_lastDailyQuestTime = time(nullptr); // last daily quest time m_DailyQuestChanged = true; break; } } - } else + } + else { m_DFQuests.insert(quest_id); m_lastDailyQuestTime = time(nullptr); @@ -23599,7 +23696,7 @@ void Player::SetMonthlyQuestStatus(uint32 quest_id) void Player::ResetDailyQuestStatus() { for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) - SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, 0); + SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx, 0); m_DFQuests.clear(); // Dungeon Finder Quests. @@ -23706,7 +23803,7 @@ float Player::GetReputationPriceDiscount(Creature const* creature) const if (rank <= REP_NEUTRAL) return 1.0f; - return 1.0f - 0.05f* (rank - REP_NEUTRAL); + return 1.0f - 0.05f * (rank - REP_NEUTRAL); } bool Player::IsSpellFitByClassAndRace(uint32 spell_id) const @@ -23777,7 +23874,7 @@ void Player::UpdateForQuestWorldObjects() UpdateData udata; WorldPacket packet; - for (ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr) + for (ClientGUIDs::iterator itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr) { if (IS_GAMEOBJECT_GUID(*itr)) { @@ -23928,33 +24025,33 @@ bool Player::HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item cons switch (spellInfo->EquippedItemClass) { case ITEM_CLASS_WEAPON: - { - for (uint8 i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i) - if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i)) - if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) - return true; - break; - } + { + for (uint8 i = EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i) + if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i)) + if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) + return true; + break; + } case ITEM_CLASS_ARMOR: - { - // tabard not have dependent spells - for (uint8 i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i) - if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i)) + { + // tabard not have dependent spells + for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_MAINHAND; ++i) + if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i)) + if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) + return true; + + // shields can be equipped to offhand slot + if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) return true; - // shields can be equipped to offhand slot - if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) - if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) - return true; + // ranged slot can have some armor subclasses + if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) + if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) + return true; - // ranged slot can have some armor subclasses - if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) - if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo)) - return true; - - break; - } + break; + } default: sLog->outError("HasItemFitToSpellRequirements: Not handled spell requirement for item class %u", spellInfo->EquippedItemClass); break; @@ -23972,8 +24069,8 @@ bool Player::CanNoReagentCast(SpellInfo const* spellInfo) const // Check no reagent use mask flag96 noReagentMask; noReagentMask[0] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1); - noReagentMask[1] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+1); - noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2); + noReagentMask[1] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1 + 1); + noReagentMask[2] = GetUInt32Value(PLAYER_NO_REAGENT_COST_1 + 2); if (spellInfo->SpellFamilyFlags & noReagentMask) return true; @@ -24025,13 +24122,27 @@ uint32 Player::GetResurrectionSpellId() { switch ((*itr)->GetId()) { - case 20707: spell_id = 3026; break; // rank 1 - case 20762: spell_id = 20758; break; // rank 2 - case 20763: spell_id = 20759; break; // rank 3 - case 20764: spell_id = 20760; break; // rank 4 - case 20765: spell_id = 20761; break; // rank 5 - case 27239: spell_id = 27240; break; // rank 6 - case 47883: spell_id = 47882; break; // rank 7 + case 20707: + spell_id = 3026; + break; // rank 1 + case 20762: + spell_id = 20758; + break; // rank 2 + case 20763: + spell_id = 20759; + break; // rank 3 + case 20764: + spell_id = 20760; + break; // rank 4 + case 20765: + spell_id = 20761; + break; // rank 5 + case 27239: + spell_id = 27240; + break; // rank 6 + case 47883: + spell_id = 47882; + break; // rank 7 default: sLog->outError("Unhandled spell %u: S.Resurrection", (*itr)->GetId()); continue; @@ -24067,9 +24178,9 @@ bool Player::isHonorOrXPTarget(Unit* victim) const if (victim->GetTypeId() == TYPEID_UNIT) { if (victim->IsTotem() || - victim->IsPet() || - victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL) - return false; + victim->IsPet() || + victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL) + return false; } return true; } @@ -24139,7 +24250,7 @@ void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewar continue; // member (alive or dead) or his corpse at req. distance // quest objectives updated only for alive group member or dead but with not released body - if (player->IsAlive()|| !player->GetCorpse()) + if (player->IsAlive() || !player->GetCorpse()) player->KilledMonsterCredit(creature_id, creature_guid); } } @@ -24220,9 +24331,9 @@ void Player::ResurectUsingRequestData() void Player::SetClientControl(Unit* target, bool allowMove, bool packetOnly /*= false*/) { - WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1); + WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size() + 1); data.append(target->GetPackGUID()); - data << uint8((allowMove && !target->HasUnitState(UNIT_STATE_FLEEING|UNIT_STATE_CONFUSED)) ? 1 : 0); + data << uint8((allowMove && !target->HasUnitState(UNIT_STATE_FLEEING | UNIT_STATE_CONFUSED)) ? 1 : 0); GetSession()->SendPacket(&data); // We want to set the packet only @@ -24360,7 +24471,7 @@ void Player::UpdateCorpseReclaimDelay() bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH; if ((pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) || - (!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))) + (!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))) return; time_t now = time(nullptr); @@ -24371,9 +24482,9 @@ void Player::UpdateCorpseReclaimDelay() uint64 count = (m_deathExpireTime - now) / DEATH_EXPIRE_STEP + 1; if (count < MAX_DEATH_COUNT) - m_deathExpireTime = now+(count + 1) * DEATH_EXPIRE_STEP; + m_deathExpireTime = now + (count + 1) * DEATH_EXPIRE_STEP; else - m_deathExpireTime = now + MAX_DEATH_COUNT*DEATH_EXPIRE_STEP; + m_deathExpireTime = now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP; } else m_deathExpireTime = now + DEATH_EXPIRE_STEP; @@ -24398,7 +24509,7 @@ int32 Player::CalculateCorpseReclaimDelay(bool load) uint64 count = 0; if ((pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) || - (!pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))) + (!pvp && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))) { count = (m_deathExpireTime - corpse->GetGhostTime()) / DEATH_EXPIRE_STEP; @@ -24442,14 +24553,14 @@ Player* Player::GetNextRandomRaidMember(float radius) // IsHostileTo check duel and controlled by enemy if (Target && Target != this && IsWithinDistInMap(Target, radius) && - !Target->HasInvisibilityAura() && !IsHostileTo(Target)) + !Target->HasInvisibilityAura() && !IsHostileTo(Target)) nearMembers.push_back(Target); } if (nearMembers.empty()) return nullptr; - uint32 randTarget = urand(0, nearMembers.size()-1); + uint32 randTarget = urand(0, nearMembers.size() - 1); return nearMembers[randTarget]; } @@ -24516,7 +24627,7 @@ bool Player::inRandomLfgDungeon() return false; } -void Player::SetBattlegroundOrBattlefieldRaid(Group *group, int8 subgroup) +void Player::SetBattlegroundOrBattlefieldRaid(Group* group, int8 subgroup) { //we must move references from m_group to m_originalGroup if (GetGroup() && (GetGroup()->isBGGroup() || GetGroup()->isBFGroup())) @@ -24560,7 +24671,7 @@ void Player::SetOriginalGroup(Group* group, int8 subgroup) void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) { // pussywizard: optimization - if (GetExactDistSq(&m_last_underwaterstate_position) < 3.0f*3.0f) + if (GetExactDistSq(&m_last_underwaterstate_position) < 3.0f * 3.0f) return; m_last_underwaterstate_position.Relocate(m_positionX, m_positionY, m_positionZ); @@ -24761,9 +24872,9 @@ bool Player::CanUseBattlegroundObject(GameObject* gameobject) const bool Player::CanCaptureTowerPoint() const { return (!HasStealthAura() && // not stealthed - !HasInvisibilityAura() && // not invisible - IsAlive() // live player -); + !HasInvisibilityAura() && // not invisible + IsAlive() // live player + ); } uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin) @@ -24910,7 +25021,7 @@ void Player::UpdateCharmedAI() if (HasUnitState(UNIT_STATE_CASTING)) return; - bool Mages = getClassMask() & (1<<(CLASS_MAGE-1) | 1<<(CLASS_WARLOCK-1) | 1<<(CLASS_DRUID-1) | 1<<(CLASS_HUNTER-1) | 1<<(CLASS_PRIEST-1)); + bool Mages = getClassMask() & (1 << (CLASS_MAGE - 1) | 1 << (CLASS_WARLOCK - 1) | 1 << (CLASS_DRUID - 1) | 1 << (CLASS_HUNTER - 1) | 1 << (CLASS_PRIEST - 1)); // Xinef: charmer type specific actions if (charmer->GetTypeId() == TYPEID_PLAYER) @@ -24956,7 +25067,7 @@ void Player::UpdateCharmedAI() else { float Distance = GetDistance(target); - uint8 rnd = urand(0,1); + uint8 rnd = urand(0, 1); if (Mages) { @@ -24968,7 +25079,7 @@ void Player::UpdateCharmedAI() if (Distance <= 3) { - if (urand(0,1)) + if (urand(0, 1)) { if (m_charmAISpells[SPELL_T_STUN] && !HasSpellCooldown(m_charmAISpells[SPELL_T_STUN])) CastSpell(target, m_charmAISpells[SPELL_T_STUN], false); @@ -24979,35 +25090,35 @@ void Player::UpdateCharmedAI() } else { - switch (urand(0,1)) + switch (urand(0, 1)) { - case 0: - if (m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd])) - CastSpell(target, m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd], false); - break; - case 1: - if (m_charmAISpells[SPELL_DOT_DAMAGE] && !HasSpellCooldown(m_charmAISpells[SPELL_DOT_DAMAGE])) - CastSpell(target, m_charmAISpells[SPELL_DOT_DAMAGE], false); - break; + case 0: + if (m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd])) + CastSpell(target, m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd], false); + break; + case 1: + if (m_charmAISpells[SPELL_DOT_DAMAGE] && !HasSpellCooldown(m_charmAISpells[SPELL_DOT_DAMAGE])) + CastSpell(target, m_charmAISpells[SPELL_DOT_DAMAGE], false); + break; } } } else { - switch (urand(0,2)) + switch (urand(0, 2)) { - case 0: - if (m_charmAISpells[SPELL_HIGH_DAMAGE1+rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_HIGH_DAMAGE1+rnd])) - CastSpell(target, m_charmAISpells[SPELL_HIGH_DAMAGE1+rnd], false); - break; - case 1: - if (m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd])) - CastSpell(target, m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd], false); - break; - case 2: - if (m_charmAISpells[SPELL_DOT_DAMAGE] && !HasSpellCooldown(m_charmAISpells[SPELL_DOT_DAMAGE])) - CastSpell(target, m_charmAISpells[SPELL_DOT_DAMAGE], false); - break; + case 0: + if (m_charmAISpells[SPELL_HIGH_DAMAGE1 + rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_HIGH_DAMAGE1 + rnd])) + CastSpell(target, m_charmAISpells[SPELL_HIGH_DAMAGE1 + rnd], false); + break; + case 1: + if (m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd])) + CastSpell(target, m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd], false); + break; + case 2: + if (m_charmAISpells[SPELL_DOT_DAMAGE] && !HasSpellCooldown(m_charmAISpells[SPELL_DOT_DAMAGE])) + CastSpell(target, m_charmAISpells[SPELL_DOT_DAMAGE], false); + break; } } } @@ -25025,15 +25136,15 @@ void Player::UpdateCharmedAI() if (HasUnitState(UNIT_STATE_CASTING)) return; - switch (urand(0,2)) + switch (urand(0, 2)) { case 0: - if (m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd])) - CastSpell(target, m_charmAISpells[SPELL_INSTANT_DAMAGE+rnd], false); + if (m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd])) + CastSpell(target, m_charmAISpells[SPELL_INSTANT_DAMAGE + rnd], false); break; case 1: - if (m_charmAISpells[SPELL_HIGH_DAMAGE1+rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_HIGH_DAMAGE1+rnd])) - CastSpell(target, m_charmAISpells[SPELL_HIGH_DAMAGE1+rnd], false); + if (m_charmAISpells[SPELL_HIGH_DAMAGE1 + rnd] && !HasSpellCooldown(m_charmAISpells[SPELL_HIGH_DAMAGE1 + rnd])) + CastSpell(target, m_charmAISpells[SPELL_HIGH_DAMAGE1 + rnd], false); break; case 2: if (m_charmAISpells[SPELL_DOT_DAMAGE] && !HasSpellCooldown(m_charmAISpells[SPELL_DOT_DAMAGE])) @@ -25049,13 +25160,13 @@ uint32 Player::GetRuneBaseCooldown(uint8 index, bool skipGrace) uint8 rune = GetBaseRune(index); uint32 cooldown = RUNE_BASE_COOLDOWN; if (!skipGrace) - cooldown -= GetGracePeriod(index) < 250 ? 0 : GetGracePeriod(index)-250; // xinef: reduce by grace period, treat first 250ms as instant use of rune + cooldown -= GetGracePeriod(index) < 250 ? 0 : GetGracePeriod(index) - 250; // xinef: reduce by grace period, treat first 250ms as instant use of rune AuraEffectList const& regenAura = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); - for (AuraEffectList::const_iterator i = regenAura.begin();i != regenAura.end(); ++i) + for (AuraEffectList::const_iterator i = regenAura.begin(); i != regenAura.end(); ++i) { if ((*i)->GetMiscValue() == POWER_RUNE && (*i)->GetMiscValueB() == rune) - cooldown = cooldown*(100-(*i)->GetAmount())/100; + cooldown = cooldown * (100 - (*i)->GetAmount()) / 100; } return cooldown; @@ -25289,7 +25400,7 @@ void Player::StoreLootItem(uint8 lootSlot, Loot* loot) SendEquipError(msg, nullptr, nullptr, item->itemid); } -void Player::UpdateLootAchievements(LootItem *item, Loot* loot) +void Player::UpdateLootAchievements(LootItem* item, Loot* loot) { UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, item->itemid, item->count); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE, loot->loot_type, item->count); @@ -25298,7 +25409,7 @@ void Player::UpdateLootAchievements(LootItem *item, Loot* loot) uint32 Player::CalculateTalentsPoints() const { - uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9; + uint32 base_talent = getLevel() < 10 ? 0 : getLevel() - 9; if (getClass() != CLASS_DEATH_KNIGHT || GetMapId() != 609) return uint32(base_talent * sWorld->getRate(RATE_TALENT)); @@ -25395,8 +25506,7 @@ void Player::_LoadSkills(PreparedQueryResult result) sLog->outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS); break; } - } - while (result->NextRow()); + } while (result->NextRow()); } for (; count < PLAYER_MAX_SKILLS; ++count) @@ -25412,7 +25522,7 @@ void Player::_LoadSkills(PreparedQueryResult result) uint8 base_level = std::min(getLevel(), uint8(sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL))); if (base_level < 1) base_level = 1; - uint16 base_skill = (base_level-1)*5; // 270 at starting level 55 + uint16 base_skill = (base_level - 1) * 5; // 270 at starting level 55 if (base_skill < 1) base_skill = 1; // skill mast be known and then > 0 in any case @@ -25460,7 +25570,7 @@ InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limi return res; // check unique-equipped on gems - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + 3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) @@ -25475,7 +25585,7 @@ InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limi // include for check equip another gems with same limit category for not equipped item (and then not counted) uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory - ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1; + ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1; if (InventoryResult res = CanEquipUniqueItem(pGem, eslot, gem_limit_count)) return res; @@ -25523,18 +25633,18 @@ void Player::HandleFall(MovementInfo const& movementInfo) //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored // 14.57 can be calculated by resolving damageperc formula below to 0 if (z_diff >= 14.57f && !isDead() && !IsGameMaster() && - !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) && - !HasAuraType(SPELL_AURA_FLY)) + !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) && + !HasAuraType(SPELL_AURA_FLY)) { //Safe fall, fall height reduction int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL); - float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f; + float damageperc = 0.018f * (z_diff - safe_fall) - 0.2426f; uint32 original_health = GetHealth(), final_damage = 0; if (damageperc > 0 && !IsImmunedToDamageOrSchool(SPELL_SCHOOL_MASK_NORMAL)) { - uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld->getRate(RATE_DAMAGE_FALL)); + uint32 damage = (uint32)(damageperc * GetMaxHealth() * sWorld->getRate(RATE_DAMAGE_FALL)); //float height = movementInfo.pos.m_positionZ; //UpdateGroundPositionZ(movementInfo.pos.m_positionX, movementInfo.pos.m_positionY, height); @@ -25547,7 +25657,7 @@ void Player::HandleFall(MovementInfo const& movementInfo) // Gust of Wind if (HasAura(43621)) - damage = GetMaxHealth()/2; + damage = GetMaxHealth() / 2; final_damage = EnvironmentalDamage(DAMAGE_FALL, damage); } @@ -25560,7 +25670,7 @@ void Player::HandleFall(MovementInfo const& movementInfo) // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case if (IsAlive() && final_damage < original_health) - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100)); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff * 100)); } } @@ -25638,7 +25748,7 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) { if (talentInfo->RankID[rank] && HasTalent(talentInfo->RankID[rank], GetActiveSpec())) { - currentTalentRank = rank+1; + currentTalentRank = rank + 1; break; } } @@ -25683,7 +25793,7 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) if (TalentEntry const* itrTalentInfo = sTalentStore.LookupEntry(talentPos->talent_id)) if (itrTalentInfo->TalentTab == talentInfo->TalentTab) if (itr->second->State != PLAYERSPELL_REMOVED && itr->second->IsInSpec(GetActiveSpec())) // pussywizard - spentPoints += talentPos->rank+1; + spentPoints += talentPos->rank + 1; } // xinef: we do not have enough talent points to add talent of this tier @@ -25775,7 +25885,7 @@ void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) // find current max talent rank (0~5) uint8 curtalent_maxrank = 0; // 0 = not learned any rank - for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) + for (int8 rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank])) { @@ -25868,7 +25978,7 @@ void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank) void Player::AddKnownCurrency(uint32 itemId) { if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId)) - SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (1LL << (ctEntry->BitIndex-1))); + SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (1LL << (ctEntry->BitIndex - 1))); } void Player::UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode) @@ -26033,7 +26143,7 @@ void Player::BuildPetTalentsInfoData(WorldPacket* data) // find max talent rank (0~4) int8 curtalent_maxrank = -1; - for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) + for (int8 rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] && pet->HasSpell(talentInfo->RankID[rank])) { @@ -26201,7 +26311,7 @@ void Player::_SaveEquipmentSets(SQLTransaction& trans) stmt->setString(j++, eqset.Name.c_str()); stmt->setString(j++, eqset.IconName.c_str()); stmt->setUInt32(j++, eqset.IgnoreMask); - for (uint8 i=0; isetUInt32(j++, eqset.Items[i]); stmt->setUInt32(j++, GetGUIDLow()); stmt->setUInt64(j++, eqset.Guid); @@ -26218,7 +26328,7 @@ void Player::_SaveEquipmentSets(SQLTransaction& trans) stmt->setString(j++, eqset.Name.c_str()); stmt->setString(j++, eqset.IconName.c_str()); stmt->setUInt32(j++, eqset.IgnoreMask); - for (uint8 i=0; isetUInt32(j++, eqset.Items[i]); trans->Append(stmt); eqset.state = EQUIPMENT_SET_UNCHANGED; @@ -26296,7 +26406,7 @@ void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/) void Player::SendClearCooldown(uint32 spell_id, Unit* target) { - WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8); + WorldPacket data(SMSG_CLEAR_COOLDOWN, 4 + 8); data << uint32(spell_id); data << uint64(target->GetGUID()); SendDirectMessage(&data); @@ -26434,7 +26544,7 @@ void Player::_SaveCharacter(bool create, SQLTransaction& trans) stmt->setUInt32(index++, GetUInt32Value(PLAYER_AMMO_ID)); ss.str(""); - for (uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i) + for (uint32 i = 0; i < KNOWN_TITLES_SIZE * 2; ++i) ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' '; stmt->setString(index++, ss.str()); @@ -26566,7 +26676,7 @@ void Player::_SaveCharacter(bool create, SQLTransaction& trans) stmt->setUInt32(index++, GetUInt32Value(PLAYER_AMMO_ID)); ss.str(""); - for (uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i) + for (uint32 i = 0; i < KNOWN_TITLES_SIZE * 2; ++i) ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' '; stmt->setString(index++, ss.str()); @@ -26601,8 +26711,7 @@ void Player::_LoadGlyphs(PreparedQueryResult result) m_Glyphs[spec][3] = fields[4].GetUInt16(); m_Glyphs[spec][4] = fields[5].GetUInt16(); m_Glyphs[spec][5] = fields[6].GetUInt16(); - } - while (result->NextRow()); + } while (result->NextRow()); } void Player::_SaveGlyphs(SQLTransaction& trans) @@ -26647,9 +26756,8 @@ void Player::_LoadTalents(PreparedQueryResult result) // xinef: increase used talent points count if (GetActiveSpecMask() & specMask) - m_usedTalentCount += talentPos->rank+1; - } - while (result->NextRow()); + m_usedTalentCount += talentPos->rank + 1; + } while (result->NextRow()); } } @@ -26819,7 +26927,7 @@ void Player::ActivateSpec(uint8 spec) _addTalentAurasAndSpells(itr->first); TalentSpellPos const* talentPos = GetTalentSpellPos(itr->first); - spentTalents += talentPos->rank+1; + spentTalents += talentPos->rank + 1; } // pussywizard: remove spells that are in previous spec, but are not present in new one (or are in new spec, but not in the old one) @@ -26841,7 +26949,7 @@ void Player::ActivateSpec(uint8 spec) for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot) if (uint32 glyphId = m_Glyphs[GetActiveSpec()][slot]) if (GlyphPropertiesEntry const* glyphEntry = sGlyphPropertiesStore.LookupEntry(glyphId)) - CastSpell(this, glyphEntry->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK&~(TRIGGERED_IGNORE_SHAPESHIFT|TRIGGERED_IGNORE_CASTER_AURASTATE))); + CastSpell(this, glyphEntry->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK & ~(TRIGGERED_IGNORE_SHAPESHIFT | TRIGGERED_IGNORE_CASTER_AURASTATE))); m_usedTalentCount = spentTalents; InitTalentForLevel(); @@ -26900,7 +27008,7 @@ void Player::GetTalentTreePoints(uint8 (&specPoints)[3]) const for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank) if (talentInfo->RankID[rank] && itr->first == talentInfo->RankID[rank]) { - currentTalentRank = rank+1; + currentTalentRank = rank + 1; break; } specPoints[tab->tabpage] += currentTalentRank; @@ -26922,14 +27030,14 @@ uint8 Player::GetMostPointsTalentTree() const for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank) if (talentInfo->RankID[rank] && itr->first == talentInfo->RankID[rank]) { - currentTalentRank = rank+1; + currentTalentRank = rank + 1; break; } specPoints[tab->tabpage] += currentTalentRank; } uint8 maxIndex = 0; uint8 maxCount = specPoints[0]; - for (uint8 i=1; i<3; ++i) + for (uint8 i = 1; i < 3; ++i) if (specPoints[i] > maxCount) { maxIndex = i; @@ -27037,7 +27145,7 @@ void Player::PrepareCharmAISpells() if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->Active || !itr->second->IsInSpec(GetActiveSpec())) continue; - SpellInfo const *spellInfo = sSpellMgr->GetSpellInfo(itr->first); + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); if (!spellInfo) continue; @@ -27062,23 +27170,23 @@ void Player::PrepareCharmAISpells() if ((int32)damage_type[offset] < dmg) { - if (!m_charmAISpells[SPELL_INSTANT_DAMAGE+offset] || !spellInfo->IsHighRankOf(sSpellMgr->GetSpellInfo(m_charmAISpells[SPELL_INSTANT_DAMAGE+offset])) || urand(0,1)) - if (damage_type[1+offset] < damage_type[offset]) + if (!m_charmAISpells[SPELL_INSTANT_DAMAGE + offset] || !spellInfo->IsHighRankOf(sSpellMgr->GetSpellInfo(m_charmAISpells[SPELL_INSTANT_DAMAGE + offset])) || urand(0, 1)) + if (damage_type[1 + offset] < damage_type[offset]) { - m_charmAISpells[SPELL_INSTANT_DAMAGE2+offset] = m_charmAISpells[SPELL_INSTANT_DAMAGE+offset]; - damage_type[1+offset] = damage_type[offset]; + m_charmAISpells[SPELL_INSTANT_DAMAGE2 + offset] = m_charmAISpells[SPELL_INSTANT_DAMAGE + offset]; + damage_type[1 + offset] = damage_type[offset]; } - m_charmAISpells[SPELL_INSTANT_DAMAGE+offset] = spellInfo->Id; + m_charmAISpells[SPELL_INSTANT_DAMAGE + offset] = spellInfo->Id; damage_type[offset] = dmg; } - else if ((int32)damage_type[1+offset] < dmg) + else if ((int32)damage_type[1 + offset] < dmg) { - if (m_charmAISpells[SPELL_INSTANT_DAMAGE+offset] && sSpellMgr->GetSpellInfo(m_charmAISpells[SPELL_INSTANT_DAMAGE+offset])->IsHighRankOf(spellInfo) && urand(0,1)) + if (m_charmAISpells[SPELL_INSTANT_DAMAGE + offset] && sSpellMgr->GetSpellInfo(m_charmAISpells[SPELL_INSTANT_DAMAGE + offset])->IsHighRankOf(spellInfo) && urand(0, 1)) continue; - m_charmAISpells[SPELL_INSTANT_DAMAGE2+offset] = spellInfo->Id; - damage_type[1+offset] = dmg; + m_charmAISpells[SPELL_INSTANT_DAMAGE2 + offset] = spellInfo->Id; + damage_type[1 + offset] = dmg; } break; } @@ -27162,7 +27270,7 @@ void Player::SendRefundInfo(Item* item) return; } - WorldPacket data(SMSG_ITEM_REFUND_INFO_RESPONSE, 8+4+4+4+4*4+4*4+4+4); + WorldPacket data(SMSG_ITEM_REFUND_INFO_RESPONSE, 8 + 4 + 4 + 4 + 4 * 4 + 4 * 4 + 4 + 4); data << uint64(item->GetGUID()); // item guid data << uint32(item->GetPaidMoney()); // money cost data << uint32(iece->reqhonorpoints); // honor point cost @@ -27213,7 +27321,7 @@ void Player::RefundItem(Item* item) if (item->IsRefundExpired()) // item refund has expired { item->SetNotRefundable(this); - WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4); + WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8 + 4); data << uint64(item->GetGUID()); // Guid data << uint32(10); // Error! GetSession()->SendPacket(&data); @@ -27253,19 +27361,19 @@ void Player::RefundItem(Item* item) store_error = true; break; } - } + } } if (store_error) { - WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4); + WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8 + 4); data << uint64(item->GetGUID()); // Guid data << uint32(10); // Error! GetSession()->SendPacket(&data); return; } - WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4+4+4+4+4*4+4*4); + WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8 + 4 + 4 + 4 + 4 + 4 * 4 + 4 * 4); data << uint64(item->GetGUID()); // item guid data << uint32(0); // 0, or error code data << uint32(item->GetPaidMoney()); // money cost @@ -27356,7 +27464,7 @@ float Player::GetAverageItemLevel() ++count; } - return std::max(0.0f, sum/(float)count); + return std::max(0.0f, sum / (float)count); } float Player::GetAverageItemLevelForDF() @@ -27374,7 +27482,7 @@ float Player::GetAverageItemLevelForDF() if (m_items[i] && m_items[i]->GetTemplate()) { if (m_items[i]->GetTemplate()->Quality == ITEM_QUALITY_HEIRLOOM) - sum += level*2.33f; + sum += level * 2.33f; else sum += m_items[i]->GetTemplate()->ItemLevel; } diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 2a92e1b51..f2982fc09 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -92,7 +92,7 @@ struct PlayerSpell PlayerSpellState State : 7; // UPPER CASE TO CAUSE CONSOLE ERRORS (CHECK EVERY USAGE)! bool Active : 1; // UPPER CASE TO CAUSE CONSOLE ERRORS (CHECK EVERY USAGE)! lower rank of a spell are not useable, but learnt uint8 specMask : 8; - bool IsInSpec(uint8 spec) { return (specMask & (1< SpellCooldowns; @@ -264,7 +264,7 @@ struct PlayerClassInfo struct PlayerLevelInfo { - PlayerLevelInfo() { for (uint8 i=0; i < MAX_STATS; ++i) stats[i] = 0; } + PlayerLevelInfo() { for (uint8 i = 0; i < MAX_STATS; ++i) stats[i] = 0; } uint8 stats[MAX_STATS]; }; @@ -285,7 +285,7 @@ typedef std::list PlayerCreateInfoActions; struct PlayerInfo { - // existence checked by displayId != 0 + // existence checked by displayId != 0 PlayerInfo() : mapId(0), areaId(0), positionX(0.0f), positionY(0.0f), positionZ(0.0f), orientation(0.0f), displayId_m(0), displayId_f(0), levelInfo(nullptr) { } uint32 mapId; @@ -382,7 +382,7 @@ struct EnchantDuration { EnchantDuration() : item(nullptr), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) {}; EnchantDuration(Item* _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot), - leftduration(_leftduration){ ASSERT(item); }; + leftduration(_leftduration) { ASSERT(item); }; Item* item; EnchantmentSlot slot; @@ -893,7 +893,7 @@ enum CharDeleteMethod { CHAR_DELETE_REMOVE = 0, // Completely remove from the database CHAR_DELETE_UNLINK = 1 // The character gets unlinked from the account, - // the name gets freed up and appears as deleted ingame + // the name gets freed up and appears as deleted ingame }; enum CurrencyItems @@ -956,60 +956,60 @@ enum EmoteBroadcastTextID class PlayerTaxi { - public: - PlayerTaxi(); - ~PlayerTaxi() {} - // Nodes - void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level); - void LoadTaxiMask(std::string const& data); +public: + PlayerTaxi(); + ~PlayerTaxi() {} + // Nodes + void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level); + void LoadTaxiMask(std::string const& data); - bool IsTaximaskNodeKnown(uint32 nodeidx) const + bool IsTaximaskNodeKnown(uint32 nodeidx) const + { + uint8 field = uint8((nodeidx - 1) / 32); + uint32 submask = 1 << ((nodeidx - 1) % 32); + return (m_taximask[field] & submask) == submask; + } + bool SetTaximaskNode(uint32 nodeidx) + { + uint8 field = uint8((nodeidx - 1) / 32); + uint32 submask = 1 << ((nodeidx - 1) % 32); + if ((m_taximask[field] & submask) != submask) { - uint8 field = uint8((nodeidx - 1) / 32); - uint32 submask = 1<<((nodeidx-1)%32); - return (m_taximask[field] & submask) == submask; + m_taximask[field] |= submask; + return true; } - bool SetTaximaskNode(uint32 nodeidx) - { - uint8 field = uint8((nodeidx - 1) / 32); - uint32 submask = 1<<((nodeidx-1)%32); - if ((m_taximask[field] & submask) != submask) - { - m_taximask[field] |= submask; - return true; - } - else - return false; - } - void AppendTaximaskTo(ByteBuffer& data, bool all); + else + return false; + } + void AppendTaximaskTo(ByteBuffer& data, bool all); - // Destinations - bool LoadTaxiDestinationsFromString(std::string const& values, TeamId teamId); - std::string SaveTaxiDestinationsToString(); + // Destinations + bool LoadTaxiDestinationsFromString(std::string const& values, TeamId teamId); + std::string SaveTaxiDestinationsToString(); - void ClearTaxiDestinations() { m_TaxiDestinations.clear(); _taxiSegment = 0; } - void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } - uint32 GetTaxiSource() const { return m_TaxiDestinations.size() <= _taxiSegment+1 ? 0 : m_TaxiDestinations[_taxiSegment]; } - uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() <= _taxiSegment+1 ? 0 : m_TaxiDestinations[_taxiSegment+1]; } - uint32 GetCurrentTaxiPath() const; - uint32 NextTaxiDestination() - { - ++_taxiSegment; - return GetTaxiDestination(); - } + void ClearTaxiDestinations() { m_TaxiDestinations.clear(); _taxiSegment = 0; } + void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } + uint32 GetTaxiSource() const { return m_TaxiDestinations.size() <= _taxiSegment + 1 ? 0 : m_TaxiDestinations[_taxiSegment]; } + uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() <= _taxiSegment + 1 ? 0 : m_TaxiDestinations[_taxiSegment + 1]; } + uint32 GetCurrentTaxiPath() const; + uint32 NextTaxiDestination() + { + ++_taxiSegment; + return GetTaxiDestination(); + } - // xinef: - void SetTaxiSegment(uint32 segment) { _taxiSegment = segment; } - uint32 GetTaxiSegment() const { return _taxiSegment; } + // xinef: + void SetTaxiSegment(uint32 segment) { _taxiSegment = segment; } + uint32 GetTaxiSegment() const { return _taxiSegment; } - std::vector const& GetPath() const { return m_TaxiDestinations; } - bool empty() const { return m_TaxiDestinations.empty(); } + std::vector const& GetPath() const { return m_TaxiDestinations; } + bool empty() const { return m_TaxiDestinations.empty(); } - friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); - private: - TaxiMask m_taximask; - std::vector m_TaxiDestinations; - uint32 _taxiSegment; + friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); +private: + TaxiMask m_taximask; + std::vector m_TaxiDestinations; + uint32 _taxiSegment; }; std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); @@ -1051,52 +1051,52 @@ struct EntryPointData class TradeData { - public: // constructors - TradeData(Player* player, Player* trader) : - m_player(player), m_trader(trader), m_accepted(false), m_acceptProccess(false), - m_money(0), m_spell(0), m_spellCastItem(0) { memset(m_items, 0, TRADE_SLOT_COUNT * sizeof(uint64)); } +public: // constructors + TradeData(Player* player, Player* trader) : + m_player(player), m_trader(trader), m_accepted(false), m_acceptProccess(false), + m_money(0), m_spell(0), m_spellCastItem(0) { memset(m_items, 0, TRADE_SLOT_COUNT * sizeof(uint64)); } - Player* GetTrader() const { return m_trader; } - TradeData* GetTraderData() const; + Player* GetTrader() const { return m_trader; } + TradeData* GetTraderData() const; - Item* GetItem(TradeSlots slot) const; - bool HasItem(uint64 itemGuid) const; - TradeSlots GetTradeSlotForItem(uint64 itemGuid) const; - void SetItem(TradeSlots slot, Item* item); + Item* GetItem(TradeSlots slot) const; + bool HasItem(uint64 itemGuid) const; + TradeSlots GetTradeSlotForItem(uint64 itemGuid) const; + void SetItem(TradeSlots slot, Item* item); - uint32 GetSpell() const { return m_spell; } - void SetSpell(uint32 spell_id, Item* castItem = nullptr); + uint32 GetSpell() const { return m_spell; } + void SetSpell(uint32 spell_id, Item* castItem = nullptr); - Item* GetSpellCastItem() const; - bool HasSpellCastItem() const { return m_spellCastItem != 0; } + Item* GetSpellCastItem() const; + bool HasSpellCastItem() const { return m_spellCastItem != 0; } - uint32 GetMoney() const { return m_money; } - void SetMoney(uint32 money); + uint32 GetMoney() const { return m_money; } + void SetMoney(uint32 money); - bool IsAccepted() const { return m_accepted; } - void SetAccepted(bool state, bool crosssend = false); + bool IsAccepted() const { return m_accepted; } + void SetAccepted(bool state, bool crosssend = false); - bool IsInAcceptProcess() const { return m_acceptProccess; } - void SetInAcceptProcess(bool state) { m_acceptProccess = state; } + bool IsInAcceptProcess() const { return m_acceptProccess; } + void SetInAcceptProcess(bool state) { m_acceptProccess = state; } - private: // internal functions +private: // internal functions - void Update(bool for_trader = true); + void Update(bool for_trader = true); - private: // fields +private: // fields - Player* m_player; // Player who own of this TradeData - Player* m_trader; // Player who trade with m_player + Player* m_player; // Player who own of this TradeData + Player* m_trader; // Player who trade with m_player - bool m_accepted; // m_player press accept for trade list - bool m_acceptProccess; // one from player/trader press accept and this processed + bool m_accepted; // m_player press accept for trade list + bool m_acceptProccess; // one from player/trader press accept and this processed - uint32 m_money; // m_player place money to trade + uint32 m_money; // m_player place money to trade - uint32 m_spell; // m_player apply spell to non-traded slot item - uint64 m_spellCastItem; // applied spell casted by item use + uint32 m_spell; // m_player apply spell to non-traded slot item + uint64 m_spellCastItem; // applied spell casted by item use - uint64 m_items[TRADE_SLOT_COUNT]; // traded itmes from m_player side including non-traded slot + uint64 m_items[TRADE_SLOT_COUNT]; // traded itmes from m_player side including non-traded slot }; class KillRewarder @@ -1136,1893 +1136,1893 @@ class Player : public Unit, public GridObject friend class WorldSession; friend void Item::AddToUpdateQueueOf(Player* player); friend void Item::RemoveFromUpdateQueueOf(Player* player); - public: - explicit Player(WorldSession* session); - ~Player(); +public: + explicit Player(WorldSession* session); + ~Player(); - void CleanupsBeforeDelete(bool finalCleanup = true) override; + void CleanupsBeforeDelete(bool finalCleanup = true) override; - void AddToWorld() override; - void RemoveFromWorld() override; + void AddToWorld() override; + void RemoveFromWorld() override; - void SetObjectScale(float scale) override + void SetObjectScale(float scale) override + { + Unit::SetObjectScale(scale); + SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, scale * DEFAULT_WORLD_OBJECT_SIZE); + SetFloatValue(UNIT_FIELD_COMBATREACH, scale * DEFAULT_COMBAT_REACH); + } + + bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0, Unit* target = nullptr); + bool TeleportTo(WorldLocation const& loc, uint32 options = 0, Unit* target = nullptr) + { + return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options, target); + } + bool TeleportToEntryPoint(); + + void SetSummonPoint(uint32 mapid, float x, float y, float z, uint32 delay = 0, bool asSpectator = false) + { + m_summon_expire = time(nullptr) + (delay ? delay : MAX_PLAYER_SUMMON_DELAY); + m_summon_mapid = mapid; + m_summon_x = x; + m_summon_y = y; + m_summon_z = z; + m_summon_asSpectator = asSpectator; + } + bool IsSummonAsSpectator() const { return m_summon_asSpectator && m_summon_expire >= time(nullptr); } + void SetSummonAsSpectator(bool on) { m_summon_asSpectator = on; } + void SummonIfPossible(bool agree, uint32 summoner_guid); + time_t GetSummonExpireTimer() const { return m_summon_expire; } + + bool Create(uint32 guidlow, CharacterCreateInfo* createInfo); + + void Update(uint32 time) override; + + static bool BuildEnumData(PreparedQueryResult result, WorldPacket* data); + + void SetInWater(bool apply); + + bool IsInWater(bool allowAbove = false) const override; + bool IsUnderWater() const override; + bool IsFalling() const; + bool IsInAreaTriggerRadius(const AreaTrigger* trigger) const; + + void SendInitialPacketsBeforeAddToMap(); + void SendInitialPacketsAfterAddToMap(); + void SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg = 0); + void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool onEnterMap); + + bool CanInteractWithQuestGiver(Object* questGiver); + Creature* GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask); + GameObject* GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const; + + void ToggleAFK(); + void ToggleDND(); + bool isAFK() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); } + bool isDND() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); } + uint8 GetChatTag() const; + std::string autoReplyMsg; + + uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin = NULL); + + PlayerSocial* GetSocial() { return m_social; } + + PlayerTaxi m_taxi; + void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); } + bool ActivateTaxiPathTo(std::vector const& nodes, Creature* npc = NULL, uint32 spellid = 1); + bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 1); + void CleanupAfterTaxiFlight(); + void ContinueTaxiFlight(); + // mount_id can be used in scripting calls + bool isAcceptWhispers() const { return m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS; } + void SetAcceptWhispers(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; } + bool IsGameMaster() const { return m_ExtraFlags & PLAYER_EXTRA_GM_ON; } + void SetGameMaster(bool on); + bool isGMChat() const { return m_ExtraFlags & PLAYER_EXTRA_GM_CHAT; } + void SetGMChat(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT; else m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT; } + bool isTaxiCheater() const { return m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT; } + void SetTaxiCheater(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT; else m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT; } + bool isGMVisible() const { return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE); } + void SetGMVisible(bool on); + bool Has310Flyer(bool checkAllSpells, uint32 excludeSpellId = 0); + void SetHas310Flyer(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_HAS_310_FLYER; else m_ExtraFlags &= ~PLAYER_EXTRA_HAS_310_FLYER; } + void SetPvPDeath(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH; else m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH; } + + void GiveXP(uint32 xp, Unit* victim, float group_rate = 1.0f); + void GiveLevel(uint8 level); + + void InitStatsForLevel(bool reapplyMods = false); + + // .cheat command related + bool GetCommandStatus(uint32 command) const { return _activeCheats & command; } + void SetCommandStatusOn(uint32 command) { _activeCheats |= command; } + void SetCommandStatusOff(uint32 command) { _activeCheats &= ~command; } + + // Played Time Stuff + time_t m_logintime; + time_t m_Last_tick; + uint32 m_Played_time[MAX_PLAYED_TIME_INDEX]; + uint32 GetTotalPlayedTime() { return m_Played_time[PLAYED_TIME_TOTAL]; } + uint32 GetLevelPlayedTime() { return m_Played_time[PLAYED_TIME_LEVEL]; } + + void setDeathState(DeathState s, bool despawn = false) override; // overwrite Unit::setDeathState + + void SetRestState(uint32 triggerId); + void RemoveRestState(); + uint32 GetXPRestBonus(uint32 xp); + float GetRestBonus() const { return _restBonus; } + void SetRestBonus(float rest_bonus_new); + uint32 GetInnTriggerId() const { return _innTriggerId; } + + Pet* GetPet() const; + bool IsPetDismissed(); + void SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 despwtime, uint32 createdBySpell, uint64 casterGUID, uint8 asynchLoadType); + void RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent = false); + uint32 GetPhaseMaskForSpawn() const; // used for proper set phase for DB at GM-mode creature/GO spawn + + void Say(std::string const& text, const uint32 language); + void Yell(std::string const& text, const uint32 language); + void TextEmote(std::string const& text); + void Whisper(std::string const& text, const uint32 language, uint64 receiver); + + /*********************************************************/ + /*** STORAGE SYSTEM ***/ + /*********************************************************/ + + void SetVirtualItemSlot(uint8 i, Item* item); + void SetSheath(SheathState sheathed) override; // overwrite Unit version + uint8 FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const; + uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = nullptr) const; + uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; + Item* GetItemByGuid(uint64 guid) const; + Item* GetItemByEntry(uint32 entry) const; + Item* GetItemByPos(uint16 pos) const; + Item* GetItemByPos(uint8 bag, uint8 slot) const; + Bag* GetBagByPos(uint8 slot) const; + inline Item* GetUseableItemByPos(uint8 bag, uint8 slot) const //Does additional check for disarmed weapons + { + if (!CanUseAttackType(GetAttackBySlot(slot))) + return nullptr; + return GetItemByPos(bag, slot); + } + Item* GetWeaponForAttack(WeaponAttackType attackType, bool useable = false) const; + Item* GetShield(bool useable = false) const; + static uint8 GetAttackBySlot(uint8 slot); // MAX_ATTACK if not weapon slot + std::vector& GetItemUpdateQueue() { return m_itemUpdateQueue; } + static bool IsInventoryPos(uint16 pos) { return IsInventoryPos(pos >> 8, pos & 255); } + static bool IsInventoryPos(uint8 bag, uint8 slot); + static bool IsEquipmentPos(uint16 pos) { return IsEquipmentPos(pos >> 8, pos & 255); } + static bool IsEquipmentPos(uint8 bag, uint8 slot); + static bool IsBagPos(uint16 pos); + static bool IsBankPos(uint16 pos) { return IsBankPos(pos >> 8, pos & 255); } + static bool IsBankPos(uint8 bag, uint8 slot); + bool IsValidPos(uint16 pos, bool explicit_pos) { return IsValidPos(pos >> 8, pos & 255, explicit_pos); } + bool IsValidPos(uint8 bag, uint8 slot, bool explicit_pos); + uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, 2); } + void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, 2, count); } + bool HasItemCount(uint32 item, uint32 count = 1, bool inBankAlso = false) const; + bool HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem = nullptr) const; + bool CanNoReagentCast(SpellInfo const* spellInfo) const; + bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; + bool HasItemOrGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; + InventoryResult CanTakeMoreSimilarItems(Item* pItem) const { return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem); } + InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count) const { return CanTakeMoreSimilarItems(entry, count, nullptr); } + InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = nullptr) const + { + return CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count); + } + InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const + { + if (!pItem) + return EQUIP_ERR_ITEM_NOT_FOUND; + uint32 count = pItem->GetCount(); + return CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, nullptr); + } + InventoryResult CanStoreItems(Item** pItem, int32 count) const; + InventoryResult CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const; + InventoryResult CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool swap, bool not_loading = true) const; + + InventoryResult CanEquipUniqueItem(Item* pItem, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; + InventoryResult CanEquipUniqueItem(ItemTemplate const* itemProto, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; + InventoryResult CanUnequipItems(uint32 item, uint32 count) const; + InventoryResult CanUnequipItem(uint16 src, bool swap) const; + InventoryResult CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap, bool not_loading = true) const; + InventoryResult CanUseItem(Item* pItem, bool not_loading = true) const; + bool HasItemTotemCategory(uint32 TotemCategory) const; + bool IsTotemCategoryCompatiableWith(const ItemTemplate* pProto, uint32 requiredTotemCategoryId) const; + InventoryResult CanUseItem(ItemTemplate const* pItem) const; + InventoryResult CanUseAmmo(uint32 item) const; + InventoryResult CanRollForItemInLFG(ItemTemplate const* item, WorldObject const* lootedObject) const; + Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0); + Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId, AllowedLooterSet& allowedLooters); + Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update); + Item* EquipNewItem(uint16 pos, uint32 item, bool update); + Item* EquipItem(uint16 pos, Item* pItem, bool update); + void AutoUnequipOffhandIfNeed(bool force = false); + bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count); + void AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast = false); + void AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast = false) { AutoStoreLoot(NULL_BAG, NULL_SLOT, loot_id, store, broadcast); } + void StoreLootItem(uint8 lootSlot, Loot* loot); + void UpdateLootAchievements(LootItem* item, Loot* loot); + void UpdateTitansGrip(); + + InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = nullptr) const; + InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = NULL, bool swap = false, uint32* no_space_count = nullptr) const; + + void AddRefundReference(uint32 it); + void DeleteRefundReference(uint32 it); + + void ApplyEquipCooldown(Item* pItem); + void SetAmmo(uint32 item); + void RemoveAmmo(); + float GetAmmoDPS() const { return m_ammoDPS; } + bool CheckAmmoCompatibility(const ItemTemplate* ammo_proto) const; + void QuickEquipItem(uint16 pos, Item* pItem); + void VisualizeItem(uint8 slot, Item* pItem); + void SetVisibleItemSlot(uint8 slot, Item* pItem); + Item* BankItem(ItemPosCountVec const& dest, Item* pItem, bool update) + { + return StoreItem(dest, pItem, update); + } + Item* BankItem(uint16 pos, Item* pItem, bool update); + void RemoveItem(uint8 bag, uint8 slot, bool update, bool swap = false); + void MoveItemFromInventory(uint8 bag, uint8 slot, bool update); + // in trade, auction, guild bank, mail.... + void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false); + // in trade, guild bank, mail.... + void RemoveItemDependentAurasAndCasts(Item* pItem); + void DestroyItem(uint8 bag, uint8 slot, bool update); + void DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check = false); + void DestroyItemCount(Item* item, uint32& count, bool update); + void DestroyConjuredItems(bool update); + void DestroyZoneLimitedItem(bool update, uint32 new_zone); + void SplitItem(uint16 src, uint16 dst, uint32 count); + void SwapItem(uint16 src, uint16 dst); + void AddItemToBuyBackSlot(Item* pItem); + Item* GetItemFromBuyBackSlot(uint32 slot); + void RemoveItemFromBuyBackSlot(uint32 slot, bool del); + uint32 GetMaxKeyringSize() const { return KEYRING_SLOT_END - KEYRING_SLOT_START; } + void SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2 = NULL, uint32 itemid = 0); + void SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param); + void SendSellError(SellResult msg, Creature* creature, uint64 guid, uint32 param); + void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; } + void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; } + uint32 GetWeaponProficiency() const { return m_WeaponProficiency; } + uint32 GetArmorProficiency() const { return m_ArmorProficiency; } + + bool IsTwoHandUsed() const + { + Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); + return mainItem && mainItem->GetTemplate()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip(); + } + void SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast = false, bool sendChatMessage = true); + bool BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot); + bool _StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot, int32 price, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore); + + float GetReputationPriceDiscount(Creature const* creature) const; + + Player* GetTrader() const { return m_trade ? m_trade->GetTrader() : nullptr; } + TradeData* GetTradeData() const { return m_trade; } + void TradeCancel(bool sendback); + + void UpdateEnchantTime(uint32 time); + void UpdateSoulboundTradeItems(); + void AddTradeableItem(Item* item); + void RemoveTradeableItem(Item* item); + void UpdateItemDuration(uint32 time, bool realtimeonly = false); + void AddEnchantmentDurations(Item* item); + void RemoveEnchantmentDurations(Item* item); + void RemoveEnchantmentDurationsReferences(Item* item); // pussywizard + void RemoveArenaEnchantments(EnchantmentSlot slot); + void AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration); + void ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur = true, bool ignore_condition = false); + void ApplyEnchantment(Item* item, bool apply); + void UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 new_value); + void SendEnchantmentDurations(); + void BuildEnchantmentsInfoData(WorldPacket* data); + void AddItemDurations(Item* item); + void RemoveItemDurations(Item* item); + void SendItemDurations(); + void LoadCorpse(); + void LoadPet(); + + bool AddItem(uint32 itemId, uint32 count); + + uint32 m_stableSlots; + + /*********************************************************/ + /*** GOSSIP SYSTEM ***/ + /*********************************************************/ + + void PrepareGossipMenu(WorldObject* source, uint32 menuId = 0, bool showQuests = false); + void SendPreparedGossip(WorldObject* source); + void OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId); + + uint32 GetGossipTextId(uint32 menuId, WorldObject* source); + uint32 GetGossipTextId(WorldObject* source); + static uint32 GetDefaultGossipMenuForSource(WorldObject* source); + + void ToggleInstantFlight(); + + /*********************************************************/ + /*** QUEST SYSTEM ***/ + /*********************************************************/ + + int32 GetQuestLevel(Quest const* quest) const { return quest && (quest->GetQuestLevel() > 0) ? quest->GetQuestLevel() : getLevel(); } + + void PrepareQuestMenu(uint64 guid); + void SendPreparedQuest(uint64 guid); + bool IsActiveQuest(uint32 quest_id) const; + Quest const* GetNextQuest(uint64 guid, Quest const* quest); + bool CanSeeStartQuest(Quest const* quest); + bool CanTakeQuest(Quest const* quest, bool msg); + bool CanAddQuest(Quest const* quest, bool msg); + bool CanCompleteQuest(uint32 quest_id, const QuestStatusData* q_savedStatus = nullptr); + bool CanCompleteRepeatableQuest(Quest const* quest); + bool CanRewardQuest(Quest const* quest, bool msg); + bool CanRewardQuest(Quest const* quest, uint32 reward, bool msg); + void AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver); + void AddQuest(Quest const* quest, Object* questGiver); + void AbandonQuest(uint32 quest_id); + void CompleteQuest(uint32 quest_id); + void IncompleteQuest(uint32 quest_id); + void RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool announce = true); + void FailQuest(uint32 quest_id); + bool SatisfyQuestSkill(Quest const* qInfo, bool msg) const; + bool SatisfyQuestLevel(Quest const* qInfo, bool msg) const; + bool SatisfyQuestLog(bool msg); + bool SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const; + bool SatisfyQuestClass(Quest const* qInfo, bool msg) const; + bool SatisfyQuestRace(Quest const* qInfo, bool msg) const; + bool SatisfyQuestReputation(Quest const* qInfo, bool msg) const; + bool SatisfyQuestStatus(Quest const* qInfo, bool msg) const; + bool SatisfyQuestConditions(Quest const* qInfo, bool msg); + bool SatisfyQuestTimed(Quest const* qInfo, bool msg) const; + bool SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const; + bool SatisfyQuestNextChain(Quest const* qInfo, bool msg) const; + bool SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const; + bool SatisfyQuestDay(Quest const* qInfo, bool msg) const; + bool SatisfyQuestWeek(Quest const* qInfo, bool msg) const; + bool SatisfyQuestMonth(Quest const* qInfo, bool msg) const; + bool SatisfyQuestSeasonal(Quest const* qInfo, bool msg) const; + bool GiveQuestSourceItem(Quest const* quest); + bool TakeQuestSourceItem(uint32 questId, bool msg); + bool GetQuestRewardStatus(uint32 quest_id) const; + QuestStatus GetQuestStatus(uint32 quest_id) const; + void SetQuestStatus(uint32 questId, QuestStatus status, bool update = true); + void RemoveActiveQuest(uint32 questId, bool update = true); + void RemoveRewardedQuest(uint32 questId, bool update = true); + void SendQuestUpdate(uint32 questId); + QuestGiverStatus GetQuestDialogStatus(Object* questGiver); + + void SetDailyQuestStatus(uint32 quest_id); + void SetWeeklyQuestStatus(uint32 quest_id); + void SetMonthlyQuestStatus(uint32 quest_id); + void SetSeasonalQuestStatus(uint32 quest_id); + void ResetDailyQuestStatus(); + void ResetWeeklyQuestStatus(); + void ResetMonthlyQuestStatus(); + void ResetSeasonalQuestStatus(uint16 event_id); + + uint16 FindQuestSlot(uint32 quest_id) const; + uint32 GetQuestSlotQuestId(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET); } + uint32 GetQuestSlotState(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET); } + uint16 GetQuestSlotCounter(uint16 slot, uint8 counter) const { return (uint16)(GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET) >> (counter * 16)); } + uint32 GetQuestSlotTime(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET); } + void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0) + { + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id); + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0); + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0); + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET + 1, 0); + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); + } + void SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count) + { + uint64 val = GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET); + val &= ~((uint64)0xFFFF << (counter * 16)); + val |= ((uint64)count << (counter * 16)); + SetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, val); + } + void SetQuestSlotState(uint16 slot, uint32 state) { SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); } + void RemoveQuestSlotState(uint16 slot, uint32 state) { RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); } + void SetQuestSlotTimer(uint16 slot, uint32 timer) { SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); } + void SwapQuestSlot(uint16 slot1, uint16 slot2) + { + for (int i = 0; i < MAX_QUEST_OFFSET; ++i) { - Unit::SetObjectScale(scale); - SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, scale * DEFAULT_WORLD_OBJECT_SIZE); - SetFloatValue(UNIT_FIELD_COMBATREACH, scale * DEFAULT_COMBAT_REACH); + uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i); + uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i); + + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2); + SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1); } + } + uint16 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry); + void AreaExploredOrEventHappens(uint32 questId); + void GroupEventHappens(uint32 questId, WorldObject const* pEventObject); + void ItemAddedQuestCheck(uint32 entry, uint32 count); + void ItemRemovedQuestCheck(uint32 entry, uint32 count); + void KilledMonster(CreatureTemplate const* cInfo, uint64 guid); + void KilledMonsterCredit(uint32 entry, uint64 guid); + void KilledPlayerCredit(); + void KillCreditGO(uint32 entry, uint64 guid = 0); + void TalkedToCreature(uint32 entry, uint64 guid); + void MoneyChanged(uint32 value); + void ReputationChanged(FactionEntry const* factionEntry); + void ReputationChanged2(FactionEntry const* factionEntry); + bool HasQuestForItem(uint32 itemId, uint32 excludeQuestId = 0, bool turnIn = false) const; + bool HasQuestForGO(int32 GOId) const; + void UpdateForQuestWorldObjects(); + bool CanShareQuest(uint32 quest_id) const; - bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0, Unit *target = nullptr); - bool TeleportTo(WorldLocation const &loc, uint32 options = 0, Unit *target = nullptr) - { - return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options, target); - } - bool TeleportToEntryPoint(); + void SendQuestComplete(uint32 quest_id); + void SendQuestReward(Quest const* quest, uint32 XP); + void SendQuestFailed(uint32 questId, InventoryResult reason = EQUIP_ERR_OK); + void SendQuestTimerFailed(uint32 quest_id); + void SendCanTakeQuestResponse(uint32 msg) const; + void SendQuestConfirmAccept(Quest const* quest, Player* pReceiver); + void SendPushToPartyResponse(Player* player, uint8 msg); + void SendQuestUpdateAddItem(Quest const* quest, uint32 item_idx, uint16 count); + void SendQuestUpdateAddCreatureOrGo(Quest const* quest, uint64 guid, uint32 creatureOrGO_idx, uint16 old_count, uint16 add_count); + void SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint16 add_count); - void SetSummonPoint(uint32 mapid, float x, float y, float z, uint32 delay = 0, bool asSpectator = false) - { - m_summon_expire = time(nullptr) + (delay ? delay : MAX_PLAYER_SUMMON_DELAY); - m_summon_mapid = mapid; - m_summon_x = x; - m_summon_y = y; - m_summon_z = z; - m_summon_asSpectator = asSpectator; - } - bool IsSummonAsSpectator() const { return m_summon_asSpectator && m_summon_expire >= time(nullptr); } - void SetSummonAsSpectator(bool on) { m_summon_asSpectator = on; } - void SummonIfPossible(bool agree, uint32 summoner_guid); - time_t GetSummonExpireTimer() const { return m_summon_expire; } + uint64 GetDivider() { return m_divider; } + void SetDivider(uint64 guid) { m_divider = guid; } - bool Create(uint32 guidlow, CharacterCreateInfo* createInfo); + uint32 GetInGameTime() { return m_ingametime; } - void Update(uint32 time) override; + void SetInGameTime(uint32 time) { m_ingametime = time; } - static bool BuildEnumData(PreparedQueryResult result, WorldPacket* data); + void AddTimedQuest(uint32 quest_id) { m_timedquests.insert(quest_id); } + void RemoveTimedQuest(uint32 quest_id) { m_timedquests.erase(quest_id); } - void SetInWater(bool apply); + bool HasPvPForcingQuest() const; - bool IsInWater(bool allowAbove = false) const override; - bool IsUnderWater() const override; - bool IsFalling() const; - bool IsInAreaTriggerRadius(const AreaTrigger* trigger) const; + /*********************************************************/ + /*** LOAD SYSTEM ***/ + /*********************************************************/ - void SendInitialPacketsBeforeAddToMap(); - void SendInitialPacketsAfterAddToMap(); - void SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg = 0); - void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool onEnterMap); + bool LoadFromDB(uint32 guid, SQLQueryHolder* holder); + bool isBeingLoaded() const override; - bool CanInteractWithQuestGiver(Object* questGiver); - Creature* GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask); - GameObject* GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const; + void Initialize(uint32 guid); + static uint32 GetUInt32ValueFromArray(Tokenizer const& data, uint16 index); + static float GetFloatValueFromArray(Tokenizer const& data, uint16 index); + static uint32 GetZoneIdFromDB(uint64 guid); + static uint32 GetLevelFromStorage(uint64 guid); + static bool LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, uint64 guid); - void ToggleAFK(); - void ToggleDND(); - bool isAFK() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); } - bool isDND() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); } - uint8 GetChatTag() const; - std::string autoReplyMsg; + static bool IsValidGender(uint8 Gender) { return Gender <= GENDER_FEMALE; } - uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin=NULL); + /*********************************************************/ + /*** SAVE SYSTEM ***/ + /*********************************************************/ - PlayerSocial *GetSocial() { return m_social; } + void SaveToDB(bool create, bool logout); + void SaveInventoryAndGoldToDB(SQLTransaction& trans); // fast save function for item/money cheating preventing + void SaveGoldToDB(SQLTransaction& trans); - PlayerTaxi m_taxi; - void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); } - bool ActivateTaxiPathTo(std::vector const& nodes, Creature* npc = NULL, uint32 spellid = 1); - bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 1); - void CleanupAfterTaxiFlight(); - void ContinueTaxiFlight(); - // mount_id can be used in scripting calls - bool isAcceptWhispers() const { return m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS; } - void SetAcceptWhispers(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; } - bool IsGameMaster() const { return m_ExtraFlags & PLAYER_EXTRA_GM_ON; } - void SetGameMaster(bool on); - bool isGMChat() const { return m_ExtraFlags & PLAYER_EXTRA_GM_CHAT; } - void SetGMChat(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT; else m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT; } - bool isTaxiCheater() const { return m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT; } - void SetTaxiCheater(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT; else m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT; } - bool isGMVisible() const { return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE); } - void SetGMVisible(bool on); - bool Has310Flyer(bool checkAllSpells, uint32 excludeSpellId = 0); - void SetHas310Flyer(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_HAS_310_FLYER; else m_ExtraFlags &= ~PLAYER_EXTRA_HAS_310_FLYER; } - void SetPvPDeath(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH; else m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH; } + static void SetUInt32ValueInArray(Tokenizer& data, uint16 index, uint32 value); + static void SetFloatValueInArray(Tokenizer& data, uint16 index, float value); + static void Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair); + static void SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, uint64 guid); - void GiveXP(uint32 xp, Unit* victim, float group_rate=1.0f); - void GiveLevel(uint8 level); + static void DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally); + static void DeleteOldCharacters(); + static void DeleteOldCharacters(uint32 keepDays); - void InitStatsForLevel(bool reapplyMods = false); + bool m_mailsLoaded; + bool m_mailsUpdated; - // .cheat command related - bool GetCommandStatus(uint32 command) const { return _activeCheats & command; } - void SetCommandStatusOn(uint32 command) { _activeCheats |= command; } - void SetCommandStatusOff(uint32 command) { _activeCheats &= ~command; } + void SetBindPoint(uint64 guid); + void SendTalentWipeConfirm(uint64 guid); + void ResetPetTalents(); + void CalcRage(uint32 damage, bool attacker); + void RegenerateAll(); + void Regenerate(Powers power); + void RegenerateHealth(); + void setRegenTimerCount(uint32 time) {m_regenTimerCount = time;} + void setWeaponChangeTimer(uint32 time) {m_weaponChangeTimer = time;} - // Played Time Stuff - time_t m_logintime; - time_t m_Last_tick; - uint32 m_Played_time[MAX_PLAYED_TIME_INDEX]; - uint32 GetTotalPlayedTime() { return m_Played_time[PLAYED_TIME_TOTAL]; } - uint32 GetLevelPlayedTime() { return m_Played_time[PLAYED_TIME_LEVEL]; } + uint32 GetMoney() const { return GetUInt32Value(PLAYER_FIELD_COINAGE); } + bool ModifyMoney(int32 amount, bool sendError = true); + bool HasEnoughMoney(uint32 amount) const { return (GetMoney() >= amount); } + bool HasEnoughMoney(int32 amount) const + { + if (amount > 0) + return (GetMoney() >= (uint32) amount); + return true; + } - void setDeathState(DeathState s, bool despawn = false) override; // overwrite Unit::setDeathState + void SetMoney(uint32 value) + { + SetUInt32Value(PLAYER_FIELD_COINAGE, value); + MoneyChanged(value); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED); + } - void SetRestState(uint32 triggerId); - void RemoveRestState(); - uint32 GetXPRestBonus(uint32 xp); - float GetRestBonus() const { return _restBonus; } - void SetRestBonus(float rest_bonus_new); - uint32 GetInnTriggerId() const { return _innTriggerId; } + RewardedQuestSet const& getRewardedQuests() const { return m_RewardedQuests; } + QuestStatusMap& getQuestStatusMap() { return m_QuestStatus; } - Pet* GetPet() const; - bool IsPetDismissed(); - void SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 despwtime, uint32 createdBySpell, uint64 casterGUID, uint8 asynchLoadType); - void RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent = false); - uint32 GetPhaseMaskForSpawn() const; // used for proper set phase for DB at GM-mode creature/GO spawn + size_t GetRewardedQuestCount() const { return m_RewardedQuests.size(); } + bool IsQuestRewarded(uint32 quest_id) const + { + return m_RewardedQuests.find(quest_id) != m_RewardedQuests.end(); + } - void Say(std::string const& text, const uint32 language); - void Yell(std::string const& text, const uint32 language); - void TextEmote(std::string const& text); - void Whisper(std::string const& text, const uint32 language, uint64 receiver); + Unit* GetSelectedUnit() const; + Player* GetSelectedPlayer() const; - /*********************************************************/ - /*** STORAGE SYSTEM ***/ - /*********************************************************/ + void SetTarget(uint64 /*guid*/) override { } /// Used for serverside target changes, does not apply to players + void SetSelection(uint64 guid); - void SetVirtualItemSlot(uint8 i, Item* item); - void SetSheath(SheathState sheathed) override; // overwrite Unit version - uint8 FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const; - uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = nullptr) const; - uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; - Item* GetItemByGuid(uint64 guid) const; - Item* GetItemByEntry(uint32 entry) const; - Item* GetItemByPos(uint16 pos) const; - Item* GetItemByPos(uint8 bag, uint8 slot) const; - Bag* GetBagByPos(uint8 slot) const; - inline Item* GetUseableItemByPos(uint8 bag, uint8 slot) const //Does additional check for disarmed weapons - { - if (!CanUseAttackType(GetAttackBySlot(slot))) - return nullptr; - return GetItemByPos(bag, slot); - } - Item* GetWeaponForAttack(WeaponAttackType attackType, bool useable = false) const; - Item* GetShield(bool useable = false) const; - static uint8 GetAttackBySlot(uint8 slot); // MAX_ATTACK if not weapon slot - std::vector &GetItemUpdateQueue() { return m_itemUpdateQueue; } - static bool IsInventoryPos(uint16 pos) { return IsInventoryPos(pos >> 8, pos & 255); } - static bool IsInventoryPos(uint8 bag, uint8 slot); - static bool IsEquipmentPos(uint16 pos) { return IsEquipmentPos(pos >> 8, pos & 255); } - static bool IsEquipmentPos(uint8 bag, uint8 slot); - static bool IsBagPos(uint16 pos); - static bool IsBankPos(uint16 pos) { return IsBankPos(pos >> 8, pos & 255); } - static bool IsBankPos(uint8 bag, uint8 slot); - bool IsValidPos(uint16 pos, bool explicit_pos) { return IsValidPos(pos >> 8, pos & 255, explicit_pos); } - bool IsValidPos(uint8 bag, uint8 slot, bool explicit_pos); - uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, 2); } - void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, 2, count); } - bool HasItemCount(uint32 item, uint32 count = 1, bool inBankAlso = false) const; - bool HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem = nullptr) const; - bool CanNoReagentCast(SpellInfo const* spellInfo) const; - bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; - bool HasItemOrGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; - InventoryResult CanTakeMoreSimilarItems(Item* pItem) const { return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem); } - InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count) const { return CanTakeMoreSimilarItems(entry, count, nullptr); } - InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = nullptr) const - { - return CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count); - } - InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const - { - if (!pItem) - return EQUIP_ERR_ITEM_NOT_FOUND; - uint32 count = pItem->GetCount(); - return CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, nullptr); - } - InventoryResult CanStoreItems(Item** pItem, int32 count) const; - InventoryResult CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const; - InventoryResult CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool swap, bool not_loading = true) const; + uint8 GetComboPoints() const { return m_comboPoints; } + uint64 GetComboTarget() const { return m_comboTarget; } - InventoryResult CanEquipUniqueItem(Item* pItem, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; - InventoryResult CanEquipUniqueItem(ItemTemplate const* itemProto, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; - InventoryResult CanUnequipItems(uint32 item, uint32 count) const; - InventoryResult CanUnequipItem(uint16 src, bool swap) const; - InventoryResult CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap, bool not_loading = true) const; - InventoryResult CanUseItem(Item* pItem, bool not_loading = true) const; - bool HasItemTotemCategory(uint32 TotemCategory) const; - bool IsTotemCategoryCompatiableWith(const ItemTemplate* pProto, uint32 requiredTotemCategoryId) const; - InventoryResult CanUseItem(ItemTemplate const* pItem) const; - InventoryResult CanUseAmmo(uint32 item) const; - InventoryResult CanRollForItemInLFG(ItemTemplate const* item, WorldObject const* lootedObject) const; - Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0); - Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId, AllowedLooterSet &allowedLooters); - Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update); - Item* EquipNewItem(uint16 pos, uint32 item, bool update); - Item* EquipItem(uint16 pos, Item* pItem, bool update); - void AutoUnequipOffhandIfNeed(bool force = false); - bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count); - void AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast = false); - void AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast = false) { AutoStoreLoot(NULL_BAG, NULL_SLOT, loot_id, store, broadcast); } - void StoreLootItem(uint8 lootSlot, Loot* loot); - void UpdateLootAchievements(LootItem *item, Loot* loot); - void UpdateTitansGrip(); + void AddComboPoints(Unit* target, int8 count); + void ClearComboPoints(); + void SendComboPoints(); - InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = nullptr) const; - InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = NULL, bool swap = false, uint32* no_space_count = nullptr) const; + void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, uint32 item_guid = 0, uint32 item_count = 0); + void SendNewMail(); + void UpdateNextMailTimeAndUnreads(); + void AddNewMailDeliverTime(time_t deliver_time); + bool IsMailsLoaded() const { return m_mailsLoaded; } - void AddRefundReference(uint32 it); - void DeleteRefundReference(uint32 it); + void RemoveMail(uint32 id); - void ApplyEquipCooldown(Item* pItem); - void SetAmmo(uint32 item); - void RemoveAmmo(); - float GetAmmoDPS() const { return m_ammoDPS; } - bool CheckAmmoCompatibility(const ItemTemplate* ammo_proto) const; - void QuickEquipItem(uint16 pos, Item* pItem); - void VisualizeItem(uint8 slot, Item* pItem); - void SetVisibleItemSlot(uint8 slot, Item* pItem); - Item* BankItem(ItemPosCountVec const& dest, Item* pItem, bool update) - { - return StoreItem(dest, pItem, update); - } - Item* BankItem(uint16 pos, Item* pItem, bool update); - void RemoveItem(uint8 bag, uint8 slot, bool update, bool swap = false); - void MoveItemFromInventory(uint8 bag, uint8 slot, bool update); - // in trade, auction, guild bank, mail.... - void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false); - // in trade, guild bank, mail.... - void RemoveItemDependentAurasAndCasts(Item* pItem); - void DestroyItem(uint8 bag, uint8 slot, bool update); - void DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check = false); - void DestroyItemCount(Item* item, uint32& count, bool update); - void DestroyConjuredItems(bool update); - void DestroyZoneLimitedItem(bool update, uint32 new_zone); - void SplitItem(uint16 src, uint16 dst, uint32 count); - void SwapItem(uint16 src, uint16 dst); - void AddItemToBuyBackSlot(Item* pItem); - Item* GetItemFromBuyBackSlot(uint32 slot); - void RemoveItemFromBuyBackSlot(uint32 slot, bool del); - uint32 GetMaxKeyringSize() const { return KEYRING_SLOT_END-KEYRING_SLOT_START; } - void SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2 = NULL, uint32 itemid = 0); - void SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param); - void SendSellError(SellResult msg, Creature* creature, uint64 guid, uint32 param); - void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; } - void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; } - uint32 GetWeaponProficiency() const { return m_WeaponProficiency; } - uint32 GetArmorProficiency() const { return m_ArmorProficiency; } + void AddMail(Mail* mail) { m_mail.push_front(mail);}// for call from WorldSession::SendMailTo + uint32 GetMailSize() { return m_mail.size();} + Mail* GetMail(uint32 id); - bool IsTwoHandUsed() const - { - Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); - return mainItem && mainItem->GetTemplate()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip(); - } - void SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast = false, bool sendChatMessage = true); - bool BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot); - bool _StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot, int32 price, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore); + PlayerMails::iterator GetMailBegin() { return m_mail.begin();} + PlayerMails::iterator GetMailEnd() { return m_mail.end();} - float GetReputationPriceDiscount(Creature const* creature) const; + /*********************************************************/ + /*** MAILED ITEMS SYSTEM ***/ + /*********************************************************/ - Player* GetTrader() const { return m_trade ? m_trade->GetTrader() : nullptr; } - TradeData* GetTradeData() const { return m_trade; } - void TradeCancel(bool sendback); + uint8 unReadMails; + time_t m_nextMailDelivereTime; - void UpdateEnchantTime(uint32 time); - void UpdateSoulboundTradeItems(); - void AddTradeableItem(Item* item); - void RemoveTradeableItem(Item* item); - void UpdateItemDuration(uint32 time, bool realtimeonly = false); - void AddEnchantmentDurations(Item* item); - void RemoveEnchantmentDurations(Item* item); - void RemoveEnchantmentDurationsReferences(Item* item); // pussywizard - void RemoveArenaEnchantments(EnchantmentSlot slot); - void AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration); - void ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur = true, bool ignore_condition = false); - void ApplyEnchantment(Item* item, bool apply); - void UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 new_value); - void SendEnchantmentDurations(); - void BuildEnchantmentsInfoData(WorldPacket* data); - void AddItemDurations(Item* item); - void RemoveItemDurations(Item* item); - void SendItemDurations(); - void LoadCorpse(); - void LoadPet(); + typedef std::unordered_map ItemMap; - bool AddItem(uint32 itemId, uint32 count); + ItemMap mMitems; //template defined in objectmgr.cpp - uint32 m_stableSlots; + Item* GetMItem(uint32 id) + { + ItemMap::const_iterator itr = mMitems.find(id); + return itr != mMitems.end() ? itr->second : nullptr; + } - /*********************************************************/ - /*** GOSSIP SYSTEM ***/ - /*********************************************************/ + void AddMItem(Item* it) + { + ASSERT(it); + //ASSERT deleted, because items can be added before loading + mMitems[it->GetGUIDLow()] = it; + } - void PrepareGossipMenu(WorldObject* source, uint32 menuId = 0, bool showQuests = false); - void SendPreparedGossip(WorldObject* source); - void OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId); + bool RemoveMItem(uint32 id) + { + return !!mMitems.erase(id); + } - uint32 GetGossipTextId(uint32 menuId, WorldObject* source); - uint32 GetGossipTextId(WorldObject* source); - static uint32 GetDefaultGossipMenuForSource(WorldObject* source); + void PetSpellInitialize(); + void CharmSpellInitialize(); + void PossessSpellInitialize(); + void VehicleSpellInitialize(); + void SendRemoveControlBar(); + bool HasSpell(uint32 spell) const override; + bool HasActiveSpell(uint32 spell) const; // show in spellbook + TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell) const; + bool IsSpellFitByClassAndRace(uint32 spell_id) const; + bool IsNeedCastPassiveSpellAtLearn(SpellInfo const* spellInfo) const; - void ToggleInstantFlight(); + void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask); + void SendInitialSpells(); + void SendLearnPacket(uint32 spellId, bool learn); + bool addSpell(uint32 spellId, uint8 addSpecMask, bool updateActive, bool temporary = false); + bool _addSpell(uint32 spellId, uint8 addSpecMask, bool temporary); + void learnSpell(uint32 spellId); + void removeSpell(uint32 spellId, uint8 removeSpecMask, bool onlyTemporary); + void resetSpells(); + void learnDefaultSpells(); + void learnQuestRewardedSpells(); + void learnQuestRewardedSpells(Quest const* quest); + void learnSpellHighRank(uint32 spellid); + void SetReputation(uint32 factionentry, uint32 value); + uint32 GetReputation(uint32 factionentry) const; + std::string const& GetGuildName(); + uint32 GetFreeTalentPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS1); } + void SetFreeTalentPoints(uint32 points); + bool resetTalents(bool noResetCost = false); + uint32 resetTalentsCost() const; + void InitTalentForLevel(); + void BuildPlayerTalentsInfoData(WorldPacket* data); + void BuildPetTalentsInfoData(WorldPacket* data); + void SendTalentsInfoData(bool pet); + void LearnTalent(uint32 talentId, uint32 talentRank); + void LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank); - /*********************************************************/ - /*** QUEST SYSTEM ***/ - /*********************************************************/ + bool addTalent(uint32 spellId, uint8 addSpecMask, uint8 oldTalentRank); + void _removeTalent(PlayerTalentMap::iterator& itr, uint8 specMask); + void _removeTalent(uint32 spellId, uint8 specMask); + void _removeTalentAurasAndSpells(uint32 spellId); + void _addTalentAurasAndSpells(uint32 spellId); + bool HasTalent(uint32 spell_id, uint8 spec) const; - int32 GetQuestLevel(Quest const* quest) const { return quest && (quest->GetQuestLevel() > 0) ? quest->GetQuestLevel() : getLevel(); } + uint32 CalculateTalentsPoints() const; - void PrepareQuestMenu(uint64 guid); - void SendPreparedQuest(uint64 guid); - bool IsActiveQuest(uint32 quest_id) const; - Quest const* GetNextQuest(uint64 guid, Quest const* quest); - bool CanSeeStartQuest(Quest const* quest); - bool CanTakeQuest(Quest const* quest, bool msg); - bool CanAddQuest(Quest const* quest, bool msg); - bool CanCompleteQuest(uint32 quest_id, const QuestStatusData* q_savedStatus = nullptr); - bool CanCompleteRepeatableQuest(Quest const* quest); - bool CanRewardQuest(Quest const* quest, bool msg); - bool CanRewardQuest(Quest const* quest, uint32 reward, bool msg); - void AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver); - void AddQuest(Quest const* quest, Object* questGiver); - void AbandonQuest(uint32 quest_id); - void CompleteQuest(uint32 quest_id); - void IncompleteQuest(uint32 quest_id); - void RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool announce = true); - void FailQuest(uint32 quest_id); - bool SatisfyQuestSkill(Quest const* qInfo, bool msg) const; - bool SatisfyQuestLevel(Quest const* qInfo, bool msg) const; - bool SatisfyQuestLog(bool msg); - bool SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const; - bool SatisfyQuestClass(Quest const* qInfo, bool msg) const; - bool SatisfyQuestRace(Quest const* qInfo, bool msg) const; - bool SatisfyQuestReputation(Quest const* qInfo, bool msg) const; - bool SatisfyQuestStatus(Quest const* qInfo, bool msg) const; - bool SatisfyQuestConditions(Quest const* qInfo, bool msg); - bool SatisfyQuestTimed(Quest const* qInfo, bool msg) const; - bool SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const; - bool SatisfyQuestNextChain(Quest const* qInfo, bool msg) const; - bool SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const; - bool SatisfyQuestDay(Quest const* qInfo, bool msg) const; - bool SatisfyQuestWeek(Quest const* qInfo, bool msg) const; - bool SatisfyQuestMonth(Quest const* qInfo, bool msg) const; - bool SatisfyQuestSeasonal(Quest const* qInfo, bool msg) const; - bool GiveQuestSourceItem(Quest const* quest); - bool TakeQuestSourceItem(uint32 questId, bool msg); - bool GetQuestRewardStatus(uint32 quest_id) const; - QuestStatus GetQuestStatus(uint32 quest_id) const; - void SetQuestStatus(uint32 questId, QuestStatus status, bool update = true); - void RemoveActiveQuest(uint32 questId, bool update = true); - void RemoveRewardedQuest(uint32 questId, bool update = true); - void SendQuestUpdate(uint32 questId); - QuestGiverStatus GetQuestDialogStatus(Object* questGiver); + // Dual Spec + void UpdateSpecCount(uint8 count); + uint8 GetActiveSpec() const { return m_activeSpec; } + uint8 GetActiveSpecMask() const { return (1 << m_activeSpec); } + void SetActiveSpec(uint8 spec) { m_activeSpec = spec; } + uint8 GetSpecsCount() const { return m_specsCount; } + void SetSpecsCount(uint8 count) { m_specsCount = count; } + void ActivateSpec(uint8 spec); + void GetTalentTreePoints(uint8 (&specPoints)[3]) const; + uint8 GetMostPointsTalentTree() const; + bool HasTankSpec(); + bool HasMeleeSpec(); + bool HasCasterSpec(); + bool HasHealSpec(); + uint32 GetSpec(int8 spec = -1); - void SetDailyQuestStatus(uint32 quest_id); - void SetWeeklyQuestStatus(uint32 quest_id); - void SetMonthlyQuestStatus(uint32 quest_id); - void SetSeasonalQuestStatus(uint32 quest_id); - void ResetDailyQuestStatus(); - void ResetWeeklyQuestStatus(); - void ResetMonthlyQuestStatus(); - void ResetSeasonalQuestStatus(uint16 event_id); + void InitGlyphsForLevel(); + void SetGlyphSlot(uint8 slot, uint32 slottype) { SetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot, slottype); } + uint32 GetGlyphSlot(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot); } + void SetGlyph(uint8 slot, uint32 glyph, bool save) + { + m_Glyphs[m_activeSpec][slot] = glyph; + SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph); - uint16 FindQuestSlot(uint32 quest_id) const; - uint32 GetQuestSlotQuestId(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET); } - uint32 GetQuestSlotState(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET); } - uint16 GetQuestSlotCounter(uint16 slot, uint8 counter) const { return (uint16)(GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET) >> (counter * 16)); } - uint32 GetQuestSlotTime(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET); } - void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0) - { - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id); - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0); - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0); - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET + 1, 0); - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); - } - void SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count) - { - uint64 val = GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET); - val &= ~((uint64)0xFFFF << (counter * 16)); - val |= ((uint64)count << (counter * 16)); - SetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, val); - } - void SetQuestSlotState(uint16 slot, uint32 state) { SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); } - void RemoveQuestSlotState(uint16 slot, uint32 state) { RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); } - void SetQuestSlotTimer(uint16 slot, uint32 timer) { SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); } - void SwapQuestSlot(uint16 slot1, uint16 slot2) - { - for (int i = 0; i < MAX_QUEST_OFFSET; ++i) + if (save) + SetNeedToSaveGlyphs(true); + } + uint32 GetGlyph(uint8 slot) const { return m_Glyphs[m_activeSpec][slot]; } + + uint32 GetFreePrimaryProfessionPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS2); } + void SetFreePrimaryProfessions(uint16 profs) { SetUInt32Value(PLAYER_CHARACTER_POINTS2, profs); } + void InitPrimaryProfessions(); + + PlayerSpellMap const& GetSpellMap() const { return m_spells; } + PlayerSpellMap& GetSpellMap() { return m_spells; } + + SpellCooldowns const& GetSpellCooldownMap() const { return m_spellCooldowns; } + SpellCooldowns& GetSpellCooldownMap() { return m_spellCooldowns; } + + void AddSpellMod(SpellModifier* mod, bool apply); + bool IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell = nullptr); + bool HasSpellMod(SpellModifier* mod, Spell* spell); + template T ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell = NULL, bool temporaryPet = false); + void RemoveSpellMods(Spell* spell); + void RestoreSpellMods(Spell* spell, uint32 ownerAuraId = 0, Aura* aura = nullptr); + void RestoreAllSpellMods(uint32 ownerAuraId = 0, Aura* aura = nullptr); + void DropModCharge(SpellModifier* mod, Spell* spell); + void SetSpellModTakingSpell(Spell* spell, bool apply); + + static uint32 const infinityCooldownDelay = 0x9A7EC800; // used for set "infinity cooldowns" for spells and check, MONTH*IN_MILLISECONDS + static uint32 const infinityCooldownDelayCheck = 0x4D3F6400; //MONTH*IN_MILLISECONDS/2; + virtual bool HasSpellCooldown(uint32 spell_id) const override + { + SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); + return itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS(); + } + virtual bool HasSpellItemCooldown(uint32 spell_id, uint32 itemid) const override + { + SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); + return itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS() && itr->second.itemid == itemid; + } + uint32 GetSpellCooldownDelay(uint32 spell_id) const + { + SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); + return uint32(itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS() ? itr->second.end - World::GetGameTimeMS() : 0); + } + void AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 itemId, Spell* spell = NULL, bool infinityCooldown = false); + void AddSpellCooldown(uint32 spell_id, uint32 itemid, uint32 end_time, bool needSendToClient = false, bool forceSendToSpectator = false) override; + void ModifySpellCooldown(uint32 spellId, int32 cooldown); + void SendCooldownEvent(SpellInfo const* spellInfo, uint32 itemId = 0, Spell* spell = NULL, bool setCooldown = true); + void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override; + void RemoveSpellCooldown(uint32 spell_id, bool update = false); + void SendClearCooldown(uint32 spell_id, Unit* target); + + GlobalCooldownMgr& GetGlobalCooldownMgr() { return m_GlobalCooldownMgr; } + + void RemoveCategoryCooldown(uint32 cat); + void RemoveArenaSpellCooldowns(bool removeActivePetCooldowns = false); + void RemoveAllSpellCooldown(); + void _LoadSpellCooldowns(PreparedQueryResult result); + void _SaveSpellCooldowns(SQLTransaction& trans, bool logout); + uint32 GetLastPotionId() { return m_lastPotionId; } + void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; } + void UpdatePotionCooldown(); + + void setResurrectRequestData(uint64 guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana) + { + m_resurrectGUID = guid; + m_resurrectMap = mapId; + m_resurrectX = X; + m_resurrectY = Y; + m_resurrectZ = Z; + m_resurrectHealth = health; + m_resurrectMana = mana; + } + void clearResurrectRequestData() { setResurrectRequestData(0, 0, 0.0f, 0.0f, 0.0f, 0, 0); } + bool isResurrectRequestedBy(uint64 guid) const { return m_resurrectGUID && m_resurrectGUID == guid; } + bool isResurrectRequested() const { return m_resurrectGUID != 0; } + void ResurectUsingRequestData(); + + uint8 getCinematic() const + { + return m_cinematic; + } + void setCinematic(uint8 cine) + { + m_cinematic = cine; + } + + ActionButton* addActionButton(uint8 button, uint32 action, uint8 type); + void removeActionButton(uint8 button); + ActionButton const* GetActionButton(uint8 button); + void SendInitialActionButtons() const { SendActionButtons(1); } + void SendActionButtons(uint32 state) const; + bool IsActionButtonDataValid(uint8 button, uint32 action, uint8 type); + + PvPInfo pvpInfo; + void UpdatePvPState(bool onlyFFA = false); + void SetPvP(bool state) + { + Unit::SetPvP(state); + if (!m_Controlled.empty()) + for (ControlSet::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) + (*itr)->SetPvP(state); + } + void UpdatePvP(bool state, bool _override = false); + void UpdateZone(uint32 newZone, uint32 newArea); + void UpdateArea(uint32 newArea); + + uint32 GetZoneId(bool forceRecalc = false) const override; + uint32 GetAreaId(bool forceRecalc = false) const override; + void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc = false) const override; + + void UpdateZoneDependentAuras(uint32 zone_id); // zones + void UpdateAreaDependentAuras(uint32 area_id); // subzones + + void UpdateAfkReport(time_t currTime); + void UpdatePvPFlag(time_t currTime); + void UpdateContestedPvP(uint32 currTime); + void SetContestedPvPTimer(uint32 newTime) {m_contestedPvPTimer = newTime;} + void ResetContestedPvP() + { + ClearUnitState(UNIT_STATE_ATTACK_PLAYER); + RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP); + m_contestedPvPTimer = 0; + } + + /** todo: -maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler.. **/ + DuelInfo* duel; + void UpdateDuelFlag(time_t currTime); + void CheckDuelDistance(time_t currTime); + void DuelComplete(DuelCompleteType type); + void SendDuelCountdown(uint32 counter); + + bool IsGroupVisibleFor(Player const* p) const; + bool IsInSameGroupWith(Player const* p) const; + bool IsInSameRaidWith(Player const* p) const { return p == this || (GetGroup() != NULL && GetGroup() == p->GetGroup()); } + void UninviteFromGroup(); + static void RemoveFromGroup(Group* group, uint64 guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, uint64 kicker = 0, const char* reason = nullptr); + void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(), GetGUID(), method); } + void SendUpdateToOutOfRangeGroupMembers(); + + void SetInGuild(uint32 GuildId) + { + SetUInt32Value(PLAYER_GUILDID, GuildId); + // xinef: update global storage + sWorld->UpdateGlobalPlayerGuild(GetGUIDLow(), GuildId); + } + void SetRank(uint8 rankId) { SetUInt32Value(PLAYER_GUILDRANK, rankId); } + uint8 GetRank() const { return uint8(GetUInt32Value(PLAYER_GUILDRANK)); } + void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; } + uint32 GetGuildId() const { return GetUInt32Value(PLAYER_GUILDID); } + Guild* GetGuild() const; + static uint32 GetGuildIdFromStorage(uint32 guid); + static uint32 GetGroupIdFromStorage(uint32 guid); + static uint32 GetArenaTeamIdFromStorage(uint32 guid, uint8 slot); + uint32 GetGuildIdInvited() { return m_GuildIdInvited; } + static void RemovePetitionsAndSigns(uint64 guid, uint32 type); + + // Arena Team + void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type) + { + SetArenaTeamInfoField(slot, ARENA_TEAM_ID, ArenaTeamId); + SetArenaTeamInfoField(slot, ARENA_TEAM_TYPE, type); + } + void SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value) + { + SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + type, value); + } + static uint32 GetArenaTeamIdFromDB(uint64 guid, uint8 slot); + static void LeaveAllArenaTeams(uint64 guid); + uint32 GetArenaTeamId(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID); } + uint32 GetArenaPersonalRating(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING); } + void SetArenaTeamIdInvited(uint32 ArenaTeamId) { m_ArenaTeamIdInvited = ArenaTeamId; } + uint32 GetArenaTeamIdInvited() { return m_ArenaTeamIdInvited; } + + Difficulty GetDifficulty(bool isRaid) const { return isRaid ? m_raidDifficulty : m_dungeonDifficulty; } + Difficulty GetDungeonDifficulty() const { return m_dungeonDifficulty; } + Difficulty GetRaidDifficulty() const { return m_raidDifficulty; } + Difficulty GetStoredRaidDifficulty() const { return m_raidMapDifficulty; } // only for use in difficulty packet after exiting to raid map + void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; } + void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; } + void StoreRaidMapDifficulty() { m_raidMapDifficulty = GetMap()->GetDifficulty(); } + + bool UpdateSkill(uint32 skill_id, uint32 step); + bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step); + + bool UpdateCraftSkill(uint32 spellid); + bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1); + bool UpdateFishingSkill(); + + uint32 GetBaseDefenseSkillValue() const { return GetBaseSkillValue(SKILL_DEFENSE); } + uint32 GetBaseWeaponSkillValue(WeaponAttackType attType) const; + + uint32 GetSpellByProto(ItemTemplate* proto); + + float GetHealthBonusFromStamina(); + float GetManaBonusFromIntellect(); + + bool UpdateStats(Stats stat) override; + bool UpdateAllStats() override; + void ApplySpellPenetrationBonus(int32 amount, bool apply); + void UpdateResistances(uint32 school) override; + void UpdateArmor() override; + void UpdateMaxHealth() override; + void UpdateMaxPower(Powers power) override; + void ApplyFeralAPBonus(int32 amount, bool apply); + void UpdateAttackPowerAndDamage(bool ranged = false) override; + void UpdateShieldBlockValue(); + void ApplySpellPowerBonus(int32 amount, bool apply); + void UpdateSpellDamageAndHealingBonus(); + void ApplyRatingMod(CombatRating cr, int32 value, bool apply); + void UpdateRating(CombatRating cr); + void UpdateAllRatings(); + + void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) override; + + void UpdateDefenseBonusesMod(); + inline void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);} + float GetMeleeCritFromAgility(); + void GetDodgeFromAgility(float& diminishing, float& nondiminishing); + float GetMissPercentageFromDefence() const; + float GetSpellCritFromIntellect(); + float OCTRegenHPPerSpirit(); + float OCTRegenMPPerSpirit(); + float GetRatingMultiplier(CombatRating cr) const; + float GetRatingBonusValue(CombatRating cr) const; + uint32 GetBaseSpellPowerBonus() { return m_baseSpellPower; } + int32 GetSpellPenetrationItemMod() const { return m_spellPenetrationItemMod; } + + float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const; + void UpdateBlockPercentage(); + void UpdateCritPercentage(WeaponAttackType attType); + void UpdateAllCritPercentages(); + void UpdateParryPercentage(); + void UpdateDodgePercentage(); + void UpdateMeleeHitChances(); + void UpdateRangedHitChances(); + void UpdateSpellHitChances(); + + void UpdateAllSpellCritChances(); + void UpdateSpellCritChance(uint32 school); + void UpdateArmorPenetration(int32 amount); + void UpdateExpertise(WeaponAttackType attType); + void ApplyManaRegenBonus(int32 amount, bool apply); + void ApplyHealthRegenBonus(int32 amount, bool apply); + void UpdateManaRegen(); + void UpdateRuneRegen(RuneType rune); + + uint64 GetLootGUID() const { return m_lootGuid; } + void SetLootGUID(uint64 guid) { m_lootGuid = guid; } + + void RemovedInsignia(Player* looterPlr); + + WorldSession* GetSession() const { return m_session; } + void SetSession(WorldSession* sess) { m_session = sess; } + + void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const override; + void DestroyForPlayer(Player* target, bool onDeath = false) const override; + void SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend = false, float group_rate = 1.0f); + + // notifiers + void SendAttackSwingCantAttack(); + void SendAttackSwingCancelAttack(); + void SendAttackSwingDeadTarget(); + void SendAttackSwingNotInRange(); + void SendAttackSwingBadFacingAttack(); + void SendAutoRepeatCancel(Unit* target); + void SendExplorationExperience(uint32 Area, uint32 Experience); + + void SendDungeonDifficulty(bool IsInGroup); + void SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty = -1); + static void ResetInstances(uint64 guid, uint8 method, bool isRaid); + void SendResetInstanceSuccess(uint32 MapId); + void SendResetInstanceFailed(uint32 reason, uint32 MapId); + void SendResetFailedNotify(uint32 mapid); + + virtual bool UpdatePosition(float x, float y, float z, float orientation, bool teleport = false) override; + bool UpdatePosition(const Position& pos, bool teleport = false) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } + void UpdateUnderwaterState(Map* m, float x, float y, float z) override; + + void SendMessageToSet(WorldPacket* data, bool self) override { SendMessageToSetInRange(data, GetVisibilityRange(), self, true); } // pussywizard! + void SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool includeMargin = false, Player const* skipped_rcvr = nullptr) override; // pussywizard! + void SendMessageToSetInRange_OwnTeam(WorldPacket* data, float dist, bool self); // pussywizard! param includeMargin not needed here + void SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr) override { SendMessageToSetInRange(data, GetVisibilityRange(), skipped_rcvr != this, true, skipped_rcvr); } // pussywizard! + + void SendTeleportAckPacket(); + + Corpse* GetCorpse() const; + void SpawnCorpseBones(); + void CreateCorpse(); + void KillPlayer(); + uint32 GetResurrectionSpellId(); + void ResurrectPlayer(float restore_percent, bool applySickness = false); + void BuildPlayerRepop(); + void RepopAtGraveyard(); + + void DurabilityLossAll(double percent, bool inventory); + void DurabilityLoss(Item* item, double percent); + void DurabilityPointsLossAll(int32 points, bool inventory); + void DurabilityPointsLoss(Item* item, int32 points); + void DurabilityPointLossForEquipSlot(EquipmentSlots slot); + uint32 DurabilityRepairAll(bool cost, float discountMod, bool guildBank); + uint32 DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank); + + void UpdateMirrorTimers(); + void StopMirrorTimers() + { + StopMirrorTimer(FATIGUE_TIMER); + StopMirrorTimer(BREATH_TIMER); + StopMirrorTimer(FIRE_TIMER); + } + bool IsMirrorTimerActive(MirrorTimerType type) { return m_MirrorTimer[type] == getMaxTimer(type); } + + void SetMovement(PlayerMovementType pType); + + bool CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone); + + void JoinedChannel(Channel* c); + void LeftChannel(Channel* c); + void CleanupChannels(); + void ClearChannelWatch(); + void UpdateLocalChannels(uint32 newZone); + + void UpdateDefense(); + void UpdateWeaponSkill (WeaponAttackType attType); + void UpdateCombatSkills(Unit* victim, WeaponAttackType attType, bool defence); + + void SetSkill(uint16 id, uint16 step, uint16 currVal, uint16 maxVal); + uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus + temp bonus + uint16 GetPureMaxSkillValue(uint32 skill) const; // max + uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus + uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus + uint16 GetPureSkillValue(uint32 skill) const; // skill value + int16 GetSkillPermBonusValue(uint32 skill) const; + int16 GetSkillTempBonusValue(uint32 skill) const; + uint16 GetSkillStep(uint16 skill) const; // 0...6 + bool HasSkill(uint32 skill) const; + void learnSkillRewardedSpells(uint32 id, uint32 value); + + WorldLocation& GetTeleportDest() { return teleportStore_dest; } + bool IsBeingTeleported() const { return mSemaphoreTeleport_Near != 0 || mSemaphoreTeleport_Far != 0; } + bool IsBeingTeleportedNear() const { return mSemaphoreTeleport_Near != 0; } + bool IsBeingTeleportedFar() const { return mSemaphoreTeleport_Far != 0; } + void SetSemaphoreTeleportNear(time_t tm) { mSemaphoreTeleport_Near = tm; } + void SetSemaphoreTeleportFar(time_t tm) { mSemaphoreTeleport_Far = tm; } + time_t GetSemaphoreTeleportNear() const { return mSemaphoreTeleport_Near; } + time_t GetSemaphoreTeleportFar() const { return mSemaphoreTeleport_Far; } + void ProcessDelayedOperations(); + uint32 GetDelayedOperations() const { return m_DelayedOperations; } + void ScheduleDelayedOperation(uint32 operation) + { + if (operation < DELAYED_END) + m_DelayedOperations |= operation; + } + + void CheckAreaExploreAndOutdoor(void); + + static TeamId TeamIdForRace(uint8 race); + TeamId GetTeamId(bool original = false) const { return original ? TeamIdForRace(getRace(true)) : m_team; }; + void setFactionForRace(uint8 race); + void setTeamId(TeamId teamid) { m_team = teamid; }; + + void InitDisplayIds(); + + bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const; + bool IsAtRecruitAFriendDistance(WorldObject const* pOther) const; + void RewardPlayerAndGroupAtKill(Unit* victim, bool isBattleGround); + void RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource); + bool isHonorOrXPTarget(Unit* victim) const; + + bool GetsRecruitAFriendBonus(bool forXP); + uint8 GetGrantableLevels() { return m_grantableLevels; } + void SetGrantableLevels(uint8 val) { m_grantableLevels = val; } + + ReputationMgr& GetReputationMgr() { return *m_reputationMgr; } + ReputationMgr const& GetReputationMgr() const { return *m_reputationMgr; } + ReputationRank GetReputationRank(uint32 faction_id) const; + void RewardReputation(Unit* victim, float rate); + void RewardReputation(Quest const* quest); + + int32 CalculateReputationGain(ReputationSource source, uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool noQuestBonus = false); + + void UpdateSkillsForLevel(); + void UpdateSkillsToMaxSkillsForLevel(); // for .levelup + void ModifySkillBonus(uint32 skillid, int32 val, bool talent); + + /*********************************************************/ + /*** PVP SYSTEM ***/ + /*********************************************************/ + void UpdateHonorFields(); + bool RewardHonor(Unit* victim, uint32 groupsize, int32 honor = -1, bool awardXP = true); + uint32 GetHonorPoints() const { return GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY); } + uint32 GetArenaPoints() const { return GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY); } + void ModifyHonorPoints(int32 value, SQLTransaction* trans = nullptr); //! If trans is specified, honor save query will be added to trans + void ModifyArenaPoints(int32 value, SQLTransaction* trans = nullptr); //! If trans is specified, arena point save query will be added to trans + uint32 GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) const; + void SetHonorPoints(uint32 value); + void SetArenaPoints(uint32 value); + + // duel health and mana reset methods + void SaveHealthBeforeDuel() { healthBeforeDuel = GetHealth(); } + void SaveManaBeforeDuel() { manaBeforeDuel = GetPower(POWER_MANA); } + void RestoreHealthAfterDuel() { SetHealth(healthBeforeDuel); } + void RestoreManaAfterDuel() { SetPower(POWER_MANA, manaBeforeDuel); } + + //End of PvP System + + inline SpellCooldowns GetSpellCooldowns() const { return m_spellCooldowns; } + + void SetDrunkValue(uint8 newDrunkValue, uint32 itemId = 0); + uint8 GetDrunkValue() const { return GetByteValue(PLAYER_BYTES_3, 1); } + static DrunkenState GetDrunkenstateByValue(uint8 value); + + uint32 GetDeathTimer() const { return m_deathTimer; } + uint32 GetCorpseReclaimDelay(bool pvp) const; + void UpdateCorpseReclaimDelay(); + int32 CalculateCorpseReclaimDelay(bool load = false); + void SendCorpseReclaimDelay(uint32 delay); + + uint32 GetShieldBlockValue() const override; // overwrite Unit version (virtual) + bool CanParry() const { return m_canParry; } + void SetCanParry(bool value); + bool CanBlock() const { return m_canBlock; } + void SetCanBlock(bool value); + bool CanTitanGrip() const { return m_canTitanGrip; } + void SetCanTitanGrip(bool value); + bool CanTameExoticPets() const { return IsGameMaster() || HasAuraType(SPELL_AURA_ALLOW_TAME_PET_TYPE); } + + void SetRegularAttackTime(); + void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value) { m_auraBaseMod[modGroup][modType] = value; } + void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply); + float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const; + float GetTotalBaseModValue(BaseModGroup modGroup) const; + float GetTotalPercentageModValue(BaseModGroup modGroup) const { return m_auraBaseMod[modGroup][FLAT_MOD] + m_auraBaseMod[modGroup][PCT_MOD]; } + void _ApplyAllStatBonuses(); + void _RemoveAllStatBonuses(); + + void ResetAllPowers(); + + void _ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply); + void _ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply); + void _ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply); + + void _ApplyItemMods(Item* item, uint8 slot, bool apply); + void _RemoveAllItemMods(); + void _ApplyAllItemMods(); + void _ApplyAllLevelScaleItemMods(bool apply); + void _ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply, bool only_level_scale = false); + void _ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, ScalingStatValuesEntry const* ssv, bool apply); + void _ApplyAmmoBonuses(); + bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot); + void ToggleMetaGemsActive(uint8 exceptslot, bool apply); + void CorrectMetaGemEnchants(uint8 slot, bool apply); + void InitDataForForm(bool reapplyMods = false); + + void ApplyItemEquipSpell(Item* item, bool apply, bool form_change = false); + void ApplyEquipSpell(SpellInfo const* spellInfo, Item* item, bool apply, bool form_change = false); + void UpdateEquipSpellsAtFormChange(); + void CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx); + void CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 cast_count, uint32 glyphIndex); + void CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item* item, ItemTemplate const* proto); + + void SendEquipmentSetList(); + void SetEquipmentSet(uint32 index, EquipmentSet eqset); + void DeleteEquipmentSet(uint64 setGuid); + + void SendInitWorldStates(uint32 zone, uint32 area); + void SendUpdateWorldState(uint32 Field, uint32 Value); + void SendDirectMessage(WorldPacket* data); + void SendBGWeekendWorldStates(); + void SendBattlefieldWorldStates(); + + void GetAurasForTarget(Unit* target); + + PlayerMenu* PlayerTalkClass; + std::vector ItemSetEff; + + void SendLoot(uint64 guid, LootType loot_type); + void SendLootError(uint64 guid, LootError error); + void SendLootRelease(uint64 guid); + void SendNotifyLootItemRemoved(uint8 lootSlot); + void SendNotifyLootMoneyRemoved(); + + /*********************************************************/ + /*** BATTLEGROUND SYSTEM ***/ + /*********************************************************/ + + bool InBattleground() const { return m_bgData.bgInstanceID != 0; } + bool InArena() const; + uint32 GetBattlegroundId() const { return m_bgData.bgInstanceID; } + BattlegroundTypeId GetBattlegroundTypeId() const { return m_bgData.bgTypeID; } + uint32 GetCurrentBattlegroundQueueSlot() const { return m_bgData.bgQueueSlot; } + bool IsInvitedForBattlegroundInstance() const { return m_bgData.isInvited; } + bool IsCurrentBattlegroundRandom() const { return m_bgData.bgIsRandom; } + BGData& GetBGData() { return m_bgData; } + void SetBGData(BGData& bgdata) { m_bgData = bgdata; } + Battleground* GetBattleground(bool create = false) const; + + bool InBattlegroundQueue() const + { + for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) + if (m_bgBattlegroundQueueID[i] != BATTLEGROUND_QUEUE_NONE) + return true; + return false; + } + + BattlegroundQueueTypeId GetBattlegroundQueueTypeId(uint32 index) const { return m_bgBattlegroundQueueID[index]; } + + uint32 GetBattlegroundQueueIndex(BattlegroundQueueTypeId bgQueueTypeId) const + { + for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) + if (m_bgBattlegroundQueueID[i] == bgQueueTypeId) + return i; + return PLAYER_MAX_BATTLEGROUND_QUEUES; + } + + bool InBattlegroundQueueForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId) const + { + return GetBattlegroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES; + } + + void SetBattlegroundId(uint32 id, BattlegroundTypeId bgTypeId, uint32 queueSlot, bool invited, bool isRandom, TeamId teamId); + + uint32 AddBattlegroundQueueId(BattlegroundQueueTypeId val) + { + for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) + if (m_bgBattlegroundQueueID[i] == BATTLEGROUND_QUEUE_NONE || m_bgBattlegroundQueueID[i] == val) { - uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i); - uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i); - - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2); - SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1); + m_bgBattlegroundQueueID[i] = val; + return i; } - } - uint16 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry); - void AreaExploredOrEventHappens(uint32 questId); - void GroupEventHappens(uint32 questId, WorldObject const* pEventObject); - void ItemAddedQuestCheck(uint32 entry, uint32 count); - void ItemRemovedQuestCheck(uint32 entry, uint32 count); - void KilledMonster(CreatureTemplate const* cInfo, uint64 guid); - void KilledMonsterCredit(uint32 entry, uint64 guid); - void KilledPlayerCredit(); - void KillCreditGO(uint32 entry, uint64 guid = 0); - void TalkedToCreature(uint32 entry, uint64 guid); - void MoneyChanged(uint32 value); - void ReputationChanged(FactionEntry const* factionEntry); - void ReputationChanged2(FactionEntry const* factionEntry); - bool HasQuestForItem(uint32 itemId, uint32 excludeQuestId = 0, bool turnIn = false) const; - bool HasQuestForGO(int32 GOId) const; - void UpdateForQuestWorldObjects(); - bool CanShareQuest(uint32 quest_id) const; - - void SendQuestComplete(uint32 quest_id); - void SendQuestReward(Quest const* quest, uint32 XP); - void SendQuestFailed(uint32 questId, InventoryResult reason = EQUIP_ERR_OK); - void SendQuestTimerFailed(uint32 quest_id); - void SendCanTakeQuestResponse(uint32 msg) const; - void SendQuestConfirmAccept(Quest const* quest, Player* pReceiver); - void SendPushToPartyResponse(Player* player, uint8 msg); - void SendQuestUpdateAddItem(Quest const* quest, uint32 item_idx, uint16 count); - void SendQuestUpdateAddCreatureOrGo(Quest const* quest, uint64 guid, uint32 creatureOrGO_idx, uint16 old_count, uint16 add_count); - void SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint16 add_count); - - uint64 GetDivider() { return m_divider; } - void SetDivider(uint64 guid) { m_divider = guid; } - - uint32 GetInGameTime() { return m_ingametime; } - - void SetInGameTime(uint32 time) { m_ingametime = time; } - - void AddTimedQuest(uint32 quest_id) { m_timedquests.insert(quest_id); } - void RemoveTimedQuest(uint32 quest_id) { m_timedquests.erase(quest_id); } - - bool HasPvPForcingQuest() const; - - /*********************************************************/ - /*** LOAD SYSTEM ***/ - /*********************************************************/ - - bool LoadFromDB(uint32 guid, SQLQueryHolder *holder); - bool isBeingLoaded() const override; - - void Initialize(uint32 guid); - static uint32 GetUInt32ValueFromArray(Tokenizer const& data, uint16 index); - static float GetFloatValueFromArray(Tokenizer const& data, uint16 index); - static uint32 GetZoneIdFromDB(uint64 guid); - static uint32 GetLevelFromStorage(uint64 guid); - static bool LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, uint64 guid); - - static bool IsValidGender(uint8 Gender) { return Gender <= GENDER_FEMALE; } - - /*********************************************************/ - /*** SAVE SYSTEM ***/ - /*********************************************************/ - - void SaveToDB(bool create, bool logout); - void SaveInventoryAndGoldToDB(SQLTransaction& trans); // fast save function for item/money cheating preventing - void SaveGoldToDB(SQLTransaction& trans); - - static void SetUInt32ValueInArray(Tokenizer& data, uint16 index, uint32 value); - static void SetFloatValueInArray(Tokenizer& data, uint16 index, float value); - static void Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair); - static void SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, uint64 guid); - - static void DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally); - static void DeleteOldCharacters(); - static void DeleteOldCharacters(uint32 keepDays); - - bool m_mailsLoaded; - bool m_mailsUpdated; - - void SetBindPoint(uint64 guid); - void SendTalentWipeConfirm(uint64 guid); - void ResetPetTalents(); - void CalcRage(uint32 damage, bool attacker); - void RegenerateAll(); - void Regenerate(Powers power); - void RegenerateHealth(); - void setRegenTimerCount(uint32 time) {m_regenTimerCount = time;} - void setWeaponChangeTimer(uint32 time) {m_weaponChangeTimer = time;} - - uint32 GetMoney() const { return GetUInt32Value(PLAYER_FIELD_COINAGE); } - bool ModifyMoney(int32 amount, bool sendError = true); - bool HasEnoughMoney(uint32 amount) const { return (GetMoney() >= amount); } - bool HasEnoughMoney(int32 amount) const - { - if (amount > 0) - return (GetMoney() >= (uint32) amount); - return true; - } - - void SetMoney(uint32 value) - { - SetUInt32Value(PLAYER_FIELD_COINAGE, value); - MoneyChanged(value); - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED); - } - - RewardedQuestSet const& getRewardedQuests() const { return m_RewardedQuests; } - QuestStatusMap& getQuestStatusMap() { return m_QuestStatus; } - - size_t GetRewardedQuestCount() const { return m_RewardedQuests.size(); } - bool IsQuestRewarded(uint32 quest_id) const - { - return m_RewardedQuests.find(quest_id) != m_RewardedQuests.end(); - } - - Unit* GetSelectedUnit() const; - Player* GetSelectedPlayer() const; - - void SetTarget(uint64 /*guid*/) override { } /// Used for serverside target changes, does not apply to players - void SetSelection(uint64 guid); - - uint8 GetComboPoints() const { return m_comboPoints; } - uint64 GetComboTarget() const { return m_comboTarget; } - - void AddComboPoints(Unit* target, int8 count); - void ClearComboPoints(); - void SendComboPoints(); - - void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, uint32 item_guid = 0, uint32 item_count = 0); - void SendNewMail(); - void UpdateNextMailTimeAndUnreads(); - void AddNewMailDeliverTime(time_t deliver_time); - bool IsMailsLoaded() const { return m_mailsLoaded; } - - void RemoveMail(uint32 id); - - void AddMail(Mail* mail) { m_mail.push_front(mail);}// for call from WorldSession::SendMailTo - uint32 GetMailSize() { return m_mail.size();} - Mail* GetMail(uint32 id); - - PlayerMails::iterator GetMailBegin() { return m_mail.begin();} - PlayerMails::iterator GetMailEnd() { return m_mail.end();} - - /*********************************************************/ - /*** MAILED ITEMS SYSTEM ***/ - /*********************************************************/ - - uint8 unReadMails; - time_t m_nextMailDelivereTime; - - typedef std::unordered_map ItemMap; - - ItemMap mMitems; //template defined in objectmgr.cpp - - Item* GetMItem(uint32 id) - { - ItemMap::const_iterator itr = mMitems.find(id); - return itr != mMitems.end() ? itr->second : nullptr; - } - - void AddMItem(Item* it) - { - ASSERT(it); - //ASSERT deleted, because items can be added before loading - mMitems[it->GetGUIDLow()] = it; - } - - bool RemoveMItem(uint32 id) - { - return !!mMitems.erase(id); - } - - void PetSpellInitialize(); - void CharmSpellInitialize(); - void PossessSpellInitialize(); - void VehicleSpellInitialize(); - void SendRemoveControlBar(); - bool HasSpell(uint32 spell) const override; - bool HasActiveSpell(uint32 spell) const; // show in spellbook - TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell) const; - bool IsSpellFitByClassAndRace(uint32 spell_id) const; - bool IsNeedCastPassiveSpellAtLearn(SpellInfo const* spellInfo) const; - - void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask); - void SendInitialSpells(); - void SendLearnPacket(uint32 spellId, bool learn); - bool addSpell(uint32 spellId, uint8 addSpecMask, bool updateActive, bool temporary = false); - bool _addSpell(uint32 spellId, uint8 addSpecMask, bool temporary); - void learnSpell(uint32 spellId); - void removeSpell(uint32 spellId, uint8 removeSpecMask, bool onlyTemporary); - void resetSpells(); - void learnDefaultSpells(); - void learnQuestRewardedSpells(); - void learnQuestRewardedSpells(Quest const* quest); - void learnSpellHighRank(uint32 spellid); - void SetReputation(uint32 factionentry, uint32 value); - uint32 GetReputation(uint32 factionentry) const; - std::string const& GetGuildName(); - uint32 GetFreeTalentPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS1); } - void SetFreeTalentPoints(uint32 points); - bool resetTalents(bool noResetCost = false); - uint32 resetTalentsCost() const; - void InitTalentForLevel(); - void BuildPlayerTalentsInfoData(WorldPacket* data); - void BuildPetTalentsInfoData(WorldPacket* data); - void SendTalentsInfoData(bool pet); - void LearnTalent(uint32 talentId, uint32 talentRank); - void LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank); - - bool addTalent(uint32 spellId, uint8 addSpecMask, uint8 oldTalentRank); - void _removeTalent(PlayerTalentMap::iterator& itr, uint8 specMask); - void _removeTalent(uint32 spellId, uint8 specMask); - void _removeTalentAurasAndSpells(uint32 spellId); - void _addTalentAurasAndSpells(uint32 spellId); - bool HasTalent(uint32 spell_id, uint8 spec) const; - - uint32 CalculateTalentsPoints() const; - - // Dual Spec - void UpdateSpecCount(uint8 count); - uint8 GetActiveSpec() const { return m_activeSpec; } - uint8 GetActiveSpecMask() const { return (1< T ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell* spell = NULL, bool temporaryPet = false); - void RemoveSpellMods(Spell* spell); - void RestoreSpellMods(Spell* spell, uint32 ownerAuraId = 0, Aura* aura = nullptr); - void RestoreAllSpellMods(uint32 ownerAuraId = 0, Aura* aura = nullptr); - void DropModCharge(SpellModifier* mod, Spell* spell); - void SetSpellModTakingSpell(Spell* spell, bool apply); - - static uint32 const infinityCooldownDelay = 0x9A7EC800; // used for set "infinity cooldowns" for spells and check, MONTH*IN_MILLISECONDS - static uint32 const infinityCooldownDelayCheck = 0x4D3F6400; //MONTH*IN_MILLISECONDS/2; - virtual bool HasSpellCooldown(uint32 spell_id) const override - { - SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); - return itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS(); - } - virtual bool HasSpellItemCooldown(uint32 spell_id, uint32 itemid) const override - { - SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); - return itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS() && itr->second.itemid == itemid; - } - uint32 GetSpellCooldownDelay(uint32 spell_id) const - { - SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); - return uint32(itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS() ? itr->second.end - World::GetGameTimeMS() : 0); - } - void AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 itemId, Spell* spell = NULL, bool infinityCooldown = false); - void AddSpellCooldown(uint32 spell_id, uint32 itemid, uint32 end_time, bool needSendToClient = false, bool forceSendToSpectator = false) override; - void ModifySpellCooldown(uint32 spellId, int32 cooldown); - void SendCooldownEvent(SpellInfo const* spellInfo, uint32 itemId = 0, Spell* spell = NULL, bool setCooldown = true); - void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override; - void RemoveSpellCooldown(uint32 spell_id, bool update = false); - void SendClearCooldown(uint32 spell_id, Unit* target); - - GlobalCooldownMgr& GetGlobalCooldownMgr() { return m_GlobalCooldownMgr; } - - void RemoveCategoryCooldown(uint32 cat); - void RemoveArenaSpellCooldowns(bool removeActivePetCooldowns = false); - void RemoveAllSpellCooldown(); - void _LoadSpellCooldowns(PreparedQueryResult result); - void _SaveSpellCooldowns(SQLTransaction& trans, bool logout); - uint32 GetLastPotionId() { return m_lastPotionId; } - void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; } - void UpdatePotionCooldown(); - - void setResurrectRequestData(uint64 guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana) - { - m_resurrectGUID = guid; - m_resurrectMap = mapId; - m_resurrectX = X; - m_resurrectY = Y; - m_resurrectZ = Z; - m_resurrectHealth = health; - m_resurrectMana = mana; - } - void clearResurrectRequestData() { setResurrectRequestData(0, 0, 0.0f, 0.0f, 0.0f, 0, 0); } - bool isResurrectRequestedBy(uint64 guid) const { return m_resurrectGUID && m_resurrectGUID == guid; } - bool isResurrectRequested() const { return m_resurrectGUID != 0; } - void ResurectUsingRequestData(); - - uint8 getCinematic() const - { - return m_cinematic; - } - void setCinematic(uint8 cine) - { - m_cinematic = cine; - } - - ActionButton* addActionButton(uint8 button, uint32 action, uint8 type); - void removeActionButton(uint8 button); - ActionButton const* GetActionButton(uint8 button); - void SendInitialActionButtons() const { SendActionButtons(1); } - void SendActionButtons(uint32 state) const; - bool IsActionButtonDataValid(uint8 button, uint32 action, uint8 type); - - PvPInfo pvpInfo; - void UpdatePvPState(bool onlyFFA = false); - void SetPvP(bool state) - { - Unit::SetPvP(state); - if (!m_Controlled.empty()) - for (ControlSet::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) - (*itr)->SetPvP(state); - } - void UpdatePvP(bool state, bool _override=false); - void UpdateZone(uint32 newZone, uint32 newArea); - void UpdateArea(uint32 newArea); - - uint32 GetZoneId(bool forceRecalc = false) const override; - uint32 GetAreaId(bool forceRecalc = false) const override; - void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc = false) const override; - - void UpdateZoneDependentAuras(uint32 zone_id); // zones - void UpdateAreaDependentAuras(uint32 area_id); // subzones - - void UpdateAfkReport(time_t currTime); - void UpdatePvPFlag(time_t currTime); - void UpdateContestedPvP(uint32 currTime); - void SetContestedPvPTimer(uint32 newTime) {m_contestedPvPTimer = newTime;} - void ResetContestedPvP() - { - ClearUnitState(UNIT_STATE_ATTACK_PLAYER); - RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP); - m_contestedPvPTimer = 0; - } - - /** todo: -maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler.. **/ - DuelInfo* duel; - void UpdateDuelFlag(time_t currTime); - void CheckDuelDistance(time_t currTime); - void DuelComplete(DuelCompleteType type); - void SendDuelCountdown(uint32 counter); - - bool IsGroupVisibleFor(Player const* p) const; - bool IsInSameGroupWith(Player const* p) const; - bool IsInSameRaidWith(Player const* p) const { return p == this || (GetGroup() != NULL && GetGroup() == p->GetGroup()); } - void UninviteFromGroup(); - static void RemoveFromGroup(Group* group, uint64 guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, uint64 kicker = 0, const char* reason = nullptr); - void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(), GetGUID(), method); } - void SendUpdateToOutOfRangeGroupMembers(); - - void SetInGuild(uint32 GuildId) - { - SetUInt32Value(PLAYER_GUILDID, GuildId); - // xinef: update global storage - sWorld->UpdateGlobalPlayerGuild(GetGUIDLow(), GuildId); - } - void SetRank(uint8 rankId) { SetUInt32Value(PLAYER_GUILDRANK, rankId); } - uint8 GetRank() const { return uint8(GetUInt32Value(PLAYER_GUILDRANK)); } - void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; } - uint32 GetGuildId() const { return GetUInt32Value(PLAYER_GUILDID); } - Guild* GetGuild() const; - static uint32 GetGuildIdFromStorage(uint32 guid); - static uint32 GetGroupIdFromStorage(uint32 guid); - static uint32 GetArenaTeamIdFromStorage(uint32 guid, uint8 slot); - uint32 GetGuildIdInvited() { return m_GuildIdInvited; } - static void RemovePetitionsAndSigns(uint64 guid, uint32 type); - - // Arena Team - void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type) - { - SetArenaTeamInfoField(slot, ARENA_TEAM_ID, ArenaTeamId); - SetArenaTeamInfoField(slot, ARENA_TEAM_TYPE, type); - } - void SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value) - { - SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + type, value); - } - static uint32 GetArenaTeamIdFromDB(uint64 guid, uint8 slot); - static void LeaveAllArenaTeams(uint64 guid); - uint32 GetArenaTeamId(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID); } - uint32 GetArenaPersonalRating(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING); } - void SetArenaTeamIdInvited(uint32 ArenaTeamId) { m_ArenaTeamIdInvited = ArenaTeamId; } - uint32 GetArenaTeamIdInvited() { return m_ArenaTeamIdInvited; } - - Difficulty GetDifficulty(bool isRaid) const { return isRaid ? m_raidDifficulty : m_dungeonDifficulty; } - Difficulty GetDungeonDifficulty() const { return m_dungeonDifficulty; } - Difficulty GetRaidDifficulty() const { return m_raidDifficulty; } - Difficulty GetStoredRaidDifficulty() const { return m_raidMapDifficulty; } // only for use in difficulty packet after exiting to raid map - void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; } - void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; } - void StoreRaidMapDifficulty() { m_raidMapDifficulty = GetMap()->GetDifficulty(); } - - bool UpdateSkill(uint32 skill_id, uint32 step); - bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step); - - bool UpdateCraftSkill(uint32 spellid); - bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1); - bool UpdateFishingSkill(); - - uint32 GetBaseDefenseSkillValue() const { return GetBaseSkillValue(SKILL_DEFENSE); } - uint32 GetBaseWeaponSkillValue(WeaponAttackType attType) const; - - uint32 GetSpellByProto(ItemTemplate* proto); - - float GetHealthBonusFromStamina(); - float GetManaBonusFromIntellect(); - - bool UpdateStats(Stats stat) override; - bool UpdateAllStats() override; - void ApplySpellPenetrationBonus(int32 amount, bool apply); - void UpdateResistances(uint32 school) override; - void UpdateArmor() override; - void UpdateMaxHealth() override; - void UpdateMaxPower(Powers power) override; - void ApplyFeralAPBonus(int32 amount, bool apply); - void UpdateAttackPowerAndDamage(bool ranged = false) override; - void UpdateShieldBlockValue(); - void ApplySpellPowerBonus(int32 amount, bool apply); - void UpdateSpellDamageAndHealingBonus(); - void ApplyRatingMod(CombatRating cr, int32 value, bool apply); - void UpdateRating(CombatRating cr); - void UpdateAllRatings(); - - void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) override; - - void UpdateDefenseBonusesMod(); - inline void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);} - float GetMeleeCritFromAgility(); - void GetDodgeFromAgility(float &diminishing, float &nondiminishing); - float GetMissPercentageFromDefence() const; - float GetSpellCritFromIntellect(); - float OCTRegenHPPerSpirit(); - float OCTRegenMPPerSpirit(); - float GetRatingMultiplier(CombatRating cr) const; - float GetRatingBonusValue(CombatRating cr) const; - uint32 GetBaseSpellPowerBonus() { return m_baseSpellPower; } - int32 GetSpellPenetrationItemMod() const { return m_spellPenetrationItemMod; } - - float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const; - void UpdateBlockPercentage(); - void UpdateCritPercentage(WeaponAttackType attType); - void UpdateAllCritPercentages(); - void UpdateParryPercentage(); - void UpdateDodgePercentage(); - void UpdateMeleeHitChances(); - void UpdateRangedHitChances(); - void UpdateSpellHitChances(); - - void UpdateAllSpellCritChances(); - void UpdateSpellCritChance(uint32 school); - void UpdateArmorPenetration(int32 amount); - void UpdateExpertise(WeaponAttackType attType); - void ApplyManaRegenBonus(int32 amount, bool apply); - void ApplyHealthRegenBonus(int32 amount, bool apply); - void UpdateManaRegen(); - void UpdateRuneRegen(RuneType rune); - - uint64 GetLootGUID() const { return m_lootGuid; } - void SetLootGUID(uint64 guid) { m_lootGuid = guid; } - - void RemovedInsignia(Player* looterPlr); - - WorldSession* GetSession() const { return m_session; } - void SetSession(WorldSession* sess) { m_session = sess; } - - void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const override; - void DestroyForPlayer(Player* target, bool onDeath = false) const override; - void SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend = false, float group_rate=1.0f); - - // notifiers - void SendAttackSwingCantAttack(); - void SendAttackSwingCancelAttack(); - void SendAttackSwingDeadTarget(); - void SendAttackSwingNotInRange(); - void SendAttackSwingBadFacingAttack(); - void SendAutoRepeatCancel(Unit* target); - void SendExplorationExperience(uint32 Area, uint32 Experience); - - void SendDungeonDifficulty(bool IsInGroup); - void SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty = -1); - static void ResetInstances(uint64 guid, uint8 method, bool isRaid); - void SendResetInstanceSuccess(uint32 MapId); - void SendResetInstanceFailed(uint32 reason, uint32 MapId); - void SendResetFailedNotify(uint32 mapid); - - virtual bool UpdatePosition(float x, float y, float z, float orientation, bool teleport = false) override; - bool UpdatePosition(const Position &pos, bool teleport = false) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } - void UpdateUnderwaterState(Map* m, float x, float y, float z) override; - - void SendMessageToSet(WorldPacket* data, bool self) override { SendMessageToSetInRange(data, GetVisibilityRange(), self, true); } // pussywizard! - void SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool includeMargin = false, Player const* skipped_rcvr = nullptr) override; // pussywizard! - void SendMessageToSetInRange_OwnTeam(WorldPacket* data, float dist, bool self); // pussywizard! param includeMargin not needed here - void SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr) override { SendMessageToSetInRange(data, GetVisibilityRange(), skipped_rcvr != this, true, skipped_rcvr); } // pussywizard! - - void SendTeleportAckPacket(); - - Corpse* GetCorpse() const; - void SpawnCorpseBones(); - void CreateCorpse(); - void KillPlayer(); - uint32 GetResurrectionSpellId(); - void ResurrectPlayer(float restore_percent, bool applySickness = false); - void BuildPlayerRepop(); - void RepopAtGraveyard(); - - void DurabilityLossAll(double percent, bool inventory); - void DurabilityLoss(Item* item, double percent); - void DurabilityPointsLossAll(int32 points, bool inventory); - void DurabilityPointsLoss(Item* item, int32 points); - void DurabilityPointLossForEquipSlot(EquipmentSlots slot); - uint32 DurabilityRepairAll(bool cost, float discountMod, bool guildBank); - uint32 DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank); - - void UpdateMirrorTimers(); - void StopMirrorTimers() - { - StopMirrorTimer(FATIGUE_TIMER); - StopMirrorTimer(BREATH_TIMER); - StopMirrorTimer(FIRE_TIMER); - } - bool IsMirrorTimerActive(MirrorTimerType type) { return m_MirrorTimer[type] == getMaxTimer(type); } - - void SetMovement(PlayerMovementType pType); - - bool CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone); - - void JoinedChannel(Channel* c); - void LeftChannel(Channel* c); - void CleanupChannels(); - void ClearChannelWatch(); - void UpdateLocalChannels(uint32 newZone); - - void UpdateDefense(); - void UpdateWeaponSkill (WeaponAttackType attType); - void UpdateCombatSkills(Unit* victim, WeaponAttackType attType, bool defence); - - void SetSkill(uint16 id, uint16 step, uint16 currVal, uint16 maxVal); - uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus + temp bonus - uint16 GetPureMaxSkillValue(uint32 skill) const; // max - uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus - uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus - uint16 GetPureSkillValue(uint32 skill) const; // skill value - int16 GetSkillPermBonusValue(uint32 skill) const; - int16 GetSkillTempBonusValue(uint32 skill) const; - uint16 GetSkillStep(uint16 skill) const; // 0...6 - bool HasSkill(uint32 skill) const; - void learnSkillRewardedSpells(uint32 id, uint32 value); - - WorldLocation& GetTeleportDest() { return teleportStore_dest; } - bool IsBeingTeleported() const { return mSemaphoreTeleport_Near != 0 || mSemaphoreTeleport_Far != 0; } - bool IsBeingTeleportedNear() const { return mSemaphoreTeleport_Near != 0; } - bool IsBeingTeleportedFar() const { return mSemaphoreTeleport_Far != 0; } - void SetSemaphoreTeleportNear(time_t tm) { mSemaphoreTeleport_Near = tm; } - void SetSemaphoreTeleportFar(time_t tm) { mSemaphoreTeleport_Far = tm; } - time_t GetSemaphoreTeleportNear() const { return mSemaphoreTeleport_Near; } - time_t GetSemaphoreTeleportFar() const { return mSemaphoreTeleport_Far; } - void ProcessDelayedOperations(); - uint32 GetDelayedOperations() const { return m_DelayedOperations; } - void ScheduleDelayedOperation(uint32 operation) - { - if (operation < DELAYED_END) - m_DelayedOperations |= operation; - } - - void CheckAreaExploreAndOutdoor(void); - - static TeamId TeamIdForRace(uint8 race); - TeamId GetTeamId(bool original = false) const { return original ? TeamIdForRace(getRace(true)) : m_team; }; - void setFactionForRace(uint8 race); - void setTeamId(TeamId teamid) { m_team = teamid; }; - - void InitDisplayIds(); - - bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const; - bool IsAtRecruitAFriendDistance(WorldObject const* pOther) const; - void RewardPlayerAndGroupAtKill(Unit* victim, bool isBattleGround); - void RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource); - bool isHonorOrXPTarget(Unit* victim) const; - - bool GetsRecruitAFriendBonus(bool forXP); - uint8 GetGrantableLevels() { return m_grantableLevels; } - void SetGrantableLevels(uint8 val) { m_grantableLevels = val; } - - ReputationMgr& GetReputationMgr() { return *m_reputationMgr; } - ReputationMgr const& GetReputationMgr() const { return *m_reputationMgr; } - ReputationRank GetReputationRank(uint32 faction_id) const; - void RewardReputation(Unit* victim, float rate); - void RewardReputation(Quest const* quest); - - int32 CalculateReputationGain(ReputationSource source, uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool noQuestBonus = false); - - void UpdateSkillsForLevel(); - void UpdateSkillsToMaxSkillsForLevel(); // for .levelup - void ModifySkillBonus(uint32 skillid, int32 val, bool talent); - - /*********************************************************/ - /*** PVP SYSTEM ***/ - /*********************************************************/ - void UpdateHonorFields(); - bool RewardHonor(Unit* victim, uint32 groupsize, int32 honor = -1, bool awardXP = true); - uint32 GetHonorPoints() const { return GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY); } - uint32 GetArenaPoints() const { return GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY); } - void ModifyHonorPoints(int32 value, SQLTransaction* trans = nullptr); //! If trans is specified, honor save query will be added to trans - void ModifyArenaPoints(int32 value, SQLTransaction* trans = nullptr); //! If trans is specified, arena point save query will be added to trans - uint32 GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) const; - void SetHonorPoints(uint32 value); - void SetArenaPoints(uint32 value); - - // duel health and mana reset methods - void SaveHealthBeforeDuel() { healthBeforeDuel = GetHealth(); } - void SaveManaBeforeDuel() { manaBeforeDuel = GetPower(POWER_MANA); } - void RestoreHealthAfterDuel() { SetHealth(healthBeforeDuel); } - void RestoreManaAfterDuel() { SetPower(POWER_MANA, manaBeforeDuel); } - - //End of PvP System - - inline SpellCooldowns GetSpellCooldowns() const { return m_spellCooldowns; } - - void SetDrunkValue(uint8 newDrunkValue, uint32 itemId = 0); - uint8 GetDrunkValue() const { return GetByteValue(PLAYER_BYTES_3, 1); } - static DrunkenState GetDrunkenstateByValue(uint8 value); - - uint32 GetDeathTimer() const { return m_deathTimer; } - uint32 GetCorpseReclaimDelay(bool pvp) const; - void UpdateCorpseReclaimDelay(); - int32 CalculateCorpseReclaimDelay(bool load = false); - void SendCorpseReclaimDelay(uint32 delay); - - uint32 GetShieldBlockValue() const override; // overwrite Unit version (virtual) - bool CanParry() const { return m_canParry; } - void SetCanParry(bool value); - bool CanBlock() const { return m_canBlock; } - void SetCanBlock(bool value); - bool CanTitanGrip() const { return m_canTitanGrip; } - void SetCanTitanGrip(bool value); - bool CanTameExoticPets() const { return IsGameMaster() || HasAuraType(SPELL_AURA_ALLOW_TAME_PET_TYPE); } - - void SetRegularAttackTime(); - void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value) { m_auraBaseMod[modGroup][modType] = value; } - void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply); - float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const; - float GetTotalBaseModValue(BaseModGroup modGroup) const; - float GetTotalPercentageModValue(BaseModGroup modGroup) const { return m_auraBaseMod[modGroup][FLAT_MOD] + m_auraBaseMod[modGroup][PCT_MOD]; } - void _ApplyAllStatBonuses(); - void _RemoveAllStatBonuses(); - - void ResetAllPowers(); - - void _ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply); - void _ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply); - void _ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply); - - void _ApplyItemMods(Item* item, uint8 slot, bool apply); - void _RemoveAllItemMods(); - void _ApplyAllItemMods(); - void _ApplyAllLevelScaleItemMods(bool apply); - void _ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply, bool only_level_scale = false); - void _ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, ScalingStatValuesEntry const* ssv, bool apply); - void _ApplyAmmoBonuses(); - bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot); - void ToggleMetaGemsActive(uint8 exceptslot, bool apply); - void CorrectMetaGemEnchants(uint8 slot, bool apply); - void InitDataForForm(bool reapplyMods = false); - - void ApplyItemEquipSpell(Item* item, bool apply, bool form_change = false); - void ApplyEquipSpell(SpellInfo const* spellInfo, Item* item, bool apply, bool form_change = false); - void UpdateEquipSpellsAtFormChange(); - void CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx); - void CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 cast_count, uint32 glyphIndex); - void CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item* item, ItemTemplate const* proto); - - void SendEquipmentSetList(); - void SetEquipmentSet(uint32 index, EquipmentSet eqset); - void DeleteEquipmentSet(uint64 setGuid); - - void SendInitWorldStates(uint32 zone, uint32 area); - void SendUpdateWorldState(uint32 Field, uint32 Value); - void SendDirectMessage(WorldPacket* data); - void SendBGWeekendWorldStates(); - void SendBattlefieldWorldStates(); - - void GetAurasForTarget(Unit* target); - - PlayerMenu* PlayerTalkClass; - std::vector ItemSetEff; - - void SendLoot(uint64 guid, LootType loot_type); - void SendLootError(uint64 guid, LootError error); - void SendLootRelease(uint64 guid); - void SendNotifyLootItemRemoved(uint8 lootSlot); - void SendNotifyLootMoneyRemoved(); - - /*********************************************************/ - /*** BATTLEGROUND SYSTEM ***/ - /*********************************************************/ - - bool InBattleground() const { return m_bgData.bgInstanceID != 0; } - bool InArena() const; - uint32 GetBattlegroundId() const { return m_bgData.bgInstanceID; } - BattlegroundTypeId GetBattlegroundTypeId() const { return m_bgData.bgTypeID; } - uint32 GetCurrentBattlegroundQueueSlot() const { return m_bgData.bgQueueSlot; } - bool IsInvitedForBattlegroundInstance() const { return m_bgData.isInvited; } - bool IsCurrentBattlegroundRandom() const { return m_bgData.bgIsRandom; } - BGData& GetBGData() { return m_bgData; } - void SetBGData(BGData& bgdata) { m_bgData = bgdata; } - Battleground* GetBattleground(bool create = false) const; - - bool InBattlegroundQueue() const - { - for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) - if (m_bgBattlegroundQueueID[i] != BATTLEGROUND_QUEUE_NONE) - return true; - return false; - } - - BattlegroundQueueTypeId GetBattlegroundQueueTypeId(uint32 index) const { return m_bgBattlegroundQueueID[index]; } - - uint32 GetBattlegroundQueueIndex(BattlegroundQueueTypeId bgQueueTypeId) const - { - for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) - if (m_bgBattlegroundQueueID[i] == bgQueueTypeId) - return i; - return PLAYER_MAX_BATTLEGROUND_QUEUES; - } - - bool InBattlegroundQueueForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId) const - { - return GetBattlegroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES; - } - - void SetBattlegroundId(uint32 id, BattlegroundTypeId bgTypeId, uint32 queueSlot, bool invited, bool isRandom, TeamId teamId); - - uint32 AddBattlegroundQueueId(BattlegroundQueueTypeId val) - { - for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) - if (m_bgBattlegroundQueueID[i] == BATTLEGROUND_QUEUE_NONE || m_bgBattlegroundQueueID[i] == val) - { - m_bgBattlegroundQueueID[i] = val; - return i; - } - return PLAYER_MAX_BATTLEGROUND_QUEUES; - } - - bool HasFreeBattlegroundQueueId() - { - for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) - if (m_bgBattlegroundQueueID[i] == BATTLEGROUND_QUEUE_NONE) - return true; - return false; - } - - void RemoveBattlegroundQueueId(BattlegroundQueueTypeId val) - { - for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) - if (m_bgBattlegroundQueueID[i] == val) - { - m_bgBattlegroundQueueID[i] = BATTLEGROUND_QUEUE_NONE; - return; - } - } - - TeamId GetBgTeamId() const { return m_bgData.bgTeamId != TEAM_NEUTRAL ? m_bgData.bgTeamId : GetTeamId(); } - - void LeaveBattleground(Battleground* bg = nullptr); - bool CanJoinToBattleground() const; - bool CanReportAfkDueToLimit(); - void ReportedAfkBy(Player* reporter); - void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); } - - bool GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const; - bool CanUseBattlegroundObject(GameObject* gameobject) const; - bool isTotalImmune() const; - bool CanCaptureTowerPoint() const; - - bool GetRandomWinner() { return m_IsBGRandomWinner; } - void SetRandomWinner(bool isWinner); - - /*********************************************************/ - /*** OUTDOOR PVP SYSTEM ***/ - /*********************************************************/ - - OutdoorPvP* GetOutdoorPvP() const; - // returns true if the player is in active state for outdoor pvp objective capturing, false otherwise - bool IsOutdoorPvPActive(); - - /*********************************************************/ - /*** ENVIROMENTAL SYSTEM ***/ - /*********************************************************/ - - bool IsImmuneToEnvironmentalDamage(); - uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage); - - /*********************************************************/ - /*** FLOOD FILTER SYSTEM ***/ - /*********************************************************/ - - void UpdateSpeakTime(uint32 specialMessageLimit = 0); - bool CanSpeak() const; - void ChangeSpeakTime(int utime); - - /*********************************************************/ - /*** VARIOUS SYSTEMS ***/ - /*********************************************************/ - void UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode); - SafeUnitPointer m_mover; - WorldObject* m_seer; - std::set m_isInSharedVisionOf; - void SetFallInformation(uint32 time, float z) - { - m_lastFallTime = time; - m_lastFallZ = z; - } - void HandleFall(MovementInfo const& movementInfo); - - bool canFlyInZone(uint32 mapid, uint32 zone) const; - - void SetClientControl(Unit* target, bool allowMove, bool packetOnly = false); - - void SetMover(Unit* target); - - void SetSeer(WorldObject* target) { m_seer = target; } - void SetViewpoint(WorldObject* target, bool apply); - WorldObject* GetViewpoint() const; - void StopCastingCharm(); - void StopCastingBindSight(); - - uint32 GetSaveTimer() const { return m_nextSave; } - void SetSaveTimer(uint32 timer) { m_nextSave = timer; } - - // Recall position - uint32 m_recallMap; - float m_recallX; - float m_recallY; - float m_recallZ; - float m_recallO; - void SaveRecallPosition(); - - void SetHomebind(WorldLocation const& loc, uint32 areaId); - - // Homebind coordinates - uint32 m_homebindMapId; - uint16 m_homebindAreaId; - float m_homebindX; - float m_homebindY; - float m_homebindZ; - - WorldLocation GetStartPosition() const; - - WorldLocation const& GetEntryPoint() const { return m_entryPointData.joinPos; } - void SetEntryPoint(); - - // currently visible objects at player client - typedef std::unordered_set ClientGUIDs; - ClientGUIDs m_clientGUIDs; - std::vector m_newVisible; // pussywizard - - bool HaveAtClient(WorldObject const* u) const { return u == this || m_clientGUIDs.find(u->GetGUID()) != m_clientGUIDs.end(); } - bool HaveAtClient(uint64 guid) const { return guid == GetGUID() || m_clientGUIDs.find(guid) != m_clientGUIDs.end(); } - - bool IsNeverVisible() const override; - - bool IsVisibleGloballyFor(Player const* player) const; - - void GetInitialVisiblePackets(Unit* target); - void UpdateObjectVisibility(bool forced = true, bool fromUpdate = false) override; - void UpdateVisibilityForPlayer(bool mapChange = false); - void UpdateVisibilityOf(WorldObject* target); - void UpdateTriggerVisibility(); - - template - void UpdateVisibilityOf(T* target, UpdateData& data, std::vector& visibleNow); - - uint8 m_forced_speed_changes[MAX_MOVE_TYPE]; - - bool HasAtLoginFlag(AtLoginFlags f) const { return m_atLoginFlags & f; } - void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; } - void RemoveAtLoginFlag(AtLoginFlags flags, bool persist = false); - - bool isUsingLfg(); - bool inRandomLfgDungeon(); - - typedef std::set DFQuestsDoneList; - DFQuestsDoneList m_DFQuests; - - // Temporarily removed pet cache - uint32 GetTemporaryUnsummonedPetNumber() const { return m_temporaryUnsummonedPetNumber; } - void SetTemporaryUnsummonedPetNumber(uint32 petnumber) { m_temporaryUnsummonedPetNumber = petnumber; } - void UnsummonPetTemporaryIfAny(); - void ResummonPetTemporaryUnSummonedIfAny(); - bool IsPetNeedBeTemporaryUnsummoned() const { return GetSession()->PlayerLogout() || !IsInWorld() || !IsAlive() || IsMounted()/*+in flight*/ || GetVehicle() || IsBeingTeleported(); } - bool CanResummonPet(uint32 spellid); - - void SendCinematicStart(uint32 CinematicSequenceId); - void SendMovieStart(uint32 MovieId); - - /*********************************************************/ - /*** INSTANCE SYSTEM ***/ - /*********************************************************/ - - void UpdateHomebindTime(uint32 time); - - uint32 m_HomebindTimer; - bool m_InstanceValid; - void BindToInstance(); - void SetPendingBind(uint32 instanceId, uint32 bindTimer) { _pendingBindId = instanceId; _pendingBindTimer = bindTimer; } - bool HasPendingBind() const { return _pendingBindId > 0; } - uint32 GetPendingBind() const { return _pendingBindId; } - void SendRaidInfo(); - void SendSavedInstances(); - bool Satisfy(AccessRequirement const* ar, uint32 target_map, bool report = false); - bool CheckInstanceLoginValid(); - bool CheckInstanceCount(uint32 instanceId) const; - - void AddInstanceEnterTime(uint32 instanceId, time_t enterTime) - { - if (_instanceResetTimes.find(instanceId) == _instanceResetTimes.end()) - _instanceResetTimes.insert(InstanceTimeMap::value_type(instanceId, enterTime + HOUR)); - } - - // last used pet number (for BG's) - uint32 GetLastPetNumber() const { return m_lastpetnumber; } - void SetLastPetNumber(uint32 petnumber) { m_lastpetnumber = petnumber; } - uint32 GetLastPetSpell() const { return m_oldpetspell; } - void SetLastPetSpell(uint32 petspell) { m_oldpetspell = petspell; } - - /*********************************************************/ - /*** GROUP SYSTEM ***/ - /*********************************************************/ - - Group* GetGroupInvite() { return m_groupInvite; } - void SetGroupInvite(Group* group) { m_groupInvite = group; } - Group* GetGroup() { return m_group.getTarget(); } - const Group* GetGroup() const { return (const Group*)m_group.getTarget(); } - GroupReference& GetGroupRef() { return m_group; } - void SetGroup(Group* group, int8 subgroup = -1); - uint8 GetSubGroup() const { return m_group.getSubGroup(); } - uint32 GetGroupUpdateFlag() const { return m_groupUpdateMask; } - void SetGroupUpdateFlag(uint32 flag) { m_groupUpdateMask |= flag; } - uint64 GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; } - void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); } - Player* GetNextRandomRaidMember(float radius); - PartyResult CanUninviteFromGroup() const; - - // Battleground Group System - void SetBattlegroundOrBattlefieldRaid(Group *group, int8 subgroup = -1); - void RemoveFromBattlegroundOrBattlefieldRaid(); - Group* GetOriginalGroup() { return m_originalGroup.getTarget(); } - GroupReference& GetOriginalGroupRef() { return m_originalGroup; } - uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); } - void SetOriginalGroup(Group* group, int8 subgroup = -1); - - void SetPassOnGroupLoot(bool bPassOnGroupLoot) { m_bPassOnGroupLoot = bPassOnGroupLoot; } - bool GetPassOnGroupLoot() const { return m_bPassOnGroupLoot; } - - MapReference &GetMapRef() { return m_mapRef; } - - // Set map to player and add reference - void SetMap(Map* map) override; - void ResetMap() override; - - bool isAllowedToLoot(const Creature* creature); - - DeclinedName const* GetDeclinedNames() const { return m_declinedname; } - uint8 GetRunesState() const { return m_runes->runeState; } - RuneType GetBaseRune(uint8 index) const { return RuneType(m_runes->runes[index].BaseRune); } - RuneType GetCurrentRune(uint8 index) const { return RuneType(m_runes->runes[index].CurrentRune); } - uint32 GetRuneCooldown(uint8 index) const { return m_runes->runes[index].Cooldown; } - uint32 GetGracePeriod(uint8 index) const { return m_runes->runes[index].GracePeriod; } - uint32 GetRuneBaseCooldown(uint8 index, bool skipGrace); - bool IsBaseRuneSlotsOnCooldown(RuneType runeType) const; - RuneType GetLastUsedRune() { return m_runes->lastUsedRune; } - void SetLastUsedRune(RuneType type) { m_runes->lastUsedRune = type; } - void SetBaseRune(uint8 index, RuneType baseRune) { m_runes->runes[index].BaseRune = baseRune; } - void SetCurrentRune(uint8 index, RuneType currentRune) { m_runes->runes[index].CurrentRune = currentRune; } - void SetRuneCooldown(uint8 index, uint32 cooldown) { m_runes->runes[index].Cooldown = cooldown; m_runes->SetRuneState(index, (cooldown == 0)); } - void SetGracePeriod(uint8 index, uint32 period) { m_runes->runes[index].GracePeriod = period; } - void SetRuneConvertAura(uint8 index, AuraEffect const* aura) { m_runes->runes[index].ConvertAura = aura; } - void AddRuneByAuraEffect(uint8 index, RuneType newType, AuraEffect const* aura) { SetRuneConvertAura(index, aura); ConvertRune(index, newType); } - void RemoveRunesByAuraEffect(AuraEffect const* aura); - void RestoreBaseRune(uint8 index); - void ConvertRune(uint8 index, RuneType newType); - void ResyncRunes(uint8 count); - void AddRunePower(uint8 index); - void InitRunes(); - - void SendRespondInspectAchievements(Player* player) const; - bool HasAchieved(uint32 achievementId) const; - void ResetAchievements(); - void CheckAllAchievementCriteria(); - void ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete = false); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); - void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost = 0); - void RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); - void CompletedAchievement(AchievementEntry const* entry); - - bool HasTitle(uint32 bitIndex) const; - bool HasTitle(CharTitlesEntry const* title) const { return HasTitle(title->bit_index); } - void SetTitle(CharTitlesEntry const* title, bool lost = false); - - //bool isActiveObject() const { return true; } - bool CanSeeSpellClickOn(Creature const* creature) const; - - uint32 GetChampioningFaction() const { return m_ChampioningFaction; } - void SetChampioningFaction(uint32 faction) { m_ChampioningFaction = faction; } - Spell* m_spellModTakingSpell; - - float GetAverageItemLevel(); - float GetAverageItemLevelForDF(); - bool isDebugAreaTriggers; - - void ClearWhisperWhiteList() { WhisperList.clear(); } - void AddWhisperWhiteList(uint64 guid) { WhisperList.push_back(guid); } - bool IsInWhisperWhiteList(uint64 guid); - - bool SetDisableGravity(bool disable, bool packetOnly /* = false */) override; - bool SetCanFly(bool apply, bool packetOnly = false) override; - bool SetWaterWalking(bool apply, bool packetOnly = false) override; - bool SetFeatherFall(bool apply, bool packetOnly = false) override; - bool SetHover(bool enable, bool packetOnly = false) override; - - bool CanFly() const override { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_CAN_FLY); } - - //! Return collision height sent to client - float GetCollisionHeight(bool mounted) - { - if (mounted) + return PLAYER_MAX_BATTLEGROUND_QUEUES; + } + + bool HasFreeBattlegroundQueueId() + { + for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) + if (m_bgBattlegroundQueueID[i] == BATTLEGROUND_QUEUE_NONE) + return true; + return false; + } + + void RemoveBattlegroundQueueId(BattlegroundQueueTypeId val) + { + for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) + if (m_bgBattlegroundQueueID[i] == val) { - CreatureDisplayInfoEntry const* mountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID)); - if (!mountDisplayInfo) - return GetCollisionHeight(false); - - CreatureModelDataEntry const* mountModelData = sCreatureModelDataStore.LookupEntry(mountDisplayInfo->ModelId); - if (!mountModelData) - return GetCollisionHeight(false); - - CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId()); - ASSERT(displayInfo); - CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId); - ASSERT(modelData); - - float scaleMod = GetFloatValue(OBJECT_FIELD_SCALE_X); // 99% sure about this - - return scaleMod * mountModelData->MountHeight + modelData->CollisionHeight * 0.5f; + m_bgBattlegroundQueueID[i] = BATTLEGROUND_QUEUE_NONE; + return; } - else - { - //! Dismounting case - use basic default model data - CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId()); - ASSERT(displayInfo); - CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId); - ASSERT(modelData); + } - return modelData->CollisionHeight; - } + TeamId GetBgTeamId() const { return m_bgData.bgTeamId != TEAM_NEUTRAL ? m_bgData.bgTeamId : GetTeamId(); } + + void LeaveBattleground(Battleground* bg = nullptr); + bool CanJoinToBattleground() const; + bool CanReportAfkDueToLimit(); + void ReportedAfkBy(Player* reporter); + void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); } + + bool GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const; + bool CanUseBattlegroundObject(GameObject* gameobject) const; + bool isTotalImmune() const; + bool CanCaptureTowerPoint() const; + + bool GetRandomWinner() { return m_IsBGRandomWinner; } + void SetRandomWinner(bool isWinner); + + /*********************************************************/ + /*** OUTDOOR PVP SYSTEM ***/ + /*********************************************************/ + + OutdoorPvP* GetOutdoorPvP() const; + // returns true if the player is in active state for outdoor pvp objective capturing, false otherwise + bool IsOutdoorPvPActive(); + + /*********************************************************/ + /*** ENVIROMENTAL SYSTEM ***/ + /*********************************************************/ + + bool IsImmuneToEnvironmentalDamage(); + uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage); + + /*********************************************************/ + /*** FLOOD FILTER SYSTEM ***/ + /*********************************************************/ + + void UpdateSpeakTime(uint32 specialMessageLimit = 0); + bool CanSpeak() const; + void ChangeSpeakTime(int utime); + + /*********************************************************/ + /*** VARIOUS SYSTEMS ***/ + /*********************************************************/ + void UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode); + SafeUnitPointer m_mover; + WorldObject* m_seer; + std::set m_isInSharedVisionOf; + void SetFallInformation(uint32 time, float z) + { + m_lastFallTime = time; + m_lastFallZ = z; + } + void HandleFall(MovementInfo const& movementInfo); + + bool canFlyInZone(uint32 mapid, uint32 zone) const; + + void SetClientControl(Unit* target, bool allowMove, bool packetOnly = false); + + void SetMover(Unit* target); + + void SetSeer(WorldObject* target) { m_seer = target; } + void SetViewpoint(WorldObject* target, bool apply); + WorldObject* GetViewpoint() const; + void StopCastingCharm(); + void StopCastingBindSight(); + + uint32 GetSaveTimer() const { return m_nextSave; } + void SetSaveTimer(uint32 timer) { m_nextSave = timer; } + + // Recall position + uint32 m_recallMap; + float m_recallX; + float m_recallY; + float m_recallZ; + float m_recallO; + void SaveRecallPosition(); + + void SetHomebind(WorldLocation const& loc, uint32 areaId); + + // Homebind coordinates + uint32 m_homebindMapId; + uint16 m_homebindAreaId; + float m_homebindX; + float m_homebindY; + float m_homebindZ; + + WorldLocation GetStartPosition() const; + + WorldLocation const& GetEntryPoint() const { return m_entryPointData.joinPos; } + void SetEntryPoint(); + + // currently visible objects at player client + typedef std::unordered_set ClientGUIDs; + ClientGUIDs m_clientGUIDs; + std::vector m_newVisible; // pussywizard + + bool HaveAtClient(WorldObject const* u) const { return u == this || m_clientGUIDs.find(u->GetGUID()) != m_clientGUIDs.end(); } + bool HaveAtClient(uint64 guid) const { return guid == GetGUID() || m_clientGUIDs.find(guid) != m_clientGUIDs.end(); } + + bool IsNeverVisible() const override; + + bool IsVisibleGloballyFor(Player const* player) const; + + void GetInitialVisiblePackets(Unit* target); + void UpdateObjectVisibility(bool forced = true, bool fromUpdate = false) override; + void UpdateVisibilityForPlayer(bool mapChange = false); + void UpdateVisibilityOf(WorldObject* target); + void UpdateTriggerVisibility(); + + template + void UpdateVisibilityOf(T* target, UpdateData& data, std::vector& visibleNow); + + uint8 m_forced_speed_changes[MAX_MOVE_TYPE]; + + bool HasAtLoginFlag(AtLoginFlags f) const { return m_atLoginFlags & f; } + void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; } + void RemoveAtLoginFlag(AtLoginFlags flags, bool persist = false); + + bool isUsingLfg(); + bool inRandomLfgDungeon(); + + typedef std::set DFQuestsDoneList; + DFQuestsDoneList m_DFQuests; + + // Temporarily removed pet cache + uint32 GetTemporaryUnsummonedPetNumber() const { return m_temporaryUnsummonedPetNumber; } + void SetTemporaryUnsummonedPetNumber(uint32 petnumber) { m_temporaryUnsummonedPetNumber = petnumber; } + void UnsummonPetTemporaryIfAny(); + void ResummonPetTemporaryUnSummonedIfAny(); + bool IsPetNeedBeTemporaryUnsummoned() const { return GetSession()->PlayerLogout() || !IsInWorld() || !IsAlive() || IsMounted()/*+in flight*/ || GetVehicle() || IsBeingTeleported(); } + bool CanResummonPet(uint32 spellid); + + void SendCinematicStart(uint32 CinematicSequenceId); + void SendMovieStart(uint32 MovieId); + + /*********************************************************/ + /*** INSTANCE SYSTEM ***/ + /*********************************************************/ + + void UpdateHomebindTime(uint32 time); + + uint32 m_HomebindTimer; + bool m_InstanceValid; + void BindToInstance(); + void SetPendingBind(uint32 instanceId, uint32 bindTimer) { _pendingBindId = instanceId; _pendingBindTimer = bindTimer; } + bool HasPendingBind() const { return _pendingBindId > 0; } + uint32 GetPendingBind() const { return _pendingBindId; } + void SendRaidInfo(); + void SendSavedInstances(); + bool Satisfy(AccessRequirement const* ar, uint32 target_map, bool report = false); + bool CheckInstanceLoginValid(); + bool CheckInstanceCount(uint32 instanceId) const; + + void AddInstanceEnterTime(uint32 instanceId, time_t enterTime) + { + if (_instanceResetTimes.find(instanceId) == _instanceResetTimes.end()) + _instanceResetTimes.insert(InstanceTimeMap::value_type(instanceId, enterTime + HOUR)); + } + + // last used pet number (for BG's) + uint32 GetLastPetNumber() const { return m_lastpetnumber; } + void SetLastPetNumber(uint32 petnumber) { m_lastpetnumber = petnumber; } + uint32 GetLastPetSpell() const { return m_oldpetspell; } + void SetLastPetSpell(uint32 petspell) { m_oldpetspell = petspell; } + + /*********************************************************/ + /*** GROUP SYSTEM ***/ + /*********************************************************/ + + Group* GetGroupInvite() { return m_groupInvite; } + void SetGroupInvite(Group* group) { m_groupInvite = group; } + Group* GetGroup() { return m_group.getTarget(); } + const Group* GetGroup() const { return (const Group*)m_group.getTarget(); } + GroupReference& GetGroupRef() { return m_group; } + void SetGroup(Group* group, int8 subgroup = -1); + uint8 GetSubGroup() const { return m_group.getSubGroup(); } + uint32 GetGroupUpdateFlag() const { return m_groupUpdateMask; } + void SetGroupUpdateFlag(uint32 flag) { m_groupUpdateMask |= flag; } + uint64 GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; } + void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); } + Player* GetNextRandomRaidMember(float radius); + PartyResult CanUninviteFromGroup() const; + + // Battleground Group System + void SetBattlegroundOrBattlefieldRaid(Group* group, int8 subgroup = -1); + void RemoveFromBattlegroundOrBattlefieldRaid(); + Group* GetOriginalGroup() { return m_originalGroup.getTarget(); } + GroupReference& GetOriginalGroupRef() { return m_originalGroup; } + uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); } + void SetOriginalGroup(Group* group, int8 subgroup = -1); + + void SetPassOnGroupLoot(bool bPassOnGroupLoot) { m_bPassOnGroupLoot = bPassOnGroupLoot; } + bool GetPassOnGroupLoot() const { return m_bPassOnGroupLoot; } + + MapReference& GetMapRef() { return m_mapRef; } + + // Set map to player and add reference + void SetMap(Map* map) override; + void ResetMap() override; + + bool isAllowedToLoot(const Creature* creature); + + DeclinedName const* GetDeclinedNames() const { return m_declinedname; } + uint8 GetRunesState() const { return m_runes->runeState; } + RuneType GetBaseRune(uint8 index) const { return RuneType(m_runes->runes[index].BaseRune); } + RuneType GetCurrentRune(uint8 index) const { return RuneType(m_runes->runes[index].CurrentRune); } + uint32 GetRuneCooldown(uint8 index) const { return m_runes->runes[index].Cooldown; } + uint32 GetGracePeriod(uint8 index) const { return m_runes->runes[index].GracePeriod; } + uint32 GetRuneBaseCooldown(uint8 index, bool skipGrace); + bool IsBaseRuneSlotsOnCooldown(RuneType runeType) const; + RuneType GetLastUsedRune() { return m_runes->lastUsedRune; } + void SetLastUsedRune(RuneType type) { m_runes->lastUsedRune = type; } + void SetBaseRune(uint8 index, RuneType baseRune) { m_runes->runes[index].BaseRune = baseRune; } + void SetCurrentRune(uint8 index, RuneType currentRune) { m_runes->runes[index].CurrentRune = currentRune; } + void SetRuneCooldown(uint8 index, uint32 cooldown) { m_runes->runes[index].Cooldown = cooldown; m_runes->SetRuneState(index, (cooldown == 0)); } + void SetGracePeriod(uint8 index, uint32 period) { m_runes->runes[index].GracePeriod = period; } + void SetRuneConvertAura(uint8 index, AuraEffect const* aura) { m_runes->runes[index].ConvertAura = aura; } + void AddRuneByAuraEffect(uint8 index, RuneType newType, AuraEffect const* aura) { SetRuneConvertAura(index, aura); ConvertRune(index, newType); } + void RemoveRunesByAuraEffect(AuraEffect const* aura); + void RestoreBaseRune(uint8 index); + void ConvertRune(uint8 index, RuneType newType); + void ResyncRunes(uint8 count); + void AddRunePower(uint8 index); + void InitRunes(); + + void SendRespondInspectAchievements(Player* player) const; + bool HasAchieved(uint32 achievementId) const; + void ResetAchievements(); + void CheckAllAchievementCriteria(); + void ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete = false); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); + void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost = 0); + void RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); + void CompletedAchievement(AchievementEntry const* entry); + + bool HasTitle(uint32 bitIndex) const; + bool HasTitle(CharTitlesEntry const* title) const { return HasTitle(title->bit_index); } + void SetTitle(CharTitlesEntry const* title, bool lost = false); + + //bool isActiveObject() const { return true; } + bool CanSeeSpellClickOn(Creature const* creature) const; + + uint32 GetChampioningFaction() const { return m_ChampioningFaction; } + void SetChampioningFaction(uint32 faction) { m_ChampioningFaction = faction; } + Spell* m_spellModTakingSpell; + + float GetAverageItemLevel(); + float GetAverageItemLevelForDF(); + bool isDebugAreaTriggers; + + void ClearWhisperWhiteList() { WhisperList.clear(); } + void AddWhisperWhiteList(uint64 guid) { WhisperList.push_back(guid); } + bool IsInWhisperWhiteList(uint64 guid); + + bool SetDisableGravity(bool disable, bool packetOnly /* = false */) override; + bool SetCanFly(bool apply, bool packetOnly = false) override; + bool SetWaterWalking(bool apply, bool packetOnly = false) override; + bool SetFeatherFall(bool apply, bool packetOnly = false) override; + bool SetHover(bool enable, bool packetOnly = false) override; + + bool CanFly() const override { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_CAN_FLY); } + + //! Return collision height sent to client + float GetCollisionHeight(bool mounted) + { + if (mounted) + { + CreatureDisplayInfoEntry const* mountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID)); + if (!mountDisplayInfo) + return GetCollisionHeight(false); + + CreatureModelDataEntry const* mountModelData = sCreatureModelDataStore.LookupEntry(mountDisplayInfo->ModelId); + if (!mountModelData) + return GetCollisionHeight(false); + + CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId()); + ASSERT(displayInfo); + CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId); + ASSERT(modelData); + + float scaleMod = GetFloatValue(OBJECT_FIELD_SCALE_X); // 99% sure about this + + return scaleMod * mountModelData->MountHeight + modelData->CollisionHeight * 0.5f; } + else + { + //! Dismounting case - use basic default model data + CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId()); + ASSERT(displayInfo); + CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId); + ASSERT(modelData); + + return modelData->CollisionHeight; + } + } + + // OURS + // saving + void AdditionalSavingAddMask(uint8 mask) { m_additionalSaveTimer = 2000; m_additionalSaveMask |= mask; } + // arena spectator + bool IsSpectator() const { return m_ExtraFlags & PLAYER_EXTRA_SPECTATOR_ON; } + void SetIsSpectator(bool on); + bool NeedSendSpectatorData() const; + void SetPendingSpectatorForBG(uint32 bgInstanceId) { m_pendingSpectatorForBG = bgInstanceId; } + bool HasPendingSpectatorForBG(uint32 bgInstanceId) const { return m_pendingSpectatorForBG == bgInstanceId; } + void SetPendingSpectatorInviteInstanceId(uint32 bgInstanceId) { m_pendingSpectatorInviteInstanceId = bgInstanceId; } + uint32 GetPendingSpectatorInviteInstanceId() const { return m_pendingSpectatorInviteInstanceId; } + bool HasReceivedSpectatorResetFor(uint32 guid) { return m_receivedSpectatorResetFor.find(guid) != m_receivedSpectatorResetFor.end(); } + void ClearReceivedSpectatorResetFor() { m_receivedSpectatorResetFor.clear(); } + void AddReceivedSpectatorResetFor(uint32 guid) { m_receivedSpectatorResetFor.insert(guid); } + void RemoveReceivedSpectatorResetFor(uint32 guid) { m_receivedSpectatorResetFor.erase(guid); } + uint32 m_pendingSpectatorForBG; + uint32 m_pendingSpectatorInviteInstanceId; + std::set m_receivedSpectatorResetFor; + + // Dancing Rune weapon + void setRuneWeaponGUID(uint64 guid) { m_drwGUID = guid; }; + uint64 getRuneWeaponGUID() { return m_drwGUID; }; + uint64 m_drwGUID; + + bool CanSeeDKPet() const { return m_ExtraFlags & PLAYER_EXTRA_SHOW_DK_PET; } + void SetShowDKPet(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_SHOW_DK_PET; else m_ExtraFlags &= ~PLAYER_EXTRA_SHOW_DK_PET; }; + void PrepareCharmAISpells(); + uint32 m_charmUpdateTimer; + + int8 GetComboPointGain() { return m_comboPointGain; } + void SetComboPointGain(int8 combo) { m_comboPointGain = combo; } + + bool NeedToSaveGlyphs() { return m_NeedToSaveGlyphs; } + void SetNeedToSaveGlyphs(bool val) { m_NeedToSaveGlyphs = val; } + + uint32 GetMountBlockId() { return m_MountBlockId; } + void SetMountBlockId(uint32 mount) { m_MountBlockId = mount; } + + float GetRealParry() const { return m_realParry; } + float GetRealDodge() const { return m_realDodge; } + // mt maps + const PlayerTalentMap& GetTalentMap() const { return m_talents; } + uint32 GetNextSave() const { return m_nextSave; } + SpellModList const& GetSpellModList(uint32 type) const { return m_spellMods[type]; } + + static std::unordered_map bgZoneIdToFillWorldStates; // zoneId -> FillInitialWorldStates + +protected: + // Gamemaster whisper whitelist + WhisperListContainer WhisperList; + + // Combo Points + int8 m_comboPointGain; + // Performance Varibales + bool m_NeedToSaveGlyphs; + // Mount block bug + uint32 m_MountBlockId; + // Real stats + float m_realDodge; + float m_realParry; + + uint32 m_charmAISpells[NUM_CAI_SPELLS]; + + uint32 m_AreaID; + uint32 m_regenTimerCount; + uint32 m_foodEmoteTimerCount; + float m_powerFraction[MAX_POWERS]; + uint32 m_contestedPvPTimer; + + /*********************************************************/ + /*** BATTLEGROUND SYSTEM ***/ + /*********************************************************/ + + BattlegroundQueueTypeId m_bgBattlegroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES]; + BGData m_bgData; + bool m_IsBGRandomWinner; + + /*********************************************************/ + /*** ENTRY POINT ***/ + /*********************************************************/ + + EntryPointData m_entryPointData; + + /*********************************************************/ + /*** QUEST SYSTEM ***/ + /*********************************************************/ + + //We allow only one timed quest active at the same time. Below can then be simple value instead of set. + typedef std::set QuestSet; + typedef std::set SeasonalQuestSet; + typedef std::unordered_map SeasonalEventQuestMap; + QuestSet m_timedquests; + QuestSet m_weeklyquests; + QuestSet m_monthlyquests; + SeasonalEventQuestMap m_seasonalquests; + + uint64 m_divider; + uint32 m_ingametime; + + /*********************************************************/ + /*** LOAD SYSTEM ***/ + /*********************************************************/ + + void _LoadActions(PreparedQueryResult result); + void _LoadAuras(PreparedQueryResult result, uint32 timediff); + void _LoadGlyphAuras(); + void _LoadInventory(PreparedQueryResult result, uint32 timeDiff); + void _LoadMailInit(PreparedQueryResult resultUnread, PreparedQueryResult resultDelivery); + void _LoadMailAsynch(PreparedQueryResult result); + void _LoadMail(); + void _LoadMailedItems(Mail* mail); + void _LoadQuestStatus(PreparedQueryResult result); + void _LoadQuestStatusRewarded(PreparedQueryResult result); + void _LoadDailyQuestStatus(PreparedQueryResult result); + void _LoadWeeklyQuestStatus(PreparedQueryResult result); + void _LoadMonthlyQuestStatus(PreparedQueryResult result); + void _LoadSeasonalQuestStatus(PreparedQueryResult result); + void _LoadRandomBGStatus(PreparedQueryResult result); + void _LoadGroup(); + void _LoadSkills(PreparedQueryResult result); + void _LoadSpells(PreparedQueryResult result); + void _LoadFriendList(PreparedQueryResult result); + bool _LoadHomeBind(PreparedQueryResult result); + void _LoadDeclinedNames(PreparedQueryResult result); + void _LoadArenaTeamInfo(); + void _LoadEquipmentSets(PreparedQueryResult result); + void _LoadEntryPointData(PreparedQueryResult result); + void _LoadGlyphs(PreparedQueryResult result); + void _LoadTalents(PreparedQueryResult result); + void _LoadInstanceTimeRestrictions(PreparedQueryResult result); + void _LoadBrewOfTheMonth(PreparedQueryResult result); + + /*********************************************************/ + /*** SAVE SYSTEM ***/ + /*********************************************************/ + + void _SaveActions(SQLTransaction& trans); + void _SaveAuras(SQLTransaction& trans, bool logout); + void _SaveInventory(SQLTransaction& trans); + void _SaveMail(SQLTransaction& trans); + void _SaveQuestStatus(SQLTransaction& trans); + void _SaveDailyQuestStatus(SQLTransaction& trans); + void _SaveWeeklyQuestStatus(SQLTransaction& trans); + void _SaveMonthlyQuestStatus(SQLTransaction& trans); + void _SaveSeasonalQuestStatus(SQLTransaction& trans); + void _SaveSkills(SQLTransaction& trans); + void _SaveSpells(SQLTransaction& trans); + void _SaveEquipmentSets(SQLTransaction& trans); + void _SaveEntryPoint(SQLTransaction& trans); + void _SaveGlyphs(SQLTransaction& trans); + void _SaveTalents(SQLTransaction& trans); + void _SaveStats(SQLTransaction& trans); + void _SaveCharacter(bool create, SQLTransaction& trans); + void _SaveInstanceTimeRestrictions(SQLTransaction& trans); + + /*********************************************************/ + /*** ENVIRONMENTAL SYSTEM ***/ + /*********************************************************/ + void HandleSobering(); + void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen); + void StopMirrorTimer(MirrorTimerType Type); + void HandleDrowning(uint32 time_diff); + int32 getMaxTimer(MirrorTimerType timer); + + /*********************************************************/ + /*** HONOR SYSTEM ***/ + /*********************************************************/ + time_t m_lastHonorUpdateTime; + + void outDebugValues() const; + uint64 m_lootGuid; + + TeamId m_team; + uint32 m_nextSave; // pussywizard + uint16 m_additionalSaveTimer; // pussywizard + uint8 m_additionalSaveMask; // pussywizard + uint16 m_hostileReferenceCheckTimer; // pussywizard + time_t m_speakTime; + uint32 m_speakCount; + Difficulty m_dungeonDifficulty; + Difficulty m_raidDifficulty; + Difficulty m_raidMapDifficulty; + + uint32 m_atLoginFlags; + + Item* m_items[PLAYER_SLOTS_COUNT]; + uint32 m_currentBuybackSlot; + + std::vector m_itemUpdateQueue; + bool m_itemUpdateQueueBlocked; + + uint32 m_ExtraFlags; + + uint64 m_comboTarget; + int8 m_comboPoints; + + QuestStatusMap m_QuestStatus; + QuestStatusSaveMap m_QuestStatusSave; + + RewardedQuestSet m_RewardedQuests; + QuestStatusSaveMap m_RewardedQuestsSave; + + SkillStatusMap mSkillStatus; + + uint32 m_GuildIdInvited; + uint32 m_ArenaTeamIdInvited; + + PlayerMails m_mail; + PlayerSpellMap m_spells; + PlayerTalentMap m_talents; + uint32 m_lastPotionId; // last used health/mana potion in combat, that block next potion use + + GlobalCooldownMgr m_GlobalCooldownMgr; + + uint8 m_activeSpec; + uint8 m_specsCount; + + uint32 m_Glyphs[MAX_TALENT_SPECS][MAX_GLYPH_SLOT_INDEX]; + + ActionButtonList m_actionButtons; + + float m_auraBaseMod[BASEMOD_END][MOD_END]; + int16 m_baseRatingValue[MAX_COMBAT_RATING]; + uint32 m_baseSpellPower; + uint32 m_baseFeralAP; + uint32 m_baseManaRegen; + uint32 m_baseHealthRegen; + int32 m_spellPenetrationItemMod; + + SpellModList m_spellMods[MAX_SPELLMOD]; + //uint32 m_pad; + // Spell* m_spellModTakingSpell; // Spell for which charges are dropped in spell::finish + + EnchantDurationList m_enchantDuration; + ItemDurationList m_itemDuration; + ItemDurationList m_itemSoulboundTradeable; + ACE_Thread_Mutex m_soulboundTradableLock; + + void ResetTimeSync(); + void SendTimeSync(); + + uint64 m_resurrectGUID; + uint32 m_resurrectMap; + float m_resurrectX, m_resurrectY, m_resurrectZ; + uint32 m_resurrectHealth, m_resurrectMana; + + WorldSession* m_session; + + typedef std::list JoinedChannelsList; + JoinedChannelsList m_channels; - // OURS - // saving - void AdditionalSavingAddMask(uint8 mask) { m_additionalSaveTimer = 2000; m_additionalSaveMask |= mask; } - // arena spectator - bool IsSpectator() const { return m_ExtraFlags & PLAYER_EXTRA_SPECTATOR_ON; } - void SetIsSpectator(bool on); - bool NeedSendSpectatorData() const; - void SetPendingSpectatorForBG(uint32 bgInstanceId) { m_pendingSpectatorForBG = bgInstanceId; } - bool HasPendingSpectatorForBG(uint32 bgInstanceId) const { return m_pendingSpectatorForBG == bgInstanceId; } - void SetPendingSpectatorInviteInstanceId(uint32 bgInstanceId) { m_pendingSpectatorInviteInstanceId = bgInstanceId; } - uint32 GetPendingSpectatorInviteInstanceId() const { return m_pendingSpectatorInviteInstanceId; } - bool HasReceivedSpectatorResetFor(uint32 guid) { return m_receivedSpectatorResetFor.find(guid) != m_receivedSpectatorResetFor.end(); } - void ClearReceivedSpectatorResetFor() { m_receivedSpectatorResetFor.clear(); } - void AddReceivedSpectatorResetFor(uint32 guid) { m_receivedSpectatorResetFor.insert(guid); } - void RemoveReceivedSpectatorResetFor(uint32 guid) { m_receivedSpectatorResetFor.erase(guid); } - uint32 m_pendingSpectatorForBG; - uint32 m_pendingSpectatorInviteInstanceId; - std::set m_receivedSpectatorResetFor; - - // Dancing Rune weapon - void setRuneWeaponGUID(uint64 guid) { m_drwGUID = guid; }; - uint64 getRuneWeaponGUID() { return m_drwGUID; }; - uint64 m_drwGUID; - - bool CanSeeDKPet() const { return m_ExtraFlags & PLAYER_EXTRA_SHOW_DK_PET; } - void SetShowDKPet(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_SHOW_DK_PET; else m_ExtraFlags &= ~PLAYER_EXTRA_SHOW_DK_PET; }; - void PrepareCharmAISpells(); - uint32 m_charmUpdateTimer; - - int8 GetComboPointGain() { return m_comboPointGain; } - void SetComboPointGain(int8 combo) { m_comboPointGain = combo; } - - bool NeedToSaveGlyphs() { return m_NeedToSaveGlyphs; } - void SetNeedToSaveGlyphs(bool val) { m_NeedToSaveGlyphs = val; } - - uint32 GetMountBlockId() { return m_MountBlockId; } - void SetMountBlockId(uint32 mount) { m_MountBlockId = mount; } - - float GetRealParry() const { return m_realParry; } - float GetRealDodge() const { return m_realDodge; } - // mt maps - const PlayerTalentMap& GetTalentMap() const { return m_talents; } - uint32 GetNextSave() const { return m_nextSave; } - SpellModList const& GetSpellModList(uint32 type) const { return m_spellMods[type]; } - - static std::unordered_map bgZoneIdToFillWorldStates; // zoneId -> FillInitialWorldStates - - protected: - // Gamemaster whisper whitelist - WhisperListContainer WhisperList; - - // Combo Points - int8 m_comboPointGain; - // Performance Varibales - bool m_NeedToSaveGlyphs; - // Mount block bug - uint32 m_MountBlockId; - // Real stats - float m_realDodge; - float m_realParry; - - uint32 m_charmAISpells[NUM_CAI_SPELLS]; - - uint32 m_AreaID; - uint32 m_regenTimerCount; - uint32 m_foodEmoteTimerCount; - float m_powerFraction[MAX_POWERS]; - uint32 m_contestedPvPTimer; - - /*********************************************************/ - /*** BATTLEGROUND SYSTEM ***/ - /*********************************************************/ - - BattlegroundQueueTypeId m_bgBattlegroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES]; - BGData m_bgData; - bool m_IsBGRandomWinner; - - /*********************************************************/ - /*** ENTRY POINT ***/ - /*********************************************************/ - - EntryPointData m_entryPointData; - - /*********************************************************/ - /*** QUEST SYSTEM ***/ - /*********************************************************/ - - //We allow only one timed quest active at the same time. Below can then be simple value instead of set. - typedef std::set QuestSet; - typedef std::set SeasonalQuestSet; - typedef std::unordered_map SeasonalEventQuestMap; - QuestSet m_timedquests; - QuestSet m_weeklyquests; - QuestSet m_monthlyquests; - SeasonalEventQuestMap m_seasonalquests; - - uint64 m_divider; - uint32 m_ingametime; - - /*********************************************************/ - /*** LOAD SYSTEM ***/ - /*********************************************************/ - - void _LoadActions(PreparedQueryResult result); - void _LoadAuras(PreparedQueryResult result, uint32 timediff); - void _LoadGlyphAuras(); - void _LoadInventory(PreparedQueryResult result, uint32 timeDiff); - void _LoadMailInit(PreparedQueryResult resultUnread, PreparedQueryResult resultDelivery); - void _LoadMailAsynch(PreparedQueryResult result); - void _LoadMail(); - void _LoadMailedItems(Mail* mail); - void _LoadQuestStatus(PreparedQueryResult result); - void _LoadQuestStatusRewarded(PreparedQueryResult result); - void _LoadDailyQuestStatus(PreparedQueryResult result); - void _LoadWeeklyQuestStatus(PreparedQueryResult result); - void _LoadMonthlyQuestStatus(PreparedQueryResult result); - void _LoadSeasonalQuestStatus(PreparedQueryResult result); - void _LoadRandomBGStatus(PreparedQueryResult result); - void _LoadGroup(); - void _LoadSkills(PreparedQueryResult result); - void _LoadSpells(PreparedQueryResult result); - void _LoadFriendList(PreparedQueryResult result); - bool _LoadHomeBind(PreparedQueryResult result); - void _LoadDeclinedNames(PreparedQueryResult result); - void _LoadArenaTeamInfo(); - void _LoadEquipmentSets(PreparedQueryResult result); - void _LoadEntryPointData(PreparedQueryResult result); - void _LoadGlyphs(PreparedQueryResult result); - void _LoadTalents(PreparedQueryResult result); - void _LoadInstanceTimeRestrictions(PreparedQueryResult result); - void _LoadBrewOfTheMonth(PreparedQueryResult result); - - /*********************************************************/ - /*** SAVE SYSTEM ***/ - /*********************************************************/ - - void _SaveActions(SQLTransaction& trans); - void _SaveAuras(SQLTransaction& trans, bool logout); - void _SaveInventory(SQLTransaction& trans); - void _SaveMail(SQLTransaction& trans); - void _SaveQuestStatus(SQLTransaction& trans); - void _SaveDailyQuestStatus(SQLTransaction& trans); - void _SaveWeeklyQuestStatus(SQLTransaction& trans); - void _SaveMonthlyQuestStatus(SQLTransaction& trans); - void _SaveSeasonalQuestStatus(SQLTransaction& trans); - void _SaveSkills(SQLTransaction& trans); - void _SaveSpells(SQLTransaction& trans); - void _SaveEquipmentSets(SQLTransaction& trans); - void _SaveEntryPoint(SQLTransaction& trans); - void _SaveGlyphs(SQLTransaction& trans); - void _SaveTalents(SQLTransaction& trans); - void _SaveStats(SQLTransaction& trans); - void _SaveCharacter(bool create, SQLTransaction& trans); - void _SaveInstanceTimeRestrictions(SQLTransaction& trans); - - /*********************************************************/ - /*** ENVIRONMENTAL SYSTEM ***/ - /*********************************************************/ - void HandleSobering(); - void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen); - void StopMirrorTimer(MirrorTimerType Type); - void HandleDrowning(uint32 time_diff); - int32 getMaxTimer(MirrorTimerType timer); - - /*********************************************************/ - /*** HONOR SYSTEM ***/ - /*********************************************************/ - time_t m_lastHonorUpdateTime; - - void outDebugValues() const; - uint64 m_lootGuid; - - TeamId m_team; - uint32 m_nextSave; // pussywizard - uint16 m_additionalSaveTimer; // pussywizard - uint8 m_additionalSaveMask; // pussywizard - uint16 m_hostileReferenceCheckTimer; // pussywizard - time_t m_speakTime; - uint32 m_speakCount; - Difficulty m_dungeonDifficulty; - Difficulty m_raidDifficulty; - Difficulty m_raidMapDifficulty; - - uint32 m_atLoginFlags; - - Item* m_items[PLAYER_SLOTS_COUNT]; - uint32 m_currentBuybackSlot; - - std::vector m_itemUpdateQueue; - bool m_itemUpdateQueueBlocked; - - uint32 m_ExtraFlags; - - uint64 m_comboTarget; - int8 m_comboPoints; - - QuestStatusMap m_QuestStatus; - QuestStatusSaveMap m_QuestStatusSave; - - RewardedQuestSet m_RewardedQuests; - QuestStatusSaveMap m_RewardedQuestsSave; - - SkillStatusMap mSkillStatus; - - uint32 m_GuildIdInvited; - uint32 m_ArenaTeamIdInvited; - - PlayerMails m_mail; - PlayerSpellMap m_spells; - PlayerTalentMap m_talents; - uint32 m_lastPotionId; // last used health/mana potion in combat, that block next potion use - - GlobalCooldownMgr m_GlobalCooldownMgr; - - uint8 m_activeSpec; - uint8 m_specsCount; - - uint32 m_Glyphs[MAX_TALENT_SPECS][MAX_GLYPH_SLOT_INDEX]; - - ActionButtonList m_actionButtons; - - float m_auraBaseMod[BASEMOD_END][MOD_END]; - int16 m_baseRatingValue[MAX_COMBAT_RATING]; - uint32 m_baseSpellPower; - uint32 m_baseFeralAP; - uint32 m_baseManaRegen; - uint32 m_baseHealthRegen; - int32 m_spellPenetrationItemMod; - - SpellModList m_spellMods[MAX_SPELLMOD]; - //uint32 m_pad; -// Spell* m_spellModTakingSpell; // Spell for which charges are dropped in spell::finish - - EnchantDurationList m_enchantDuration; - ItemDurationList m_itemDuration; - ItemDurationList m_itemSoulboundTradeable; - ACE_Thread_Mutex m_soulboundTradableLock; - - void ResetTimeSync(); - void SendTimeSync(); - - uint64 m_resurrectGUID; - uint32 m_resurrectMap; - float m_resurrectX, m_resurrectY, m_resurrectZ; - uint32 m_resurrectHealth, m_resurrectMana; - - WorldSession* m_session; - - typedef std::list JoinedChannelsList; - JoinedChannelsList m_channels; + uint8 m_cinematic; - uint8 m_cinematic; + TradeData* m_trade; - TradeData* m_trade; + bool m_DailyQuestChanged; + bool m_WeeklyQuestChanged; + bool m_MonthlyQuestChanged; + bool m_SeasonalQuestChanged; + time_t m_lastDailyQuestTime; - bool m_DailyQuestChanged; - bool m_WeeklyQuestChanged; - bool m_MonthlyQuestChanged; - bool m_SeasonalQuestChanged; - time_t m_lastDailyQuestTime; + uint32 m_drunkTimer; + uint32 m_weaponChangeTimer; - uint32 m_drunkTimer; - uint32 m_weaponChangeTimer; + uint32 m_zoneUpdateId; + uint32 m_zoneUpdateTimer; + uint32 m_areaUpdateId; - uint32 m_zoneUpdateId; - uint32 m_zoneUpdateTimer; - uint32 m_areaUpdateId; + uint32 m_deathTimer; + time_t m_deathExpireTime; - uint32 m_deathTimer; - time_t m_deathExpireTime; + uint32 m_WeaponProficiency; + uint32 m_ArmorProficiency; + bool m_canParry; + bool m_canBlock; + bool m_canTitanGrip; + uint8 m_swingErrorMsg; + float m_ammoDPS; - uint32 m_WeaponProficiency; - uint32 m_ArmorProficiency; - bool m_canParry; - bool m_canBlock; - bool m_canTitanGrip; - uint8 m_swingErrorMsg; - float m_ammoDPS; + ////////////////////Rest System///////////////////// + time_t _restTime; + uint32 _innTriggerId; + float _restBonus; + ////////////////////Rest System///////////////////// + uint32 m_resetTalentsCost; + time_t m_resetTalentsTime; + uint32 m_usedTalentCount; + uint32 m_questRewardTalentCount; - ////////////////////Rest System///////////////////// - time_t _restTime; - uint32 _innTriggerId; - float _restBonus; - ////////////////////Rest System///////////////////// - uint32 m_resetTalentsCost; - time_t m_resetTalentsTime; - uint32 m_usedTalentCount; - uint32 m_questRewardTalentCount; + // Social + PlayerSocial* m_social; - // Social - PlayerSocial *m_social; + // Groups + GroupReference m_group; + GroupReference m_originalGroup; + Group* m_groupInvite; + uint32 m_groupUpdateMask; + uint64 m_auraRaidUpdateMask; + bool m_bPassOnGroupLoot; - // Groups - GroupReference m_group; - GroupReference m_originalGroup; - Group* m_groupInvite; - uint32 m_groupUpdateMask; - uint64 m_auraRaidUpdateMask; - bool m_bPassOnGroupLoot; + // last used pet number (for BG's) + uint32 m_lastpetnumber; - // last used pet number (for BG's) - uint32 m_lastpetnumber; + // Player summoning + time_t m_summon_expire; + uint32 m_summon_mapid; + float m_summon_x; + float m_summon_y; + float m_summon_z; + bool m_summon_asSpectator; - // Player summoning - time_t m_summon_expire; - uint32 m_summon_mapid; - float m_summon_x; - float m_summon_y; - float m_summon_z; - bool m_summon_asSpectator; + DeclinedName* m_declinedname; + Runes* m_runes; + EquipmentSets m_EquipmentSets; - DeclinedName *m_declinedname; - Runes *m_runes; - EquipmentSets m_EquipmentSets; + bool CanAlwaysSee(WorldObject const* obj) const override; - bool CanAlwaysSee(WorldObject const* obj) const override; + bool IsAlwaysDetectableFor(WorldObject const* seer) const override; - bool IsAlwaysDetectableFor(WorldObject const* seer) const override; + uint8 m_grantableLevels; - uint8 m_grantableLevels; + AchievementMgr* GetAchievementMgr() const { return m_achievementMgr; } - AchievementMgr* GetAchievementMgr() const { return m_achievementMgr; } +private: + // internal common parts for CanStore/StoreItem functions + InventoryResult CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const; + InventoryResult CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; + InventoryResult CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; + Item* _StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update); + Item* _LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields); - private: - // internal common parts for CanStore/StoreItem functions - InventoryResult CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const; - InventoryResult CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; - InventoryResult CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; - Item* _StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update); - Item* _LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields); + typedef std::set RefundableItemsSet; + RefundableItemsSet m_refundableItems; + void SendRefundInfo(Item* item); + void RefundItem(Item* item); - typedef std::set RefundableItemsSet; - RefundableItemsSet m_refundableItems; - void SendRefundInfo(Item* item); - void RefundItem(Item* item); + // know currencies are not removed at any point (0 displayed) + void AddKnownCurrency(uint32 itemId); - // know currencies are not removed at any point (0 displayed) - void AddKnownCurrency(uint32 itemId); + void AdjustQuestReqItemCount(Quest const* quest, QuestStatusData& questStatusData); - void AdjustQuestReqItemCount(Quest const* quest, QuestStatusData& questStatusData); + bool MustDelayTeleport() const { return m_bMustDelayTeleport; } // pussywizard: must delay teleports during player update to the very end + void SetMustDelayTeleport(bool setting) { m_bMustDelayTeleport = setting; } + bool HasDelayedTeleport() const { return m_bHasDelayedTeleport; } + void SetHasDelayedTeleport(bool setting) { m_bHasDelayedTeleport = setting; } - bool MustDelayTeleport() const { return m_bMustDelayTeleport; } // pussywizard: must delay teleports during player update to the very end - void SetMustDelayTeleport(bool setting) { m_bMustDelayTeleport = setting; } - bool HasDelayedTeleport() const { return m_bHasDelayedTeleport; } - void SetHasDelayedTeleport(bool setting) { m_bHasDelayedTeleport = setting; } + MapReference m_mapRef; - MapReference m_mapRef; + void UpdateCharmedAI(); - void UpdateCharmedAI(); + uint32 m_lastFallTime; + float m_lastFallZ; - uint32 m_lastFallTime; - float m_lastFallZ; + int32 m_MirrorTimer[MAX_TIMERS]; + uint8 m_MirrorTimerFlags; + uint8 m_MirrorTimerFlagsLast; + bool m_isInWater; - int32 m_MirrorTimer[MAX_TIMERS]; - uint8 m_MirrorTimerFlags; - uint8 m_MirrorTimerFlagsLast; - bool m_isInWater; + // Current teleport data + WorldLocation teleportStore_dest; + uint32 teleportStore_options; + time_t mSemaphoreTeleport_Near; + time_t mSemaphoreTeleport_Far; - // Current teleport data - WorldLocation teleportStore_dest; - uint32 teleportStore_options; - time_t mSemaphoreTeleport_Near; - time_t mSemaphoreTeleport_Far; + uint32 m_DelayedOperations; + bool m_bMustDelayTeleport; + bool m_bHasDelayedTeleport; - uint32 m_DelayedOperations; - bool m_bMustDelayTeleport; - bool m_bHasDelayedTeleport; + // Temporary removed pet cache + uint32 m_temporaryUnsummonedPetNumber; + uint32 m_oldpetspell; + + AchievementMgr* m_achievementMgr; + ReputationMgr* m_reputationMgr; - // Temporary removed pet cache - uint32 m_temporaryUnsummonedPetNumber; - uint32 m_oldpetspell; - - AchievementMgr* m_achievementMgr; - ReputationMgr* m_reputationMgr; + SpellCooldowns m_spellCooldowns; - SpellCooldowns m_spellCooldowns; + uint32 m_ChampioningFaction; - uint32 m_ChampioningFaction; + uint32 m_timeSyncCounter; + uint32 m_timeSyncTimer; + uint32 m_timeSyncClient; + uint32 m_timeSyncServer; - uint32 m_timeSyncCounter; - uint32 m_timeSyncTimer; - uint32 m_timeSyncClient; - uint32 m_timeSyncServer; + InstanceTimeMap _instanceResetTimes; + uint32 _pendingBindId; + uint32 _pendingBindTimer; - InstanceTimeMap _instanceResetTimes; - uint32 _pendingBindId; - uint32 _pendingBindTimer; + uint32 _activeCheats; - uint32 _activeCheats; + // duel health and mana reset attributes + uint32 healthBeforeDuel; + uint32 manaBeforeDuel; - // duel health and mana reset attributes - uint32 healthBeforeDuel; - uint32 manaBeforeDuel; - - bool m_isInstantFlightOn; + bool m_isInstantFlightOn; }; void AddItemsSetItem(Player* player, Item* item); void RemoveItemsSetItem(Player* player, ItemTemplate const* proto); // "the bodies of template functions must be made available in a header file" -template T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell* spell, bool temporaryPet) +template T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell, bool temporaryPet) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) @@ -3075,7 +3075,7 @@ template T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &bas // xinef: those two mods should be multiplicative (Glyph of Renew) if (mod->op == SPELLMOD_DAMAGE || mod->op == SPELLMOD_DOT) - totalmul *= CalculatePct(1.0f, 100.0f+mod->value); + totalmul *= CalculatePct(1.0f, 100.0f + mod->value); else totalmul += CalculatePct(1.0f, mod->value); } diff --git a/src/server/game/Entities/Player/SocialMgr.cpp b/src/server/game/Entities/Player/SocialMgr.cpp index fdf3dfc41..804ef0b69 100644 --- a/src/server/game/Entities/Player/SocialMgr.cpp +++ b/src/server/game/Entities/Player/SocialMgr.cpp @@ -143,7 +143,7 @@ void PlayerSocial::SendSocialList(Player* player) uint32 size = m_playerSocialMap.size(); - WorldPacket data(SMSG_CONTACT_LIST, (4+4+size*25)); // just can guess size + WorldPacket data(SMSG_CONTACT_LIST, (4 + 4 + size * 25)); // just can guess size data << uint32(7); // 0x1 = Friendlist update. 0x2 = Ignorelist update. 0x4 = Mutelist update. data << uint32(size); // friends count @@ -202,7 +202,7 @@ SocialMgr* SocialMgr::instance() return &instance; } -void SocialMgr::GetFriendInfo(Player* player, uint32 friendGUID, FriendInfo &friendInfo) +void SocialMgr::GetFriendInfo(Player* player, uint32 friendGUID, FriendInfo& friendInfo) { if (!player) return; @@ -311,7 +311,7 @@ void SocialMgr::BroadcastToFriendListers(Player* player, WorldPacket* packet) PlayerSocial* SocialMgr::LoadFromDB(PreparedQueryResult result, uint32 guid) { - PlayerSocial *social = &m_socialMap[guid]; + PlayerSocial* social = &m_socialMap[guid]; social->SetPlayerGUID(guid); if (!result) @@ -334,8 +334,7 @@ PlayerSocial* SocialMgr::LoadFromDB(PreparedQueryResult result, uint32 guid) // client's friends list and ignore list limit if (social->m_playerSocialMap.size() >= (SOCIALMGR_FRIEND_LIMIT + SOCIALMGR_IGNORE_LIMIT)) break; - } - while (result->NextRow()); + } while (result->NextRow()); return social; } diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index 22b3ef373..f9b358698 100644 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -89,47 +89,47 @@ enum FriendsResult class PlayerSocial { friend class SocialMgr; - public: - PlayerSocial(); - ~PlayerSocial(); - // adding/removing - bool AddToSocialList(uint32 friend_guid, bool ignore); - void RemoveFromSocialList(uint32 friend_guid, bool ignore); - void SetFriendNote(uint32 friendGuid, std::string note); - // Packet send's - void SendSocialList(Player* player); - // Misc - bool HasFriend(uint32 friend_guid) const; - bool HasIgnore(uint32 ignore_guid) const; - uint32 GetPlayerGUID() const { return m_playerGUID; } - void SetPlayerGUID(uint32 guid) { m_playerGUID = guid; } - uint32 GetNumberOfSocialsWithFlag(SocialFlag flag) const; - private: - PlayerSocialMap m_playerSocialMap; - uint32 m_playerGUID; +public: + PlayerSocial(); + ~PlayerSocial(); + // adding/removing + bool AddToSocialList(uint32 friend_guid, bool ignore); + void RemoveFromSocialList(uint32 friend_guid, bool ignore); + void SetFriendNote(uint32 friendGuid, std::string note); + // Packet send's + void SendSocialList(Player* player); + // Misc + bool HasFriend(uint32 friend_guid) const; + bool HasIgnore(uint32 ignore_guid) const; + uint32 GetPlayerGUID() const { return m_playerGUID; } + void SetPlayerGUID(uint32 guid) { m_playerGUID = guid; } + uint32 GetNumberOfSocialsWithFlag(SocialFlag flag) const; +private: + PlayerSocialMap m_playerSocialMap; + uint32 m_playerGUID; }; class SocialMgr { - private: - SocialMgr(); - ~SocialMgr(); +private: + SocialMgr(); + ~SocialMgr(); - public: - static SocialMgr* instance(); +public: + static SocialMgr* instance(); - // Misc - void RemovePlayerSocial(uint32 guid) { m_socialMap.erase(guid); } + // Misc + void RemovePlayerSocial(uint32 guid) { m_socialMap.erase(guid); } - void GetFriendInfo(Player* player, uint32 friendGUID, FriendInfo &friendInfo); - // Packet management - void MakeFriendStatusPacket(FriendsResult result, uint32 friend_guid, WorldPacket* data); - void SendFriendStatus(Player* player, FriendsResult result, uint32 friend_guid, bool broadcast); - void BroadcastToFriendListers(Player* player, WorldPacket* packet); - // Loading - PlayerSocial *LoadFromDB(PreparedQueryResult result, uint32 guid); - private: - SocialMap m_socialMap; + void GetFriendInfo(Player* player, uint32 friendGUID, FriendInfo& friendInfo); + // Packet management + void MakeFriendStatusPacket(FriendsResult result, uint32 friend_guid, WorldPacket* data); + void SendFriendStatus(Player* player, FriendsResult result, uint32 friend_guid, bool broadcast); + void BroadcastToFriendListers(Player* player, WorldPacket* packet); + // Loading + PlayerSocial* LoadFromDB(PreparedQueryResult result, uint32 guid); +private: + SocialMap m_socialMap; }; #define sSocialMgr SocialMgr::instance() diff --git a/src/server/game/Entities/Totem/Totem.cpp b/src/server/game/Entities/Totem/Totem.cpp index ecb33d87c..20ec5631a 100644 --- a/src/server/game/Entities/Totem/Totem.cpp +++ b/src/server/game/Entities/Totem/Totem.cpp @@ -23,7 +23,7 @@ Totem::Totem(SummonPropertiesEntry const* properties, uint64 owner) : Minion(pro } void Totem::Update(uint32 time) -{ +{ if (!GetOwner()->IsAlive() || !IsAlive()) { UnSummon(); // remove self @@ -42,7 +42,7 @@ void Totem::Update(uint32 time) } void Totem::InitStats(uint32 duration) -{ +{ // client requires SMSG_TOTEM_CREATED to be sent before adding to world and before removing old totem // Xinef: Set level for Unit totems if (Unit* owner = ObjectAccessor::FindUnit(m_owner)) @@ -75,7 +75,7 @@ void Totem::InitStats(uint32 duration) } void Totem::InitSummon() -{ +{ if (m_type == TOTEM_PASSIVE && GetSpell()) CastSpell(this, GetSpell(), true); @@ -94,7 +94,7 @@ void Totem::InitSummon() } void Totem::UnSummon(uint32 msTime) -{ +{ if (msTime) { m_Events.AddEvent(new ForcedUnsummonDelayEvent(*this), m_Events.CalculateTime(msTime)); @@ -104,7 +104,7 @@ void Totem::UnSummon(uint32 msTime) CombatStop(); RemoveAurasDueToSpell(GetSpell(), GetGUID()); - Unit *owner = GetOwner(); + Unit* owner = GetOwner(); // clear owner's totem slot for (uint8 i = SUMMON_SLOT_TOTEM; i < MAX_TOTEM_SLOT; ++i) { @@ -144,13 +144,13 @@ void Totem::UnSummon(uint32 msTime) } bool Totem::IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const -{ +{ // xinef: immune to all positive spells, except of stoneclaw totem absorb and sentry totem bind sight // totems positive spells have unit_caster target - if (spellInfo->Effects[index].Effect != SPELL_EFFECT_DUMMY && - spellInfo->Effects[index].Effect != SPELL_EFFECT_SCRIPT_EFFECT && - spellInfo->IsPositive() && spellInfo->Effects[index].TargetA.GetTarget() != TARGET_UNIT_CASTER && - spellInfo->Effects[index].TargetA.GetCheckType() != TARGET_CHECK_ENTRY && spellInfo->Id != 55277 && spellInfo->Id != 6277) + if (spellInfo->Effects[index].Effect != SPELL_EFFECT_DUMMY && + spellInfo->Effects[index].Effect != SPELL_EFFECT_SCRIPT_EFFECT && + spellInfo->IsPositive() && spellInfo->Effects[index].TargetA.GetTarget() != TARGET_UNIT_CASTER && + spellInfo->Effects[index].TargetA.GetCheckType() != TARGET_CHECK_ENTRY && spellInfo->Id != 55277 && spellInfo->Id != 6277) return true; switch (spellInfo->Effects[index].ApplyAuraName) diff --git a/src/server/game/Entities/Totem/Totem.h b/src/server/game/Entities/Totem/Totem.h index b6668cc8f..e05bd9583 100644 --- a/src/server/game/Entities/Totem/Totem.h +++ b/src/server/game/Entities/Totem/Totem.h @@ -23,31 +23,31 @@ enum TotemType class Totem : public Minion { - public: - explicit Totem(SummonPropertiesEntry const *properties, uint64 owner); - virtual ~Totem(){}; - void Update(uint32 time); - void InitStats(uint32 duration); - void InitSummon(); - void UnSummon(uint32 msTime = 0); - uint32 GetSpell(uint8 slot = 0) const { return m_spells[slot]; } - uint32 GetTotemDuration() const { return m_duration; } - void SetTotemDuration(uint32 duration) { m_duration = duration; } - TotemType GetTotemType() const { return m_type; } +public: + explicit Totem(SummonPropertiesEntry const* properties, uint64 owner); + virtual ~Totem() {}; + void Update(uint32 time); + void InitStats(uint32 duration); + void InitSummon(); + void UnSummon(uint32 msTime = 0); + uint32 GetSpell(uint8 slot = 0) const { return m_spells[slot]; } + uint32 GetTotemDuration() const { return m_duration; } + void SetTotemDuration(uint32 duration) { m_duration = duration; } + TotemType GetTotemType() const { return m_type; } - bool UpdateStats(Stats /*stat*/) { return true; } - bool UpdateAllStats() { return true; } - void UpdateResistances(uint32 /*school*/) {} - void UpdateArmor() {} - void UpdateMaxHealth() {} - void UpdateMaxPower(Powers /*power*/) {} - void UpdateAttackPowerAndDamage(bool /*ranged*/) {} - void UpdateDamagePhysical(WeaponAttackType /*attType*/) {} + bool UpdateStats(Stats /*stat*/) { return true; } + bool UpdateAllStats() { return true; } + void UpdateResistances(uint32 /*school*/) {} + void UpdateArmor() {} + void UpdateMaxHealth() {} + void UpdateMaxPower(Powers /*power*/) {} + void UpdateAttackPowerAndDamage(bool /*ranged*/) {} + void UpdateDamagePhysical(WeaponAttackType /*attType*/) {} - bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const; + bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const; - protected: - TotemType m_type; - uint32 m_duration; +protected: + TotemType m_type; + uint32 m_duration; }; #endif diff --git a/src/server/game/Entities/Transport/Transport.cpp b/src/server/game/Entities/Transport/Transport.cpp index 40729c3d3..46aab0194 100644 --- a/src/server/game/Entities/Transport/Transport.cpp +++ b/src/server/game/Entities/Transport/Transport.cpp @@ -33,13 +33,13 @@ MotionTransport::~MotionTransport() } bool MotionTransport::CreateMoTrans(uint32 guidlow, uint32 entry, uint32 mapid, float x, float y, float z, float ang, uint32 animprogress) -{ +{ Relocate(x, y, z, ang); if (!IsPositionValid()) { sLog->outError("Transport (GUID: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)", - guidlow, x, y); + guidlow, x, y); return false; } @@ -96,7 +96,7 @@ bool MotionTransport::CreateMoTrans(uint32 guidlow, uint32 entry, uint32 mapid, } void MotionTransport::CleanupsBeforeDelete(bool finalCleanup /*= true*/) -{ +{ UnloadStaticPassengers(); while (!_passengers.empty()) { @@ -111,7 +111,7 @@ void MotionTransport::CleanupsBeforeDelete(bool finalCleanup /*= true*/) } void MotionTransport::BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet&) -{ +{ Map::PlayerList const& players = GetMap()->GetPlayers(); if (players.isEmpty()) return; @@ -123,7 +123,7 @@ void MotionTransport::BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet&) } void MotionTransport::Update(uint32 diff) -{ +{ uint32 const positionUpdateDelay = 1; if (AI()) @@ -223,7 +223,7 @@ void MotionTransport::Update(uint32 diff) sScriptMgr->OnTransportUpdate(this, diff); } - + void MotionTransport::DelayedUpdate(uint32 /*diff*/) { if (GetKeyFrames().size() <= 1) @@ -233,7 +233,7 @@ void MotionTransport::DelayedUpdate(uint32 /*diff*/) } void MotionTransport::UpdatePosition(float x, float y, float z, float o) -{ +{ if (!GetMap()->IsGridLoaded(x, y)) // pussywizard: should not happen, but just in case GetMap()->LoadGrid(x, y); @@ -274,7 +274,7 @@ void MotionTransport::AddPassenger(WorldObject* passenger, bool withAll) } void MotionTransport::RemovePassenger(WorldObject* passenger, bool withAll) -{ +{ ACORE_GUARD(ACE_Thread_Mutex, Lock); if (_passengers.erase(passenger) || _staticPassengers.erase(passenger)) { @@ -295,7 +295,7 @@ void MotionTransport::RemovePassenger(WorldObject* passenger, bool withAll) } Creature* MotionTransport::CreateNPCPassenger(uint32 guid, CreatureData const* data) -{ +{ Map* map = GetMap(); Creature* creature = new Creature(); @@ -325,7 +325,7 @@ Creature* MotionTransport::CreateNPCPassenger(uint32 guid, CreatureData const* d if (!creature->IsPositionValid()) { - sLog->outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates aren't valid (X: %f Y: %f)",creature->GetGUIDLow(),creature->GetEntry(),creature->GetPositionX(),creature->GetPositionY()); + sLog->outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates aren't valid (X: %f Y: %f)", creature->GetGUIDLow(), creature->GetEntry(), creature->GetPositionX(), creature->GetPositionY()); delete creature; return nullptr; } @@ -342,7 +342,7 @@ Creature* MotionTransport::CreateNPCPassenger(uint32 guid, CreatureData const* d } GameObject* MotionTransport::CreateGOPassenger(uint32 guid, GameObjectData const* data) -{ +{ Map* map = GetMap(); GameObject* go = new GameObject(); ASSERT(!sObjectMgr->IsGameObjectStaticTransport(data->id)); @@ -382,7 +382,7 @@ GameObject* MotionTransport::CreateGOPassenger(uint32 guid, GameObjectData const } void MotionTransport::LoadStaticPassengers() -{ +{ if (PassengersLoaded()) return; SetPassengersLoaded(true); @@ -406,7 +406,7 @@ void MotionTransport::LoadStaticPassengers() } void MotionTransport::UnloadStaticPassengers() -{ +{ SetPassengersLoaded(false); while (!_staticPassengers.empty()) { @@ -416,7 +416,7 @@ void MotionTransport::UnloadStaticPassengers() } void MotionTransport::UnloadNonStaticPassengers() -{ +{ for (PassengerSet::iterator itr = _passengers.begin(); itr != _passengers.end(); ) { if ((*itr)->GetTypeId() == TYPEID_PLAYER) @@ -430,7 +430,7 @@ void MotionTransport::UnloadNonStaticPassengers() } void MotionTransport::EnableMovement(bool enabled) -{ +{ if (!GetGOInfo()->moTransport.canBeStopped) return; @@ -438,7 +438,7 @@ void MotionTransport::EnableMovement(bool enabled) } void MotionTransport::MoveToNextWaypoint() -{ +{ // Clear events flagging _triggeredArrivalEvent = false; _triggeredDepartureEvent = false; @@ -450,12 +450,12 @@ void MotionTransport::MoveToNextWaypoint() } float MotionTransport::CalculateSegmentPos(float now) -{ +{ KeyFrame const& frame = *_currentFrame; const float speed = float(m_goInfo->moTransport.moveSpeed); const float accel = float(m_goInfo->moTransport.accelRate); - float timeSinceStop = frame.TimeFrom + (now - (1.0f/IN_MILLISECONDS) * frame.DepartureTime); - float timeUntilStop = frame.TimeTo - (now - (1.0f/IN_MILLISECONDS) * frame.DepartureTime); + float timeSinceStop = frame.TimeFrom + (now - (1.0f / IN_MILLISECONDS) * frame.DepartureTime); + float timeUntilStop = frame.TimeTo - (now - (1.0f / IN_MILLISECONDS) * frame.DepartureTime); float segmentPos, dist; float accelTime = _transportInfo->accelTime; float accelDist = _transportInfo->accelDist; @@ -481,7 +481,7 @@ float MotionTransport::CalculateSegmentPos(float now) } bool MotionTransport::TeleportTransport(uint32 newMapid, float x, float y, float z, float o) -{ +{ Map const* oldMap = GetMap(); if (oldMap->GetId() != newMapid) @@ -521,7 +521,7 @@ void MotionTransport::DelayedTeleportTransport() float x = _nextFrame->Node->x, y = _nextFrame->Node->y, z = _nextFrame->Node->z, - o =_nextFrame->InitialOrientation; + o = _nextFrame->InitialOrientation; PassengerSet _passengersCopy = _passengers; for (PassengerSet::iterator itr = _passengersCopy.begin(); itr != _passengersCopy.end(); ) @@ -580,7 +580,7 @@ void MotionTransport::DelayedTeleportTransport() } void MotionTransport::UpdatePassengerPositions(PassengerSet& passengers) -{ +{ for (PassengerSet::iterator itr = passengers.begin(); itr != passengers.end(); ++itr) { WorldObject* passenger = *itr; @@ -631,7 +631,7 @@ void MotionTransport::UpdatePassengerPositions(PassengerSet& passengers) } void MotionTransport::DoEventIfAny(KeyFrame const& node, bool departure) -{ +{ if (uint32 eventid = departure ? node.Node->departureEventID : node.Node->arrivalEventID) { //TC_LOG_DEBUG("maps.script", "Taxi %s event %u of node %u of %s path", departure ? "departure" : "arrival", eventid, node.Node->index, GetName().c_str()); @@ -763,7 +763,7 @@ void StaticTransport::CleanupsBeforeDelete(bool finalCleanup /*= true*/) } void StaticTransport::BuildUpdate(UpdateDataMapType& data_map, UpdatePlayerSet&) -{ +{ Map::PlayerList const& players = GetMap()->GetPlayers(); if (players.isEmpty()) return; @@ -829,7 +829,7 @@ void StaticTransport::Update(uint32 diff) void StaticTransport::RelocateToProgress(uint32 progress) { - TransportAnimationEntry const *curr = NULL, *next = nullptr; + TransportAnimationEntry const* curr = NULL, *next = nullptr; float percPos; if (m_goValue.Transport.AnimationInfo->GetAnimNode(progress, curr, next, percPos)) { @@ -845,7 +845,7 @@ void StaticTransport::RelocateToProgress(uint32 progress) float sign = GetFloatValue(GAMEOBJECT_PARENTROTATION + 2) >= 0.0f ? 1.0f : -1.0f; float pathRotAngle = sign * 2.0f * acos(GetFloatValue(GAMEOBJECT_PARENTROTATION + 3)); float cs = cos(pathRotAngle), sn = sin(pathRotAngle); - float nx = pos.x * cs - pos.y * sn; + float nx = pos.x * cs - pos.y * sn; float ny = pos.x * sn + pos.y * cs; pos.x = nx; pos.y = ny; @@ -875,7 +875,7 @@ void StaticTransport::RelocateToProgress(uint32 progress) } void StaticTransport::UpdatePosition(float x, float y, float z, float o) -{ +{ if (!GetMap()->IsGridLoaded(x, y)) // pussywizard: should not happen, but just in case GetMap()->LoadGrid(x, y); @@ -884,7 +884,7 @@ void StaticTransport::UpdatePosition(float x, float y, float z, float o) } void StaticTransport::UpdatePassengerPositions() -{ +{ for (PassengerSet::iterator itr = _passengers.begin(); itr != _passengers.end(); ++itr) { WorldObject* passenger = *itr; diff --git a/src/server/game/Entities/Transport/Transport.h b/src/server/game/Entities/Transport/Transport.h index 4900a72a1..76a17c828 100644 --- a/src/server/game/Entities/Transport/Transport.h +++ b/src/server/game/Entities/Transport/Transport.h @@ -116,7 +116,7 @@ public: uint32 GetPauseTime() const { return GetUInt32Value(GAMEOBJECT_LEVEL); } void SetPauseTime(uint32 val) { SetUInt32Value(GAMEOBJECT_LEVEL, val); } - uint32 GetPeriod() const { return m_goValue.Transport.AnimationInfo ? m_goValue.Transport.AnimationInfo->TotalTime : GetPauseTime()+2; } + uint32 GetPeriod() const { return m_goValue.Transport.AnimationInfo ? m_goValue.Transport.AnimationInfo->TotalTime : GetPauseTime() + 2; } private: bool _needDoInitialRelocation; }; diff --git a/src/server/game/Entities/Unit/StatSystem.cpp b/src/server/game/Entities/Unit/StatSystem.cpp index cf67bdfee..c9b0f5011 100644 --- a/src/server/game/Entities/Unit/StatSystem.cpp +++ b/src/server/game/Entities/Unit/StatSystem.cpp @@ -41,13 +41,13 @@ inline bool _ModifyUInt32(bool apply, uint32& baseValue, int32& amount) #######################################*/ void Unit::UpdateAllResistances() -{ +{ for (uint8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i) UpdateResistances(i); } void Unit::UpdateDamagePhysical(WeaponAttackType attType) -{ +{ float minDamage = 0.0f; float maxDamage = 0.0f; @@ -78,7 +78,7 @@ void Unit::UpdateDamagePhysical(WeaponAttackType attType) #######################################*/ bool Player::UpdateStats(Stats stat) -{ +{ if (stat > STAT_SPIRIT) return false; @@ -97,7 +97,9 @@ bool Player::UpdateStats(Stats stat) UpdateAllCritPercentages(); UpdateDodgePercentage(); break; - case STAT_STAMINA: UpdateMaxHealth(); break; + case STAT_STAMINA: + UpdateMaxHealth(); + break; case STAT_INTELLECT: UpdateMaxPower(POWER_MANA); UpdateAllSpellCritChances(); @@ -146,7 +148,7 @@ bool Player::UpdateStats(Stats stat) } void Player::ApplySpellPowerBonus(int32 amount, bool apply) -{ +{ apply = _ModifyUInt32(apply, m_baseSpellPower, amount); // For speed just update for client @@ -156,18 +158,18 @@ void Player::ApplySpellPowerBonus(int32 amount, bool apply) } void Player::UpdateSpellDamageAndHealingBonus() -{ +{ // Magic damage modifiers implemented in Unit::SpellDamageBonusDone // This information for client side use only // Get healing bonus for all schools SetStatInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS, SpellBaseHealingBonusDone(SPELL_SCHOOL_MASK_ALL)); // Get damage bonus for all schools for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) - SetStatInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, SpellBaseDamageBonusDone(SpellSchoolMask(1 << i))); + SetStatInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, SpellBaseDamageBonusDone(SpellSchoolMask(1 << i))); } bool Player::UpdateAllStats() -{ +{ for (int8 i = STAT_STRENGTH; i < MAX_STATS; ++i) { float value = GetTotalStatValue(Stats(i)); @@ -198,13 +200,13 @@ bool Player::UpdateAllStats() } void Player::ApplySpellPenetrationBonus(int32 amount, bool apply) -{ +{ ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, -amount, apply); m_spellPenetrationItemMod += apply ? amount : -amount; } void Player::UpdateResistances(uint32 school) -{ +{ if (school > SPELL_SCHOOL_NORMAL) { // cant use GetTotalAuraModValue because of total pct multiplier :P @@ -216,9 +218,9 @@ void Player::UpdateResistances(uint32 school) value += GetModifierValue(unitMod, TOTAL_VALUE); AuraEffectList const& mResbyIntellect = GetAuraEffectsByType(SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT); - for(AuraEffectList::const_iterator i = mResbyIntellect.begin();i != mResbyIntellect.end(); ++i) + for(AuraEffectList::const_iterator i = mResbyIntellect.begin(); i != mResbyIntellect.end(); ++i) { - if((*i)->GetMiscValue() & (1 << (school-1)) ) + if((*i)->GetMiscValue() & (1 << (school - 1)) ) value += int32(GetStat(Stats((*i)->GetMiscValueB())) * (*i)->GetAmount() / 100.0f); } @@ -231,7 +233,7 @@ void Player::UpdateResistances(uint32 school) } void Player::UpdateArmor() -{ +{ UnitMods unitMod = UNIT_MOD_ARMOR; float value = GetModifierValue(unitMod, BASE_VALUE); // base armor (from items) @@ -255,27 +257,27 @@ void Player::UpdateArmor() } float Player::GetHealthBonusFromStamina() -{ +{ float stamina = GetStat(STAT_STAMINA); float baseStam = stamina < 20 ? stamina : 20; float moreStam = stamina - baseStam; - return baseStam + (moreStam*10.0f); + return baseStam + (moreStam * 10.0f); } float Player::GetManaBonusFromIntellect() -{ +{ float intellect = GetStat(STAT_INTELLECT); float baseInt = intellect < 20 ? intellect : 20; float moreInt = intellect - baseInt; - return baseInt + (moreInt*15.0f); + return baseInt + (moreInt * 15.0f); } void Player::UpdateMaxHealth() -{ +{ UnitMods unitMod = UNIT_MOD_HEALTH; float value = GetModifierValue(unitMod, BASE_VALUE) + GetCreateHealth(); @@ -288,7 +290,7 @@ void Player::UpdateMaxHealth() } void Player::UpdateMaxPower(Powers power) -{ +{ UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + power); float bonusPower = (power == POWER_MANA && GetCreatePowers(power) > 0) ? GetManaBonusFromIntellect() : 0; @@ -303,16 +305,16 @@ void Player::UpdateMaxPower(Powers power) } void Player::ApplyFeralAPBonus(int32 amount, bool apply) -{ +{ _ModifyUInt32(apply, m_baseFeralAP, amount); UpdateAttackPowerAndDamage(); } void Player::UpdateAttackPowerAndDamage(bool ranged) -{ +{ float val2 = 0.0f; float level = float(getLevel()); - + sScriptMgr->OnBeforeUpdateAttackPowerAndDamage(this, level, val2, ranged); UnitMods unitMod = ranged ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER; @@ -342,12 +344,16 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) case FORM_CAT: case FORM_BEAR: case FORM_DIREBEAR: - val2 = 0.0f; break; + val2 = 0.0f; + break; default: - val2 = GetStat(STAT_AGILITY) - 10.0f; break; + val2 = GetStat(STAT_AGILITY) - 10.0f; + break; } break; - default: val2 = GetStat(STAT_AGILITY) - 10.0f; break; + default: + val2 = GetStat(STAT_AGILITY) - 10.0f; + break; } } else @@ -365,87 +371,87 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; case CLASS_DRUID: - { - // Check if Predatory Strikes is skilled - float mLevelMult = 0.0f; - float weapon_bonus = 0.0f; - if (IsInFeralForm()) { - Unit::AuraEffectList const& mDummy = GetAuraEffectsByType(SPELL_AURA_DUMMY); - for (Unit::AuraEffectList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr) + // Check if Predatory Strikes is skilled + float mLevelMult = 0.0f; + float weapon_bonus = 0.0f; + if (IsInFeralForm()) { - AuraEffect* aurEff = *itr; - if (aurEff->GetSpellInfo()->SpellIconID == 1563) + Unit::AuraEffectList const& mDummy = GetAuraEffectsByType(SPELL_AURA_DUMMY); + for (Unit::AuraEffectList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr) { - switch (aurEff->GetEffIndex()) + AuraEffect* aurEff = *itr; + if (aurEff->GetSpellInfo()->SpellIconID == 1563) { - case 0: // Predatory Strikes (effect 0) - mLevelMult = CalculatePct(1.0f, aurEff->GetAmount()); - break; - case 1: // Predatory Strikes (effect 1) - if (Item* mainHand = m_items[EQUIPMENT_SLOT_MAINHAND]) - { - // also gains % attack power from equipped weapon - ItemTemplate const* proto = mainHand->GetTemplate(); - if (!proto) - continue; - - uint32 ap = proto->getFeralBonus(); - // Get AP Bonuses from weapon - for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i) + switch (aurEff->GetEffIndex()) + { + case 0: // Predatory Strikes (effect 0) + mLevelMult = CalculatePct(1.0f, aurEff->GetAmount()); + break; + case 1: // Predatory Strikes (effect 1) + if (Item* mainHand = m_items[EQUIPMENT_SLOT_MAINHAND]) { - if (i >= proto->StatsCount) - break; - - if (proto->ItemStat[i].ItemStatType == ITEM_MOD_ATTACK_POWER) - ap += proto->ItemStat[i].ItemStatValue; - } - - // Get AP Bonuses from weapon spells - for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) - { - // no spell - if (!proto->Spells[i].SpellId || proto->Spells[i].SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP) + // also gains % attack power from equipped weapon + ItemTemplate const* proto = mainHand->GetTemplate(); + if (!proto) continue; - // check if it is valid spell - SpellInfo const* spellproto = sSpellMgr->GetSpellInfo(proto->Spells[i].SpellId); - if (!spellproto) - continue; + uint32 ap = proto->getFeralBonus(); + // Get AP Bonuses from weapon + for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i) + { + if (i >= proto->StatsCount) + break; - for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) - if (spellproto->Effects[j].ApplyAuraName == SPELL_AURA_MOD_ATTACK_POWER) - ap += spellproto->Effects[j].CalcValue(); + if (proto->ItemStat[i].ItemStatType == ITEM_MOD_ATTACK_POWER) + ap += proto->ItemStat[i].ItemStatValue; + } + + // Get AP Bonuses from weapon spells + for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) + { + // no spell + if (!proto->Spells[i].SpellId || proto->Spells[i].SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP) + continue; + + // check if it is valid spell + SpellInfo const* spellproto = sSpellMgr->GetSpellInfo(proto->Spells[i].SpellId); + if (!spellproto) + continue; + + for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) + if (spellproto->Effects[j].ApplyAuraName == SPELL_AURA_MOD_ATTACK_POWER) + ap += spellproto->Effects[j].CalcValue(); + } + + weapon_bonus = CalculatePct(float(ap), aurEff->GetAmount()); } - - weapon_bonus = CalculatePct(float(ap), aurEff->GetAmount()); - } - break; - default: - break; + break; + default: + break; + } } } } - } - switch (GetShapeshiftForm()) - { - case FORM_CAT: - val2 = (getLevel() * mLevelMult) + GetStat(STAT_STRENGTH) * 2.0f + GetStat(STAT_AGILITY) - 20.0f + weapon_bonus + m_baseFeralAP; - break; - case FORM_BEAR: - case FORM_DIREBEAR: - val2 = (getLevel() * mLevelMult) + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + weapon_bonus + m_baseFeralAP; - break; - case FORM_MOONKIN: - val2 = (getLevel() * mLevelMult) + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + m_baseFeralAP; - break; - default: - val2 = GetStat(STAT_STRENGTH) * 2.0f - 20.0f; - break; + switch (GetShapeshiftForm()) + { + case FORM_CAT: + val2 = (getLevel() * mLevelMult) + GetStat(STAT_STRENGTH) * 2.0f + GetStat(STAT_AGILITY) - 20.0f + weapon_bonus + m_baseFeralAP; + break; + case FORM_BEAR: + case FORM_DIREBEAR: + val2 = (getLevel() * mLevelMult) + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + weapon_bonus + m_baseFeralAP; + break; + case FORM_MOONKIN: + val2 = (getLevel() * mLevelMult) + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + m_baseFeralAP; + break; + default: + val2 = GetStat(STAT_STRENGTH) * 2.0f - 20.0f; + break; + } + break; } - break; - } case CLASS_MAGE: case CLASS_PRIEST: case CLASS_WARLOCK: @@ -504,12 +510,12 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) } void Player::UpdateShieldBlockValue() -{ +{ SetUInt32Value(PLAYER_SHIELD_BLOCK, GetShieldBlockValue()); } void Player::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) -{ +{ UnitMods unitMod; switch (attType) @@ -576,14 +582,14 @@ void Player::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bo } void Player::UpdateDefenseBonusesMod() -{ +{ UpdateBlockPercentage(); UpdateParryPercentage(); UpdateDodgePercentage(); } void Player::UpdateBlockPercentage() -{ +{ // No block float value = 0.0f; if (CanBlock()) @@ -602,7 +608,7 @@ void Player::UpdateBlockPercentage() } void Player::UpdateCritPercentage(WeaponAttackType attType) -{ +{ BaseModGroup modGroup; uint16 index; CombatRating cr; @@ -635,7 +641,7 @@ void Player::UpdateCritPercentage(WeaponAttackType attType) } void Player::UpdateAllCritPercentages() -{ +{ float value = GetMeleeCritFromAgility(); SetBaseModValue(CRIT_PERCENTAGE, PCT_MOD, value); @@ -663,7 +669,7 @@ const float m_diminishing_k[MAX_CLASSES] = }; float Player::GetMissPercentageFromDefence() const -{ +{ float const miss_cap[MAX_CLASSES] = { 16.00f, // Warrior //correct @@ -685,12 +691,12 @@ float Player::GetMissPercentageFromDefence() const diminishing += (int32(GetRatingBonusValue(CR_DEFENSE_SKILL))) * 0.04f; // apply diminishing formula to diminishing miss chance - uint32 pclass = getClass()-1; + uint32 pclass = getClass() - 1; return nondiminishing + (diminishing * miss_cap[pclass] / (diminishing + miss_cap[pclass] * m_diminishing_k[pclass])); } void Player::UpdateParryPercentage() -{ +{ const float parry_cap[MAX_CLASSES] = { 47.003525f, // Warrior @@ -709,7 +715,7 @@ void Player::UpdateParryPercentage() // No parry float value = 0.0f; m_realParry = 0.0f; - uint32 pclass = getClass()-1; + uint32 pclass = getClass() - 1; if (CanParry() && parry_cap[pclass] > 0.0f) { float nondiminishing = 5.0f; @@ -731,7 +737,7 @@ void Player::UpdateParryPercentage() } void Player::UpdateDodgePercentage() -{ +{ const float dodge_cap[MAX_CLASSES] = { 88.129021f, // Warrior @@ -757,9 +763,9 @@ void Player::UpdateDodgePercentage() // Dodge from rating diminishing += GetRatingBonusValue(CR_DODGE); // apply diminishing formula to diminishing dodge chance - uint32 pclass = getClass()-1; + uint32 pclass = getClass() - 1; m_realDodge = nondiminishing + (diminishing * dodge_cap[pclass] / (diminishing + dodge_cap[pclass] * m_diminishing_k[pclass])); - + m_realDodge = m_realDodge < 0.0f ? 0.0f : m_realDodge; float value = std::max(diminishing + nondiminishing, 0.0f); @@ -767,7 +773,7 @@ void Player::UpdateDodgePercentage() } void Player::UpdateSpellCritChance(uint32 school) -{ +{ // For normal school set zero crit chance if (school == SPELL_SCHOOL_NORMAL) { @@ -783,7 +789,7 @@ void Player::UpdateSpellCritChance(uint32 school) // Increase crit from SPELL_AURA_MOD_CRIT_PCT crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit by school from SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL - crit += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, 1<= NUM_RUNE_TYPES) return; @@ -924,7 +930,7 @@ void Player::UpdateRuneRegen(RuneType rune) } void Player::_ApplyAllStatBonuses() -{ +{ SetCanModifyStats(false); _ApplyAllAuraStatMods(); @@ -936,7 +942,7 @@ void Player::_ApplyAllStatBonuses() } void Player::_RemoveAllStatBonuses() -{ +{ SetCanModifyStats(false); _RemoveAllItemMods(); @@ -954,12 +960,12 @@ void Player::_RemoveAllStatBonuses() #######################################*/ bool Creature::UpdateStats(Stats /*stat*/) -{ +{ return true; } bool Creature::UpdateAllStats() -{ +{ UpdateMaxHealth(); UpdateAttackPowerAndDamage(); UpdateAttackPowerAndDamage(true); @@ -973,7 +979,7 @@ bool Creature::UpdateAllStats() } void Creature::UpdateResistances(uint32 school) -{ +{ if (school > SPELL_SCHOOL_NORMAL) { float value = GetTotalAuraModValue(UnitMods(UNIT_MOD_RESISTANCE_START + school)); @@ -984,19 +990,19 @@ void Creature::UpdateResistances(uint32 school) } void Creature::UpdateArmor() -{ +{ float value = GetTotalAuraModValue(UNIT_MOD_ARMOR); SetArmor(int32(value)); } void Creature::UpdateMaxHealth() -{ +{ float value = GetTotalAuraModValue(UNIT_MOD_HEALTH); SetMaxHealth(uint32(value)); } void Creature::UpdateMaxPower(Powers power) -{ +{ UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + power); float value = GetTotalAuraModValue(unitMod); @@ -1004,7 +1010,7 @@ void Creature::UpdateMaxPower(Powers power) } void Creature::UpdateAttackPowerAndDamage(bool ranged) -{ +{ UnitMods unitMod = ranged ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER; uint16 index = UNIT_FIELD_ATTACK_POWER; @@ -1037,7 +1043,7 @@ void Creature::UpdateAttackPowerAndDamage(bool ranged) } void Creature::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) -{ +{ UnitMods unitMod; switch (attType) { @@ -1098,7 +1104,7 @@ void Creature::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool Guardian::UpdateStats(Stats stat) -{ +{ if (stat >= MAX_STATS) return false; @@ -1107,18 +1113,27 @@ bool Guardian::UpdateStats(Stats stat) switch (stat) { - case STAT_STRENGTH: UpdateAttackPowerAndDamage(); break; - case STAT_AGILITY: UpdateArmor(); break; - case STAT_STAMINA: UpdateMaxHealth(); break; - case STAT_INTELLECT: UpdateMaxPower(POWER_MANA); break; - case STAT_SPIRIT: break; + case STAT_STRENGTH: + UpdateAttackPowerAndDamage(); + break; + case STAT_AGILITY: + UpdateArmor(); + break; + case STAT_STAMINA: + UpdateMaxHealth(); + break; + case STAT_INTELLECT: + UpdateMaxPower(POWER_MANA); + break; + case STAT_SPIRIT: + break; } return true; } bool Guardian::UpdateAllStats() -{ +{ for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) UpdateStats(Stats(i)); @@ -1130,7 +1145,7 @@ bool Guardian::UpdateAllStats() } void Guardian::UpdateArmor() -{ +{ float value = GetModifierValue(UNIT_MOD_ARMOR, BASE_VALUE); value *= GetModifierValue(UNIT_MOD_ARMOR, BASE_PCT); value += std::max(GetStat(STAT_AGILITY) - GetCreateStat(STAT_AGILITY), 0.0f) * 2.0f; @@ -1140,22 +1155,40 @@ void Guardian::UpdateArmor() } void Guardian::UpdateMaxHealth() -{ +{ UnitMods unitMod = UNIT_MOD_HEALTH; float stamina = std::max(GetStat(STAT_STAMINA) - GetCreateStat(STAT_STAMINA), 0.0f); float multiplicator; switch (GetEntry()) { - case NPC_IMP: multiplicator = 8.4f; break; - case NPC_WATER_ELEMENTAL_TEMP: multiplicator = 7.5f; break; - case NPC_WATER_ELEMENTAL_PERM: multiplicator = 7.5f; break; - case NPC_VOIDWALKER: multiplicator = 11.0f; break; - case NPC_SUCCUBUS: multiplicator = 9.1f; break; - case NPC_FELHUNTER: multiplicator = 9.5f; break; - case NPC_FELGUARD: multiplicator = 11.0f; break; - case NPC_BLOODWORM: multiplicator = 1.0f; break; - default: multiplicator = 10.0f; break; + case NPC_IMP: + multiplicator = 8.4f; + break; + case NPC_WATER_ELEMENTAL_TEMP: + multiplicator = 7.5f; + break; + case NPC_WATER_ELEMENTAL_PERM: + multiplicator = 7.5f; + break; + case NPC_VOIDWALKER: + multiplicator = 11.0f; + break; + case NPC_SUCCUBUS: + multiplicator = 9.1f; + break; + case NPC_FELHUNTER: + multiplicator = 9.5f; + break; + case NPC_FELGUARD: + multiplicator = 11.0f; + break; + case NPC_BLOODWORM: + multiplicator = 1.0f; + break; + default: + multiplicator = 10.0f; + break; } float value = GetModifierValue(unitMod, BASE_VALUE);// xinef: Do NOT add base health TWICE + GetCreateHealth(); @@ -1167,7 +1200,7 @@ void Guardian::UpdateMaxHealth() } void Guardian::UpdateMaxPower(Powers power) -{ +{ UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + power); float addValue = (power == POWER_MANA) ? std::max(GetStat(STAT_INTELLECT) - GetCreateStat(STAT_INTELLECT), 0.0f) : 0.0f; @@ -1175,7 +1208,7 @@ void Guardian::UpdateMaxPower(Powers power) switch (GetEntry()) { - case NPC_IMP: + case NPC_IMP: case NPC_WATER_ELEMENTAL_TEMP: case NPC_WATER_ELEMENTAL_PERM: multiplicator = 4.95f; @@ -1201,7 +1234,7 @@ void Guardian::UpdateMaxPower(Powers power) } void Guardian::UpdateAttackPowerAndDamage(bool ranged) -{ +{ if (ranged) return; @@ -1216,7 +1249,7 @@ void Guardian::UpdateAttackPowerAndDamage(bool ranged) val = 2 * GetStat(STAT_STRENGTH) - 20.0f; SetModifierValue(unitMod, BASE_VALUE, val); - + //in BASE_VALUE of UNIT_MOD_ATTACK_POWER for creatures we store data of meleeattackpower field in DB float base_attPower = GetModifierValue(unitMod, BASE_VALUE) * GetModifierValue(unitMod, BASE_PCT); float attPowerMod = GetModifierValue(unitMod, TOTAL_VALUE); @@ -1234,15 +1267,15 @@ void Guardian::UpdateAttackPowerAndDamage(bool ranged) } void Guardian::UpdateDamagePhysical(WeaponAttackType attType) -{ +{ if (attType > BASE_ATTACK) return; UnitMods unitMod = UNIT_MOD_DAMAGE_MAINHAND; - float att_speed = float(GetAttackTime(BASE_ATTACK))/1000.0f; + float att_speed = float(GetAttackTime(BASE_ATTACK)) / 1000.0f; - float base_value = GetModifierValue(unitMod, BASE_VALUE) + GetTotalAttackPowerValue(attType)/ 14.0f * att_speed; + float base_value = GetModifierValue(unitMod, BASE_VALUE) + GetTotalAttackPowerValue(attType) / 14.0f * att_speed; float base_pct = GetModifierValue(unitMod, BASE_PCT); float total_value = GetModifierValue(unitMod, TOTAL_VALUE); float total_pct = GetModifierValue(unitMod, TOTAL_PCT); diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index 1a9a21ca1..31ce971be 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -98,16 +98,16 @@ static bool isAlwaysTriggeredAura[TOTAL_AURAS]; static bool procPrepared = InitTriggerAuraData(); DamageInfo::DamageInfo(Unit* _attacker, Unit* _victim, uint32 _damage, SpellInfo const* _spellInfo, SpellSchoolMask _schoolMask, DamageEffectType _damageType) -: m_attacker(_attacker), m_victim(_victim), m_damage(_damage), m_spellInfo(_spellInfo), m_schoolMask(_schoolMask), -m_damageType(_damageType), m_attackType(BASE_ATTACK) + : m_attacker(_attacker), m_victim(_victim), m_damage(_damage), m_spellInfo(_spellInfo), m_schoolMask(_schoolMask), + m_damageType(_damageType), m_attackType(BASE_ATTACK) { m_absorb = 0; m_resist = 0; m_block = 0; } DamageInfo::DamageInfo(CalcDamageInfo& dmgInfo) -: m_attacker(dmgInfo.attacker), m_victim(dmgInfo.target), m_damage(dmgInfo.damage), m_spellInfo(nullptr), m_schoolMask(SpellSchoolMask(dmgInfo.damageSchoolMask)), -m_damageType(DIRECT_DAMAGE), m_attackType(dmgInfo.attackType) + : m_attacker(dmgInfo.attacker), m_victim(dmgInfo.target), m_damage(dmgInfo.damage), m_spellInfo(nullptr), m_schoolMask(SpellSchoolMask(dmgInfo.damageSchoolMask)), + m_damageType(DIRECT_DAMAGE), m_attackType(dmgInfo.attackType) { m_absorb = 0; m_resist = 0; @@ -142,8 +142,8 @@ void DamageInfo::BlockDamage(uint32 amount) } ProcEventInfo::ProcEventInfo(Unit* actor, Unit* actionTarget, Unit* procTarget, uint32 typeMask, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* /*spell*/, DamageInfo* damageInfo, HealInfo* healInfo, SpellInfo const* triggeredByAuraSpell) -:_actor(actor), _actionTarget(actionTarget), _procTarget(procTarget), _typeMask(typeMask), _spellTypeMask(spellTypeMask), _spellPhaseMask(spellPhaseMask), -_hitMask(hitMask), _damageInfo(damageInfo), _healInfo(healInfo), _triggeredByAuraSpell(triggeredByAuraSpell) + : _actor(actor), _actionTarget(actionTarget), _procTarget(procTarget), _typeMask(typeMask), _spellTypeMask(spellTypeMask), _spellPhaseMask(spellPhaseMask), + _hitMask(hitMask), _damageInfo(damageInfo), _healInfo(healInfo), _triggeredByAuraSpell(triggeredByAuraSpell) { } @@ -153,9 +153,9 @@ _hitMask(hitMask), _damageInfo(damageInfo), _healInfo(healInfo), _triggeredByAur #pragma warning(disable:4355) #endif Unit::Unit(bool isWorldObject) : WorldObject(isWorldObject), -m_movedByPlayer(nullptr), m_lastSanctuaryTime(0), IsAIEnabled(false), NeedChangeAI(false), -m_ControlledByPlayer(false), m_CreatedByPlayer(false), movespline(new Movement::MoveSpline()), i_AI(nullptr), i_disabledAI(nullptr), m_realRace(0), m_race(0), m_AutoRepeatFirstCast(false), m_procDeep(0), m_removedAurasCount(0), -i_motionMaster(new MotionMaster(this)), m_regenTimer(0), m_ThreatManager(this), m_vehicle(nullptr), m_vehicleKit(nullptr), m_unitTypeMask(UNIT_MASK_NONE), m_HostileRefManager(this) + m_movedByPlayer(nullptr), m_lastSanctuaryTime(0), IsAIEnabled(false), NeedChangeAI(false), + m_ControlledByPlayer(false), m_CreatedByPlayer(false), movespline(new Movement::MoveSpline()), i_AI(nullptr), i_disabledAI(nullptr), m_realRace(0), m_race(0), m_AutoRepeatFirstCast(false), m_procDeep(0), m_removedAurasCount(0), + i_motionMaster(new MotionMaster(this)), m_regenTimer(0), m_ThreatManager(this), m_vehicle(nullptr), m_vehicleKit(nullptr), m_unitTypeMask(UNIT_MASK_NONE), m_HostileRefManager(this) { #ifdef _MSC_VER #pragma warning(default:4355) @@ -206,7 +206,7 @@ i_motionMaster(new MotionMaster(this)), m_regenTimer(0), m_ThreatManager(this), m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f; m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f; } - // implement 50% base damage from offhand + // implement 50% base damage from offhand m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f; for (uint8 i = 0; i < MAX_ATTACK; ++i) @@ -434,14 +434,14 @@ bool Unit::haveOffhandWeapon() const void Unit::MonsterMoveWithSpeed(float x, float y, float z, float speed) { Movement::MoveSplineInit init(this); - init.MoveTo(x,y,z); + init.MoveTo(x, y, z); init.SetVelocity(speed); init.Launch(); } void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 TransitTime, SplineFlags sf) { - WorldPacket data(SMSG_MONSTER_MOVE, 1+12+4+1+4+4+4+12+GetPackGUID().size()); + WorldPacket data(SMSG_MONSTER_MOVE, 1 + 12 + 4 + 1 + 4 + 4 + 4 + 12 + GetPackGUID().size()); data.append(GetPackGUID()); data << uint8(0); // new in 3.1 @@ -458,23 +458,23 @@ void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 T class SplineHandler { - public: - SplineHandler(Unit* unit) : _unit(unit) { } +public: + SplineHandler(Unit* unit) : _unit(unit) { } - bool operator()(Movement::MoveSpline::UpdateResult result) - { - if ((result & (Movement::MoveSpline::Result_NextSegment|Movement::MoveSpline::Result_JustArrived)) && + bool operator()(Movement::MoveSpline::UpdateResult result) + { + if ((result & (Movement::MoveSpline::Result_NextSegment | Movement::MoveSpline::Result_JustArrived)) && _unit->GetTypeId() == TYPEID_UNIT && _unit->GetMotionMaster()->GetCurrentMovementGeneratorType() == ESCORT_MOTION_TYPE && _unit->movespline->GetId() == _unit->GetMotionMaster()->GetCurrentSplineId()) - { - _unit->ToCreature()->AI()->MovementInform(ESCORT_MOTION_TYPE, _unit->movespline->currentPathIdx()-1); - } - - return true; + { + _unit->ToCreature()->AI()->MovementInform(ESCORT_MOTION_TYPE, _unit->movespline->currentPathIdx() - 1); } - private: - Unit* _unit; + return true; + } + +private: + Unit* _unit; }; void Unit::UpdateSplineMovement(uint32 t_diff) @@ -535,14 +535,14 @@ void Unit::UpdateSplinePosition() void Unit::DisableSpline() { - m_movementInfo.RemoveMovementFlag(MovementFlags(MOVEMENTFLAG_SPLINE_ENABLED|MOVEMENTFLAG_FORWARD)); + m_movementInfo.RemoveMovementFlag(MovementFlags(MOVEMENTFLAG_SPLINE_ENABLED | MOVEMENTFLAG_FORWARD)); movespline->_Interrupt(); } void Unit::resetAttackTimer(WeaponAttackType type) { int32 time = int32(GetAttackTime(type) * m_modAttackSpeedPct[type]); - m_attackTimer[type] = std::min(m_attackTimer[type]+time, time); + m_attackTimer[type] = std::min(m_attackTimer[type] + time, time); } bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const @@ -569,7 +569,7 @@ bool Unit::IsWithinMeleeRange(const Unit* obj, float dist) const float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float dz = GetPositionZ() - obj->GetPositionZ(); - float distsq = dx*dx + dy*dy + dz*dz; + float distsq = dx * dx + dy * dy + dz * dz; float sizefactor = GetMeleeReach() + obj->GetMeleeReach(); float maxdist = dist + sizefactor; @@ -577,7 +577,7 @@ bool Unit::IsWithinMeleeRange(const Unit* obj, float dist) const return distsq < maxdist * maxdist; } -bool Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, bool force) const +bool Unit::GetRandomContactPoint(const Unit* obj, float& x, float& y, float& z, bool force) const { float combat_reach = GetCombatReach(); if (combat_reach < 0.1f) // sometimes bugged for players @@ -591,11 +591,11 @@ bool Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, if (c->isWorldBoss() || c->IsDungeonBoss() || (obj->IsPet() && const_cast(obj)->ToPet()->isControlled())) attacker_number = 0; // pussywizard: pets and bosses just come to target from their angle - GetNearPoint(obj, x, y, z, isMoving() ? (obj->GetCombatReach() > 7.75f ? obj->GetCombatReach()-7.5f : 0.25f) : obj->GetCombatReach(), 0.0f, - GetAngle(obj) + (attacker_number ? (static_cast(M_PI/2) - static_cast(M_PI) * (float)rand_norm()) * float(attacker_number) / combat_reach * 0.3f : 0)); + GetNearPoint(obj, x, y, z, isMoving() ? (obj->GetCombatReach() > 7.75f ? obj->GetCombatReach() - 7.5f : 0.25f) : obj->GetCombatReach(), 0.0f, + GetAngle(obj) + (attacker_number ? (static_cast(M_PI / 2) - static_cast(M_PI) * (float)rand_norm()) * float(attacker_number) / combat_reach * 0.3f : 0)); // pussywizard - if (fabs(this->GetPositionZ()-z) > 3.0f || !IsWithinLOS(x, y, z)) + if (fabs(this->GetPositionZ() - z) > 3.0f || !IsWithinLOS(x, y, z)) { x = this->GetPositionX(); y = this->GetPositionY(); @@ -603,7 +603,7 @@ bool Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, obj->UpdateAllowedPositionZ(x, y, z); } float maxDist = MELEE_RANGE + GetMeleeReach() + obj->GetMeleeReach(); - if (GetExactDistSq(x, y, z) >= maxDist*maxDist) + if (GetExactDistSq(x, y, z) >= maxDist * maxDist) { if (force) { @@ -645,7 +645,7 @@ bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const AuraEffectList const& auras = GetAuraEffectsByType(type); for (AuraEffectList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) if ((!excludeAura || excludeAura != (*itr)->GetSpellInfo()->Id) && //Avoid self interrupt of channeled Crowd Control spells like Seduction - ((*itr)->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_TAKE_DAMAGE)) + ((*itr)->GetSpellInfo()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_TAKE_DAMAGE)) return true; return false; } @@ -657,13 +657,13 @@ bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) cons excludeAura = currentChanneledSpell->GetSpellInfo()->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction return ( HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura) - || HasBreakableByDamageAuraType(SPELL_AURA_MOD_FEAR, excludeAura) - || HasBreakableByDamageAuraType(SPELL_AURA_MOD_STUN, excludeAura) - || HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT, excludeAura) - || HasBreakableByDamageAuraType(SPELL_AURA_TRANSFORM, excludeAura)); + || HasBreakableByDamageAuraType(SPELL_AURA_MOD_FEAR, excludeAura) + || HasBreakableByDamageAuraType(SPELL_AURA_MOD_STUN, excludeAura) + || HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT, excludeAura) + || HasBreakableByDamageAuraType(SPELL_AURA_TRANSFORM, excludeAura)); } -void Unit::DealDamageMods(Unit const* victim, uint32 &damage, uint32* absorb) +void Unit::DealDamageMods(Unit const* victim, uint32& damage, uint32* absorb) { if (!victim || !victim->IsAlive() || victim->IsInFlight() || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())) { @@ -755,7 +755,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage } if (attacker && shareDamageTarget->GetTypeId() == TYPEID_PLAYER) - attacker->SendSpellNonMeleeDamageLog(shareDamageTarget, spell->Id, shareDamage+shareAbsorb+shareResist, damageSchoolMask, shareAbsorb, shareResist, damagetype == DIRECT_DAMAGE, 0, false); + attacker->SendSpellNonMeleeDamageLog(shareDamageTarget, spell->Id, shareDamage + shareAbsorb + shareResist, damageSchoolMask, shareAbsorb, shareResist, damagetype == DIRECT_DAMAGE, 0, false); Unit::DealDamage(attacker, shareDamageTarget, shareDamage, cleanDamage, NODAMAGE, damageSchoolMask, spellProto, false); } @@ -770,14 +770,14 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage { case BASE_ATTACK: case OFF_ATTACK: - { - weaponSpeedHitFactor = uint32(attacker->GetAttackTime(cleanDamage->attackType) / 1000.0f * (cleanDamage->attackType == BASE_ATTACK ? 3.5f : 1.75f)); - if (cleanDamage->hitOutCome == MELEE_HIT_CRIT) - weaponSpeedHitFactor *= 2; + { + weaponSpeedHitFactor = uint32(attacker->GetAttackTime(cleanDamage->attackType) / 1000.0f * (cleanDamage->attackType == BASE_ATTACK ? 3.5f : 1.75f)); + if (cleanDamage->hitOutCome == MELEE_HIT_CRIT) + weaponSpeedHitFactor *= 2; - attacker->RewardRage(rage_damage, weaponSpeedHitFactor, true); - break; - } + attacker->RewardRage(rage_damage, weaponSpeedHitFactor, true); + break; + } case RANGED_ATTACK: break; default: @@ -812,7 +812,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage // duel ends when player has 1 or less hp bool duel_hasEnded = false; bool duel_wasMounted = false; - if (victim->GetTypeId() == TYPEID_PLAYER && victim->ToPlayer()->duel && damage >= (health-1)) + if (victim->GetTypeId() == TYPEID_PLAYER && victim->ToPlayer()->duel && damage >= (health - 1)) { // xinef: situation not possible earlier, just return silently. if (!attacker) @@ -824,7 +824,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage duel_hasEnded = true; } - else if (victim->IsVehicle() && damage >= (health-1) && victim->GetCharmer() && victim->GetCharmer()->GetTypeId() == TYPEID_PLAYER) + else if (victim->IsVehicle() && damage >= (health - 1) && victim->GetCharmer() && victim->GetCharmer()->GetTypeId() == TYPEID_PLAYER) { Player* victimRider = victim->GetCharmer()->ToPlayer(); @@ -876,7 +876,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage #endif //if (attacker && victim->GetTypeId() == TYPEID_PLAYER && victim != attacker) - //victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health); // pussywizard: optimization + //victim->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health); // pussywizard: optimization Unit::Kill(attacker, victim, durabilityLoss, cleanDamage ? cleanDamage->attackType : BASE_ATTACK, spellProto); } @@ -898,7 +898,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage { // Part of Evade mechanics. DoT's and Thorns / Retribution Aura do not contribute to this if (damagetype != DOT && damage > 0 && !IS_PLAYER_GUID(victim->GetOwnerGUID()) && (!spellProto || !spellProto->HasAura(SPELL_AURA_DAMAGE_SHIELD))) - victim->ToCreature()->SetLastDamagedTime(sWorld->GetGameTime()+MAX_AGGRO_RESET_TIME); + victim->ToCreature()->SetLastDamagedTime(sWorld->GetGameTime() + MAX_AGGRO_RESET_TIME); if (attacker) victim->AddThreat(attacker, float(damage), damageSchoolMask, spellProto); @@ -908,7 +908,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage // random durability for items (HIT TAKEN) if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE))) { - EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END-1)); + EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END - 1)); victim->ToPlayer()->DurabilityPointLossForEquipSlot(slot); } } @@ -925,7 +925,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage // random durability for items (HIT DONE) if (roll_chance_f(sWorld->getRate(RATE_DURABILITY_LOSS_DAMAGE))) { - EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END-1)); + EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END - 1)); attacker->ToPlayer()->DurabilityPointLossForEquipSlot(slot); } } @@ -986,7 +986,7 @@ void Unit::CastStop(uint32 except_spellid, bool withInstant) { for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++) if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id != except_spellid) - InterruptSpell(CurrentSpellTypes(i),false, withInstant); + InterruptSpell(CurrentSpellTypes(i), false, withInstant); } void Unit::CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags, Item* castItem, AuraEffect const* triggeredByAura, uint64 originalCaster) @@ -1130,78 +1130,78 @@ void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 dama // Melee and Ranged Spells case SPELL_DAMAGE_CLASS_RANGED: case SPELL_DAMAGE_CLASS_MELEE: - { - // Physical Damage - if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) { - // Get blocked status - blocked = isSpellBlocked(victim, spellInfo, attackType); + // Physical Damage + if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) + { + // Get blocked status + blocked = isSpellBlocked(victim, spellInfo, attackType); + } + + if (crit) + { + damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; + + // Calculate crit bonus + uint32 crit_bonus = damage; + // Apply crit_damage bonus for melee spells + if (Player* modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); + damage += crit_bonus; + + // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE + float critPctDamageMod = 0.0f; + if (attackType == RANGED_ATTACK) + critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); + else + critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); + + // Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS + critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, spellInfo->GetSchoolMask()); + + // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS + critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); + + if (critPctDamageMod != 0) + AddPct(damage, critPctDamageMod); + } + + // Spell weapon based damage CAN BE crit & blocked at same time + if (blocked) + { + damageInfo->blocked = victim->GetShieldBlockValue(); + // double blocked amount if block is critical + if (victim->isBlockCritical()) + damageInfo->blocked += damageInfo->blocked; + if (damage < int32(damageInfo->blocked)) + damageInfo->blocked = uint32(damage); + damage -= damageInfo->blocked; + } + + if (CanApplyResilience()) + { + if (attackType != RANGED_ATTACK) + Unit::ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_MELEE); + else + Unit::ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_RANGED); + } + break; } - - if (crit) - { - damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; - - // Calculate crit bonus - uint32 crit_bonus = damage; - // Apply crit_damage bonus for melee spells - if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); - damage += crit_bonus; - - // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE - float critPctDamageMod = 0.0f; - if (attackType == RANGED_ATTACK) - critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); - else - critPctDamageMod += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); - - // Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS - critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, spellInfo->GetSchoolMask()); - - // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS - critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); - - if (critPctDamageMod != 0) - AddPct(damage, critPctDamageMod); - } - - // Spell weapon based damage CAN BE crit & blocked at same time - if (blocked) - { - damageInfo->blocked = victim->GetShieldBlockValue(); - // double blocked amount if block is critical - if (victim->isBlockCritical()) - damageInfo->blocked += damageInfo->blocked; - if (damage < int32(damageInfo->blocked)) - damageInfo->blocked = uint32(damage); - damage -= damageInfo->blocked; - } - - if (CanApplyResilience()) - { - if (attackType != RANGED_ATTACK) - Unit::ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_MELEE); - else - Unit::ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_RANGED); - } - break; - } // Magical Attacks case SPELL_DAMAGE_CLASS_NONE: case SPELL_DAMAGE_CLASS_MAGIC: - { - // If crit add critical bonus - if (crit) { - damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; - damage = Unit::SpellCriticalDamageBonus(this, spellInfo, damage, victim); - } + // If crit add critical bonus + if (crit) + { + damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; + damage = Unit::SpellCriticalDamageBonus(this, spellInfo, damage, victim); + } - if (CanApplyResilience()) - Unit::ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_SPELL); - break; - } + if (CanApplyResilience()) + Unit::ApplyResilience(victim, NULL, &damage, crit, CR_CRIT_TAKEN_SPELL); + break; + } default: break; } @@ -1293,11 +1293,11 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam // Physical Immune check if (damageInfo->target->IsImmunedToDamageOrSchool(SpellSchoolMask(damageInfo->damageSchoolMask))) { - damageInfo->HitInfo |= HITINFO_NORMALSWING; - damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE; + damageInfo->HitInfo |= HITINFO_NORMALSWING; + damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE; - damageInfo->procEx |= PROC_EX_IMMUNE; - return; + damageInfo->procEx |= PROC_EX_IMMUNE; + return; } damage += CalculateDamage(damageInfo->attackType, false, true); @@ -1340,33 +1340,33 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam damageInfo->procEx |= PROC_EX_NORMAL_HIT; break; case MELEE_HIT_CRIT: - { - damageInfo->HitInfo |= HITINFO_CRITICALHIT; - damageInfo->TargetState = VICTIMSTATE_HIT; - - damageInfo->procEx |= PROC_EX_CRITICAL_HIT; - // Crit bonus calc - damageInfo->damage += damageInfo->damage; - float mod = 0.0f; - // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE - if (damageInfo->attackType == RANGED_ATTACK) - mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); - else { - mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); + damageInfo->HitInfo |= HITINFO_CRITICALHIT; + damageInfo->TargetState = VICTIMSTATE_HIT; - // Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS - mod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, damageInfo->damageSchoolMask) - 1.0f) * 100; + damageInfo->procEx |= PROC_EX_CRITICAL_HIT; + // Crit bonus calc + damageInfo->damage += damageInfo->damage; + float mod = 0.0f; + // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE + if (damageInfo->attackType == RANGED_ATTACK) + mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); + else + { + mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); + + // Increase crit damage from SPELL_AURA_MOD_CRIT_DAMAGE_BONUS + mod += (GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, damageInfo->damageSchoolMask) - 1.0f) * 100; + } + + uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask(); + + // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS + mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); + if (mod != 0) + AddPct(damageInfo->damage, mod); + break; } - - uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask(); - - // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS - mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); - if (mod != 0) - AddPct(damageInfo->damage, mod); - break; - } case MELEE_HIT_PARRY: damageInfo->TargetState = VICTIMSTATE_PARRY; damageInfo->procEx |= PROC_EX_PARRY; @@ -1386,7 +1386,7 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue(); // double blocked amount if block is critical if (damageInfo->target->isBlockCritical()) - damageInfo->blocked_amount+=damageInfo->blocked_amount; + damageInfo->blocked_amount += damageInfo->blocked_amount; if (damageInfo->blocked_amount >= damageInfo->damage) { damageInfo->TargetState = VICTIMSTATE_BLOCKS; @@ -1399,18 +1399,18 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam damageInfo->cleanDamage += damageInfo->blocked_amount; break; case MELEE_HIT_GLANCING: - { - damageInfo->HitInfo |= HITINFO_GLANCING; - damageInfo->TargetState = VICTIMSTATE_HIT; - damageInfo->procEx |= PROC_EX_NORMAL_HIT; - int32 leveldif = int32(victim->getLevel()) - int32(getLevel()); - if (leveldif > 3) - leveldif = 3; - float reducePercent = 1 - leveldif * 0.1f; - damageInfo->cleanDamage += damageInfo->damage - uint32(reducePercent * damageInfo->damage); - damageInfo->damage = uint32(reducePercent * damageInfo->damage); - break; - } + { + damageInfo->HitInfo |= HITINFO_GLANCING; + damageInfo->TargetState = VICTIMSTATE_HIT; + damageInfo->procEx |= PROC_EX_NORMAL_HIT; + int32 leveldif = int32(victim->getLevel()) - int32(getLevel()); + if (leveldif > 3) + leveldif = 3; + float reducePercent = 1 - leveldif * 0.1f; + damageInfo->cleanDamage += damageInfo->damage - uint32(reducePercent * damageInfo->damage); + damageInfo->damage = uint32(reducePercent * damageInfo->damage); + break; + } case MELEE_HIT_CRUSHING: damageInfo->HitInfo |= HITINFO_CRUSHING; damageInfo->TargetState = VICTIMSTATE_HIT; @@ -1509,8 +1509,8 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) // If this is a creature and it attacks from behind it has a probability to daze it's victim if (damageInfo->damage && ((damageInfo->hitOutCome == MELEE_HIT_CRIT || damageInfo->hitOutCome == MELEE_HIT_CRUSHING || damageInfo->hitOutCome == MELEE_HIT_NORMAL || damageInfo->hitOutCome == MELEE_HIT_GLANCING) && - GetTypeId() != TYPEID_PLAYER && !ToCreature()->IsControlledByPlayer() && !victim->HasInArc(M_PI, this) - && (victim->GetTypeId() == TYPEID_PLAYER || !victim->ToCreature()->isWorldBoss())&& !victim->IsVehicle())) + GetTypeId() != TYPEID_PLAYER && !ToCreature()->IsControlledByPlayer() && !victim->HasInArc(M_PI, this) + && (victim->GetTypeId() == TYPEID_PLAYER || !victim->ToCreature()->isWorldBoss()) && !victim->IsVehicle())) { // -probability is between 0% and 40% // 20% base chance @@ -1520,8 +1520,8 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) if (victim->getLevel() < 30) Probability = 0.65f * victim->getLevel() + 0.5f; - uint32 VictimDefense=victim->GetDefenseSkillValue(); - uint32 AttackerMeleeSkill=GetUnitMeleeSkill(); + uint32 VictimDefense = victim->GetDefenseSkillValue(); + uint32 AttackerMeleeSkill = GetUnitMeleeSkill(); // xinef: fix daze mechanics Probability -= ((float)VictimDefense - AttackerMeleeSkill) * 0.1428f; @@ -1568,7 +1568,7 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) Unit::DealDamageMods(this, damage, nullptr); // TODO: Move this to a packet handler - WorldPacket data(SMSG_SPELLDAMAGESHIELD, (8+8+4+4+4+4)); + WorldPacket data(SMSG_SPELLDAMAGESHIELD, (8 + 8 + 4 + 4 + 4 + 4)); data << uint64(victim->GetGUID()); data << uint64(GetGUID()); data << uint32(i_spellProto->Id); @@ -1606,8 +1606,8 @@ bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* s if (effIndex != MAX_SPELL_EFFECTS) { if (spellInfo->Effects[effIndex].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE || - spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SCHOOL_DAMAGE) - if (spellInfo->GetEffectMechanicMask(effIndex) & (1<Effects[effIndex].Effect == SPELL_EFFECT_SCHOOL_DAMAGE) + if (spellInfo->GetEffectMechanicMask(effIndex) & (1 << MECHANIC_BLEED)) return false; } } @@ -1632,7 +1632,7 @@ uint32 Unit::CalcArmorReducedDamage(Unit const* attacker, Unit const* victim, co for (AuraEffectList::const_iterator j = ResIgnoreAurasAb.begin(); j != ResIgnoreAurasAb.end(); ++j) { if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL - && (*j)->IsAffectedOnSpell(spellInfo)) + && (*j)->IsAffectedOnSpell(spellInfo)) armor = floor(AddPct(armor, -(*j)->GetAmount())); } @@ -1722,7 +1722,7 @@ float Unit::GetEffectiveResistChance(Unit const* owner, SpellSchoolMask schoolMa victimResistance = std::max(victimResistance, 0.0f); if (owner) - victimResistance += std::max((float(victim->getLevel())-float(owner->getLevel()))*5.0f, 0.0f); + victimResistance += std::max((float(victim->getLevel()) - float(owner->getLevel())) * 5.0f, 0.0f); static uint32 const BOSS_LEVEL = 83; @@ -1738,7 +1738,7 @@ float Unit::GetEffectiveResistChance(Unit const* owner, SpellSchoolMask schoolMa return victimResistance / (victimResistance + resistanceConstant); } -void Unit::CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellInfo const *spellInfo, bool Splited) +void Unit::CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32* absorb, uint32* resist, SpellInfo const* spellInfo, bool Splited) { if (!victim || !victim->IsAlive() || !damage) return; @@ -1995,7 +1995,7 @@ void Unit::CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask school caster->ProcDamageAndSpellFor(true, attacker, procVictim, procEx, BASE_ATTACK, spellInfo, splitted, nullptr); if (attacker) - attacker->SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellInfo()->Id, splitted+splitted_absorb, schoolMask, splitted_absorb, 0, false, 0, false); + attacker->SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellInfo()->Id, splitted + splitted_absorb, schoolMask, splitted_absorb, 0, false, 0, false); CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); Unit::DealDamage(attacker, caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellInfo(), false); @@ -2063,7 +2063,7 @@ void Unit::CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask school caster->ProcDamageAndSpellFor(true, attacker, procVictim, procEx, BASE_ATTACK, spellInfo, splitted, nullptr); if (attacker) - attacker->SendSpellNonMeleeDamageLog(caster, splitSpellInfo->Id, splitted+splitted_absorb, splitSchoolMask, splitted_absorb, 0, false, 0, false); + attacker->SendSpellNonMeleeDamageLog(caster, splitSpellInfo->Id, splitted + splitted_absorb, splitSchoolMask, splitted_absorb, 0, false, 0, false); CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); Unit::DealDamage(attacker, caster, splitted, &cleanDamage, DIRECT_DAMAGE, splitSchoolMask, splitSpellInfo, false); @@ -2074,7 +2074,7 @@ void Unit::CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask school *absorb = dmgInfo.GetAbsorb(); } -void Unit::CalcHealAbsorb(Unit const* victim, const SpellInfo* healSpell, uint32 &healAmount, uint32 &absorb) +void Unit::CalcHealAbsorb(Unit const* victim, const SpellInfo* healSpell, uint32& healAmount, uint32& absorb) { if (!healAmount) return; @@ -2126,7 +2126,7 @@ void Unit::CalcHealAbsorb(Unit const* victim, const SpellInfo* healSpell, uint32 { uint32 removedAuras = victim->m_removedAurasCount; auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL); - if (removedAuras+1 < victim->m_removedAurasCount) + if (removedAuras + 1 < victim->m_removedAurasCount) i = vHealAbsorb.begin(); } } @@ -2175,10 +2175,10 @@ void Unit::AttackerStateUpdate (Unit* victim, WeaponAttackType attType, bool ext #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) if (GetTypeId() == TYPEID_PLAYER) sLog->outStaticDebug("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", - GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist); + GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist); else sLog->outStaticDebug("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", - GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist); + GetGUIDLow(), victim->GetGUIDLow(), victim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist); #endif } } @@ -2272,7 +2272,7 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE - dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100; + dodge_chance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100; dodge_chance = int32 (float (dodge_chance) * GetTotalAuraMultiplier(SPELL_AURA_MOD_ENEMY_DODGE)); tmp = dodge_chance; @@ -2282,11 +2282,11 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy tmp = 0; if ((tmp > 0) // check if unit _can_ dodge - && ((tmp -= skillBonus) > 0) - && roll < (sum += tmp)) + && ((tmp -= skillBonus) > 0) + && roll < (sum += tmp)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum); + sLog->outStaticDebug ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum - tmp, sum); #endif return MELEE_HIT_DODGE; } @@ -2318,11 +2318,11 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy tmp = 0; if (tmp > 0 // check if unit _can_ parry - && (tmp -= skillBonus) > 0 - && roll < (sum += tmp)) + && (tmp -= skillBonus) > 0 + && roll < (sum += tmp)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum); + sLog->outStaticDebug ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum - tmp, sum); #endif return MELEE_HIT_PARRY; } @@ -2337,11 +2337,11 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy tmp = 0; if (tmp > 0 // check if unit _can_ block - && (tmp -= skillBonus) > 0 - && roll < (sum += tmp)) + && (tmp -= skillBonus) > 0 + && roll < (sum += tmp)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum); + sLog->outStaticDebug ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum - tmp, sum); #endif return MELEE_HIT_BLOCK; } @@ -2350,9 +2350,9 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy // Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon) if (attType != RANGED_ATTACK && - (GetTypeId() == TYPEID_PLAYER || IsPet()) && - victim->GetTypeId() != TYPEID_PLAYER && !victim->IsPet() && - getLevel() < victim->getLevelForTarget(this)) + (GetTypeId() == TYPEID_PLAYER || IsPet()) && + victim->GetTypeId() != TYPEID_PLAYER && !victim->IsPet() && + getLevel() < victim->getLevelForTarget(this)) { // cap possible value (with bonuses > max skill) int32 skill = attackerWeaponSkill; @@ -2364,7 +2364,7 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy if (roll < (sum += tmp)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum); + sLog->outStaticDebug ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum - 4000, sum); #endif return MELEE_HIT_GLANCING; } @@ -2372,9 +2372,9 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy // mobs can score crushing blows if they're 4 or more levels above victim if (getLevelForTarget(victim) >= victim->getLevelForTarget(this) + 4 && - // can be from by creature (if can) or from controlled player that considered as creature - !IsControlledByPlayer() && - !(GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH)) + // can be from by creature (if can) or from controlled player that considered as creature + !IsControlledByPlayer() && + !(GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH)) { // when their weapon skill is 15 or more above victim's defense skill tmp = victimDefenseSkill; @@ -2390,7 +2390,7 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy if (roll < (sum += tmp)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum); + sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum - tmp, sum); #endif return MELEE_HIT_CRUSHING; } @@ -2403,7 +2403,7 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy if (tmp > 0 && roll < (sum += tmp)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum); + sLog->outStaticDebug ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum - tmp, sum); #endif if (GetTypeId() == TYPEID_UNIT && (ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRIT)) { @@ -2500,7 +2500,7 @@ void Unit::SendMeleeAttackStop(Unit* victim) // pussywizard: this happens in some boss scripts, just add clearing here // ClearUnitState(UNIT_STATE_MELEE_ATTACKING); // ZOMG! commented out for now - WorldPacket data(SMSG_ATTACKSTOP, (8+8+4)); + WorldPacket data(SMSG_ATTACKSTOP, (8 + 8 + 4)); data.append(GetPackGUID()); data.append(victim ? victim->GetPackGUID() : 0); data << uint32(0); //! Can also take the value 0x01, which seems related to updating rotation @@ -2525,8 +2525,8 @@ bool Unit::isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttac { // Check creatures flags_extra for disable block if (victim->GetTypeId() == TYPEID_UNIT && - victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) - return false; + victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) + return false; float blockChance = victim->GetUnitBlockChance(); blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(victim->GetMaxSkillValueForLevel())) * 0.04f; @@ -2556,7 +2556,7 @@ int32 Unit::GetMechanicResistChance(const SpellInfo* spell) for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff) { if (!spell->Effects[eff].IsEffect()) - break; + break; int32 effect_mech = spell->GetEffectMechanic(eff); if (effect_mech) { @@ -2619,10 +2619,10 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* victim, SpellInfo const* spell) if (attType == RANGED_ATTACK) { // only if in front - if (!victim->HasUnitState(UNIT_STATE_STUNNED) && (victim->HasInArc(M_PI,this) || victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))) + if (!victim->HasUnitState(UNIT_STATE_STUNNED) && (victim->HasInArc(M_PI, this) || victim->HasAuraType(SPELL_AURA_IGNORE_HIT_DIRECTION))) { int32 deflect_chance = victim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS) * 100; - tmp+=deflect_chance; + tmp += deflect_chance; if (roll < tmp) return SPELL_MISS_DEFLECT; } @@ -2667,9 +2667,15 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* victim, SpellInfo const* spell) continue; switch ((*i)->GetMiscValue()) { - case MELEE_HIT_DODGE: canDodge = false; break; - case MELEE_HIT_BLOCK: canBlock = false; break; - case MELEE_HIT_PARRY: canParry = false; break; + case MELEE_HIT_DODGE: + canDodge = false; + break; + case MELEE_HIT_BLOCK: + canBlock = false; + break; + case MELEE_HIT_PARRY: + canParry = false; + break; default: #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT has unhandled state %d", (*i)->GetId(), (*i)->GetMiscValue()); @@ -2836,11 +2842,11 @@ SpellMissInfo Unit::MagicSpellHitResult(Unit* victim, SpellInfo const* spell) } // Players resistance for binary spells - if (spell->HasAttribute(SPELL_ATTR0_CU_BINARY_SPELL) && (spell->GetSchoolMask() & (SPELL_SCHOOL_MASK_NORMAL|SPELL_SCHOOL_MASK_HOLY)) == 0) + if (spell->HasAttribute(SPELL_ATTR0_CU_BINARY_SPELL) && (spell->GetSchoolMask() & (SPELL_SCHOOL_MASK_NORMAL | SPELL_SCHOOL_MASK_HOLY)) == 0) tmp += int32(Unit::GetEffectiveResistChance(this, spell->GetSchoolMask(), victim, spell) * 10000.0f); // 100 for spell calculations, and 100 for return value percentage } - // Roll chance + // Roll chance if (rand < tmp) return SPELL_MISS_RESIST; @@ -2873,7 +2879,7 @@ SpellMissInfo Unit::SpellHitResult(Unit* victim, SpellInfo const* spell, bool Ca // All positive spells can`t miss // TODO: client not show miss log for this spells - so need find info for this in dbc and use it! if ((spell->IsPositive() || spell->HasEffect(SPELL_EFFECT_DISPEL)) - &&(!IsHostileTo(victim))) // prevent from affecting enemy by "positive" spell + && (!IsHostileTo(victim))) // prevent from affecting enemy by "positive" spell return SPELL_MISS_NONE; // Check for immune @@ -2910,18 +2916,18 @@ SpellMissInfo Unit::SpellHitResult(Unit* victim, SpellInfo const* spell, bool Ca case SPELL_DAMAGE_CLASS_MELEE: return MeleeSpellHitResult(victim, spell); case SPELL_DAMAGE_CLASS_NONE: - { - if (spell->SpellFamilyName) { - return SPELL_MISS_NONE; + if (spell->SpellFamilyName) + { + return SPELL_MISS_NONE; + } + // Xinef: apply DAMAGE_CLASS_MAGIC conditions to damaging DAMAGE_CLASS_NONE spells + for (uint8 i = EFFECT_0; i < MAX_SPELL_EFFECTS; ++i) + if (spell->Effects[i].Effect && spell->Effects[i].Effect != SPELL_EFFECT_SCHOOL_DAMAGE) + if (spell->Effects[i].ApplyAuraName != SPELL_AURA_PERIODIC_DAMAGE) + return SPELL_MISS_NONE; + [[fallthrough]]; } - // Xinef: apply DAMAGE_CLASS_MAGIC conditions to damaging DAMAGE_CLASS_NONE spells - for (uint8 i = EFFECT_0; i < MAX_SPELL_EFFECTS; ++i) - if (spell->Effects[i].Effect && spell->Effects[i].Effect != SPELL_EFFECT_SCHOOL_DAMAGE) - if (spell->Effects[i].ApplyAuraName != SPELL_AURA_PERIODIC_DAMAGE) - return SPELL_MISS_NONE; - [[fallthrough]]; - } case SPELL_DAMAGE_CLASS_MAGIC: return MagicSpellHitResult(victim, spell); } @@ -2934,8 +2940,8 @@ uint32 Unit::GetDefenseSkillValue(Unit const* target) const { // in PvP use full skill instead current skill value uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER) - ? ToPlayer()->GetMaxSkillValue(SKILL_DEFENSE) - : ToPlayer()->GetSkillValue(SKILL_DEFENSE); + ? ToPlayer()->GetMaxSkillValue(SKILL_DEFENSE) + : ToPlayer()->GetSkillValue(SKILL_DEFENSE); value += uint32(ToPlayer()->GetRatingBonusValue(CR_DEFENSE_SKILL)); return value; } @@ -3048,7 +3054,7 @@ float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victi case RANGED_ATTACK: crit = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE); break; - // Just for good manner + // Just for good manner default: crit = 0.0f; break; @@ -3116,21 +3122,28 @@ uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) // in PvP use full skill instead current skill value value = (target && target->IsControlledByPlayer()) - ? player->GetMaxSkillValue(skill) - : player->GetSkillValue(skill); + ? player->GetMaxSkillValue(skill) + : player->GetSkillValue(skill); // Modify value from ratings value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL)); switch (attType) { - case BASE_ATTACK: value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND)); break; - case OFF_ATTACK: value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND)); break; - case RANGED_ATTACK: value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED)); break; - default: break; + case BASE_ATTACK: + value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND)); + break; + case OFF_ATTACK: + value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND)); + break; + case RANGED_ATTACK: + value += uint32(player->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED)); + break; + default: + break; } } else value = GetUnitMeleeSkill(target); - return value; + return value; } void Unit::_DeleteRemovedAuras() @@ -3250,53 +3263,53 @@ void Unit::SetCurrentCastedSpell(Spell* pSpell) switch (CSpellType) { case CURRENT_GENERIC_SPELL: - { - // generic spells always break channeled not delayed spells - if (Spell* s = GetCurrentSpell(CURRENT_CHANNELED_SPELL)) - if (s->GetSpellInfo()->Id != 69051) // pussywizard: FoS, boss Devourer of Souls, Mirrored Soul, does not have any special attribute - InterruptSpell(CURRENT_CHANNELED_SPELL, false); - - // autorepeat breaking - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) { - // break autorepeat if not Auto Shot - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - m_AutoRepeatFirstCast = true; + // generic spells always break channeled not delayed spells + if (Spell* s = GetCurrentSpell(CURRENT_CHANNELED_SPELL)) + if (s->GetSpellInfo()->Id != 69051) // pussywizard: FoS, boss Devourer of Souls, Mirrored Soul, does not have any special attribute + InterruptSpell(CURRENT_CHANNELED_SPELL, false); + + // autorepeat breaking + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) + { + // break autorepeat if not Auto Shot + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + m_AutoRepeatFirstCast = true; + } + if (pSpell->GetCastTime() > 0) + AddUnitState(UNIT_STATE_CASTING); + + break; } - if (pSpell->GetCastTime() > 0) + case CURRENT_CHANNELED_SPELL: + { + // channel spells always break generic non-delayed and any channeled spells + InterruptSpell(CURRENT_GENERIC_SPELL, false); + InterruptSpell(CURRENT_CHANNELED_SPELL); + + // it also does break autorepeat if not Auto Shot + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && + m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); AddUnitState(UNIT_STATE_CASTING); - break; - } - case CURRENT_CHANNELED_SPELL: - { - // channel spells always break generic non-delayed and any channeled spells - InterruptSpell(CURRENT_GENERIC_SPELL, false); - InterruptSpell(CURRENT_CHANNELED_SPELL); - - // it also does break autorepeat if not Auto Shot - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && - m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != 75) - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - AddUnitState(UNIT_STATE_CASTING); - - break; - } - case CURRENT_AUTOREPEAT_SPELL: - { - // only Auto Shoot does not break anything - if (pSpell->m_spellInfo->Id != 75) - { - // generic autorepeats break generic non-delayed and channeled non-delayed spells - InterruptSpell(CURRENT_GENERIC_SPELL, false); - InterruptSpell(CURRENT_CHANNELED_SPELL, false); + break; } - // special action: set first cast flag - m_AutoRepeatFirstCast = true; + case CURRENT_AUTOREPEAT_SPELL: + { + // only Auto Shoot does not break anything + if (pSpell->m_spellInfo->Id != 75) + { + // generic autorepeats break generic non-delayed and channeled non-delayed spells + InterruptSpell(CURRENT_GENERIC_SPELL, false); + InterruptSpell(CURRENT_CHANNELED_SPELL, false); + } + // special action: set first cast flag + m_AutoRepeatFirstCast = true; - break; - } + break; + } default: // other spell types don't break anything now @@ -3319,8 +3332,8 @@ void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool wi //sLog->outDebug(LOG_FILTER_UNITS, "Interrupt spell for unit %u.", GetEntry()); Spell* spell = m_currentSpells[spellType]; if (spell - && (withDelayed || spell->getState() != SPELL_STATE_DELAYED) - && (withInstant || spell->GetCastTime() > 0 || spell->getState() == SPELL_STATE_CASTING)) // xinef: or spell is in casting state (channeled spells only) + && (withDelayed || spell->getState() != SPELL_STATE_DELAYED) + && (withInstant || spell->GetCastTime() > 0 || spell->getState() == SPELL_STATE_CASTING)) // xinef: or spell is in casting state (channeled spells only) { // for example, do not let self-stun aura interrupt itself if (!spell->IsInterruptable()) @@ -3358,8 +3371,8 @@ bool Unit::IsNonMeleeSpellCast(bool withDelayed, bool skipChanneled, bool skipAu // generic spells are cast when they are not finished and not delayed if (m_currentSpells[CURRENT_GENERIC_SPELL] && - (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && - (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED)) + (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && + (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED)) { if (!skipInstant || m_currentSpells[CURRENT_GENERIC_SPELL]->GetCastTime()) { @@ -3369,7 +3382,7 @@ bool Unit::IsNonMeleeSpellCast(bool withDelayed, bool skipChanneled, bool skipAu } // channeled spells may be delayed, but they are still considered cast if (!skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] && - (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)) + (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)) { if (!isAutoshoot || !m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->HasAttribute(SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS)) return true; @@ -3498,7 +3511,7 @@ void Unit::UpdateEnvironmentIfNeeded(const uint8 option) return; } - if (option <= 1 && GetExactDistSq(&m_last_environment_position) < 2.5f*2.5f) + if (option <= 1 && GetExactDistSq(&m_last_environment_position) < 2.5f * 2.5f) return; m_last_environment_position.Relocate(GetPositionX(), GetPositionY(), GetPositionZ()); @@ -3518,14 +3531,15 @@ void Unit::UpdateEnvironmentIfNeeded(const uint8 option) float x = GetPositionX(), y = GetPositionY(), z = GetPositionZ(); bool isInAir = true; float ground_z = z; - LiquidData liquidData; liquidData.level = INVALID_HEIGHT; + LiquidData liquidData; + liquidData.level = INVALID_HEIGHT; ZLiquidStatus liquidStatus = baseMap->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquidData); // IsInWater - bool enoughWater = (liquidData.level > INVALID_HEIGHT && liquidData.level > liquidData.depth_level && liquidData.level-liquidData.depth_level >= 1.5f); // also check if theres enough water - at least 2yd - m_last_isinwater_status = (liquidStatus & (LIQUID_MAP_IN_WATER|LIQUID_MAP_UNDER_WATER)) && enoughWater; - m_last_islittleabovewater_status = (liquidData.level > INVALID_HEIGHT && liquidData.level > liquidData.depth_level && liquidData.level <= z+3.0f && liquidData.level > z-1.0f); + bool enoughWater = (liquidData.level > INVALID_HEIGHT && liquidData.level > liquidData.depth_level && liquidData.level - liquidData.depth_level >= 1.5f); // also check if theres enough water - at least 2yd + m_last_isinwater_status = (liquidStatus & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER)) && enoughWater; + m_last_islittleabovewater_status = (liquidData.level > INVALID_HEIGHT && liquidData.level > liquidData.depth_level && liquidData.level <= z + 3.0f && liquidData.level > z - 1.0f); // IsUnderWater m_last_isunderwater_status = (liquidStatus & LIQUID_MAP_UNDER_WATER) && enoughWater; @@ -3578,7 +3592,7 @@ void Unit::UpdateEnvironmentIfNeeded(const uint8 option) // Refresh being in water if (m_last_isinwater_status) { - if (!c->CanFly() || z < liquidData.level-2.0f) + if (!c->CanFly() || z < liquidData.level - 2.0f) { if (!HasUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD) && c->CanSwim() && (!HasUnitMovementFlag(MOVEMENTFLAG_SWIMMING) || !HasUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY))) { @@ -3682,7 +3696,7 @@ void Unit::UpdateEnvironmentIfNeeded(const uint8 option) if (changed) propagateSpeedChange(); - if (!HasUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD) && canFallGround && !c->CanFly() && !c->IsFalling() && !m_last_isinwater_status && (c->GetUnitMovementFlags()&(MOVEMENTFLAG_CAN_FLY|MOVEMENTFLAG_DISABLE_GRAVITY|MOVEMENTFLAG_HOVER|MOVEMENTFLAG_SWIMMING)) == 0 && z - ground_z > 5.0f && z-ground_z < 80.0f) + if (!HasUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD) && canFallGround && !c->CanFly() && !c->IsFalling() && !m_last_isinwater_status && (c->GetUnitMovementFlags() & (MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_HOVER | MOVEMENTFLAG_SWIMMING)) == 0 && z - ground_z > 5.0f && z - ground_z < 80.0f) GetMotionMaster()->MoveFall(); m_is_updating_environment = false; @@ -3800,7 +3814,7 @@ Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 // correct cast item guid if needed if (castItemGUID != foundAura->GetCastItemGUID()) { - uint64* oldGUID = const_cast(&foundAura->m_castItemGuid); + uint64* oldGUID = const_cast(&foundAura->m_castItemGuid); *oldGUID = castItemGUID; } @@ -3827,10 +3841,10 @@ void Unit::_AddAura(UnitAura* aura, Unit* caster) if (aura->IsSingleTarget()) { ASSERT((IsInWorld() && !IsDuringRemoveFromWorld()) || (aura->GetCasterGUID() == GetGUID())); - /* @HACK: Player is not in world during loading auras. - * Single target auras are not saved or loaded from database - * but may be created as a result of aura links (player mounts with passengers) - */ + /* @HACK: Player is not in world during loading auras. + * Single target auras are not saved or loaded from database + * but may be created as a result of aura links (player mounts with passengers) + */ // register single target aura caster->GetSingleCastAuras().push_back(aura); @@ -3839,7 +3853,7 @@ void Unit::_AddAura(UnitAura* aura, Unit* caster) for (Unit::AuraList::iterator itr = scAuras.begin(); itr != scAuras.end();) { if ((*itr) != aura && - (*itr)->IsSingleTargetWith(aura)) + (*itr)->IsSingleTargetWith(aura)) { (*itr)->Remove(); itr = scAuras.begin(); @@ -3852,7 +3866,7 @@ void Unit::_AddAura(UnitAura* aura, Unit* caster) // creates aura application instance and registers it in lists // aura application effects are handled separately to prevent aura list corruption -AuraApplication * Unit::_CreateAuraApplication(Aura* aura, uint8 effMask) +AuraApplication* Unit::_CreateAuraApplication(Aura* aura, uint8 effMask) { // can't apply aura on unit which is going to be deleted - to not create a memory leak ASSERT(!m_cleanupDone); @@ -3872,7 +3886,7 @@ AuraApplication * Unit::_CreateAuraApplication(Aura* aura, uint8 effMask) Unit* caster = aura->GetCaster(); - AuraApplication * aurApp = new AuraApplication(this, caster, aura, effMask); + AuraApplication* aurApp = new AuraApplication(this, caster, aura, effMask); m_appliedAuras.insert(AuraApplicationMap::value_type(aurId, aurApp)); // xinef: do not insert our application to interruptible list if application target is not the owner (area auras) @@ -3894,17 +3908,17 @@ void Unit::_ApplyAuraEffect(Aura* aura, uint8 effIndex) { ASSERT(aura); ASSERT(aura->HasEffect(effIndex)); - AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()); + AuraApplication* aurApp = aura->GetApplicationOfTarget(GetGUID()); ASSERT(aurApp); if (!aurApp->GetEffectMask()) - _ApplyAura(aurApp, 1<_HandleEffect(effIndex, true); } // handles effects of aura application // should be done after registering aura in lists -void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask) +void Unit::_ApplyAura(AuraApplication* aurApp, uint8 effMask) { Aura* aura = aurApp->GetBase(); @@ -3913,7 +3927,7 @@ void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask) if (aurApp->GetRemoveMode()) return; - Unit * caster = aura->GetCaster(); + Unit* caster = aura->GetCaster(); // Update target aura state flag const SpellInfo* spellInfo = aura->GetSpellInfo(); @@ -3929,7 +3943,7 @@ void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask) } else if (caster) { - ConflagrateAuraStateDelayEvent *pEvent = new ConflagrateAuraStateDelayEvent(GetGUID(), caster->GetGUID()); + ConflagrateAuraStateDelayEvent* pEvent = new ConflagrateAuraStateDelayEvent(GetGUID(), caster->GetGUID()); m_Events.AddEvent(pEvent, m_Events.CalculateTime(700)); // intended 700ms delay before allowing to cast conflagrate } } @@ -3949,15 +3963,15 @@ void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask) // apply effects of the aura for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - if (effMask & 1<GetRemoveMode())) + if (effMask & 1 << i && (!aurApp->GetRemoveMode())) aurApp->_HandleEffect(i, true); } } // removes aura application from lists and unapplies effects -void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode) +void Unit::_UnapplyAura(AuraApplicationMap::iterator& i, AuraRemoveMode removeMode) { - AuraApplication * aurApp = i->second; + AuraApplication* aurApp = i->second; ASSERT(aurApp); ASSERT(!aurApp->GetRemoveMode()); ASSERT(aurApp->GetTarget() == this); @@ -4034,10 +4048,10 @@ void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMo // only way correctly remove all auras from list //if (removedAuras != m_removedAurasCount) new aura may be added - i = m_appliedAuras.begin(); + i = m_appliedAuras.begin(); } -void Unit::_UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode) +void Unit::_UnapplyAura(AuraApplication* aurApp, AuraRemoveMode removeMode) { // aura can be removed from unit only if it's applied on it, shouldn't happen ASSERT(aurApp->GetBase()->GetApplicationOfTarget(GetGUID()) == aurApp); @@ -4096,7 +4110,7 @@ void Unit::_RegisterAuraEffect(AuraEffect* aurEff, bool apply) } // All aura base removes should go threw this function! -void Unit::RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode) +void Unit::RemoveOwnedAura(AuraMap::iterator& i, AuraRemoveMode removeMode) { Aura* aura = i->second; ASSERT(!aura->IsRemoved()); @@ -4167,9 +4181,9 @@ Aura* Unit::GetOwnedAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUI return nullptr; } -void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode) +void Unit::RemoveAura(AuraApplicationMap::iterator& i, AuraRemoveMode mode) { - AuraApplication * aurApp = i->second; + AuraApplication* aurApp = i->second; // Do not remove aura which is already being removed if (aurApp->GetRemoveMode()) return; @@ -4197,7 +4211,7 @@ void Unit::RemoveAura(uint32 spellId, uint64 caster, uint8 reqEffMask, AuraRemov } } -void Unit::RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode) +void Unit::RemoveAura(AuraApplication* aurApp, AuraRemoveMode mode) { // we've special situation here, RemoveAura called while during aura removal // this kind of call is needed only when aura effect removal handler @@ -4236,7 +4250,7 @@ void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode) { if (aura->IsRemoved()) return; - if (AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID())) + if (AuraApplication* aurApp = aura->GetApplicationOfTarget(GetGUID())) RemoveAura(aurApp, mode); } @@ -4246,7 +4260,7 @@ void Unit::RemoveAurasDueToSpell(uint32 spellId, uint64 casterGUID, uint8 reqEff { Aura const* aura = iter->second->GetBase(); if (((aura->GetEffectMask() & reqEffMask) == reqEffMask) - && (!casterGUID || aura->GetCasterGUID() == casterGUID)) + && (!casterGUID || aura->GetCasterGUID() == casterGUID)) { RemoveAura(iter, removeMode); iter = m_appliedAuras.lower_bound(spellId); @@ -4297,36 +4311,36 @@ void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId switch (aura->GetSpellInfo()->SpellFamilyName) { case SPELLFAMILY_HUNTER: - { - // Noxious Stings - if (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x1000) { - if (Unit* caster = aura->GetCaster()) + // Noxious Stings + if (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x1000) { - if (AuraEffect *aureff = caster->GetAuraEffect(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS, SPELLFAMILY_HUNTER, 3521, 1)) + if (Unit* caster = aura->GetCaster()) { - if (Aura *noxious = Aura::TryCreate(aura->GetSpellInfo(), aura->GetEffectMask(), dispeller, caster)) + if (AuraEffect* aureff = caster->GetAuraEffect(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS, SPELLFAMILY_HUNTER, 3521, 1)) { - noxious->SetDuration(aura->GetDuration() * aureff->GetAmount() / 100); - if (aura->GetUnitOwner() ) - if (const std::vector *spell_triggered = sSpellMgr->GetSpellLinked(-int32(aura->GetId()))) - for (std::vector::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) - aura->GetUnitOwner()->RemoveAurasDueToSpell(*itr); + if (Aura* noxious = Aura::TryCreate(aura->GetSpellInfo(), aura->GetEffectMask(), dispeller, caster)) + { + noxious->SetDuration(aura->GetDuration() * aureff->GetAmount() / 100); + if (aura->GetUnitOwner() ) + if (const std::vector* spell_triggered = sSpellMgr->GetSpellLinked(-int32(aura->GetId()))) + for (std::vector::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) + aura->GetUnitOwner()->RemoveAurasDueToSpell(*itr); + } } } } + break; } - break; - } case SPELLFAMILY_DEATHKNIGHT: - { - // Icy Clutch, remove with Frost Fever - if (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x4000000) { - if (AuraEffect *aureff = GetAuraEffect(SPELL_AURA_MOD_DECREASE_SPEED, SPELLFAMILY_DEATHKNIGHT, 0, 0x40000, 0, casterGUID)) - RemoveAurasDueToSpell(aureff->GetId()); + // Icy Clutch, remove with Frost Fever + if (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x4000000) + { + if (AuraEffect* aureff = GetAuraEffect(SPELL_AURA_MOD_DECREASE_SPEED, SPELLFAMILY_DEATHKNIGHT, 0, 0x40000, 0, casterGUID)) + RemoveAurasDueToSpell(aureff->GetId()); + } } - } default: break; } @@ -4356,9 +4370,9 @@ void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit* { baseDamage[i] = aura->GetEffect(i)->GetBaseAmount(); damage[i] = aura->GetEffect(i)->GetAmount(); - effMask |= (1<GetEffect(i)->CanBeRecalculated()) - recalculateMask |= (1<GetBase(); - AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()); + AuraApplication* aurApp = aura->GetApplicationOfTarget(GetGUID()); ++iter; if (aura != except && (!casterGUID || aura->GetCasterGUID() == casterGUID) - && ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive()))) + && ((negative && !aurApp->IsPositive()) || (positive && aurApp->IsPositive()))) { uint32 removedAuras = m_removedAurasCount; RemoveAura(aurApp); @@ -4523,8 +4537,8 @@ void Unit::RemoveAurasWithInterruptFlags(uint32 flag, uint32 except) // interrupt channeled spell if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL]) if (spell->getState() == SPELL_STATE_CASTING - && (spell->m_spellInfo->ChannelInterruptFlags & flag) - && spell->m_spellInfo->Id != except) + && (spell->m_spellInfo->ChannelInterruptFlags & flag) + && spell->m_spellInfo->Id != except) InterruptNonMeleeSpells(false, spell->m_spellInfo->Id); UpdateInterruptMask(); @@ -4551,7 +4565,7 @@ void Unit::RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, ui void Unit::RemoveMovementImpairingAuras(bool withRoot) { if (withRoot) - RemoveAurasWithMechanic(1<second->GetBase(); if ((aura->GetSpellInfo()->GetAllEffectsMechanicMask() & mechanic_mask) && - (!aura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_CU_DONT_BREAK_STEALTH) || (aura->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARRIOR && (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x20)))) + (!aura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_CU_DONT_BREAK_STEALTH) || (aura->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARRIOR && (aura->GetSpellInfo()->SpellFamilyFlags[1] & 0x20)))) { RemoveAura(iter); continue; @@ -4613,9 +4627,9 @@ void Unit::RemoveAreaAurasDueToLeaveWorld() Aura* aura = iter->second; ++iter; Aura::ApplicationMap const& appMap = aura->GetApplicationMap(); - for (Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr!= appMap.end();) + for (Aura::ApplicationMap::const_iterator itr = appMap.begin(); itr != appMap.end();) { - AuraApplication * aurApp = itr->second; + AuraApplication* aurApp = itr->second; ++itr; Unit* target = aurApp->GetTarget(); if (target == this) @@ -4663,9 +4677,9 @@ void Unit::RemoveArenaAuras() AuraApplication const* aurApp = iter->second; Aura const* aura = aurApp->GetBase(); if (!aura->GetSpellInfo()->HasAttribute(SPELL_ATTR4_UNK21) // don't remove stances, shadowform, pally/hunter auras - && !aura->IsPassive() // don't remove passive auras - && !aura->IsArea() // don't remove area auras, eg pet talents affecting owner - && (aurApp->IsPositive() || IsPet() || !aura->GetSpellInfo()->HasAttribute(SPELL_ATTR3_DEATH_PERSISTENT))) // not negative death persistent auras + && !aura->IsPassive() // don't remove passive auras + && !aura->IsArea() // don't remove area auras, eg pet talents affecting owner + && (aurApp->IsPositive() || IsPet() || !aura->GetSpellInfo()->HasAttribute(SPELL_ATTR3_DEATH_PERSISTENT))) // not negative death persistent auras { RemoveAura(iter); } @@ -4888,7 +4902,7 @@ AuraEffect* Unit::GetAuraEffectDummy(uint32 spellid) const return nullptr; } -AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication * except) const +AuraApplication* Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const { AuraApplicationMapBounds range = m_appliedAuras.equal_range(spellId); for (; range.first != range.second; ++range.first) @@ -4909,16 +4923,16 @@ AuraApplication * Unit::GetAuraApplication(uint32 spellId, uint64 casterGUID, ui Aura* Unit::GetAura(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const { - AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask); + AuraApplication* aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask); return aurApp ? aurApp->GetBase() : nullptr; } -AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const +AuraApplication* Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const { uint32 rankSpell = sSpellMgr->GetFirstSpellInChain(spellId); while (rankSpell) { - if (AuraApplication * aurApp = GetAuraApplication(rankSpell, casterGUID, itemCasterGUID, reqEffMask, except)) + if (AuraApplication* aurApp = GetAuraApplication(rankSpell, casterGUID, itemCasterGUID, reqEffMask, except)) return aurApp; rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell); } @@ -4927,7 +4941,7 @@ AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 c Aura* Unit::GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID, uint64 itemCasterGUID, uint8 reqEffMask) const { - AuraApplication * aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask); + AuraApplication* aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask); return aurApp ? aurApp->GetBase() : nullptr; } @@ -4938,10 +4952,10 @@ void Unit::GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelCharges dispelMask &= ~(1 << DISPEL_DISEASE); bool positive = IsFriendlyTo(caster); - Unit::VisibleAuraMap const *visibleAuras = GetVisibleAuras(); + Unit::VisibleAuraMap const* visibleAuras = GetVisibleAuras(); for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr) { - Aura *aura = itr->second->GetBase(); + Aura* aura = itr->second->GetBase(); // don't try to remove passive auras if (aura->IsPassive()) @@ -5129,7 +5143,7 @@ uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, uint8 mode) { // Get auras with disease dispel type by caster if ((*i)->GetSpellInfo()->Dispel == DISPEL_DISEASE - && ((*i)->GetCasterGUID() == casterGUID || (*i)->GetCasterGUID() == drwGUID)) // if its caster or his dancing rune weapon + && ((*i)->GetCasterGUID() == casterGUID || (*i)->GetCasterGUID() == drwGUID)) // if its caster or his dancing rune weapon { ++diseases; @@ -5144,8 +5158,8 @@ uint32 Unit::GetDiseasesByCaster(uint64 casterGUID, uint8 mode) { Aura* aura = (*i)->GetBase(); if (aura && !aura->IsRemoved() && aura->GetDuration() > 0) - if ((aura->GetApplyTime() + aura->GetMaxDuration()/1000 + 8) > (time(nullptr) + aura->GetDuration()/1000)) - aura->SetDuration(aura->GetDuration()+3000); + if ((aura->GetApplyTime() + aura->GetMaxDuration() / 1000 + 8) > (time(nullptr) + aura->GetDuration() / 1000)) + aura->SetDuration(aura->GetDuration() + 3000); } } ++i; @@ -5419,7 +5433,7 @@ DynamicObject* Unit::GetDynObject(uint32 spellId) { if (m_dynObj.empty()) return nullptr; - for (DynObjectList::const_iterator i = m_dynObj.begin(); i != m_dynObj.end();++i) + for (DynObjectList::const_iterator i = m_dynObj.begin(); i != m_dynObj.end(); ++i) { DynamicObject* dynObj = *i; if (dynObj->GetSpellId() == spellId) @@ -5566,7 +5580,7 @@ void Unit::SendSpellNonMeleeReflectLog(SpellNonMeleeDamage* log, Unit* attacker) if (GetTypeId() != TYPEID_PLAYER) return; - WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size + WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16 + 4 + 4 + 4 + 1 + 4 + 4 + 1 + 1 + 4 + 4 + 1)); // we guess size data.append(log->target->GetPackGUID()); data.append(attacker->GetPackGUID()); data << uint32(log->SpellID); @@ -5586,7 +5600,7 @@ void Unit::SendSpellNonMeleeReflectLog(SpellNonMeleeDamage* log, Unit* attacker) void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log) { - WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size + WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16 + 4 + 4 + 4 + 1 + 4 + 4 + 1 + 1 + 4 + 4 + 1)); // we guess size data.append(log->target->GetPackGUID()); data.append(log->attacker->GetPackGUID()); data << uint32(log->SpellID); @@ -5620,7 +5634,7 @@ void Unit::SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damag void Unit::ProcDamageAndSpell(Unit* victim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellInfo const* procSpell, SpellInfo const* procAura) { - // Not much to do if no flags are set. + // Not much to do if no flags are set. if (procAttacker) ProcDamageAndSpellFor(false, victim, procAttacker, procExtra, attType, procSpell, amount, procAura); // Now go on with a victim's events'n'auras @@ -5677,7 +5691,7 @@ void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo) void Unit::SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo) { - WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1)); + WorldPacket data(SMSG_SPELLLOGMISS, (4 + 8 + 1 + 4 + 8 + 1)); data << uint32(spellID); data << uint64(GetGUID()); data << uint8(0); // can be 0 or 1 @@ -5691,7 +5705,7 @@ void Unit::SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo) void Unit::SendSpellDamageResist(Unit* target, uint32 spellId) { - WorldPacket data(SMSG_PROCRESIST, 8+8+4+1); + WorldPacket data(SMSG_PROCRESIST, 8 + 8 + 4 + 1); data << uint64(GetGUID()); data << uint64(target->GetGUID()); data << uint32(spellId); @@ -5701,7 +5715,7 @@ void Unit::SendSpellDamageResist(Unit* target, uint32 spellId) void Unit::SendSpellDamageImmune(Unit* target, uint32 spellId) { - WorldPacket data(SMSG_SPELLORDAMAGE_IMMUNE, 8+8+4+1); + WorldPacket data(SMSG_SPELLORDAMAGE_IMMUNE, 8 + 8 + 4 + 1); data << uint64(GetGUID()); data << uint64(target->GetGUID()); data << uint32(spellId); @@ -5716,7 +5730,7 @@ void Unit::SendAttackStateUpdate(CalcDamageInfo* damageInfo) #endif uint32 count = 1; - size_t maxsize = 4+5+5+4+4+1+4+4+4+4+4+1+4+4+4+4+4*12; + size_t maxsize = 4 + 5 + 5 + 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4 * 12; WorldPacket data(SMSG_ATTACKERSTATEUPDATE, maxsize); // we guess size data << uint32(damageInfo->HitInfo); data.append(damageInfo->attacker->GetPackGUID()); @@ -5798,11 +5812,11 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere int32 triggerAmount = triggeredByAura->GetAmount(); Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER - ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : nullptr; + ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : nullptr; uint32 triggered_spell_id = 0; uint32 cooldown_spell_id = 0; // for random trigger, will be one of the triggered spell to avoid repeatable triggers - // otherwise, it's the triggered_spell_id by default + // otherwise, it's the triggered_spell_id by default Unit* target = victim; int32 basepoints0 = 0; uint64 originalCaster = 0; @@ -5810,2071 +5824,2149 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere switch (dummySpell->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - switch (dummySpell->Id) { - // Overkill - case 58426: - { - triggered_spell_id = 58427; - break; - } - // Unstable Power - case 24658: - { - if (!procSpell || procSpell->Id == 24659) - return false; - // Need remove one 24659 aura - RemoveAuraFromStack(24659); - return true; - } - // Restless Strength - case 24661: - { - // Need remove one 24662 aura - RemoveAuraFromStack(24662); - return true; - } - // Mark of Malice - case 33493: - { - if (triggeredByAura->GetBase()->GetCharges() > 1) - return true; - - target = this; - triggered_spell_id = 33494; - break; - } - // Twisted Reflection (boss spell) - case 21063: - triggered_spell_id = 21064; - break; - // Vampiric Aura (boss spell) - case 38196: - { - basepoints0 = 3 * damage; // 300% - if (basepoints0 < 0) - return false; - - triggered_spell_id = 31285; - target = this; - break; - } - // Aura of Madness (Darkmoon Card: Madness trinket) - //===================================================== - // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior) - // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid) - // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid) - // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin) - // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes) - // 41005 Manic: +35 haste (spell, melee and ranged) (All classes) - // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter) - // 41011 Martyr Complex: +35 stamina (All classes) - // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) - // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) - case 39446: - { - if (GetTypeId() != TYPEID_PLAYER || !IsAlive()) - return false; - - // Select class defined buff - switch (getClass()) - { - case CLASS_PALADIN: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 - case CLASS_DRUID: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 - triggered_spell_id = RAND(39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409); - cooldown_spell_id = 39511; - break; - case CLASS_ROGUE: // 39511, 40997, 40998, 41002, 41005, 41011 - case CLASS_WARRIOR: // 39511, 40997, 40998, 41002, 41005, 41011 - case CLASS_DEATH_KNIGHT: - triggered_spell_id = RAND(39511, 40997, 40998, 41002, 41005, 41011); - cooldown_spell_id = 39511; - break; - case CLASS_PRIEST: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 - case CLASS_SHAMAN: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 - case CLASS_MAGE: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 - case CLASS_WARLOCK: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 - triggered_spell_id = RAND(40999, 41002, 41005, 41009, 41011, 41406, 41409); - cooldown_spell_id = 40999; - break; - case CLASS_HUNTER: // 40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409 - triggered_spell_id = RAND(40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409); - cooldown_spell_id = 40997; - break; - default: - return false; - } - - target = this; - if (roll_chance_i(10)) - ToPlayer()->Say("This is Madness!", LANG_UNIVERSAL); // TODO: It should be moved to database, shouldn't it? - break; - } - // Sunwell Exalted Caster Neck (??? neck) - // cast ??? Light's Wrath if Exalted by Aldor - // cast ??? Arcane Bolt if Exalted by Scryers - case 46569: - return false; // old unused version - // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck) - // cast 45479 Light's Wrath if Exalted by Aldor - // cast 45429 Arcane Bolt if Exalted by Scryers - case 45481: - { - Player* player = ToPlayer(); - if (!player) - return false; - - // Get Aldor reputation rank - if (player->GetReputationRank(932) == REP_EXALTED) - { - target = this; - triggered_spell_id = 45479; - break; - } - // Get Scryers reputation rank - if (player->GetReputationRank(934) == REP_EXALTED) - { - // triggered at positive/self casts also, current attack target used then - if (target && IsFriendlyTo(target)) - { - target = GetVictim(); - if (!target) - { - target = player->GetSelectedUnit(); - if (!target) - return false; - } - if (IsFriendlyTo(target)) - return false; - } - - triggered_spell_id = 45429; - break; - } - return false; - } - // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck) - // cast 45480 Light's Strength if Exalted by Aldor - // cast 45428 Arcane Strike if Exalted by Scryers - case 45482: - { - if (GetTypeId() != TYPEID_PLAYER) - return false; - - // Get Aldor reputation rank - if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) - { - target = this; - triggered_spell_id = 45480; - break; - } - // Get Scryers reputation rank - if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) - { - triggered_spell_id = 45428; - break; - } - return false; - } - // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck) - // cast 45431 Arcane Insight if Exalted by Aldor - // cast 45432 Light's Ward if Exalted by Scryers - case 45483: - { - if (GetTypeId() != TYPEID_PLAYER) - return false; - - // Get Aldor reputation rank - if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) - { - target = this; - triggered_spell_id = 45432; - break; - } - // Get Scryers reputation rank - if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) - { - target = this; - triggered_spell_id = 45431; - break; - } - return false; - } - // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck) - // cast 45478 Light's Salvation if Exalted by Aldor - // cast 45430 Arcane Surge if Exalted by Scryers - case 45484: - { - if (GetTypeId() != TYPEID_PLAYER) - return false; - - // Get Aldor reputation rank - if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) - { - target = this; - triggered_spell_id = 45478; - break; - } - // Get Scryers reputation rank - if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) - { - triggered_spell_id = 45430; - break; - } - return false; - } - // Kill command - case 58914: - { - // Remove aura stack from pet - RemoveAuraFromStack(58914); - Unit* owner = GetOwner(); - if (!owner) - return true; - // reduce the owner's aura stack - owner->RemoveAuraFromStack(34027); - return true; - } - // Vampiric Touch (generic, used by some boss) - case 52723: - case 60501: - { - triggered_spell_id = 52724; - basepoints0 = damage / 2; - target = this; - break; - } - // Divine purpose - case 31871: - case 31872: - { - // Roll chane - if (!victim || !victim->IsAlive() || !roll_chance_i(triggerAmount)) - return false; - - // Remove any stun effect on target - victim->RemoveAurasWithMechanic(1< RandomSpells; - switch (getClass()) - { - case CLASS_WARRIOR: - case CLASS_PALADIN: - case CLASS_DEATH_KNIGHT: - RandomSpells.push_back(71484); - RandomSpells.push_back(71491); - RandomSpells.push_back(71492); - break; - case CLASS_SHAMAN: - case CLASS_ROGUE: - RandomSpells.push_back(71486); - RandomSpells.push_back(71485); - RandomSpells.push_back(71492); - break; - case CLASS_DRUID: - RandomSpells.push_back(71484); - RandomSpells.push_back(71485); - RandomSpells.push_back(71492); - break; - case CLASS_HUNTER: - RandomSpells.push_back(71486); - RandomSpells.push_back(71491); - RandomSpells.push_back(71485); - break; - default: - return false; - } - if (RandomSpells.empty()) // shouldn't happen - return false; - - uint8 rand_spell = irand(0, (RandomSpells.size() - 1)); - CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster); - break; - } - case 71562: // Deathbringer's Will Heroic - { - if (GetTypeId() != TYPEID_PLAYER || HasSpellCooldown(71561)) - return false; - - AddSpellCooldown(71561, 0, cooldown); - - std::vector RandomSpells; - switch (getClass()) - { - case CLASS_WARRIOR: - case CLASS_PALADIN: - case CLASS_DEATH_KNIGHT: - RandomSpells.push_back(71561); - RandomSpells.push_back(71559); - RandomSpells.push_back(71560); - break; - case CLASS_SHAMAN: - case CLASS_ROGUE: - RandomSpells.push_back(71558); - RandomSpells.push_back(71556); - RandomSpells.push_back(71560); - break; - case CLASS_DRUID: - RandomSpells.push_back(71561); - RandomSpells.push_back(71556); - RandomSpells.push_back(71560); - break; - case CLASS_HUNTER: - RandomSpells.push_back(71558); - RandomSpells.push_back(71559); - RandomSpells.push_back(71556); - break; - default: - return false; - } - if (RandomSpells.empty()) // shouldn't happen - return false; - - uint8 rand_spell = irand(0, (RandomSpells.size() - 1)); - CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster); - break; - } - // Freya, Petrified Bark - case 62933: - case 62337: - { - if (!victim) - return false; - - int32 dmg = damage; - victim->CastCustomSpell(this, 62379, &dmg, 0, 0, true); - return true; - } - // Trial of the Champion, Earth Shield - case 67534: - { - const int32 dmg = (int32)damage; - CastCustomSpell(this, 67535, &dmg, nullptr, nullptr, true, 0, triggeredByAura, triggeredByAura->GetCasterGUID()); - return true; - } - // Trial of the Crusader, Faction Champions, Retaliation - case 65932: - { - // check attack comes not from behind - if (!victim || !HasInArc(M_PI, victim)) - return false; - - triggered_spell_id = 65934; - break; - } - // Pit of Saron, Tyrannus, Overlord's Brand - case 69172: // everything except for DoTs - { - if (!target) - return false; - if (Unit* caster = triggeredByAura->GetCaster()) - { - if (procFlag & (PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS|PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS)) - { - int32 dmg = 5.5f*damage; - target->CastCustomSpell(caster, 69190, &dmg, 0, 0, true); - } - else - { - if (caster->GetVictim()) - { - int32 dmg = damage; - target->CastCustomSpell(caster->GetVictim(), 69189, &dmg, 0, 0, true); - } - } - } - return true; - } - // Pit of Saron, Tyrannus, Overlord's Brand - case 69173: // only DoTs - { - if (!target) - return false; - if (Unit* caster = triggeredByAura->GetCaster()) - { - if (procEx & PROC_EX_INTERNAL_HOT) - { - int32 dmg = 5.5f*damage; - target->CastCustomSpell(caster, 69190, &dmg, 0, 0, true); - } - else - { - if (caster->GetVictim()) - { - int32 dmg = damage; - target->CastCustomSpell(caster->GetVictim(), 69189, &dmg, 0, 0, true); - } - } - } - return true; - } - // Icecrown Citadel, Lady Deathwhisper, Vampiric Might - case 70674: - { - if (Unit* caster = triggeredByAura->GetCaster()) - { - int32 dmg = 3*damage; - caster->CastCustomSpell(caster, 70677, &dmg, 0, 0, true); - } - return true; - } - // Item: Purified Shard of the Gods - case 69755: - { - triggered_spell_id = ((procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69733 : 69729); - break; - } - // Item: Shiny Shard of the Gods - case 69739: - { - triggered_spell_id = ((procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69734 : 69730); - break; - } - // VoA: Meteor Fists koralon - case 66725: - case 68161: - { - triggered_spell_id = 66765; // handled by spell_difficulty - break; - } - } - break; - } - case SPELLFAMILY_MAGE: - { - // Magic Absorption - if (dummySpell->SpellIconID == 459) // only this spell has SpellIconID == 459 and dummy aura - { - if (getPowerType() != POWER_MANA) - return false; - - // mana reward - basepoints0 = CalculatePct(int32(GetMaxPower(POWER_MANA)), triggerAmount); - target = this; - triggered_spell_id = 29442; - break; - } - // Hot Streak - if (dummySpell->SpellIconID == 2999) - { - if (effIndex != 0) - return false; - AuraEffect* counter = triggeredByAura->GetBase()->GetEffect(EFFECT_1); - if (!counter) - return true; - - // Count spell criticals in a row in second aura - if (procEx & PROC_EX_CRITICAL_HIT) - { - counter->SetAmount(counter->GetAmount() * 2); - if (counter->GetAmount() < 100) // not enough - return true; - // Crititcal counted -> roll chance - if (roll_chance_i(triggerAmount)) - CastSpell(this, 48108, true, castItem, triggeredByAura); - } - counter->SetAmount(25); - return true; - } - // Incanter's Regalia set (add trigger chance to Mana Shield) - if (dummySpell->SpellFamilyFlags[0] & 0x8000) - { - if (GetTypeId() != TYPEID_PLAYER) - return false; - - target = this; - triggered_spell_id = 37436; - break; - } - switch (dummySpell->Id) - { - // Glyph of Polymorph - case 56375: - { - if (!target) - return false; - target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed. - target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT); - target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH); - return true; - } - // Glyph of Icy Veins - case 56374: - { - RemoveAurasByType(SPELL_AURA_HASTE_SPELLS, 0, 0, true, false); - RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED); - return true; - } - // Glyph of Ice Block - case 56372: - { - Player* player = ToPlayer(); - if (!player) - return false; - - SpellCooldowns const cooldowns = player->GetSpellCooldowns(); - // remove cooldowns on all ranks of Frost Nova - for (SpellCooldowns::const_iterator itr = cooldowns.begin(); itr != cooldowns.end(); ++itr) - { - SpellInfo const* cdSpell = sSpellMgr->GetSpellInfo(itr->first); - // Frost Nova - if (cdSpell && cdSpell->SpellFamilyName == SPELLFAMILY_MAGE - && cdSpell->SpellFamilyFlags[0] & 0x00000040) - player->RemoveSpellCooldown(cdSpell->Id, true); - } - break; - } - } - break; - } - case SPELLFAMILY_WARRIOR: - { - switch (dummySpell->Id) - { - // Victorious - case 32216: - { - RemoveAura(dummySpell->Id); - return false; - } - } - - // Second Wind - if (dummySpell->SpellIconID == 1697) - { - // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example) - if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim) - return false; - // Need stun or root mechanic - if (!(procSpell->GetAllEffectsMechanicMask() & ((1<Id) { - case 29838: triggered_spell_id=29842; break; - case 29834: triggered_spell_id=29841; break; - case 42770: triggered_spell_id=42771; break; - default: - sLog->outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)", dummySpell->Id); - return false; - } - - target = this; - break; - } - break; - } - case SPELLFAMILY_WARLOCK: - { - // Seed of Corruption - if (dummySpell->SpellFamilyFlags[1] & 0x00000010) - { - if (procSpell && procSpell->SpellFamilyFlags[1] & 0x8000) - return false; - // if damage is more than need or target die from damage deal finish spell - if (triggeredByAura->GetAmount() <= int32(damage) || GetHealth() <= damage) - { - // remember guid before aura delete - uint64 casterGuid = triggeredByAura->GetCasterGUID(); - - // Remove aura (before cast for prevent infinite loop handlers) - RemoveAurasDueToSpell(triggeredByAura->GetId()); - - uint32 spell = sSpellMgr->GetSpellWithRank(27285, dummySpell->GetRank()); - - // Cast finish spell (triggeredByAura already not exist!) - if (Unit* caster = ObjectAccessor::GetUnit(*this, casterGuid)) - { - this->CastSpell(this, 37826, true); // VISUAL! - caster->CastSpell(this, spell, true, castItem); - } - - return true; // no hidden cooldown - } - - // Damage counting - triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage); - return true; - } - // Seed of Corruption (Mobs cast) - no die req - if (dummySpell->SpellFamilyFlags.IsEqual(0, 0, 0) && dummySpell->SpellIconID == 1932) - { - // if damage is more than need deal finish spell - if (triggeredByAura->GetAmount() <= int32(damage)) - { - // remember guid before aura delete - uint64 casterGuid = triggeredByAura->GetCasterGUID(); - - // Remove aura (before cast for prevent infinite loop handlers) - RemoveAurasDueToSpell(triggeredByAura->GetId()); - - // Cast finish spell (triggeredByAura already not exist!) - if (Unit* caster = ObjectAccessor::GetUnit(*this, casterGuid)) - { - this->CastSpell(this, 37826, true); // VISUAL! - caster->CastSpell(this, 32865, true, castItem); - } - return true; // no hidden cooldown - } - // Damage counting - triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage); - return true; - } - switch (dummySpell->Id) - { - // Nightfall - case 18094: - case 18095: - // Glyph of corruption - case 56218: - { - target = this; - triggered_spell_id = 17941; - break; - } - // Soul Leech - case 30293: - case 30295: - case 30296: - { - // Improved Soul Leech - AuraEffectList const& SoulLeechAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY); - for (Unit::AuraEffectList::const_iterator i = SoulLeechAuras.begin(); i != SoulLeechAuras.end(); ++i) - { - if ((*i)->GetId() == 54117 || (*i)->GetId() == 54118) + // Overkill + case 58426: { - if ((*i)->GetEffIndex() != 0) - continue; - basepoints0 = int32((*i)->GetAmount()); - target = GetGuardianPet(); - if (target) - { - // regen mana for pet - CastCustomSpell(target, 54607, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); - } - // regen mana for caster - CastCustomSpell(this, 59117, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); - // Get second aura of spell for replenishment effect on party - if (AuraEffect const* aurEff = (*i)->GetBase()->GetEffect(EFFECT_1)) - { - // Replenishment - roll chance - if (roll_chance_i(aurEff->GetAmount())) - { - CastSpell(this, 57669, true, castItem, triggeredByAura); - } - } + triggered_spell_id = 58427; break; } - } - // health - basepoints0 = CalculatePct(int32(damage), triggerAmount); - target = this; - triggered_spell_id = 30294; - break; - } - // Shadowflame (Voidheart Raiment set bonus) - case 37377: - { - triggered_spell_id = 37379; - break; - } - // Pet Healing (Corruptor Raiment or Rift Stalker Armor) - case 37381: - { - target = GetGuardianPet(); - if (!target) - return false; - - // heal amount - basepoints0 = CalculatePct(int32(damage), triggerAmount); - triggered_spell_id = 37382; - break; - } - // Shadowflame Hellfire (Voidheart Raiment set bonus) - case 39437: - { - triggered_spell_id = 37378; - break; - } - } - break; - } - case SPELLFAMILY_PRIEST: - { - // Body and Soul - if (dummySpell->SpellIconID == 2218) - { - // Proc only from Abolish desease on self cast - if (procSpell->Id != 552 || victim != this || !roll_chance_i(triggerAmount)) - return false; - triggered_spell_id = 64136; - target = this; - break; - } - switch (dummySpell->Id) - { - // Vampiric Embrace - case 15286: - { - if (!victim || !victim->IsAlive() || procSpell->SpellFamilyFlags[1] & 0x80000) - return false; - - // heal amount - int32 total = CalculatePct(int32(damage), triggerAmount); - int32 team = total / 5; - int32 self = total - team; - CastCustomSpell(this, 15290, &team, &self, NULL, true, castItem, triggeredByAura); - return true; // no hidden cooldown - } - // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen) - case 40438: - { - // Shadow Word: Pain - if (procSpell->SpellFamilyFlags[0] & 0x8000) - triggered_spell_id = 40441; - // Renew - else if (procSpell->SpellFamilyFlags[0] & 0x40) - triggered_spell_id = 40440; - else - return false; - - target = this; - break; - } - // Improved Shadowform - case 47570: - case 47569: - { - if (!roll_chance_i(triggerAmount)) - return false; - - RemoveMovementImpairingAuras(true); - break; - } - // Glyph of Dispel Magic - case 55677: - { - // Dispel Magic shares spellfamilyflag with abolish disease - if (procSpell->SpellIconID != 74) - return false; - if (!target || !target->IsFriendlyTo(this)) - return false; - - basepoints0 = int32(target->CountPctFromMaxHealth(triggerAmount)); - triggered_spell_id = 56131; - break; - } - // Oracle Healing Bonus ("Garments of the Oracle" set) - case 26169: - { - // heal amount - basepoints0 = int32(CalculatePct(damage, 10)); - target = this; - triggered_spell_id = 26170; - break; - } - // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set - case 39372: - { - if (!procSpell || (procSpell->GetSchoolMask() & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW)) == 0) - return false; - - // heal amount - basepoints0 = CalculatePct(int32(damage), triggerAmount); - target = this; - triggered_spell_id = 39373; - break; - } - // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus) - case 28809: - { - triggered_spell_id = 28810; - break; - } - // Priest T10 Healer 2P Bonus - case 70770: - // Flash Heal - if (procSpell->SpellFamilyFlags[0] & 0x800) - { - triggered_spell_id = 70772; - SpellInfo const* blessHealing = sSpellMgr->GetSpellInfo(triggered_spell_id); - if (!blessHealing || !victim) - return false; - basepoints0 = int32(CalculatePct(damage, triggerAmount) / (blessHealing->GetMaxDuration() / blessHealing->Effects[0].Amplitude)); - victim->CastDelayedSpellWithPeriodicAmount(this, triggered_spell_id, SPELL_AURA_PERIODIC_HEAL, basepoints0); - return true; - } - break; - } - break; - } - case SPELLFAMILY_DRUID: - { - switch (dummySpell->Id) - { - // Glyph of Innervate - case 54832: - { - if (procSpell->SpellIconID != 62) - return false; - - int32 mana_perc = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcValue(); - basepoints0 = int32(CalculatePct(GetCreatePowers(POWER_MANA), mana_perc) / 10); - triggered_spell_id = 54833; - target = this; - break; - } - // Glyph of Starfire - case 54845: - { - triggered_spell_id = 54846; - break; - } - // Glyph of Shred - case 54815: - { - if (!target) - return false; - - // try to find spell Rip on the target - if (AuraEffect const* AurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00800000, 0x0, 0x0, GetGUID())) - { - // Rip's max duration, note: spells which modifies Rip's duration also counted like Glyph of Rip - uint32 CountMin = AurEff->GetBase()->GetMaxDuration(); - - // just Rip's max duration without other spells - uint32 CountMax = AurEff->GetSpellInfo()->GetMaxDuration(); - - // add possible auras' and Glyph of Shred's max duration - CountMax += 3 * triggerAmount * IN_MILLISECONDS; // Glyph of Shred -> +6 seconds - CountMax += HasAura(54818) ? 4 * IN_MILLISECONDS : 0; // Glyph of Rip -> +4 seconds - CountMax += HasAura(60141) ? 4 * IN_MILLISECONDS : 0; // Rip Duration/Lacerate Damage -> +4 seconds - - // if min < max -> that means caster didn't cast 3 shred yet - // so set Rip's duration and max duration - if (CountMin < CountMax) + // Unstable Power + case 24658: { - AurEff->GetBase()->SetDuration(AurEff->GetBase()->GetDuration() + triggerAmount * IN_MILLISECONDS); - AurEff->GetBase()->SetMaxDuration(CountMin + triggerAmount * IN_MILLISECONDS); + if (!procSpell || procSpell->Id == 24659) + return false; + // Need remove one 24659 aura + RemoveAuraFromStack(24659); return true; } - } - // if not found Rip - return false; - } - // Glyph of Rake - case 54821: - { - if (procSpell->SpellVisual[0] == 750 && procSpell->Effects[1].ApplyAuraName == 3) - { - if (target && target->GetTypeId() == TYPEID_UNIT) + // Restless Strength + case 24661: { - triggered_spell_id = 54820; + // Need remove one 24662 aura + RemoveAuraFromStack(24662); + return true; + } + // Mark of Malice + case 33493: + { + if (triggeredByAura->GetBase()->GetCharges() > 1) + return true; + + target = this; + triggered_spell_id = 33494; break; } - } - return false; - } - // Leader of the Pack - case 24932: - { - if (triggerAmount <= 0) - return false; - basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); - target = this; - triggered_spell_id = 34299; - if (triggeredByAura->GetCasterGUID() != GetGUID()) + // Twisted Reflection (boss spell) + case 21063: + triggered_spell_id = 21064; break; - int32 basepoints1 = CalculatePct(GetMaxPower(Powers(POWER_MANA)), triggerAmount * 2); - // Improved Leader of the Pack - // Check cooldown of heal spell cooldown - if (GetTypeId() == TYPEID_PLAYER && !ToPlayer()->HasSpellCooldown(34299)) - CastCustomSpell(this, 68285, &basepoints1, 0, 0, true, 0, triggeredByAura); - break; - } - // Healing Touch (Dreamwalker Raiment set) - case 28719: - { - // mana back - basepoints0 = int32(CalculatePct(procSpell->ManaCost, 30)); - target = this; - triggered_spell_id = 28742; - break; - } - // Glyph of Rejuvenation - case 54754: - { - if (!victim || !victim->HealthBelowPct(uint32(triggerAmount))) - return false; - basepoints0 = CalculatePct(int32(damage), triggerAmount); - triggered_spell_id = 54755; - break; - } - // Healing Touch Refund (Idol of Longevity trinket) - case 28847: - { - target = this; - triggered_spell_id = 28848; - break; - } - // Mana Restore (Malorne Raiment set / Malorne Regalia set) - case 37288: - case 37295: - { - target = this; - triggered_spell_id = 37238; - break; - } - // Druid Tier 6 Trinket - case 40442: - { - float chance; + // Vampiric Aura (boss spell) + case 38196: + { + basepoints0 = 3 * damage; // 300% + if (basepoints0 < 0) + return false; - // Starfire - if (procSpell->SpellFamilyFlags[0] & 0x4) - { - triggered_spell_id = 40445; - chance = 25.0f; - } - // Rejuvenation - else if (procSpell->SpellFamilyFlags[0] & 0x10) - { - triggered_spell_id = 40446; - chance = 25.0f; - } - // Mangle (Bear) and Mangle (Cat) - else if (procSpell->SpellFamilyFlags[1] & 0x00000440) - { - triggered_spell_id = 40452; - chance = 40.0f; - } - else - return false; + triggered_spell_id = 31285; + target = this; + break; + } + // Aura of Madness (Darkmoon Card: Madness trinket) + //===================================================== + // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior) + // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid) + // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid) + // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin) + // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes) + // 41005 Manic: +35 haste (spell, melee and ranged) (All classes) + // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter) + // 41011 Martyr Complex: +35 stamina (All classes) + // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) + // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) + case 39446: + { + if (GetTypeId() != TYPEID_PLAYER || !IsAlive()) + return false; - if (!roll_chance_f(chance)) - return false; + // Select class defined buff + switch (getClass()) + { + case CLASS_PALADIN: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 + case CLASS_DRUID: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 + triggered_spell_id = RAND(39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409); + cooldown_spell_id = 39511; + break; + case CLASS_ROGUE: // 39511, 40997, 40998, 41002, 41005, 41011 + case CLASS_WARRIOR: // 39511, 40997, 40998, 41002, 41005, 41011 + case CLASS_DEATH_KNIGHT: + triggered_spell_id = RAND(39511, 40997, 40998, 41002, 41005, 41011); + cooldown_spell_id = 39511; + break; + case CLASS_PRIEST: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 + case CLASS_SHAMAN: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 + case CLASS_MAGE: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 + case CLASS_WARLOCK: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 + triggered_spell_id = RAND(40999, 41002, 41005, 41009, 41011, 41406, 41409); + cooldown_spell_id = 40999; + break; + case CLASS_HUNTER: // 40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409 + triggered_spell_id = RAND(40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409); + cooldown_spell_id = 40997; + break; + default: + return false; + } - target = this; - break; - } - // Maim Interrupt - case 44835: - { - // Deadly Interrupt Effect - triggered_spell_id = 32747; - break; - } - // Item - Druid T10 Restoration 4P Bonus (Rejuvenation) - case 70664: - { - // xinef: proc only from normal Rejuvenation, and proc rejuvenation - if (!victim || !procSpell || procSpell->SpellIconID != 64) - return false; + target = this; + if (roll_chance_i(10)) + ToPlayer()->Say("This is Madness!", LANG_UNIVERSAL); // TODO: It should be moved to database, shouldn't it? + break; + } + // Sunwell Exalted Caster Neck (??? neck) + // cast ??? Light's Wrath if Exalted by Aldor + // cast ??? Arcane Bolt if Exalted by Scryers + case 46569: + return false; // old unused version + // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck) + // cast 45479 Light's Wrath if Exalted by Aldor + // cast 45429 Arcane Bolt if Exalted by Scryers + case 45481: + { + Player* player = ToPlayer(); + if (!player) + return false; - Player* caster = ToPlayer(); - if (!caster) - return false; - if (!caster->GetGroup() && victim == this) - return false; - - CastCustomSpell(70691, SPELLVALUE_BASE_POINT0, damage, victim, true); - return true; - } - } - // Eclipse - if (dummySpell->SpellIconID == 2856 && GetTypeId() == TYPEID_PLAYER) - { - if (!procSpell || effIndex != 0) - return false; - - bool isWrathSpell = (procSpell->SpellFamilyFlags[0] & 1); - - if (!roll_chance_f(dummySpell->ProcChance * (isWrathSpell ? 0.6f : 1.0f))) - return false; - - target = this; - if (target->HasAura(isWrathSpell ? 48517 : 48518)) - return false; - - triggered_spell_id = isWrathSpell ? 48518 : 48517; - break; - } - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - } - case SPELLFAMILY_ROGUE: - { - switch(dummySpell->Id) - { - // Glyph of Backstab - case 56800: - { - if (victim) - if (AuraEffect* aurEff = victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x100000, 0, 0, GetGUID())) - if (Aura* aur = aurEff->GetBase()) - if (!aur->IsRemoved() && aur->GetDuration() > 0) - if ((aur->GetApplyTime() + aur->GetMaxDuration()/1000 + 5) > (time(nullptr) + aur->GetDuration()/1000) ) + // Get Aldor reputation rank + if (player->GetReputationRank(932) == REP_EXALTED) + { + target = this; + triggered_spell_id = 45479; + break; + } + // Get Scryers reputation rank + if (player->GetReputationRank(934) == REP_EXALTED) + { + // triggered at positive/self casts also, current attack target used then + if (target && IsFriendlyTo(target)) + { + target = GetVictim(); + if (!target) { - aur->SetDuration(aur->GetDuration()+2000); - return true; + target = player->GetSelectedUnit(); + if (!target) + return false; } - return false; + if (IsFriendlyTo(target)) + return false; + } + + triggered_spell_id = 45429; + break; + } + return false; + } + // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck) + // cast 45480 Light's Strength if Exalted by Aldor + // cast 45428 Arcane Strike if Exalted by Scryers + case 45482: + { + if (GetTypeId() != TYPEID_PLAYER) + return false; + + // Get Aldor reputation rank + if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) + { + target = this; + triggered_spell_id = 45480; + break; + } + // Get Scryers reputation rank + if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) + { + triggered_spell_id = 45428; + break; + } + return false; + } + // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck) + // cast 45431 Arcane Insight if Exalted by Aldor + // cast 45432 Light's Ward if Exalted by Scryers + case 45483: + { + if (GetTypeId() != TYPEID_PLAYER) + return false; + + // Get Aldor reputation rank + if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) + { + target = this; + triggered_spell_id = 45432; + break; + } + // Get Scryers reputation rank + if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) + { + target = this; + triggered_spell_id = 45431; + break; + } + return false; + } + // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck) + // cast 45478 Light's Salvation if Exalted by Aldor + // cast 45430 Arcane Surge if Exalted by Scryers + case 45484: + { + if (GetTypeId() != TYPEID_PLAYER) + return false; + + // Get Aldor reputation rank + if (ToPlayer()->GetReputationRank(932) == REP_EXALTED) + { + target = this; + triggered_spell_id = 45478; + break; + } + // Get Scryers reputation rank + if (ToPlayer()->GetReputationRank(934) == REP_EXALTED) + { + triggered_spell_id = 45430; + break; + } + return false; + } + // Kill command + case 58914: + { + // Remove aura stack from pet + RemoveAuraFromStack(58914); + Unit* owner = GetOwner(); + if (!owner) + return true; + // reduce the owner's aura stack + owner->RemoveAuraFromStack(34027); + return true; + } + // Vampiric Touch (generic, used by some boss) + case 52723: + case 60501: + { + triggered_spell_id = 52724; + basepoints0 = damage / 2; + target = this; + break; + } + // Divine purpose + case 31871: + case 31872: + { + // Roll chane + if (!victim || !victim->IsAlive() || !roll_chance_i(triggerAmount)) + return false; + + // Remove any stun effect on target + victim->RemoveAurasWithMechanic(1 << MECHANIC_STUN, AURA_REMOVE_BY_ENEMY_SPELL); + return true; + } + // Glyph of Life Tap + case 63320: + { + triggered_spell_id = 63321; // Life Tap + break; + } + case 71519: // Deathbringer's Will Normal + { + if (GetTypeId() != TYPEID_PLAYER || HasSpellCooldown(71484)) + return false; + + AddSpellCooldown(71484, 0, cooldown); + + std::vector RandomSpells; + switch (getClass()) + { + case CLASS_WARRIOR: + case CLASS_PALADIN: + case CLASS_DEATH_KNIGHT: + RandomSpells.push_back(71484); + RandomSpells.push_back(71491); + RandomSpells.push_back(71492); + break; + case CLASS_SHAMAN: + case CLASS_ROGUE: + RandomSpells.push_back(71486); + RandomSpells.push_back(71485); + RandomSpells.push_back(71492); + break; + case CLASS_DRUID: + RandomSpells.push_back(71484); + RandomSpells.push_back(71485); + RandomSpells.push_back(71492); + break; + case CLASS_HUNTER: + RandomSpells.push_back(71486); + RandomSpells.push_back(71491); + RandomSpells.push_back(71485); + break; + default: + return false; + } + if (RandomSpells.empty()) // shouldn't happen + return false; + + uint8 rand_spell = irand(0, (RandomSpells.size() - 1)); + CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster); + break; + } + case 71562: // Deathbringer's Will Heroic + { + if (GetTypeId() != TYPEID_PLAYER || HasSpellCooldown(71561)) + return false; + + AddSpellCooldown(71561, 0, cooldown); + + std::vector RandomSpells; + switch (getClass()) + { + case CLASS_WARRIOR: + case CLASS_PALADIN: + case CLASS_DEATH_KNIGHT: + RandomSpells.push_back(71561); + RandomSpells.push_back(71559); + RandomSpells.push_back(71560); + break; + case CLASS_SHAMAN: + case CLASS_ROGUE: + RandomSpells.push_back(71558); + RandomSpells.push_back(71556); + RandomSpells.push_back(71560); + break; + case CLASS_DRUID: + RandomSpells.push_back(71561); + RandomSpells.push_back(71556); + RandomSpells.push_back(71560); + break; + case CLASS_HUNTER: + RandomSpells.push_back(71558); + RandomSpells.push_back(71559); + RandomSpells.push_back(71556); + break; + default: + return false; + } + if (RandomSpells.empty()) // shouldn't happen + return false; + + uint8 rand_spell = irand(0, (RandomSpells.size() - 1)); + CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster); + break; + } + // Freya, Petrified Bark + case 62933: + case 62337: + { + if (!victim) + return false; + + int32 dmg = damage; + victim->CastCustomSpell(this, 62379, &dmg, 0, 0, true); + return true; + } + // Trial of the Champion, Earth Shield + case 67534: + { + const int32 dmg = (int32)damage; + CastCustomSpell(this, 67535, &dmg, nullptr, nullptr, true, 0, triggeredByAura, triggeredByAura->GetCasterGUID()); + return true; + } + // Trial of the Crusader, Faction Champions, Retaliation + case 65932: + { + // check attack comes not from behind + if (!victim || !HasInArc(M_PI, victim)) + return false; + + triggered_spell_id = 65934; + break; + } + // Pit of Saron, Tyrannus, Overlord's Brand + case 69172: // everything except for DoTs + { + if (!target) + return false; + if (Unit* caster = triggeredByAura->GetCaster()) + { + if (procFlag & (PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS)) + { + int32 dmg = 5.5f * damage; + target->CastCustomSpell(caster, 69190, &dmg, 0, 0, true); + } + else + { + if (caster->GetVictim()) + { + int32 dmg = damage; + target->CastCustomSpell(caster->GetVictim(), 69189, &dmg, 0, 0, true); + } + } + } + return true; + } + // Pit of Saron, Tyrannus, Overlord's Brand + case 69173: // only DoTs + { + if (!target) + return false; + if (Unit* caster = triggeredByAura->GetCaster()) + { + if (procEx & PROC_EX_INTERNAL_HOT) + { + int32 dmg = 5.5f * damage; + target->CastCustomSpell(caster, 69190, &dmg, 0, 0, true); + } + else + { + if (caster->GetVictim()) + { + int32 dmg = damage; + target->CastCustomSpell(caster->GetVictim(), 69189, &dmg, 0, 0, true); + } + } + } + return true; + } + // Icecrown Citadel, Lady Deathwhisper, Vampiric Might + case 70674: + { + if (Unit* caster = triggeredByAura->GetCaster()) + { + int32 dmg = 3 * damage; + caster->CastCustomSpell(caster, 70677, &dmg, 0, 0, true); + } + return true; + } + // Item: Purified Shard of the Gods + case 69755: + { + triggered_spell_id = ((procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69733 : 69729); + break; + } + // Item: Shiny Shard of the Gods + case 69739: + { + triggered_spell_id = ((procFlag & PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS) ? 69734 : 69730); + break; + } + // VoA: Meteor Fists koralon + case 66725: + case 68161: + { + triggered_spell_id = 66765; // handled by spell_difficulty + break; + } } - // Deadly Throw Interrupt - case 32748: + break; + } + case SPELLFAMILY_MAGE: + { + // Magic Absorption + if (dummySpell->SpellIconID == 459) // only this spell has SpellIconID == 459 and dummy aura { - // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw - if (this == victim) + if (getPowerType() != POWER_MANA) return false; - triggered_spell_id = 32747; + // mana reward + basepoints0 = CalculatePct(int32(GetMaxPower(POWER_MANA)), triggerAmount); + target = this; + triggered_spell_id = 29442; break; } - } - // Master of subtlety - if( dummySpell->SpellIconID == 2114 ) - { - triggered_spell_id = 31665; - basepoints0 = triggerAmount; - break; - } - // Cut to the Chase - if (dummySpell->SpellIconID == 2909) - { - // "refresh your Slice and Dice duration to its 5 combo point maximum" - // lookup Slice and Dice - if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_ROGUE, 0x40000, 0, 0)) + // Hot Streak + if (dummySpell->SpellIconID == 2999) { - aur->GetBase()->SetDuration(aur->GetSpellInfo()->GetMaxDuration(), true); + if (effIndex != 0) + return false; + AuraEffect* counter = triggeredByAura->GetBase()->GetEffect(EFFECT_1); + if (!counter) + return true; + + // Count spell criticals in a row in second aura + if (procEx & PROC_EX_CRITICAL_HIT) + { + counter->SetAmount(counter->GetAmount() * 2); + if (counter->GetAmount() < 100) // not enough + return true; + // Crititcal counted -> roll chance + if (roll_chance_i(triggerAmount)) + CastSpell(this, 48108, true, castItem, triggeredByAura); + } + counter->SetAmount(25); return true; } - return false; - } - // Deadly Brew - else if (dummySpell->SpellIconID == 2963) - { - triggered_spell_id = 3409; + // Incanter's Regalia set (add trigger chance to Mana Shield) + if (dummySpell->SpellFamilyFlags[0] & 0x8000) + { + if (GetTypeId() != TYPEID_PLAYER) + return false; + + target = this; + triggered_spell_id = 37436; + break; + } + switch (dummySpell->Id) + { + // Glyph of Polymorph + case 56375: + { + if (!target) + return false; + target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE, 0, target->GetAura(32409)); // SW:D shall not be removed. + target->RemoveAurasByType(SPELL_AURA_PERIODIC_DAMAGE_PERCENT); + target->RemoveAurasByType(SPELL_AURA_PERIODIC_LEECH); + return true; + } + // Glyph of Icy Veins + case 56374: + { + RemoveAurasByType(SPELL_AURA_HASTE_SPELLS, 0, 0, true, false); + RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED); + return true; + } + // Glyph of Ice Block + case 56372: + { + Player* player = ToPlayer(); + if (!player) + return false; + + SpellCooldowns const cooldowns = player->GetSpellCooldowns(); + // remove cooldowns on all ranks of Frost Nova + for (SpellCooldowns::const_iterator itr = cooldowns.begin(); itr != cooldowns.end(); ++itr) + { + SpellInfo const* cdSpell = sSpellMgr->GetSpellInfo(itr->first); + // Frost Nova + if (cdSpell && cdSpell->SpellFamilyName == SPELLFAMILY_MAGE + && cdSpell->SpellFamilyFlags[0] & 0x00000040) + player->RemoveSpellCooldown(cdSpell->Id, true); + } + break; + } + } break; } - // Quick Recovery - else if (dummySpell->SpellIconID == 2116) + case SPELLFAMILY_WARRIOR: { - if (!procSpell) - return false; + switch (dummySpell->Id) + { + // Victorious + case 32216: + { + RemoveAura(dummySpell->Id); + return false; + } + } - // energy cost save - basepoints0 = CalculatePct(int32(procSpell->ManaCost), triggerAmount); - if (basepoints0 <= 0) - return false; + // Second Wind + if (dummySpell->SpellIconID == 1697) + { + // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example) + if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) || this == victim) + return false; + // Need stun or root mechanic + if (!(procSpell->GetAllEffectsMechanicMask() & ((1 << MECHANIC_ROOT) | (1 << MECHANIC_STUN)))) + return false; - target = this; - triggered_spell_id = 31663; + switch (dummySpell->Id) + { + case 29838: + triggered_spell_id = 29842; + break; + case 29834: + triggered_spell_id = 29841; + break; + case 42770: + triggered_spell_id = 42771; + break; + default: + sLog->outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)", dummySpell->Id); + return false; + } + + target = this; + break; + } break; } - break; - } - case SPELLFAMILY_HUNTER: - { - switch (dummySpell->SpellIconID) + case SPELLFAMILY_WARLOCK: { - case 2236: // Thrill of the Hunt + // Seed of Corruption + if (dummySpell->SpellFamilyFlags[1] & 0x00000010) + { + if (procSpell && procSpell->SpellFamilyFlags[1] & 0x8000) + return false; + // if damage is more than need or target die from damage deal finish spell + if (triggeredByAura->GetAmount() <= int32(damage) || GetHealth() <= damage) + { + // remember guid before aura delete + uint64 casterGuid = triggeredByAura->GetCasterGUID(); + + // Remove aura (before cast for prevent infinite loop handlers) + RemoveAurasDueToSpell(triggeredByAura->GetId()); + + uint32 spell = sSpellMgr->GetSpellWithRank(27285, dummySpell->GetRank()); + + // Cast finish spell (triggeredByAura already not exist!) + if (Unit* caster = ObjectAccessor::GetUnit(*this, casterGuid)) + { + this->CastSpell(this, 37826, true); // VISUAL! + caster->CastSpell(this, spell, true, castItem); + } + + return true; // no hidden cooldown + } + + // Damage counting + triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage); + return true; + } + // Seed of Corruption (Mobs cast) - no die req + if (dummySpell->SpellFamilyFlags.IsEqual(0, 0, 0) && dummySpell->SpellIconID == 1932) + { + // if damage is more than need deal finish spell + if (triggeredByAura->GetAmount() <= int32(damage)) + { + // remember guid before aura delete + uint64 casterGuid = triggeredByAura->GetCasterGUID(); + + // Remove aura (before cast for prevent infinite loop handlers) + RemoveAurasDueToSpell(triggeredByAura->GetId()); + + // Cast finish spell (triggeredByAura already not exist!) + if (Unit* caster = ObjectAccessor::GetUnit(*this, casterGuid)) + { + this->CastSpell(this, 37826, true); // VISUAL! + caster->CastSpell(this, 32865, true, castItem); + } + return true; // no hidden cooldown + } + // Damage counting + triggeredByAura->SetAmount(triggeredByAura->GetAmount() - damage); + return true; + } + switch (dummySpell->Id) + { + // Nightfall + case 18094: + case 18095: + // Glyph of corruption + case 56218: + { + target = this; + triggered_spell_id = 17941; + break; + } + // Soul Leech + case 30293: + case 30295: + case 30296: + { + // Improved Soul Leech + AuraEffectList const& SoulLeechAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY); + for (Unit::AuraEffectList::const_iterator i = SoulLeechAuras.begin(); i != SoulLeechAuras.end(); ++i) + { + if ((*i)->GetId() == 54117 || (*i)->GetId() == 54118) + { + if ((*i)->GetEffIndex() != 0) + continue; + basepoints0 = int32((*i)->GetAmount()); + target = GetGuardianPet(); + if (target) + { + // regen mana for pet + CastCustomSpell(target, 54607, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); + } + // regen mana for caster + CastCustomSpell(this, 59117, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); + // Get second aura of spell for replenishment effect on party + if (AuraEffect const* aurEff = (*i)->GetBase()->GetEffect(EFFECT_1)) + { + // Replenishment - roll chance + if (roll_chance_i(aurEff->GetAmount())) + { + CastSpell(this, 57669, true, castItem, triggeredByAura); + } + } + break; + } + } + // health + basepoints0 = CalculatePct(int32(damage), triggerAmount); + target = this; + triggered_spell_id = 30294; + break; + } + // Shadowflame (Voidheart Raiment set bonus) + case 37377: + { + triggered_spell_id = 37379; + break; + } + // Pet Healing (Corruptor Raiment or Rift Stalker Armor) + case 37381: + { + target = GetGuardianPet(); + if (!target) + return false; + + // heal amount + basepoints0 = CalculatePct(int32(damage), triggerAmount); + triggered_spell_id = 37382; + break; + } + // Shadowflame Hellfire (Voidheart Raiment set bonus) + case 39437: + { + triggered_spell_id = 37378; + break; + } + } + break; + } + case SPELLFAMILY_PRIEST: + { + // Body and Soul + if (dummySpell->SpellIconID == 2218) + { + // Proc only from Abolish desease on self cast + if (procSpell->Id != 552 || victim != this || !roll_chance_i(triggerAmount)) + return false; + triggered_spell_id = 64136; + target = this; + break; + } + switch (dummySpell->Id) + { + // Vampiric Embrace + case 15286: + { + if (!victim || !victim->IsAlive() || procSpell->SpellFamilyFlags[1] & 0x80000) + return false; + + // heal amount + int32 total = CalculatePct(int32(damage), triggerAmount); + int32 team = total / 5; + int32 self = total - team; + CastCustomSpell(this, 15290, &team, &self, NULL, true, castItem, triggeredByAura); + return true; // no hidden cooldown + } + // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen) + case 40438: + { + // Shadow Word: Pain + if (procSpell->SpellFamilyFlags[0] & 0x8000) + triggered_spell_id = 40441; + // Renew + else if (procSpell->SpellFamilyFlags[0] & 0x40) + triggered_spell_id = 40440; + else + return false; + + target = this; + break; + } + // Improved Shadowform + case 47570: + case 47569: + { + if (!roll_chance_i(triggerAmount)) + return false; + + RemoveMovementImpairingAuras(true); + break; + } + // Glyph of Dispel Magic + case 55677: + { + // Dispel Magic shares spellfamilyflag with abolish disease + if (procSpell->SpellIconID != 74) + return false; + if (!target || !target->IsFriendlyTo(this)) + return false; + + basepoints0 = int32(target->CountPctFromMaxHealth(triggerAmount)); + triggered_spell_id = 56131; + break; + } + // Oracle Healing Bonus ("Garments of the Oracle" set) + case 26169: + { + // heal amount + basepoints0 = int32(CalculatePct(damage, 10)); + target = this; + triggered_spell_id = 26170; + break; + } + // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set + case 39372: + { + if (!procSpell || (procSpell->GetSchoolMask() & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW)) == 0) + return false; + + // heal amount + basepoints0 = CalculatePct(int32(damage), triggerAmount); + target = this; + triggered_spell_id = 39373; + break; + } + // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus) + case 28809: + { + triggered_spell_id = 28810; + break; + } + // Priest T10 Healer 2P Bonus + case 70770: + // Flash Heal + if (procSpell->SpellFamilyFlags[0] & 0x800) + { + triggered_spell_id = 70772; + SpellInfo const* blessHealing = sSpellMgr->GetSpellInfo(triggered_spell_id); + if (!blessHealing || !victim) + return false; + basepoints0 = int32(CalculatePct(damage, triggerAmount) / (blessHealing->GetMaxDuration() / blessHealing->Effects[0].Amplitude)); + victim->CastDelayedSpellWithPeriodicAmount(this, triggered_spell_id, SPELL_AURA_PERIODIC_HEAL, basepoints0); + return true; + } + break; + } + break; + } + case SPELLFAMILY_DRUID: + { + switch (dummySpell->Id) + { + // Glyph of Innervate + case 54832: + { + if (procSpell->SpellIconID != 62) + return false; + + int32 mana_perc = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcValue(); + basepoints0 = int32(CalculatePct(GetCreatePowers(POWER_MANA), mana_perc) / 10); + triggered_spell_id = 54833; + target = this; + break; + } + // Glyph of Starfire + case 54845: + { + triggered_spell_id = 54846; + break; + } + // Glyph of Shred + case 54815: + { + if (!target) + return false; + + // try to find spell Rip on the target + if (AuraEffect const* AurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00800000, 0x0, 0x0, GetGUID())) + { + // Rip's max duration, note: spells which modifies Rip's duration also counted like Glyph of Rip + uint32 CountMin = AurEff->GetBase()->GetMaxDuration(); + + // just Rip's max duration without other spells + uint32 CountMax = AurEff->GetSpellInfo()->GetMaxDuration(); + + // add possible auras' and Glyph of Shred's max duration + CountMax += 3 * triggerAmount * IN_MILLISECONDS; // Glyph of Shred -> +6 seconds + CountMax += HasAura(54818) ? 4 * IN_MILLISECONDS : 0; // Glyph of Rip -> +4 seconds + CountMax += HasAura(60141) ? 4 * IN_MILLISECONDS : 0; // Rip Duration/Lacerate Damage -> +4 seconds + + // if min < max -> that means caster didn't cast 3 shred yet + // so set Rip's duration and max duration + if (CountMin < CountMax) + { + AurEff->GetBase()->SetDuration(AurEff->GetBase()->GetDuration() + triggerAmount * IN_MILLISECONDS); + AurEff->GetBase()->SetMaxDuration(CountMin + triggerAmount * IN_MILLISECONDS); + return true; + } + } + // if not found Rip + return false; + } + // Glyph of Rake + case 54821: + { + if (procSpell->SpellVisual[0] == 750 && procSpell->Effects[1].ApplyAuraName == 3) + { + if (target && target->GetTypeId() == TYPEID_UNIT) + { + triggered_spell_id = 54820; + break; + } + } + return false; + } + // Leader of the Pack + case 24932: + { + if (triggerAmount <= 0) + return false; + basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); + target = this; + triggered_spell_id = 34299; + if (triggeredByAura->GetCasterGUID() != GetGUID()) + break; + int32 basepoints1 = CalculatePct(GetMaxPower(Powers(POWER_MANA)), triggerAmount * 2); + // Improved Leader of the Pack + // Check cooldown of heal spell cooldown + if (GetTypeId() == TYPEID_PLAYER && !ToPlayer()->HasSpellCooldown(34299)) + CastCustomSpell(this, 68285, &basepoints1, 0, 0, true, 0, triggeredByAura); + break; + } + // Healing Touch (Dreamwalker Raiment set) + case 28719: + { + // mana back + basepoints0 = int32(CalculatePct(procSpell->ManaCost, 30)); + target = this; + triggered_spell_id = 28742; + break; + } + // Glyph of Rejuvenation + case 54754: + { + if (!victim || !victim->HealthBelowPct(uint32(triggerAmount))) + return false; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + triggered_spell_id = 54755; + break; + } + // Healing Touch Refund (Idol of Longevity trinket) + case 28847: + { + target = this; + triggered_spell_id = 28848; + break; + } + // Mana Restore (Malorne Raiment set / Malorne Regalia set) + case 37288: + case 37295: + { + target = this; + triggered_spell_id = 37238; + break; + } + // Druid Tier 6 Trinket + case 40442: + { + float chance; + + // Starfire + if (procSpell->SpellFamilyFlags[0] & 0x4) + { + triggered_spell_id = 40445; + chance = 25.0f; + } + // Rejuvenation + else if (procSpell->SpellFamilyFlags[0] & 0x10) + { + triggered_spell_id = 40446; + chance = 25.0f; + } + // Mangle (Bear) and Mangle (Cat) + else if (procSpell->SpellFamilyFlags[1] & 0x00000440) + { + triggered_spell_id = 40452; + chance = 40.0f; + } + else + return false; + + if (!roll_chance_f(chance)) + return false; + + target = this; + break; + } + // Maim Interrupt + case 44835: + { + // Deadly Interrupt Effect + triggered_spell_id = 32747; + break; + } + // Item - Druid T10 Restoration 4P Bonus (Rejuvenation) + case 70664: + { + // xinef: proc only from normal Rejuvenation, and proc rejuvenation + if (!victim || !procSpell || procSpell->SpellIconID != 64) + return false; + + Player* caster = ToPlayer(); + if (!caster) + return false; + if (!caster->GetGroup() && victim == this) + return false; + + CastCustomSpell(70691, SPELLVALUE_BASE_POINT0, damage, victim, true); + return true; + } + } + // Eclipse + if (dummySpell->SpellIconID == 2856 && GetTypeId() == TYPEID_PLAYER) + { + if (!procSpell || effIndex != 0) + return false; + + bool isWrathSpell = (procSpell->SpellFamilyFlags[0] & 1); + + if (!roll_chance_f(dummySpell->ProcChance * (isWrathSpell ? 0.6f : 1.0f))) + return false; + + target = this; + if (target->HasAura(isWrathSpell ? 48517 : 48518)) + return false; + + triggered_spell_id = isWrathSpell ? 48518 : 48517; + break; + } + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + } + case SPELLFAMILY_ROGUE: + { + switch(dummySpell->Id) + { + // Glyph of Backstab + case 56800: + { + if (victim) + if (AuraEffect* aurEff = victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x100000, 0, 0, GetGUID())) + if (Aura* aur = aurEff->GetBase()) + if (!aur->IsRemoved() && aur->GetDuration() > 0) + if ((aur->GetApplyTime() + aur->GetMaxDuration() / 1000 + 5) > (time(nullptr) + aur->GetDuration() / 1000) ) + { + aur->SetDuration(aur->GetDuration() + 2000); + return true; + } + return false; + } + // Deadly Throw Interrupt + case 32748: + { + // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw + if (this == victim) + return false; + + triggered_spell_id = 32747; + break; + } + } + // Master of subtlety + if( dummySpell->SpellIconID == 2114 ) + { + triggered_spell_id = 31665; + basepoints0 = triggerAmount; + break; + } + // Cut to the Chase + if (dummySpell->SpellIconID == 2909) + { + // "refresh your Slice and Dice duration to its 5 combo point maximum" + // lookup Slice and Dice + if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_ROGUE, 0x40000, 0, 0)) + { + aur->GetBase()->SetDuration(aur->GetSpellInfo()->GetMaxDuration(), true); + return true; + } + return false; + } + // Deadly Brew + else if (dummySpell->SpellIconID == 2963) + { + triggered_spell_id = 3409; + break; + } + // Quick Recovery + else if (dummySpell->SpellIconID == 2116) { if (!procSpell) return false; - Spell* spell = ToPlayer()->m_spellModTakingSpell; - - // Disable charge drop because of Lock and Load - if (spell) - ToPlayer()->SetSpellModTakingSpell(spell, false); - - // Explosive Shot - if (procSpell->SpellFamilyFlags[2] & 0x200) - { - if (!victim) - return false; - if (AuraEffect const* pEff = victim->GetAuraEffect(SPELL_AURA_PERIODIC_DUMMY, SPELLFAMILY_HUNTER, 0x0, 0x80000000, 0x0, GetGUID())) - basepoints0 = pEff->GetSpellInfo()->CalcPowerCost(this, SpellSchoolMask(pEff->GetSpellInfo()->SchoolMask)) * 4/10/3; - } - else - basepoints0 = procSpell->CalcPowerCost(this, SpellSchoolMask(procSpell->SchoolMask)) * 4/10; - - if (spell) - ToPlayer()->SetSpellModTakingSpell(spell, true); - + // energy cost save + basepoints0 = CalculatePct(int32(procSpell->ManaCost), triggerAmount); if (basepoints0 <= 0) return false; target = this; - triggered_spell_id = 34720; - break; - } - case 3406: // Hunting Party - { - triggered_spell_id = 57669; - target = this; - break; - } - case 3560: // Rapid Recuperation - { - // This effect only from Rapid Killing (mana regen) - if (!(procSpell->SpellFamilyFlags[1] & 0x01000000)) - return false; - - target = this; - - switch (dummySpell->Id) - { - case 53228: // Rank 1 - triggered_spell_id = 56654; - break; - case 53232: // Rank 2 - triggered_spell_id = 58882; - break; - } - break; - } - case 3579: // Lock and Load - { - // Proc only from periodic (from trap activation proc another aura of this spell) - if (!(procFlag & PROC_FLAG_DONE_PERIODIC) || !roll_chance_i(triggerAmount)) - return false; - triggered_spell_id = 56453; - target = this; + triggered_spell_id = 31663; break; } + break; } - - switch (dummySpell->Id) + case SPELLFAMILY_HUNTER: { - case 57870: // Glyph of Mend Pet + switch (dummySpell->SpellIconID) { - if (!victim) - return false; + case 2236: // Thrill of the Hunt + { + if (!procSpell) + return false; - victim->CastSpell(victim, 57894, true, nullptr, nullptr, GetGUID()); - return true; + Spell* spell = ToPlayer()->m_spellModTakingSpell; + + // Disable charge drop because of Lock and Load + if (spell) + ToPlayer()->SetSpellModTakingSpell(spell, false); + + // Explosive Shot + if (procSpell->SpellFamilyFlags[2] & 0x200) + { + if (!victim) + return false; + if (AuraEffect const* pEff = victim->GetAuraEffect(SPELL_AURA_PERIODIC_DUMMY, SPELLFAMILY_HUNTER, 0x0, 0x80000000, 0x0, GetGUID())) + basepoints0 = pEff->GetSpellInfo()->CalcPowerCost(this, SpellSchoolMask(pEff->GetSpellInfo()->SchoolMask)) * 4 / 10 / 3; + } + else + basepoints0 = procSpell->CalcPowerCost(this, SpellSchoolMask(procSpell->SchoolMask)) * 4 / 10; + + if (spell) + ToPlayer()->SetSpellModTakingSpell(spell, true); + + if (basepoints0 <= 0) + return false; + + target = this; + triggered_spell_id = 34720; + break; + } + case 3406: // Hunting Party + { + triggered_spell_id = 57669; + target = this; + break; + } + case 3560: // Rapid Recuperation + { + // This effect only from Rapid Killing (mana regen) + if (!(procSpell->SpellFamilyFlags[1] & 0x01000000)) + return false; + + target = this; + + switch (dummySpell->Id) + { + case 53228: // Rank 1 + triggered_spell_id = 56654; + break; + case 53232: // Rank 2 + triggered_spell_id = 58882; + break; + } + break; + } + case 3579: // Lock and Load + { + // Proc only from periodic (from trap activation proc another aura of this spell) + if (!(procFlag & PROC_FLAG_DONE_PERIODIC) || !roll_chance_i(triggerAmount)) + return false; + triggered_spell_id = 56453; + target = this; + break; + } } - // Glyph of Freezing Trap - case 56845: + + switch (dummySpell->Id) { - victim->CastSpell(this, 61394, true, nullptr, nullptr, victim->GetGUID()); - return true; + case 57870: // Glyph of Mend Pet + { + if (!victim) + return false; + + victim->CastSpell(victim, 57894, true, nullptr, nullptr, GetGUID()); + return true; + } + // Glyph of Freezing Trap + case 56845: + { + victim->CastSpell(this, 61394, true, nullptr, nullptr, victim->GetGUID()); + return true; + } } + break; } - break; - } case SPELLFAMILY_PALADIN: - { - // Light's Beacon - Beacon of Light - if (dummySpell->Id == 53651) { - if (!victim) - return false; - - Unit* beaconTarget = triggeredByAura->GetBase()->GetCaster(); - if (!beaconTarget || beaconTarget == this || !beaconTarget->GetAura(53563, victim->GetGUID())) - return false; - - basepoints0 = int32(damage); - triggered_spell_id = procSpell->IsRankOf(sSpellMgr->GetSpellInfo(635)) ? 53652 : 53654; - - victim->CastCustomSpell(beaconTarget, triggered_spell_id, &basepoints0, nullptr, nullptr, true, 0, triggeredByAura, victim->GetGUID()); - return true; - } - // Judgements of the Wise - if (dummySpell->SpellIconID == 3017) - { - target = this; - triggered_spell_id = 31930; - // replenishment - CastSpell(this, 57669, true, castItem, triggeredByAura); - break; - } - // Righteous Vengeance - if (dummySpell->SpellIconID == 3025) - { - if (!victim) - return false; - - // 4 damage tick - basepoints0 = triggerAmount * damage / 400; - triggered_spell_id = 61840; - // Add remaining ticks to damage done - victim->CastDelayedSpellWithPeriodicAmount(this, triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE, basepoints0); - return true; - } - // Sheath of Light - if (dummySpell->SpellIconID == 3030) - { - // 4 healing tick - basepoints0 = triggerAmount * damage / 400; - triggered_spell_id = 54203; - break; - } - switch (dummySpell->Id) - { - // Judgement of Light - case 20185: - { - if (!victim || !victim->IsAlive() || victim->HasSpellCooldown(20267)) - return false; - // 2% of base mana - basepoints0 = int32(victim->CountPctFromMaxHealth(2)); - victim->CastCustomSpell(victim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura); - victim->AddSpellCooldown(20267, 0, 4*IN_MILLISECONDS); - return true; - } - // Judgement of Wisdom - case 20186: - { - if (!victim || !victim->IsAlive() || victim->getPowerType() != POWER_MANA || victim->HasSpellCooldown(20268)) - return false; - - // 2% of base mana - basepoints0 = int32(CalculatePct(victim->GetCreateMana(), 2)); - victim->CastCustomSpell(victim, 20268, &basepoints0, nullptr, nullptr, true, 0, triggeredByAura); - victim->AddSpellCooldown(20268, 0, 4*IN_MILLISECONDS); - return true; - } - // Holy Power (Redemption Armor set) - case 28789: + // Light's Beacon - Beacon of Light + if (dummySpell->Id == 53651) { if (!victim) return false; - // Set class defined buff - switch (victim->getClass()) - { - case CLASS_PALADIN: - case CLASS_PRIEST: - case CLASS_SHAMAN: - case CLASS_DRUID: - triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. - break; - case CLASS_MAGE: - case CLASS_WARLOCK: - triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d. - break; - case CLASS_HUNTER: - case CLASS_ROGUE: - triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d. - break; - case CLASS_WARRIOR: - triggered_spell_id = 28790; // Increases the friendly target's armor - break; - default: - return false; - } - break; + Unit* beaconTarget = triggeredByAura->GetBase()->GetCaster(); + if (!beaconTarget || beaconTarget == this || !beaconTarget->GetAura(53563, victim->GetGUID())) + return false; + + basepoints0 = int32(damage); + triggered_spell_id = procSpell->IsRankOf(sSpellMgr->GetSpellInfo(635)) ? 53652 : 53654; + + victim->CastCustomSpell(beaconTarget, triggered_spell_id, &basepoints0, nullptr, nullptr, true, 0, triggeredByAura, victim->GetGUID()); + return true; } - // Seal of Vengeance (damage calc on apply aura) - case 31801: + // Judgements of the Wise + if (dummySpell->SpellIconID == 3017) { - if (effIndex != 0 || !victim) // effect 1, 2 used by seal unleashing code - return false; - - // At melee attack or Hammer of the Righteous spell damage considered as melee attack - bool stacker = !procSpell || procSpell->Id == 53595; - // spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements - bool damager = procSpell && (procSpell->EquippedItemClass != -1 || (procSpell->SpellIconID == 243 && procSpell->SpellVisual[0] == 39)); - - if (!stacker && !damager) - return false; - - triggered_spell_id = 31803; - - // On target with 5 stacks of Holy Vengeance direct damage is done - if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID())) - { - if (aur->GetStackAmount() == 5) - { - if (stacker) - aur->RefreshDuration(); - - CastSpell(victim, 42463, true, castItem, triggeredByAura); - return true; - } - } - - if (!stacker) - return false; - break; - } - // Seal of Corruption - case 53736: - { - if (effIndex != 0 || !victim) // effect 1, 2 used by seal unleashing code - return false; - - // At melee attack or Hammer of the Righteous spell damage considered as melee attack - bool stacker = !procSpell || procSpell->Id == 53595; - // spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements - bool damager = procSpell && (procSpell->EquippedItemClass != -1 || (procSpell->SpellIconID == 243 && procSpell->SpellVisual[0] == 39)); - - if (!stacker && !damager) - return false; - - triggered_spell_id = 53742; - - // On target with 5 stacks of Blood Corruption direct damage is done - if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID())) - { - if (aur->GetStackAmount() == 5) - { - if (stacker) - aur->RefreshDuration(); - - CastSpell(victim, 53739, true, castItem, triggeredByAura); - return true; - } - } - - if (!stacker) - return false; - break; - } - // Spiritual Attunement - case 31785: - case 33776: - { - // if healed by another unit (victim) - if (this == victim) - return false; - - // dont allow non-positive dots to proc - if (!procSpell || !procSpell->IsPositive()) - return false; - - // heal amount - basepoints0 = int32(CalculatePct(std::min(damage, GetMaxHealth() - GetHealth()), triggerAmount)); target = this; - - if (basepoints0) - triggered_spell_id = 31786; + triggered_spell_id = 31930; + // replenishment + CastSpell(this, 57669, true, castItem, triggeredByAura); break; } - // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal) - case 40470: + // Righteous Vengeance + if (dummySpell->SpellIconID == 3025) { - if (!procSpell) + if (!victim) return false; - float chance = 0.0f; - - // Flash of light/Holy light - if (procSpell->SpellFamilyFlags[0] & 0xC0000000) - { - triggered_spell_id = 40471; - chance = 15.0f; - } - // Judgement (any) - else if (procSpell->SpellFamilyFlags[0] & 0x800000) - { - triggered_spell_id = 40472; - chance = 50.0f; - } - else - return false; - - if (!roll_chance_f(chance)) - return false; - - break; + // 4 damage tick + basepoints0 = triggerAmount * damage / 400; + triggered_spell_id = 61840; + // Add remaining ticks to damage done + victim->CastDelayedSpellWithPeriodicAmount(this, triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE, basepoints0); + return true; } - // Glyph of Holy Light - case 54937: + // Sheath of Light + if (dummySpell->SpellIconID == 3030) { - triggered_spell_id = 54968; - basepoints0 = CalculatePct(int32(damage), triggerAmount); + // 4 healing tick + basepoints0 = triggerAmount * damage / 400; + triggered_spell_id = 54203; break; } - // Item - Paladin T8 Holy 2P Bonus - case 64890: + switch (dummySpell->Id) { - triggered_spell_id = 64891; - basepoints0 = triggerAmount * damage / 300; - break; - } - case 71406: // Tiny Abomination in a Jar - case 71545: // Tiny Abomination in a Jar (Heroic) - { - if (!victim || !victim->IsAlive()) - return false; + // Judgement of Light + case 20185: + { + if (!victim || !victim->IsAlive() || victim->HasSpellCooldown(20267)) + return false; + // 2% of base mana + basepoints0 = int32(victim->CountPctFromMaxHealth(2)); + victim->CastCustomSpell(victim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura); + victim->AddSpellCooldown(20267, 0, 4 * IN_MILLISECONDS); + return true; + } + // Judgement of Wisdom + case 20186: + { + if (!victim || !victim->IsAlive() || victim->getPowerType() != POWER_MANA || victim->HasSpellCooldown(20268)) + return false; - CastSpell(this, 71432, true, NULL, triggeredByAura); + // 2% of base mana + basepoints0 = int32(CalculatePct(victim->GetCreateMana(), 2)); + victim->CastCustomSpell(victim, 20268, &basepoints0, nullptr, nullptr, true, 0, triggeredByAura); + victim->AddSpellCooldown(20268, 0, 4 * IN_MILLISECONDS); + return true; + } + // Holy Power (Redemption Armor set) + case 28789: + { + if (!victim) + return false; - Aura const* dummy = GetAura(71432); - if (!dummy || dummy->GetStackAmount() < (dummySpell->Id == 71406 ? 8 : 7)) - return false; + // Set class defined buff + switch (victim->getClass()) + { + case CLASS_PALADIN: + case CLASS_PRIEST: + case CLASS_SHAMAN: + case CLASS_DRUID: + triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. + break; + case CLASS_MAGE: + case CLASS_WARLOCK: + triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d. + break; + case CLASS_HUNTER: + case CLASS_ROGUE: + triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d. + break; + case CLASS_WARRIOR: + triggered_spell_id = 28790; // Increases the friendly target's armor + break; + default: + return false; + } + break; + } + // Seal of Vengeance (damage calc on apply aura) + case 31801: + { + if (effIndex != 0 || !victim) // effect 1, 2 used by seal unleashing code + return false; - RemoveAurasDueToSpell(71432); - triggered_spell_id = 71433; // default main hand attack - // roll if offhand - if (Player const* player = ToPlayer()) - if (player->GetWeaponForAttack(OFF_ATTACK, true) && urand(0, 1)) - triggered_spell_id = 71434; - target = victim; - break; - } - // Item - Icecrown 25 Normal Dagger Proc - case 71880: - { - switch (getPowerType()) - { - case POWER_MANA: - triggered_spell_id = 71881; - break; - case POWER_RAGE: - triggered_spell_id = 71883; - break; - case POWER_ENERGY: - triggered_spell_id = 71882; - break; - case POWER_RUNIC_POWER: - triggered_spell_id = 71884; - break; - default: - return false; - } - break; - } - // Item - Icecrown 25 Heroic Dagger Proc - case 71892: - { - switch (getPowerType()) - { - case POWER_MANA: - triggered_spell_id = 71888; - break; - case POWER_RAGE: - triggered_spell_id = 71886; - break; - case POWER_ENERGY: - triggered_spell_id = 71887; - break; - case POWER_RUNIC_POWER: - triggered_spell_id = 71885; - break; - default: - return false; - } - break; + // At melee attack or Hammer of the Righteous spell damage considered as melee attack + bool stacker = !procSpell || procSpell->Id == 53595; + // spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements + bool damager = procSpell && (procSpell->EquippedItemClass != -1 || (procSpell->SpellIconID == 243 && procSpell->SpellVisual[0] == 39)); + + if (!stacker && !damager) + return false; + + triggered_spell_id = 31803; + + // On target with 5 stacks of Holy Vengeance direct damage is done + if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID())) + { + if (aur->GetStackAmount() == 5) + { + if (stacker) + aur->RefreshDuration(); + + CastSpell(victim, 42463, true, castItem, triggeredByAura); + return true; + } + } + + if (!stacker) + return false; + break; + } + // Seal of Corruption + case 53736: + { + if (effIndex != 0 || !victim) // effect 1, 2 used by seal unleashing code + return false; + + // At melee attack or Hammer of the Righteous spell damage considered as melee attack + bool stacker = !procSpell || procSpell->Id == 53595; + // spells with SPELL_DAMAGE_CLASS_MELEE excluding Judgements + bool damager = procSpell && (procSpell->EquippedItemClass != -1 || (procSpell->SpellIconID == 243 && procSpell->SpellVisual[0] == 39)); + + if (!stacker && !damager) + return false; + + triggered_spell_id = 53742; + + // On target with 5 stacks of Blood Corruption direct damage is done + if (Aura* aur = victim->GetAura(triggered_spell_id, GetGUID())) + { + if (aur->GetStackAmount() == 5) + { + if (stacker) + aur->RefreshDuration(); + + CastSpell(victim, 53739, true, castItem, triggeredByAura); + return true; + } + } + + if (!stacker) + return false; + break; + } + // Spiritual Attunement + case 31785: + case 33776: + { + // if healed by another unit (victim) + if (this == victim) + return false; + + // dont allow non-positive dots to proc + if (!procSpell || !procSpell->IsPositive()) + return false; + + // heal amount + basepoints0 = int32(CalculatePct(std::min(damage, GetMaxHealth() - GetHealth()), triggerAmount)); + target = this; + + if (basepoints0) + triggered_spell_id = 31786; + break; + } + // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal) + case 40470: + { + if (!procSpell) + return false; + + float chance = 0.0f; + + // Flash of light/Holy light + if (procSpell->SpellFamilyFlags[0] & 0xC0000000) + { + triggered_spell_id = 40471; + chance = 15.0f; + } + // Judgement (any) + else if (procSpell->SpellFamilyFlags[0] & 0x800000) + { + triggered_spell_id = 40472; + chance = 50.0f; + } + else + return false; + + if (!roll_chance_f(chance)) + return false; + + break; + } + // Glyph of Holy Light + case 54937: + { + triggered_spell_id = 54968; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + break; + } + // Item - Paladin T8 Holy 2P Bonus + case 64890: + { + triggered_spell_id = 64891; + basepoints0 = triggerAmount * damage / 300; + break; + } + case 71406: // Tiny Abomination in a Jar + case 71545: // Tiny Abomination in a Jar (Heroic) + { + if (!victim || !victim->IsAlive()) + return false; + + CastSpell(this, 71432, true, NULL, triggeredByAura); + + Aura const* dummy = GetAura(71432); + if (!dummy || dummy->GetStackAmount() < (dummySpell->Id == 71406 ? 8 : 7)) + return false; + + RemoveAurasDueToSpell(71432); + triggered_spell_id = 71433; // default main hand attack + // roll if offhand + if (Player const* player = ToPlayer()) + if (player->GetWeaponForAttack(OFF_ATTACK, true) && urand(0, 1)) + triggered_spell_id = 71434; + target = victim; + break; + } + // Item - Icecrown 25 Normal Dagger Proc + case 71880: + { + switch (getPowerType()) + { + case POWER_MANA: + triggered_spell_id = 71881; + break; + case POWER_RAGE: + triggered_spell_id = 71883; + break; + case POWER_ENERGY: + triggered_spell_id = 71882; + break; + case POWER_RUNIC_POWER: + triggered_spell_id = 71884; + break; + default: + return false; + } + break; + } + // Item - Icecrown 25 Heroic Dagger Proc + case 71892: + { + switch (getPowerType()) + { + case POWER_MANA: + triggered_spell_id = 71888; + break; + case POWER_RAGE: + triggered_spell_id = 71886; + break; + case POWER_ENERGY: + triggered_spell_id = 71887; + break; + case POWER_RUNIC_POWER: + triggered_spell_id = 71885; + break; + default: + return false; + } + break; + } } + break; } - break; - } case SPELLFAMILY_SHAMAN: - { - switch (dummySpell->Id) { - // Tidal Force - case 55198: + switch (dummySpell->Id) { - // Remove aura stack from caster - RemoveAuraFromStack(55166); - // drop charges - return false; - } - // Totemic Power (The Earthshatterer set) - case 28823: - { - if (!victim) - return false; - - // Set class defined buff - switch (victim->getClass()) - { - case CLASS_PALADIN: - case CLASS_PRIEST: - case CLASS_SHAMAN: - case CLASS_DRUID: - triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. - break; - case CLASS_MAGE: - case CLASS_WARLOCK: - triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d. - break; - case CLASS_HUNTER: - case CLASS_ROGUE: - triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d. - break; - case CLASS_WARRIOR: - triggered_spell_id = 28827; // Increases the friendly target's armor - break; - default: - return false; - } - break; - } - // Lesser Healing Wave (Totem of Flowing Water Relic) - case 28849: - { - target = this; - triggered_spell_id = 28850; - break; - } - // Windfury Weapon (Passive) 1-8 Ranks - case 33757: - { - Player* player = ToPlayer(); - if (!player || !castItem || !castItem->IsEquipped() || !victim || !victim->IsAlive()) - return false; - - if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID()) - return false; - - WeaponAttackType attType = WeaponAttackType(player->GetAttackBySlot(castItem->GetSlot())); - if ((attType != BASE_ATTACK && attType != OFF_ATTACK) - || (attType == BASE_ATTACK && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) - || (attType == OFF_ATTACK && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK)) - return false; - - // Now amount of extra power stored in 1 effect of Enchant spell - // Get it by item enchant id - uint32 spellId; - switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT))) - { - case 283: spellId = 8232; break; // 1 Rank - case 284: spellId = 8235; break; // 2 Rank - case 525: spellId = 10486; break; // 3 Rank - case 1669:spellId = 16362; break; // 4 Rank - case 2636:spellId = 25505; break; // 5 Rank - case 3785:spellId = 58801; break; // 6 Rank - case 3786:spellId = 58803; break; // 7 Rank - case 3787:spellId = 58804; break; // 8 Rank - default: + // Tidal Force + case 55198: { - sLog->outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)", - castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)), dummySpell->Id); + // Remove aura stack from caster + RemoveAuraFromStack(55166); + // drop charges return false; } - } + // Totemic Power (The Earthshatterer set) + case 28823: + { + if (!victim) + return false; - SpellInfo const* windfurySpellInfo = sSpellMgr->GetSpellInfo(spellId); - if (!windfurySpellInfo) + // Set class defined buff + switch (victim->getClass()) + { + case CLASS_PALADIN: + case CLASS_PRIEST: + case CLASS_SHAMAN: + case CLASS_DRUID: + triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. + break; + case CLASS_MAGE: + case CLASS_WARLOCK: + triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d. + break; + case CLASS_HUNTER: + case CLASS_ROGUE: + triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d. + break; + case CLASS_WARRIOR: + triggered_spell_id = 28827; // Increases the friendly target's armor + break; + default: + return false; + } + break; + } + // Lesser Healing Wave (Totem of Flowing Water Relic) + case 28849: + { + target = this; + triggered_spell_id = 28850; + break; + } + // Windfury Weapon (Passive) 1-8 Ranks + case 33757: + { + Player* player = ToPlayer(); + if (!player || !castItem || !castItem->IsEquipped() || !victim || !victim->IsAlive()) + return false; + + if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID()) + return false; + + WeaponAttackType attType = WeaponAttackType(player->GetAttackBySlot(castItem->GetSlot())); + if ((attType != BASE_ATTACK && attType != OFF_ATTACK) + || (attType == BASE_ATTACK && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) + || (attType == OFF_ATTACK && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK)) + return false; + + // Now amount of extra power stored in 1 effect of Enchant spell + // Get it by item enchant id + uint32 spellId; + switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT))) + { + case 283: + spellId = 8232; + break; // 1 Rank + case 284: + spellId = 8235; + break; // 2 Rank + case 525: + spellId = 10486; + break; // 3 Rank + case 1669: + spellId = 16362; + break; // 4 Rank + case 2636: + spellId = 25505; + break; // 5 Rank + case 3785: + spellId = 58801; + break; // 6 Rank + case 3786: + spellId = 58803; + break; // 7 Rank + case 3787: + spellId = 58804; + break; // 8 Rank + default: + { + sLog->outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)", + castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)), dummySpell->Id); + return false; + } + } + + SpellInfo const* windfurySpellInfo = sSpellMgr->GetSpellInfo(spellId); + if (!windfurySpellInfo) + { + sLog->outError("Unit::HandleDummyAuraProc: non-existing spell id: %u (Windfury)", spellId); + return false; + } + + int32 extra_attack_power = CalculateSpellDamage(victim, windfurySpellInfo, 1); + + // Value gained from additional AP + basepoints0 = int32(extra_attack_power / 14.0f * GetAttackTime(attType) / 1000); + + if (procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK) + triggered_spell_id = 25504; + + if (procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) + triggered_spell_id = 33750; + + // custom cooldown processing case + if (player->HasSpellCooldown(dummySpell->Id)) + return false; + + // apply cooldown before cast to prevent processing itself + player->AddSpellCooldown(dummySpell->Id, 0, 3 * IN_MILLISECONDS); + + // Attack Twice + for (uint32 i = 0; i < 2; ++i) + CastCustomSpell(victim, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); + + return true; + } + // Shaman Tier 6 Trinket + case 40463: + { + if (!procSpell) + return false; + + float chance; + if (procSpell->SpellFamilyFlags[0] & 0x1) + { + triggered_spell_id = 40465; // Lightning Bolt + chance = 15.0f; + } + else if (procSpell->SpellFamilyFlags[0] & 0x80) + { + triggered_spell_id = 40465; // Lesser Healing Wave + chance = 10.0f; + } + else if (procSpell->SpellFamilyFlags[1] & 0x00000010) + { + triggered_spell_id = 40466; // Stormstrike + chance = 50.0f; + } + else + return false; + + if (!roll_chance_f(chance)) + return false; + + target = this; + break; + } + // Glyph of Healing Wave + case 55440: + { + // Not proc from self heals + if (this == victim) + return false; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + target = this; + triggered_spell_id = 55533; + break; + } + // Spirit Hunt + case 58877: + { + // Cast on owner + target = GetOwner(); + if (!target) + return false; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + triggered_spell_id = 58879; + // Heal wolf + CastCustomSpell(this, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura, originalCaster); + break; + } + // Shaman T8 Elemental 4P Bonus + case 64928: + { + basepoints0 = CalculatePct(int32(damage), triggerAmount); + triggered_spell_id = 64930; // Electrified + break; + } + // Shaman T9 Elemental 4P Bonus + case 67228: + { + // Lava Burst + if (procSpell->SpellFamilyFlags[1] & 0x1000) + { + triggered_spell_id = 71824; + SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id); + if (!triggeredSpell) + return false; + basepoints0 = CalculatePct(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude); + } + break; + } + // Item - Shaman T10 Elemental 4P Bonus + case 70817: + { + if (!target) + return false; + // try to find spell Flame Shock on the target + if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0x0, 0x0, GetGUID())) + { + Aura* flameShock = aurEff->GetBase(); + int32 maxDuration = flameShock->GetMaxDuration(); + int32 newDuration = flameShock->GetDuration() + 2 * aurEff->GetAmplitude(); + + flameShock->SetDuration(newDuration); + // is it blizzlike to change max duration for FS? + if (newDuration > maxDuration) + flameShock->SetMaxDuration(newDuration); + + return true; + } + // if not found Flame Shock + return false; + } + break; + } + // Frozen Power + if (dummySpell->SpellIconID == 3780) + { + if (!target) + return false; + if (GetDistance(target) < 15.0f) + return false; + float chance = (float)triggerAmount; + if (!roll_chance_f(chance)) + return false; + + triggered_spell_id = 63685; + break; + } + // Ancestral Awakening + if (dummySpell->SpellIconID == 3065) + { + triggered_spell_id = 52759; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + target = this; + break; + } + // Flametongue Weapon (Passive) + if (dummySpell->SpellFamilyFlags[0] & 0x200000) + { + if (GetTypeId() != TYPEID_PLAYER || !victim || !victim->IsAlive() || !castItem || !castItem->IsEquipped()) + return false; + + WeaponAttackType attType = WeaponAttackType(Player::GetAttackBySlot(castItem->GetSlot())); + if ((attType != BASE_ATTACK && attType != OFF_ATTACK) + || (attType == BASE_ATTACK && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) + || (attType == OFF_ATTACK && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK)) + return false; + + float fire_onhit = float(CalculatePct(dummySpell->Effects[EFFECT_0]. CalcValue(), 1.0f)); + + float add_spellpower = (float)(SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_FIRE) + + victim->SpellBaseDamageBonusTaken(SPELL_SCHOOL_MASK_FIRE)); + + // 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84% + ApplyPct(add_spellpower, 3.84f); + + // Enchant on Off-Hand and ready? + if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) { - sLog->outError("Unit::HandleDummyAuraProc: non-existing spell id: %u (Windfury)", spellId); - return false; + float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK) / 1000.0f; + + // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed + basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed)); + triggered_spell_id = 10444; } - int32 extra_attack_power = CalculateSpellDamage(victim, windfurySpellInfo, 1); + // Enchant on Main-Hand and ready? + else if (castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK) + { + float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK) / 1000.0f; - // Value gained from additional AP - basepoints0 = int32(extra_attack_power / 14.0f * GetAttackTime(attType) / 1000); + // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed + basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed)); + triggered_spell_id = 10444; + } - if (procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK) - triggered_spell_id = 25504; - - if (procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) - triggered_spell_id = 33750; - - // custom cooldown processing case - if (player->HasSpellCooldown(dummySpell->Id)) + // If not ready, we should return, shouldn't we?! + else return false; - // apply cooldown before cast to prevent processing itself - player->AddSpellCooldown(dummySpell->Id, 0, 3*IN_MILLISECONDS); - - // Attack Twice - for (uint32 i = 0; i < 2; ++i) - CastCustomSpell(victim, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); - + CastCustomSpell(victim, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); return true; } - // Shaman Tier 6 Trinket - case 40463: + // Improved Water Shield + if (dummySpell->SpellIconID == 2287) { if (!procSpell) return false; - float chance; - if (procSpell->SpellFamilyFlags[0] & 0x1) - { - triggered_spell_id = 40465; // Lightning Bolt - chance = 15.0f; - } - else if (procSpell->SpellFamilyFlags[0] & 0x80) - { - triggered_spell_id = 40465; // Lesser Healing Wave - chance = 10.0f; - } - else if (procSpell->SpellFamilyFlags[1] & 0x00000010) - { - triggered_spell_id = 40466; // Stormstrike - chance = 50.0f; - } - else - return false; + // Default chance for Healing Wave and Riptide + float chance = (float)triggeredByAura->GetAmount(); + + if (procSpell->SpellFamilyFlags[0] & 0x80) + // Lesser Healing Wave - 0.6 of default + chance *= 0.6f; + else if (procSpell->SpellFamilyFlags[0] & 0x100) + // Chain heal - 0.3 of default + chance *= 0.3f; if (!roll_chance_f(chance)) return false; - target = this; - break; - } - // Glyph of Healing Wave - case 55440: - { - // Not proc from self heals - if (this == victim) - return false; - basepoints0 = CalculatePct(int32(damage), triggerAmount); - target = this; - triggered_spell_id = 55533; - break; - } - // Spirit Hunt - case 58877: - { - // Cast on owner - target = GetOwner(); - if (!target) - return false; - basepoints0 = CalculatePct(int32(damage), triggerAmount); - triggered_spell_id = 58879; - // Heal wolf - CastCustomSpell(this, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura, originalCaster); - break; - } - // Shaman T8 Elemental 4P Bonus - case 64928: - { - basepoints0 = CalculatePct(int32(damage), triggerAmount); - triggered_spell_id = 64930; // Electrified - break; - } - // Shaman T9 Elemental 4P Bonus - case 67228: - { - // Lava Burst - if (procSpell->SpellFamilyFlags[1] & 0x1000) + // Water Shield + if (AuraEffect const* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0, 0x00000020, 0)) { - triggered_spell_id = 71824; - SpellInfo const* triggeredSpell = sSpellMgr->GetSpellInfo(triggered_spell_id); - if (!triggeredSpell) - return false; - basepoints0 = CalculatePct(int32(damage), triggerAmount) / (triggeredSpell->GetMaxDuration() / triggeredSpell->Effects[0].Amplitude); - } - break; - } - // Item - Shaman T10 Elemental 4P Bonus - case 70817: - { - if (!target) - return false; - // try to find spell Flame Shock on the target - if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0x0, 0x0, GetGUID())) - { - Aura* flameShock = aurEff->GetBase(); - int32 maxDuration = flameShock->GetMaxDuration(); - int32 newDuration = flameShock->GetDuration() + 2 * aurEff->GetAmplitude(); - - flameShock->SetDuration(newDuration); - // is it blizzlike to change max duration for FS? - if (newDuration > maxDuration) - flameShock->SetMaxDuration(newDuration); - + uint32 spell = aurEff->GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; + CastSpell(this, spell, true, castItem, triggeredByAura); return true; } - // if not found Flame Shock return false; } - break; - } - // Frozen Power - if (dummySpell->SpellIconID == 3780) - { - if (!target) - return false; - if (GetDistance(target) < 15.0f) - return false; - float chance = (float)triggerAmount; - if (!roll_chance_f(chance)) - return false; - - triggered_spell_id = 63685; - break; - } - // Ancestral Awakening - if (dummySpell->SpellIconID == 3065) - { - triggered_spell_id = 52759; - basepoints0 = CalculatePct(int32(damage), triggerAmount); - target = this; - break; - } - // Flametongue Weapon (Passive) - if (dummySpell->SpellFamilyFlags[0] & 0x200000) - { - if (GetTypeId() != TYPEID_PLAYER || !victim || !victim->IsAlive() || !castItem || !castItem->IsEquipped()) - return false; - - WeaponAttackType attType = WeaponAttackType(Player::GetAttackBySlot(castItem->GetSlot())); - if ((attType != BASE_ATTACK && attType != OFF_ATTACK) - || (attType == BASE_ATTACK && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) - || (attType == OFF_ATTACK && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK)) - return false; - - float fire_onhit = float(CalculatePct(dummySpell->Effects[EFFECT_0]. CalcValue(), 1.0f)); - - float add_spellpower = (float)(SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_FIRE) - + victim->SpellBaseDamageBonusTaken(SPELL_SCHOOL_MASK_FIRE)); - - // 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84% - ApplyPct(add_spellpower, 3.84f); - - // Enchant on Off-Hand and ready? - if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) + // Lightning Overload + if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura { - float BaseWeaponSpeed = GetAttackTime(OFF_ATTACK) / 1000.0f; + if(!procSpell || GetTypeId() != TYPEID_PLAYER || !victim) + return false; - // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed - basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed)); - triggered_spell_id = 10444; - } + if (procEx & PROC_EX_CRITICAL_HIT) + damage /= 2; - // Enchant on Main-Hand and ready? - else if (castItem->GetSlot() == EQUIPMENT_SLOT_MAINHAND && procFlag & PROC_FLAG_DONE_MAINHAND_ATTACK) - { - float BaseWeaponSpeed = GetAttackTime(BASE_ATTACK) / 1000.0f; - - // Value1: add the tooltip damage by swingspeed + Value2: add spelldmg by swingspeed - basepoints0 = int32((fire_onhit * BaseWeaponSpeed) + (add_spellpower * BaseWeaponSpeed)); - triggered_spell_id = 10444; - } - - // If not ready, we should return, shouldn't we?! - else - return false; - - CastCustomSpell(victim, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); - return true; - } - // Improved Water Shield - if (dummySpell->SpellIconID == 2287) - { - if (!procSpell) - return false; - - // Default chance for Healing Wave and Riptide - float chance = (float)triggeredByAura->GetAmount(); - - if (procSpell->SpellFamilyFlags[0] & 0x80) - // Lesser Healing Wave - 0.6 of default - chance *= 0.6f; - else if (procSpell->SpellFamilyFlags[0] & 0x100) - // Chain heal - 0.3 of default - chance *= 0.3f; - - if (!roll_chance_f(chance)) - return false; - - // Water Shield - if (AuraEffect const* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0, 0x00000020, 0)) - { - uint32 spell = aurEff->GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; - CastSpell(this, spell, true, castItem, triggeredByAura); - return true; - } - return false; - } - // Lightning Overload - if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura - { - if(!procSpell || GetTypeId() != TYPEID_PLAYER || !victim) - return false; - - if (procEx & PROC_EX_CRITICAL_HIT) - damage /= 2; - - do - { - uint32 spell = 0; - - if (procSpell->SpellFamilyFlags[0] & 0x2) + do { - // 1/3 of 33% if 11% - if (!roll_chance_i(33)) - return false; + uint32 spell = 0; - spell = 45297; - } - else - spell = 45284; + if (procSpell->SpellFamilyFlags[0] & 0x2) + { + // 1/3 of 33% if 11% + if (!roll_chance_i(33)) + return false; - // do not reduce damage-spells have correct basepoints - damage /= 2; - int32 dmg = damage; + spell = 45297; + } + else + spell = 45284; - // Cast - CastCustomSpell(victim, spell, &dmg, 0, 0, true, castItem, triggeredByAura); - } while (roll_chance_i(33)); - return true; - } - // Static Shock - if (dummySpell->SpellIconID == 3059) - { - // Lightning Shield - if (AuraEffect const* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0)) - { - uint32 spell = sSpellMgr->GetSpellWithRank(26364, aurEff->GetSpellInfo()->GetRank()); - CastSpell(target, spell, true, castItem, triggeredByAura); - aurEff->GetBase()->DropCharge(); + // do not reduce damage-spells have correct basepoints + damage /= 2; + int32 dmg = damage; + + // Cast + CastCustomSpell(victim, spell, &dmg, 0, 0, true, castItem, triggeredByAura); + } while (roll_chance_i(33)); return true; } - return false; + // Static Shock + if (dummySpell->SpellIconID == 3059) + { + // Lightning Shield + if (AuraEffect const* aurEff = GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400, 0, 0)) + { + uint32 spell = sSpellMgr->GetSpellWithRank(26364, aurEff->GetSpellInfo()->GetRank()); + CastSpell(target, spell, true, castItem, triggeredByAura); + aurEff->GetBase()->DropCharge(); + return true; + } + return false; + } + break; } - break; - } case SPELLFAMILY_DEATHKNIGHT: - { - // Improved Blood Presence - if (dummySpell->SpellIconID == 2636) { - if (GetTypeId() != TYPEID_PLAYER) - return false; - basepoints0 = CalculatePct(int32(damage), triggerAmount); - break; - } - // Butchery - if (dummySpell->SpellIconID == 2664) - { - basepoints0 = triggerAmount; - triggered_spell_id = 50163; - target = this; - break; - } - // Mark of Blood - if (dummySpell->Id == 49005) - { - // TODO: need more info (cooldowns/PPM) - triggered_spell_id = 61607; - break; - } - // Unholy Blight - if (dummySpell->Id == 49194) - { - triggered_spell_id = 50536; - SpellInfo const* unholyBlight = sSpellMgr->GetSpellInfo(triggered_spell_id); - if (!unholyBlight || !victim) - return false; - - basepoints0 = CalculatePct(int32(damage), triggerAmount); - - //Glyph of Unholy Blight - if (AuraEffect* glyph=GetAuraEffect(63332, 0)) - AddPct(basepoints0, glyph->GetAmount()); - - basepoints0 = basepoints0 / (unholyBlight->GetMaxDuration() / unholyBlight->Effects[0].Amplitude); - victim->CastDelayedSpellWithPeriodicAmount(this, triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE, basepoints0); - return true; - } - // Vendetta - if (dummySpell->SpellFamilyFlags[0] & 0x10000) - { - basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); - triggered_spell_id = 50181; - target = this; - break; - } - // Necrosis - if (dummySpell->SpellIconID == 2709) - { - basepoints0 = CalculatePct(int32(damage), triggerAmount); - triggered_spell_id = 51460; - break; - } - // Threat of Thassarian - if (dummySpell->SpellIconID == 2023) - { - // Must Dual Wield - if (!procSpell || !haveOffhandWeapon()) - return false; - // Chance as basepoints for dummy aura - if (!roll_chance_i(triggerAmount)) - return false; - - switch (procSpell->Id) + // Improved Blood Presence + if (dummySpell->SpellIconID == 2636) { - // Obliterate - case 49020: triggered_spell_id = 66198; break; // Rank 1 - case 51423: triggered_spell_id = 66972; break; // Rank 2 - case 51424: triggered_spell_id = 66973; break; // Rank 3 - case 51425: triggered_spell_id = 66974; break; // Rank 4 - - // Frost Strike - case 49143: triggered_spell_id = 66196; break; // Rank 1 - case 51416: triggered_spell_id = 66958; break; // Rank 2 - case 51417: triggered_spell_id = 66959; break; // Rank 3 - case 51418: triggered_spell_id = 66960; break; // Rank 4 - case 51419: triggered_spell_id = 66961; break; // Rank 5 - case 55268: triggered_spell_id = 66962; break; // Rank 6 - - // Plague Strike - case 45462: triggered_spell_id = 66216; break; // Rank 1 - case 49917: triggered_spell_id = 66988; break; // Rank 2 - case 49918: triggered_spell_id = 66989; break; // Rank 3 - case 49919: triggered_spell_id = 66990; break; // Rank 4 - case 49920: triggered_spell_id = 66991; break; // Rank 5 - case 49921: triggered_spell_id = 66992; break; // Rank 6 - - // Death Strike - case 49998: triggered_spell_id = 66188; break; // Rank 1 - case 49999: triggered_spell_id = 66950; break; // Rank 2 - case 45463: triggered_spell_id = 66951; break; // Rank 3 - case 49923: triggered_spell_id = 66952; break; // Rank 4 - case 49924: triggered_spell_id = 66953; break; // Rank 5 - - // Rune Strike - case 56815: triggered_spell_id = 66217; break; // Rank 1 - - // Blood Strike - case 45902: triggered_spell_id = 66215; break; // Rank 1 - case 49926: triggered_spell_id = 66975; break; // Rank 2 - case 49927: triggered_spell_id = 66976; break; // Rank 3 - case 49928: triggered_spell_id = 66977; break; // Rank 4 - case 49929: triggered_spell_id = 66978; break; // Rank 5 - case 49930: triggered_spell_id = 66979; break; // Rank 6 - default: + if (GetTypeId() != TYPEID_PLAYER) return false; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + break; } - - // This should do, restore spell mod so next attack can also use this! - // crit chance for first strike is already computed - ToPlayer()->RestoreSpellMods(m_currentSpells[CURRENT_GENERIC_SPELL], 51124, nullptr); // Killing Machine - ToPlayer()->RestoreSpellMods(m_currentSpells[CURRENT_GENERIC_SPELL], 49796, nullptr); // Deathchill - - // Xinef: Somehow basepoints are divided by 2 which is later divided by 2 (offhand multiplier) - SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id); - if (triggerEntry->SchoolMask & SPELL_SCHOOL_MASK_NORMAL) - basepoints0 = triggerEntry->Effects[EFFECT_0].BasePoints*2; - - SetCantProc(true); - if(basepoints0) - CastCustomSpell(target, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura, originalCaster); - else - CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura, originalCaster); - SetCantProc(false); - return true; - } - // Runic Power Back on Snare/Root - if (dummySpell->Id == 61257) - { - // only for spells and hit/crit (trigger start always) and not start from self casted spells - if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim) - return false; - // Need snare or root mechanic - if (!(procSpell->GetAllEffectsMechanicMask() & ((1<SpellIconID == 1939 && GetTypeId() == TYPEID_PLAYER) - { - SpellChainNode const* chain = nullptr; - // get highest rank of the Death Coil spell - PlayerSpellMap const& sp_list = ToPlayer()->GetSpellMap(); - for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) + // Butchery + if (dummySpell->SpellIconID == 2664) { - // check if shown in spell book - if (!itr->second->Active || !itr->second->IsInSpec(ToPlayer()->GetActiveSpec()) || itr->second->State == PLAYERSPELL_REMOVED) - continue; - - SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(itr->first); - if (!spellProto) - continue; - - if (spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT - && spellProto->SpellFamilyFlags[0] & 0x2000) - { - SpellChainNode const* newChain = sSpellMgr->GetSpellChainNode(itr->first); - - // No chain entry or entry lower than found entry - if (!chain || !newChain || (chain->rank < newChain->rank)) - { - triggered_spell_id = itr->first; - chain = newChain; - } - else - continue; - // Found spell is last in chain - do not need to look more - // Optimisation for most common case - if (chain && chain->last->Id == itr->first) - break; - } + basepoints0 = triggerAmount; + triggered_spell_id = 50163; + target = this; + break; } - } - break; - } - case SPELLFAMILY_POTION: - { - // alchemist's stone - if (dummySpell->Id == 17619) - { - if (procSpell->SpellFamilyName == SPELLFAMILY_POTION) + // Mark of Blood + if (dummySpell->Id == 49005) { - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) - { - if (procSpell->Effects[i].Effect == SPELL_EFFECT_HEAL) - { - triggered_spell_id = 21399; - } - else if (procSpell->Effects[i].Effect == SPELL_EFFECT_ENERGIZE) - { - triggered_spell_id = 21400; - } - else - continue; + // TODO: need more info (cooldowns/PPM) + triggered_spell_id = 61607; + break; + } + // Unholy Blight + if (dummySpell->Id == 49194) + { + triggered_spell_id = 50536; + SpellInfo const* unholyBlight = sSpellMgr->GetSpellInfo(triggered_spell_id); + if (!unholyBlight || !victim) + return false; - basepoints0 = int32(CalculateSpellDamage(this, procSpell, i) * 0.4f); - CastCustomSpell(this, triggered_spell_id, &basepoints0, nullptr, nullptr, true, NULL, triggeredByAura); - } + basepoints0 = CalculatePct(int32(damage), triggerAmount); + + //Glyph of Unholy Blight + if (AuraEffect* glyph = GetAuraEffect(63332, 0)) + AddPct(basepoints0, glyph->GetAmount()); + + basepoints0 = basepoints0 / (unholyBlight->GetMaxDuration() / unholyBlight->Effects[0].Amplitude); + victim->CastDelayedSpellWithPeriodicAmount(this, triggered_spell_id, SPELL_AURA_PERIODIC_DAMAGE, basepoints0); return true; } - } - break; - } - case SPELLFAMILY_PET: - { - switch (dummySpell->SpellIconID) - { - // Guard Dog - case 201: + // Vendetta + if (dummySpell->SpellFamilyFlags[0] & 0x10000) { - if (!victim) - return false; - - triggered_spell_id = 54445; + basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); + triggered_spell_id = 50181; target = this; - float addThreat = float(CalculatePct(procSpell->Effects[0].CalcValue(this), triggerAmount)); - victim->AddThreat(this, addThreat); break; } - // Silverback - case 1582: - triggered_spell_id = dummySpell->Id == 62765 ? 62801 : 62800; + // Necrosis + if (dummySpell->SpellIconID == 2709) + { + basepoints0 = CalculatePct(int32(damage), triggerAmount); + triggered_spell_id = 51460; + break; + } + // Threat of Thassarian + if (dummySpell->SpellIconID == 2023) + { + // Must Dual Wield + if (!procSpell || !haveOffhandWeapon()) + return false; + // Chance as basepoints for dummy aura + if (!roll_chance_i(triggerAmount)) + return false; + + switch (procSpell->Id) + { + // Obliterate + case 49020: + triggered_spell_id = 66198; + break; // Rank 1 + case 51423: + triggered_spell_id = 66972; + break; // Rank 2 + case 51424: + triggered_spell_id = 66973; + break; // Rank 3 + case 51425: + triggered_spell_id = 66974; + break; // Rank 4 + + // Frost Strike + case 49143: + triggered_spell_id = 66196; + break; // Rank 1 + case 51416: + triggered_spell_id = 66958; + break; // Rank 2 + case 51417: + triggered_spell_id = 66959; + break; // Rank 3 + case 51418: + triggered_spell_id = 66960; + break; // Rank 4 + case 51419: + triggered_spell_id = 66961; + break; // Rank 5 + case 55268: + triggered_spell_id = 66962; + break; // Rank 6 + + // Plague Strike + case 45462: + triggered_spell_id = 66216; + break; // Rank 1 + case 49917: + triggered_spell_id = 66988; + break; // Rank 2 + case 49918: + triggered_spell_id = 66989; + break; // Rank 3 + case 49919: + triggered_spell_id = 66990; + break; // Rank 4 + case 49920: + triggered_spell_id = 66991; + break; // Rank 5 + case 49921: + triggered_spell_id = 66992; + break; // Rank 6 + + // Death Strike + case 49998: + triggered_spell_id = 66188; + break; // Rank 1 + case 49999: + triggered_spell_id = 66950; + break; // Rank 2 + case 45463: + triggered_spell_id = 66951; + break; // Rank 3 + case 49923: + triggered_spell_id = 66952; + break; // Rank 4 + case 49924: + triggered_spell_id = 66953; + break; // Rank 5 + + // Rune Strike + case 56815: + triggered_spell_id = 66217; + break; // Rank 1 + + // Blood Strike + case 45902: + triggered_spell_id = 66215; + break; // Rank 1 + case 49926: + triggered_spell_id = 66975; + break; // Rank 2 + case 49927: + triggered_spell_id = 66976; + break; // Rank 3 + case 49928: + triggered_spell_id = 66977; + break; // Rank 4 + case 49929: + triggered_spell_id = 66978; + break; // Rank 5 + case 49930: + triggered_spell_id = 66979; + break; // Rank 6 + default: + return false; + } + + // This should do, restore spell mod so next attack can also use this! + // crit chance for first strike is already computed + ToPlayer()->RestoreSpellMods(m_currentSpells[CURRENT_GENERIC_SPELL], 51124, nullptr); // Killing Machine + ToPlayer()->RestoreSpellMods(m_currentSpells[CURRENT_GENERIC_SPELL], 49796, nullptr); // Deathchill + + // Xinef: Somehow basepoints are divided by 2 which is later divided by 2 (offhand multiplier) + SpellInfo const* triggerEntry = sSpellMgr->GetSpellInfo(triggered_spell_id); + if (triggerEntry->SchoolMask & SPELL_SCHOOL_MASK_NORMAL) + basepoints0 = triggerEntry->Effects[EFFECT_0].BasePoints * 2; + + SetCantProc(true); + if(basepoints0) + CastCustomSpell(target, triggered_spell_id, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura, originalCaster); + else + CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura, originalCaster); + SetCantProc(false); + return true; + } + // Runic Power Back on Snare/Root + if (dummySpell->Id == 61257) + { + // only for spells and hit/crit (trigger start always) and not start from self casted spells + if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) || this == victim) + return false; + // Need snare or root mechanic + if (!(procSpell->GetAllEffectsMechanicMask() & ((1 << MECHANIC_ROOT) | (1 << MECHANIC_SNARE)))) + return false; + triggered_spell_id = 61258; target = this; break; + } + // Sudden Doom + if (dummySpell->SpellIconID == 1939 && GetTypeId() == TYPEID_PLAYER) + { + SpellChainNode const* chain = nullptr; + // get highest rank of the Death Coil spell + PlayerSpellMap const& sp_list = ToPlayer()->GetSpellMap(); + for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) + { + // check if shown in spell book + if (!itr->second->Active || !itr->second->IsInSpec(ToPlayer()->GetActiveSpec()) || itr->second->State == PLAYERSPELL_REMOVED) + continue; + + SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(itr->first); + if (!spellProto) + continue; + + if (spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT + && spellProto->SpellFamilyFlags[0] & 0x2000) + { + SpellChainNode const* newChain = sSpellMgr->GetSpellChainNode(itr->first); + + // No chain entry or entry lower than found entry + if (!chain || !newChain || (chain->rank < newChain->rank)) + { + triggered_spell_id = itr->first; + chain = newChain; + } + else + continue; + // Found spell is last in chain - do not need to look more + // Optimisation for most common case + if (chain && chain->last->Id == itr->first) + break; + } + } + } + break; + } + case SPELLFAMILY_POTION: + { + // alchemist's stone + if (dummySpell->Id == 17619) + { + if (procSpell->SpellFamilyName == SPELLFAMILY_POTION) + { + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) + { + if (procSpell->Effects[i].Effect == SPELL_EFFECT_HEAL) + { + triggered_spell_id = 21399; + } + else if (procSpell->Effects[i].Effect == SPELL_EFFECT_ENERGIZE) + { + triggered_spell_id = 21400; + } + else + continue; + + basepoints0 = int32(CalculateSpellDamage(this, procSpell, i) * 0.4f); + CastCustomSpell(this, triggered_spell_id, &basepoints0, nullptr, nullptr, true, NULL, triggeredByAura); + } + return true; + } + } + break; + } + case SPELLFAMILY_PET: + { + switch (dummySpell->SpellIconID) + { + // Guard Dog + case 201: + { + if (!victim) + return false; + + triggered_spell_id = 54445; + target = this; + float addThreat = float(CalculatePct(procSpell->Effects[0].CalcValue(this), triggerAmount)); + victim->AddThreat(this, addThreat); + break; + } + // Silverback + case 1582: + triggered_spell_id = dummySpell->Id == 62765 ? 62801 : 62800; + target = this; + break; + } + break; } - break; - } default: break; } @@ -7915,7 +8007,7 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere // Used in case when access to whole aura is needed // All procs should be handled like this... -bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 /*procFlag*/, uint32 procEx, uint32 /*cooldown*/, bool * handled) +bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* /*procSpell*/, uint32 /*procFlag*/, uint32 procEx, uint32 /*cooldown*/, bool* handled) { SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo(); @@ -7934,20 +8026,20 @@ bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, Sp case 72455: case 72832: case 72833: - { - if (Unit* caster = triggeredByAura->GetCaster()) - if (victim && caster->GetGUID() == victim->GetGUID()) - { - *handled = true; - uint32 stack = triggeredByAura->GetStackAmount(); - int32 const mod = (GetMap()->GetSpawnMode() & 1) ? 1500 : 1250; - int32 dmg = 0; - for (uint8 i = 1; i <= stack; ++i) - dmg += mod * i; - caster->CastCustomSpell(70701, SPELLVALUE_BASE_POINT0, dmg); - } - break; - } + { + if (Unit* caster = triggeredByAura->GetCaster()) + if (victim && caster->GetGUID() == victim->GetGUID()) + { + *handled = true; + uint32 stack = triggeredByAura->GetStackAmount(); + int32 const mod = (GetMap()->GetSpawnMode() & 1) ? 1500 : 1250; + int32 dmg = 0; + for (uint8 i = 1; i <= stack; ++i) + dmg += mod * i; + caster->CastCustomSpell(70701, SPELLVALUE_BASE_POINT0, dmg); + } + break; + } // Ball of Flames Proc case 71756: case 72782: @@ -7958,136 +8050,136 @@ bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, Sp break; // Discerning Eye of the Beast case 59915: - { - CastSpell(this, 59914, true); // 59914 already has correct basepoints in DBC, no need for custom bp - *handled = true; - break; - } + { + CastSpell(this, 59914, true); // 59914 already has correct basepoints in DBC, no need for custom bp + *handled = true; + break; + } // Swift Hand of Justice case 59906: - { - int32 bp0 = CalculatePct(GetMaxHealth(), dummySpell->Effects[EFFECT_0]. CalcValue()); - CastCustomSpell(this, 59913, &bp0, nullptr, nullptr, true); - *handled = true; - break; - } + { + int32 bp0 = CalculatePct(GetMaxHealth(), dummySpell->Effects[EFFECT_0]. CalcValue()); + CastCustomSpell(this, 59913, &bp0, nullptr, nullptr, true); + *handled = true; + break; + } } break; case SPELLFAMILY_MAGE: - { - // Combustion - switch (dummySpell->Id) { - case 11129: + // Combustion + switch (dummySpell->Id) { - *handled = true; - Unit* caster = triggeredByAura->GetCaster(); - if (!caster || !damage) - return false; + case 11129: + { + *handled = true; + Unit* caster = triggeredByAura->GetCaster(); + if (!caster || !damage) + return false; - // last charge and crit - if (triggeredByAura->GetCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT)) - return true; // charge counting (will removed) + // last charge and crit + if (triggeredByAura->GetCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT)) + return true; // charge counting (will removed) - CastSpell(this, 28682, true); + CastSpell(this, 28682, true); - return procEx & PROC_EX_CRITICAL_HIT; - } - // Empowered Fire - case 31656: - case 31657: - case 31658: - { - *handled = true; - - SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(67545); - if (!spInfo) - return false; - - int32 bp0 = int32(CalculatePct(GetMaxPower(POWER_MANA), spInfo->Effects[0].CalcValue())); - CastCustomSpell(this, 67545, &bp0, nullptr, nullptr, true, NULL, triggeredByAura->GetEffect(EFFECT_0), GetGUID()); - return true; + return procEx & PROC_EX_CRITICAL_HIT; + } + // Empowered Fire + case 31656: + case 31657: + case 31658: + { + *handled = true; + + SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(67545); + if (!spInfo) + return false; + + int32 bp0 = int32(CalculatePct(GetMaxPower(POWER_MANA), spInfo->Effects[0].CalcValue())); + CastCustomSpell(this, 67545, &bp0, nullptr, nullptr, true, NULL, triggeredByAura->GetEffect(EFFECT_0), GetGUID()); + return true; + } } + break; } - break; - } case SPELLFAMILY_DEATHKNIGHT: - { - // Blood of the North - // Reaping - // Death Rune Mastery - // xinef: Icon 22 is used for item bonus, skip - if (dummySpell->SpellIconID == 3041 || (dummySpell->SpellIconID == 22 && dummySpell->Id != 62459) || dummySpell->SpellIconID == 2622) { - *handled = true; - // Convert recently used Blood Rune to Death Rune - if (Player* player = ToPlayer()) + // Blood of the North + // Reaping + // Death Rune Mastery + // xinef: Icon 22 is used for item bonus, skip + if (dummySpell->SpellIconID == 3041 || (dummySpell->SpellIconID == 22 && dummySpell->Id != 62459) || dummySpell->SpellIconID == 2622) { - if (player->getClass() != CLASS_DEATH_KNIGHT) - return false; - - // xinef: not true - //RuneType rune = ToPlayer()->GetLastUsedRune(); - // can't proc from death rune use - //if (rune == RUNE_DEATH) - // return false; - AuraEffect* aurEff = triggeredByAura->GetEffect(EFFECT_0); - if (!aurEff) - return false; - - // Reset amplitude - set death rune remove timer to 30s - aurEff->ResetPeriodic(true); - uint32 runesLeft; - - if (dummySpell->SpellIconID == 2622) - runesLeft = 2; - else - runesLeft = 1; - - for (uint8 i = 0; i < MAX_RUNES && runesLeft; ++i) + *handled = true; + // Convert recently used Blood Rune to Death Rune + if (Player* player = ToPlayer()) { - if (dummySpell->SpellIconID == 2622) - { - if (player->GetCurrentRune(i) == RUNE_DEATH || - player->GetBaseRune(i) == RUNE_BLOOD) - continue; - } - else - { - if (player->GetCurrentRune(i) == RUNE_DEATH || - player->GetBaseRune(i) != RUNE_BLOOD) - continue; - } - if (player->GetRuneCooldown(i) != player->GetRuneBaseCooldown(i, false)) - continue; + if (player->getClass() != CLASS_DEATH_KNIGHT) + return false; - --runesLeft; - // Mark aura as used - player->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff); + // xinef: not true + //RuneType rune = ToPlayer()->GetLastUsedRune(); + // can't proc from death rune use + //if (rune == RUNE_DEATH) + // return false; + AuraEffect* aurEff = triggeredByAura->GetEffect(EFFECT_0); + if (!aurEff) + return false; + + // Reset amplitude - set death rune remove timer to 30s + aurEff->ResetPeriodic(true); + uint32 runesLeft; + + if (dummySpell->SpellIconID == 2622) + runesLeft = 2; + else + runesLeft = 1; + + for (uint8 i = 0; i < MAX_RUNES && runesLeft; ++i) + { + if (dummySpell->SpellIconID == 2622) + { + if (player->GetCurrentRune(i) == RUNE_DEATH || + player->GetBaseRune(i) == RUNE_BLOOD) + continue; + } + else + { + if (player->GetCurrentRune(i) == RUNE_DEATH || + player->GetBaseRune(i) != RUNE_BLOOD) + continue; + } + if (player->GetRuneCooldown(i) != player->GetRuneBaseCooldown(i, false)) + continue; + + --runesLeft; + // Mark aura as used + player->AddRuneByAuraEffect(i, RUNE_DEATH, aurEff); + } + return true; } - return true; + return false; } - return false; + break; } - break; - } case SPELLFAMILY_WARRIOR: - { - switch (dummySpell->Id) { - // Item - Warrior T10 Protection 4P Bonus - case 70844: + switch (dummySpell->Id) { - int32 basepoints0 = CalculatePct(GetMaxHealth(), dummySpell->Effects[EFFECT_1]. CalcValue()); - CastCustomSpell(this, 70845, &basepoints0, nullptr, nullptr, true); - break; + // Item - Warrior T10 Protection 4P Bonus + case 70844: + { + int32 basepoints0 = CalculatePct(GetMaxHealth(), dummySpell->Effects[EFFECT_1]. CalcValue()); + CastCustomSpell(this, 70845, &basepoints0, nullptr, nullptr, true); + break; + } + default: + break; } - default: - break; + break; } - break; - } } return false; } @@ -8110,7 +8202,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg basepoints0 = triggerAmount; Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER - ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : nullptr; + ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : nullptr; // Try handle unknown trigger spells //if (sSpellMgr->GetSpellInfo(trigger_spell_id) == nullptr) @@ -8128,72 +8220,72 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg target = victim; break; case 57345: // Darkmoon Card: Greatness - { - float stat = 0.0f; - // strength - if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); } - // agility - if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); } - // intellect - if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);} - // spirit - if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; } - break; - } + { + float stat = 0.0f; + // strength + if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229; stat = GetStat(STAT_STRENGTH); } + // agility + if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233; stat = GetStat(STAT_AGILITY); } + // intellect + if (GetStat(STAT_INTELLECT) > stat) { trigger_spell_id = 60234; stat = GetStat(STAT_INTELLECT);} + // spirit + if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; } + break; + } case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket - { - if (!damage) - return false; - float stat = 0.0f; - // strength - if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); } - // agility - if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; } - break; - } + { + if (!damage) + return false; + float stat = 0.0f; + // strength + if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708; stat = GetStat(STAT_STRENGTH); } + // agility + if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; } + break; + } case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket - { - if (!damage) - return false; - float stat = 0.0f; - // strength - if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); } - // agility - if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; } - break; - } + { + if (!damage) + return false; + float stat = 0.0f; + // strength + if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773; stat = GetStat(STAT_STRENGTH); } + // agility + if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; } + break; + } // Mana Drain Trigger case 27522: case 40336: - { - // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target. - if (IsAlive()) - CastSpell(this, 29471, true, castItem, triggeredByAura); - if (victim && victim->IsAlive()) - CastSpell(victim, 27526, true, castItem, triggeredByAura); - return true; - } + { + // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target. + if (IsAlive()) + CastSpell(this, 29471, true, castItem, triggeredByAura); + if (victim && victim->IsAlive()) + CastSpell(victim, 27526, true, castItem, triggeredByAura); + return true; + } // Forge of Souls, Devourer of Souls, Mirrored Soul case 69023: - { - int32 dmg = damage * 0.45f; - if (dmg>0) - if (Aura* a = GetAura(69023)) - if (Unit* c = a->GetCaster()) - CastCustomSpell(c, 69034, &dmg, 0, 0, true); - return true; - } + { + int32 dmg = damage * 0.45f; + if (dmg > 0) + if (Aura* a = GetAura(69023)) + if (Unit* c = a->GetCaster()) + CastCustomSpell(c, 69034, &dmg, 0, 0, true); + return true; + } // Soul-Trader Beacon proc aura case 50051: - { - if (!victim) + { + if (!victim) + return false; + + if (Creature* cr = ObjectAccessor::GetCreature(*this, m_SummonSlot[SUMMON_SLOT_MINIPET])) + cr->CastSpell(victim, 50101, true); + return false; - - if (Creature* cr = ObjectAccessor::GetCreature(*this, m_SummonSlot[SUMMON_SLOT_MINIPET])) - cr->CastSpell(victim, 50101, true); - - return false; - } + } } break; case SPELLFAMILY_MAGE: @@ -8212,315 +8304,373 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg } break; case SPELLFAMILY_WARLOCK: - { - // Drain Soul - if (auraSpellInfo->SpellFamilyFlags[0] & 0x4000) { - // Improved Drain Soul - Unit::AuraEffectList const& mAddFlatModifier = GetAuraEffectsByType(SPELL_AURA_DUMMY); - for (Unit::AuraEffectList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i) + // Drain Soul + if (auraSpellInfo->SpellFamilyFlags[0] & 0x4000) { - if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellInfo()->SpellIconID == 113) + // Improved Drain Soul + Unit::AuraEffectList const& mAddFlatModifier = GetAuraEffectsByType(SPELL_AURA_DUMMY); + for (Unit::AuraEffectList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i) { - int32 value2 = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 2); - basepoints0 = int32(CalculatePct(GetMaxPower(POWER_MANA), value2)); - // Drain Soul - CastCustomSpell(this, 18371, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); - break; + if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellInfo()->SpellIconID == 113) + { + int32 value2 = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 2); + basepoints0 = int32(CalculatePct(GetMaxPower(POWER_MANA), value2)); + // Drain Soul + CastCustomSpell(this, 18371, &basepoints0, nullptr, nullptr, true, castItem, triggeredByAura); + break; + } } - } - // Not remove charge (aura removed on death in any cases) - // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura - return false; - } - // Nether Protection - else if (auraSpellInfo->SpellIconID == 1985) - { - if (!procSpell) + // Not remove charge (aura removed on death in any cases) + // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura return false; - switch (GetFirstSchoolInMask(procSpell->GetSchoolMask())) + } + // Nether Protection + else if (auraSpellInfo->SpellIconID == 1985) { - case SPELL_SCHOOL_NORMAL: - return false; // ignore - case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break; - case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break; - case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break; - case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break; - case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break; - case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break; - default: + if (!procSpell) return false; - } - } - break; - } - case SPELLFAMILY_PRIEST: - { - // Blessed Recovery - if (auraSpellInfo->SpellIconID == 1875) - { - switch (auraSpellInfo->Id) - { - case 27811: trigger_spell_id = 27813; break; - case 27815: trigger_spell_id = 27817; break; - case 27816: trigger_spell_id = 27818; break; - default: - sLog->outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id); - return false; - } - basepoints0 = CalculatePct(int32(damage), triggerAmount) / 3; - target = this; - // Add remaining ticks to healing done - CastDelayedSpellWithPeriodicAmount(this, trigger_spell_id, SPELL_AURA_PERIODIC_HEAL, basepoints0); - return true; - } - break; - } - case SPELLFAMILY_DRUID: - { - switch (auraSpellInfo->Id) - { - // Druid Forms Trinket - case 37336: - { - switch (GetShapeshiftForm()) + switch (GetFirstSchoolInMask(procSpell->GetSchoolMask())) { - case FORM_NONE: trigger_spell_id = 37344; break; - case FORM_CAT: trigger_spell_id = 37341; break; - case FORM_BEAR: - case FORM_DIREBEAR: trigger_spell_id = 37340; break; - case FORM_TREE: trigger_spell_id = 37342; break; - case FORM_MOONKIN: trigger_spell_id = 37343; break; + case SPELL_SCHOOL_NORMAL: + return false; // ignore + case SPELL_SCHOOL_HOLY: + trigger_spell_id = 54370; + break; + case SPELL_SCHOOL_FIRE: + trigger_spell_id = 54371; + break; + case SPELL_SCHOOL_NATURE: + trigger_spell_id = 54375; + break; + case SPELL_SCHOOL_FROST: + trigger_spell_id = 54372; + break; + case SPELL_SCHOOL_SHADOW: + trigger_spell_id = 54374; + break; + case SPELL_SCHOOL_ARCANE: + trigger_spell_id = 54373; + break; default: return false; } - break; } - // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred) - case 67353: - { - switch (GetShapeshiftForm()) - { - case FORM_CAT: trigger_spell_id = 67355; break; - case FORM_BEAR: - case FORM_DIREBEAR: trigger_spell_id = 67354; break; - default: - return false; - } - break; - } - default: - break; - } - break; - } - case SPELLFAMILY_HUNTER: - { - if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots - { - if (!victim) - return false; - - switch (auraSpellInfo->Id) - { - case 53234: // Rank 1 - case 53237: // Rank 2 - case 53238: // Rank 3 - trigger_spell_id = 63468; - break; - default: - sLog->outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots", auraSpellInfo->Id); - return false; - } - SpellInfo const* TriggerPS = sSpellMgr->GetSpellInfo(trigger_spell_id); - if (!TriggerPS) - return false; - - basepoints0 = CalculatePct(int32(damage), triggerAmount) / (TriggerPS->GetMaxDuration() / TriggerPS->Effects[0].Amplitude); - victim->CastDelayedSpellWithPeriodicAmount(this, trigger_spell_id, SPELL_AURA_PERIODIC_DAMAGE, basepoints0); - return true; - } - // Item - Hunter T9 4P Bonus (Steady Shot) - else if (auraSpellInfo->Id == 67151) - { - if (GetTypeId() != TYPEID_PLAYER || !ToPlayer()->GetPet()) - return false; - - target = ToPlayer()->GetPet(); - trigger_spell_id = 68130; break; } - break; - } - case SPELLFAMILY_PALADIN: - { - switch (auraSpellInfo->Id) + case SPELLFAMILY_PRIEST: { - // Soul Preserver - case 60510: + // Blessed Recovery + if (auraSpellInfo->SpellIconID == 1875) { - switch (getClass()) - { - case CLASS_DRUID: - trigger_spell_id = 60512; - break; - case CLASS_PALADIN: - trigger_spell_id = 60513; - break; - case CLASS_PRIEST: - trigger_spell_id = 60514; - break; - case CLASS_SHAMAN: - trigger_spell_id = 60515; - break; - } - - target = this; - break; - } - case 37657: // Lightning Capacitor - case 54841: // Thunder Capacitor - case 67712: // Item - Coliseum 25 Normal Caster Trinket - case 67758: // Item - Coliseum 25 Heroic Caster Trinket - { - if (!victim || !victim->IsAlive() || GetTypeId() != TYPEID_PLAYER) - return false; - - uint32 stack_spell_id = 0; switch (auraSpellInfo->Id) { - case 37657: - stack_spell_id = 37658; - trigger_spell_id = 37661; + case 27811: + trigger_spell_id = 27813; break; - case 54841: - stack_spell_id = 54842; - trigger_spell_id = 54843; + case 27815: + trigger_spell_id = 27817; break; - case 67712: - stack_spell_id = 67713; - trigger_spell_id = 67714; + case 27816: + trigger_spell_id = 27818; break; - case 67758: - stack_spell_id = 67759; - trigger_spell_id = 67760; - break; - } - - if (cooldown && GetTypeId() == TYPEID_PLAYER) - { - if (ToPlayer()->HasSpellCooldown(stack_spell_id)) + default: + sLog->outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id); return false; - - ToPlayer()->AddSpellCooldown(stack_spell_id, 0, cooldown); } - - CastSpell(this, stack_spell_id, true, NULL, triggeredByAura); - - Aura* dummy = GetAura(stack_spell_id); - if (!dummy || dummy->GetStackAmount() < triggerAmount) - return false; - - RemoveAurasDueToSpell(stack_spell_id); - CastSpell(victim, trigger_spell_id, true, NULL, triggeredByAura); + basepoints0 = CalculatePct(int32(damage), triggerAmount) / 3; + target = this; + // Add remaining ticks to healing done + CastDelayedSpellWithPeriodicAmount(this, trigger_spell_id, SPELL_AURA_PERIODIC_HEAL, basepoints0); return true; } - default: - // Illumination - if (auraSpellInfo->SpellIconID == 241) - { - if (!procSpell) - return false; - // procspell is triggered spell but we need mana cost of original casted spell - uint32 originalSpellId = procSpell->Id; - // Holy Shock heal - if (procSpell->SpellFamilyFlags[1] & 0x00010000) - { - switch (procSpell->Id) - { - case 25914: originalSpellId = 20473; break; - case 25913: originalSpellId = 20929; break; - case 25903: originalSpellId = 20930; break; - case 27175: originalSpellId = 27174; break; - case 33074: originalSpellId = 33072; break; - case 48820: originalSpellId = 48824; break; - case 48821: originalSpellId = 48825; break; - default: - sLog->outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock", procSpell->Id); - return false; - } - } - SpellInfo const* originalSpell = sSpellMgr->GetSpellInfo(originalSpellId); - if (!originalSpell) - { - sLog->outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu", originalSpellId); - return false; - } - // percent stored in effect 1 (class scripts) base points - int32 cost = int32(originalSpell->ManaCost + CalculatePct(GetCreateMana(), originalSpell->ManaCostPercentage)); - basepoints0 = CalculatePct(cost, auraSpellInfo->Effects[1].CalcValue()); - trigger_spell_id = 20272; - target = this; - } - break; + break; } - break; - } - case SPELLFAMILY_SHAMAN: - { - // Lightning Shield (overwrite non existing triggered spell call in spell.dbc - if (auraSpellInfo->SpellFamilyFlags[0] & 0x400) + case SPELLFAMILY_DRUID: { - trigger_spell_id = sSpellMgr->GetSpellWithRank(26364, auraSpellInfo->GetRank()); - } - // Nature's Guardian - else if (auraSpellInfo->SpellIconID == 2013) - { - // Check health condition - should drop to less 30% (damage deal after this!) - if (!HealthBelowPctDamaged(30, damage)) - return false; - - if (victim && victim->IsAlive()) - victim->getThreatManager().modifyThreatPercent(this, -10); - - basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); - trigger_spell_id = 31616; - target = this; - } - break; - } - case SPELLFAMILY_DEATHKNIGHT: - { - // Acclimation - if (auraSpellInfo->SpellIconID == 1930) - { - if (!procSpell) - return false; - switch (GetFirstSchoolInMask(procSpell->GetSchoolMask())) + switch (auraSpellInfo->Id) { - case SPELL_SCHOOL_NORMAL: - return false; // ignore - case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break; - case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break; - case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break; - case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break; - case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break; - case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break; + // Druid Forms Trinket + case 37336: + { + switch (GetShapeshiftForm()) + { + case FORM_NONE: + trigger_spell_id = 37344; + break; + case FORM_CAT: + trigger_spell_id = 37341; + break; + case FORM_BEAR: + case FORM_DIREBEAR: + trigger_spell_id = 37340; + break; + case FORM_TREE: + trigger_spell_id = 37342; + break; + case FORM_MOONKIN: + trigger_spell_id = 37343; + break; + default: + return false; + } + break; + } + // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred) + case 67353: + { + switch (GetShapeshiftForm()) + { + case FORM_CAT: + trigger_spell_id = 67355; + break; + case FORM_BEAR: + case FORM_DIREBEAR: + trigger_spell_id = 67354; + break; + default: + return false; + } + break; + } default: - return false; + break; } + break; } - // Blood Presence (Improved) - else if (auraSpellInfo->Id == 63611) + case SPELLFAMILY_HUNTER: { - if (GetTypeId() != TYPEID_PLAYER) - return false; + if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots + { + if (!victim) + return false; - trigger_spell_id = 50475; - basepoints0 = CalculatePct(int32(damage), triggerAmount); + switch (auraSpellInfo->Id) + { + case 53234: // Rank 1 + case 53237: // Rank 2 + case 53238: // Rank 3 + trigger_spell_id = 63468; + break; + default: + sLog->outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots", auraSpellInfo->Id); + return false; + } + SpellInfo const* TriggerPS = sSpellMgr->GetSpellInfo(trigger_spell_id); + if (!TriggerPS) + return false; + + basepoints0 = CalculatePct(int32(damage), triggerAmount) / (TriggerPS->GetMaxDuration() / TriggerPS->Effects[0].Amplitude); + victim->CastDelayedSpellWithPeriodicAmount(this, trigger_spell_id, SPELL_AURA_PERIODIC_DAMAGE, basepoints0); + return true; + } + // Item - Hunter T9 4P Bonus (Steady Shot) + else if (auraSpellInfo->Id == 67151) + { + if (GetTypeId() != TYPEID_PLAYER || !ToPlayer()->GetPet()) + return false; + + target = ToPlayer()->GetPet(); + trigger_spell_id = 68130; + break; + } + break; + } + case SPELLFAMILY_PALADIN: + { + switch (auraSpellInfo->Id) + { + // Soul Preserver + case 60510: + { + switch (getClass()) + { + case CLASS_DRUID: + trigger_spell_id = 60512; + break; + case CLASS_PALADIN: + trigger_spell_id = 60513; + break; + case CLASS_PRIEST: + trigger_spell_id = 60514; + break; + case CLASS_SHAMAN: + trigger_spell_id = 60515; + break; + } + + target = this; + break; + } + case 37657: // Lightning Capacitor + case 54841: // Thunder Capacitor + case 67712: // Item - Coliseum 25 Normal Caster Trinket + case 67758: // Item - Coliseum 25 Heroic Caster Trinket + { + if (!victim || !victim->IsAlive() || GetTypeId() != TYPEID_PLAYER) + return false; + + uint32 stack_spell_id = 0; + switch (auraSpellInfo->Id) + { + case 37657: + stack_spell_id = 37658; + trigger_spell_id = 37661; + break; + case 54841: + stack_spell_id = 54842; + trigger_spell_id = 54843; + break; + case 67712: + stack_spell_id = 67713; + trigger_spell_id = 67714; + break; + case 67758: + stack_spell_id = 67759; + trigger_spell_id = 67760; + break; + } + + if (cooldown && GetTypeId() == TYPEID_PLAYER) + { + if (ToPlayer()->HasSpellCooldown(stack_spell_id)) + return false; + + ToPlayer()->AddSpellCooldown(stack_spell_id, 0, cooldown); + } + + CastSpell(this, stack_spell_id, true, NULL, triggeredByAura); + + Aura* dummy = GetAura(stack_spell_id); + if (!dummy || dummy->GetStackAmount() < triggerAmount) + return false; + + RemoveAurasDueToSpell(stack_spell_id); + CastSpell(victim, trigger_spell_id, true, NULL, triggeredByAura); + return true; + } + default: + // Illumination + if (auraSpellInfo->SpellIconID == 241) + { + if (!procSpell) + return false; + // procspell is triggered spell but we need mana cost of original casted spell + uint32 originalSpellId = procSpell->Id; + // Holy Shock heal + if (procSpell->SpellFamilyFlags[1] & 0x00010000) + { + switch (procSpell->Id) + { + case 25914: + originalSpellId = 20473; + break; + case 25913: + originalSpellId = 20929; + break; + case 25903: + originalSpellId = 20930; + break; + case 27175: + originalSpellId = 27174; + break; + case 33074: + originalSpellId = 33072; + break; + case 48820: + originalSpellId = 48824; + break; + case 48821: + originalSpellId = 48825; + break; + default: + sLog->outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock", procSpell->Id); + return false; + } + } + SpellInfo const* originalSpell = sSpellMgr->GetSpellInfo(originalSpellId); + if (!originalSpell) + { + sLog->outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu", originalSpellId); + return false; + } + // percent stored in effect 1 (class scripts) base points + int32 cost = int32(originalSpell->ManaCost + CalculatePct(GetCreateMana(), originalSpell->ManaCostPercentage)); + basepoints0 = CalculatePct(cost, auraSpellInfo->Effects[1].CalcValue()); + trigger_spell_id = 20272; + target = this; + } + break; + } + break; + } + case SPELLFAMILY_SHAMAN: + { + // Lightning Shield (overwrite non existing triggered spell call in spell.dbc + if (auraSpellInfo->SpellFamilyFlags[0] & 0x400) + { + trigger_spell_id = sSpellMgr->GetSpellWithRank(26364, auraSpellInfo->GetRank()); + } + // Nature's Guardian + else if (auraSpellInfo->SpellIconID == 2013) + { + // Check health condition - should drop to less 30% (damage deal after this!) + if (!HealthBelowPctDamaged(30, damage)) + return false; + + if (victim && victim->IsAlive()) + victim->getThreatManager().modifyThreatPercent(this, -10); + + basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); + trigger_spell_id = 31616; + target = this; + } + break; + } + case SPELLFAMILY_DEATHKNIGHT: + { + // Acclimation + if (auraSpellInfo->SpellIconID == 1930) + { + if (!procSpell) + return false; + switch (GetFirstSchoolInMask(procSpell->GetSchoolMask())) + { + case SPELL_SCHOOL_NORMAL: + return false; // ignore + case SPELL_SCHOOL_HOLY: + trigger_spell_id = 50490; + break; + case SPELL_SCHOOL_FIRE: + trigger_spell_id = 50362; + break; + case SPELL_SCHOOL_NATURE: + trigger_spell_id = 50488; + break; + case SPELL_SCHOOL_FROST: + trigger_spell_id = 50485; + break; + case SPELL_SCHOOL_SHADOW: + trigger_spell_id = 50489; + break; + case SPELL_SCHOOL_ARCANE: + trigger_spell_id = 50486; + break; + default: + return false; + } + } + // Blood Presence (Improved) + else if (auraSpellInfo->Id == 63611) + { + if (GetTypeId() != TYPEID_PLAYER) + return false; + + trigger_spell_id = 50475; + basepoints0 = CalculatePct(int32(damage), triggerAmount); + } + break; } - break; - } } } @@ -8545,76 +8695,76 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 12834: case 12849: case 12867: - { - if (GetTypeId() != TYPEID_PLAYER) - return false; + { + if (GetTypeId() != TYPEID_PLAYER) + return false; - if (procFlags & PROC_FLAG_DONE_OFFHAND_ATTACK) - basepoints0 = int32((GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE)+GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE))/2.0f); - else - basepoints0 = int32((GetFloatValue(UNIT_FIELD_MAXDAMAGE)+GetFloatValue(UNIT_FIELD_MINDAMAGE))/2.0f); - break; - } + if (procFlags & PROC_FLAG_DONE_OFFHAND_ATTACK) + basepoints0 = int32((GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE)) / 2.0f); + else + basepoints0 = int32((GetFloatValue(UNIT_FIELD_MAXDAMAGE) + GetFloatValue(UNIT_FIELD_MINDAMAGE)) / 2.0f); + break; + } // Persistent Shield (Scarab Brooch trinket) // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect) case 26467: - { - basepoints0 = int32(CalculatePct(damage, 15)); - target = victim; - trigger_spell_id = 26470; - break; - } + { + basepoints0 = int32(CalculatePct(damage, 15)); + target = victim; + trigger_spell_id = 26470; + break; + } // Unyielding Knights (item exploit 29108\29109) case 38164: - { - if (!victim || victim->GetEntry() != 19457) // Proc only if your target is Grillok - return false; - break; - } + { + if (!victim || victim->GetEntry() != 19457) // Proc only if your target is Grillok + return false; + break; + } // Deflection case 52420: - { - if (!HealthBelowPct(35)) - return false; - break; - } + { + if (!HealthBelowPct(35)) + return false; + break; + } // Cheat Death case 28845: - { - // When your health drops below 20% - if (HealthBelowPctDamaged(20, damage) || HealthBelowPct(20)) - return false; - break; - } + { + // When your health drops below 20% + if (HealthBelowPctDamaged(20, damage) || HealthBelowPct(20)) + return false; + break; + } // Deadly Swiftness (Rank 1) case 31255: - { - // whenever you deal damage to a target who is below 20% health. - if (!victim || !victim->IsAlive() || victim->HealthAbovePct(20)) - return false; + { + // whenever you deal damage to a target who is below 20% health. + if (!victim || !victim->IsAlive() || victim->HealthAbovePct(20)) + return false; - target = this; - trigger_spell_id = 22588; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - } + target = this; + trigger_spell_id = 22588; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + } // Bonus Healing (Crystal Spire of Karabor mace) case 40971: - { - // If your target is below $s1% health - if (!victim || !victim->IsAlive() || victim->HealthAbovePct(triggerAmount)) - return false; - break; - } + { + // If your target is below $s1% health + if (!victim || !victim->IsAlive() || victim->HealthAbovePct(triggerAmount)) + return false; + break; + } // Rapid Recuperation case 53228: case 53232: - { - // This effect only from Rapid Fire (ability cast) - if (!(procSpell->SpellFamilyFlags[0] & 0x20)) - return false; - break; - } + { + // This effect only from Rapid Fire (ability cast) + if (!(procSpell->SpellFamilyFlags[0] & 0x20)) + return false; + break; + } // Decimation case 63156: case 63158: @@ -8629,17 +8779,17 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg break; case 15337: // Improved Spirit Tap (Rank 1) case 15338: // Improved Spirit Tap (Rank 2) - { - if (!procSpell) - return false; - - if (procSpell->SpellFamilyFlags[0] & 0x800000) - if ((procSpell->Id != 58381) || !roll_chance_i(50)) + { + if (!procSpell) return false; - target = victim; - break; - } + if (procSpell->SpellFamilyFlags[0] & 0x800000) + if ((procSpell->Id != 58381) || !roll_chance_i(50)) + return false; + + target = victim; + break; + } // Professor Putricide - Ooze Spell Tank Protection case 71770: if (victim) @@ -8650,12 +8800,12 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 71640: // Item - Icecrown 25 Heroic Tank Trinket 1 case 75475: // Item - Chamber of Aspects 25 Normal Tank Trinket case 75481: // Item - Chamber of Aspects 25 Heroic Tank Trinket - { - // Procs only if damage takes health below $s1% - if (!HealthBelowPctDamaged(triggerAmount, damage)) - return false; - break; - } + { + // Procs only if damage takes health below $s1% + if (!HealthBelowPctDamaged(triggerAmount, damage)) + return false; + break; + } default: break; } @@ -8719,7 +8869,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg if (!victim) return false; - if (AuraEffect *aurEff = victim->GetAuraEffect(SPELL_AURA_MOD_ROOT, SPELLFAMILY_DRUID, 20, 0)) + if (AuraEffect* aurEff = victim->GetAuraEffect(SPELL_AURA_MOD_ROOT, SPELLFAMILY_DRUID, 20, 0)) if ((aurEff->GetBase()->GetMaxDuration() - aurEff->GetBase()->GetDuration()) < 1000) return false; @@ -8740,250 +8890,250 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 52910: // Honor Among Thieves case 51699: - { - target = triggeredByAura->GetBase()->GetCaster(); - if (!target) - return false; - - if (Player* pTarget = target->ToPlayer()) { - if (cooldown) - { - if (pTarget->HasSpellCooldown(trigger_spell_id) ) - return false; - pTarget->AddSpellCooldown(trigger_spell_id, 0, cooldown); - } + target = triggeredByAura->GetBase()->GetCaster(); + if (!target) + return false; - Unit* cptarget = nullptr; - if (trigger_spell_id == 51699) + if (Player* pTarget = target->ToPlayer()) { - cptarget = ObjectAccessor::GetUnit(*target, pTarget->GetComboTarget()); - if (!cptarget) - cptarget = pTarget->GetSelectedUnit(); - } - else - cptarget = target; + if (cooldown) + { + if (pTarget->HasSpellCooldown(trigger_spell_id) ) + return false; + pTarget->AddSpellCooldown(trigger_spell_id, 0, cooldown); + } - if (cptarget) - { - target->CastSpell(cptarget, trigger_spell_id, true); - return true; + Unit* cptarget = nullptr; + if (trigger_spell_id == 51699) + { + cptarget = ObjectAccessor::GetUnit(*target, pTarget->GetComboTarget()); + if (!cptarget) + cptarget = pTarget->GetSelectedUnit(); + } + else + cptarget = target; + + if (cptarget) + { + target->CastSpell(cptarget, trigger_spell_id, true); + return true; + } } + return false; } - return false; - } // Cast positive spell on enemy target case 7099: // Curse of Mending case 39703: // Curse of Mending case 29494: // Temptation case 20233: // Improved Lay on Hands (cast on target) - { - target = victim; - break; - } + { + target = victim; + break; + } // Ruby Drake, Evasive Aura case 50241: - { - if( GetAura(50240) ) - return false; + { + if( GetAura(50240) ) + return false; - break; - } + break; + } // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset) case 15250: // Rogue Setup - { - // applied only for main target - if (!victim || (GetTypeId() == TYPEID_PLAYER && victim != ToPlayer()->GetSelectedUnit())) - return false; - break; // continue normal case - } + { + // applied only for main target + if (!victim || (GetTypeId() == TYPEID_PLAYER && victim != ToPlayer()->GetSelectedUnit())) + return false; + break; // continue normal case + } // Finish movies that add combo case 14189: // Seal Fate (Netherblade set) case 14157: // Ruthlessness - { - if (!victim || victim == this) - return false; - // Need add combopoint AFTER finish movie (or they dropped in finish phase) - break; - } + { + if (!victim || victim == this) + return false; + // Need add combopoint AFTER finish movie (or they dropped in finish phase) + break; + } // Item - Druid T10 Balance 2P Bonus case 16870: - { - if (HasAura(70718)) - CastSpell(this, 70721, true); - RemoveAurasDueToSpell(trigger_spell_id); - break; - } + { + if (HasAura(70718)) + CastSpell(this, 70721, true); + RemoveAurasDueToSpell(trigger_spell_id); + break; + } // Shamanistic Rage triggered spell case 30824: - { - basepoints0 = int32(CalculatePct(GetTotalAttackPowerValue(BASE_ATTACK), triggerAmount)); - break; - } + { + basepoints0 = int32(CalculatePct(GetTotalAttackPowerValue(BASE_ATTACK), triggerAmount)); + break; + } // Enlightenment (trigger only from mana cost spells) case 35095: - { - if (!procSpell || procSpell->PowerType != POWER_MANA || (procSpell->ManaCost == 0 && procSpell->ManaCostPercentage == 0 && procSpell->ManaCostPerlevel == 0)) - return false; - break; - } + { + if (!procSpell || procSpell->PowerType != POWER_MANA || (procSpell->ManaCost == 0 && procSpell->ManaCostPercentage == 0 && procSpell->ManaCostPerlevel == 0)) + return false; + break; + } // Demonic Pact case 48090: - { - // Get talent aura from owner - if (IsPet()) - if (Unit* owner = GetOwner()) - { - if (HasSpellCooldown(trigger_spell_id)) - return false; - AddSpellCooldown(trigger_spell_id, 0, cooldown); - - if (AuraEffect* aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0)) + { + // Get talent aura from owner + if (IsPet()) + if (Unit* owner = GetOwner()) { - basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonusDone(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f); // TODO: Is it right? - CastCustomSpell(this, trigger_spell_id, &basepoints0, &basepoints0, NULL, true, castItem, triggeredByAura); - return true; + if (HasSpellCooldown(trigger_spell_id)) + return false; + AddSpellCooldown(trigger_spell_id, 0, cooldown); + + if (AuraEffect* aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0)) + { + basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonusDone(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f); // TODO: Is it right? + CastCustomSpell(this, trigger_spell_id, &basepoints0, &basepoints0, NULL, true, castItem, triggeredByAura); + return true; + } } - } - break; - } + break; + } case 46916: // Slam! (Bloodsurge proc) case 52437: // Sudden Death - { - // Item - Warrior T10 Melee 4P Bonus - if (AuraEffect const* aurEff = GetAuraEffect(70847, 0)) { - if (!roll_chance_i(aurEff->GetAmount())) + // Item - Warrior T10 Melee 4P Bonus + if (AuraEffect const* aurEff = GetAuraEffect(70847, 0)) { - // Xinef: dont allow normal proc to override set one - if (GetAura((trigger_spell_id == 46916) ? 71072 : 71069)) - return false; - // Xinef: just to be sure + if (!roll_chance_i(aurEff->GetAmount())) + { + // Xinef: dont allow normal proc to override set one + if (GetAura((trigger_spell_id == 46916) ? 71072 : 71069)) + return false; + // Xinef: just to be sure + RemoveAurasDueToSpell(70849); + break; + } + + // Xinef: fully remove all auras and reapply once more RemoveAurasDueToSpell(70849); - break; + RemoveAurasDueToSpell(71072); + RemoveAurasDueToSpell(71069); + + CastSpell(this, 70849, true, castItem, triggeredByAura); // Extra Charge! + if (trigger_spell_id == 46916) + CastSpell(this, 71072, true, castItem, triggeredByAura); // Slam GCD Reduced + else + CastSpell(this, 71069, true, castItem, triggeredByAura); // Execute GCD Reduced } - - // Xinef: fully remove all auras and reapply once more - RemoveAurasDueToSpell(70849); - RemoveAurasDueToSpell(71072); - RemoveAurasDueToSpell(71069); - - CastSpell(this, 70849, true, castItem, triggeredByAura); // Extra Charge! - if (trigger_spell_id == 46916) - CastSpell(this, 71072, true, castItem, triggeredByAura); // Slam GCD Reduced - else - CastSpell(this, 71069, true, castItem, triggeredByAura); // Execute GCD Reduced + break; } - break; - } // Sword and Board case 50227: - { - // Remove cooldown on Shield Slam - if (GetTypeId() == TYPEID_PLAYER) - ToPlayer()->RemoveCategoryCooldown(1209); - break; - } + { + // Remove cooldown on Shield Slam + if (GetTypeId() == TYPEID_PLAYER) + ToPlayer()->RemoveCategoryCooldown(1209); + break; + } // Maelstrom Weapon case 53817: - { - // have rank dependent proc chance, ignore too often cases - // PPM = 2.5 * (rank of talent), - uint32 rank = auraSpellInfo->GetRank(); - // 5 rank -> 100% 4 rank -> 80% and etc from full rate - if (!roll_chance_i(20*rank)) - return false; + { + // have rank dependent proc chance, ignore too often cases + // PPM = 2.5 * (rank of talent), + uint32 rank = auraSpellInfo->GetRank(); + // 5 rank -> 100% 4 rank -> 80% and etc from full rate + if (!roll_chance_i(20 * rank)) + return false; - // Item - Shaman T10 Enhancement 4P Bonus - if (AuraEffect const* aurEff = GetAuraEffect(70832, 0)) - if (Aura const* maelstrom = GetAura(53817)) - // xinef: we have 4 charges and all proc conditions are met - aura reaches 5 charges - if ((maelstrom->GetStackAmount() == 4) && roll_chance_i(aurEff->GetAmount())) - CastSpell(this, 70831, true, castItem, triggeredByAura); + // Item - Shaman T10 Enhancement 4P Bonus + if (AuraEffect const* aurEff = GetAuraEffect(70832, 0)) + if (Aura const* maelstrom = GetAura(53817)) + // xinef: we have 4 charges and all proc conditions are met - aura reaches 5 charges + if ((maelstrom->GetStackAmount() == 4) && roll_chance_i(aurEff->GetAmount())) + CastSpell(this, 70831, true, castItem, triggeredByAura); - break; - } + break; + } // Astral Shift case 52179: - { - if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim) - return false; + { + if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) || this == victim) + return false; - // Need stun, fear or silence mechanic - if (!(procSpell->GetAllEffectsMechanicMask() & ((1<GetAllEffectsMechanicMask() & ((1 << MECHANIC_SILENCE) | (1 << MECHANIC_STUN) | (1 << MECHANIC_FEAR)))) + return false; + break; + } // Lock and Load case 56453: - { - // Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere) - if (!(procFlags & PROC_FLAG_DONE_TRAP_ACTIVATION) || !procSpell || !roll_chance_i(triggerAmount)) - return false; - if (procSpell->Id != 63487 /*frost trap*/ && !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST)) - return false; - break; - } + { + // Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere) + if (!(procFlags & PROC_FLAG_DONE_TRAP_ACTIVATION) || !procSpell || !roll_chance_i(triggerAmount)) + return false; + if (procSpell->Id != 63487 /*frost trap*/ && !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST)) + return false; + break; + } // Glyph of Death's Embrace case 58679: - { - // Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags - if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags[0] == 0x80002000)) - return false; - break; - } + { + // Proc only from healing part of Death Coil. Check is essential as all Death Coil spells have 0x2000 mask in SpellFamilyFlags + if (!procSpell || !(procSpell->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && procSpell->SpellFamilyFlags[0] == 0x80002000)) + return false; + break; + } // Glyph of Death Grip case 58628: - { - // remove cooldown of Death Grip - if (GetTypeId() == TYPEID_PLAYER) - ToPlayer()->RemoveSpellCooldown(49576, true); - return true; - } + { + // remove cooldown of Death Grip + if (GetTypeId() == TYPEID_PLAYER) + ToPlayer()->RemoveSpellCooldown(49576, true); + return true; + } // Savage Defense case 62606: - { - basepoints0 = CalculatePct(triggerAmount, GetTotalAttackPowerValue(BASE_ATTACK)); - break; - } + { + basepoints0 = CalculatePct(triggerAmount, GetTotalAttackPowerValue(BASE_ATTACK)); + break; + } // Body and Soul case 64128: case 65081: - { - // Proc only from PW:S cast - if (!(procSpell->SpellFamilyFlags[0] & 0x00000001)) - return false; - break; - } + { + // Proc only from PW:S cast + if (!(procSpell->SpellFamilyFlags[0] & 0x00000001)) + return false; + break; + } // Culling the Herd case 70893: - { - // check if we're doing a critical hit - if (!(procSpell->SpellFamilyFlags[1] & 0x10000000) && (procEx != PROC_EX_CRITICAL_HIT)) - return false; - // check if we're procced by Claw, Bite or Smack (need to use the spell icon ID to detect it) - if (!(procSpell->SpellIconID == 262 || procSpell->SpellIconID == 1680 || procSpell->SpellIconID == 473)) - return false; - break; - } + { + // check if we're doing a critical hit + if (!(procSpell->SpellFamilyFlags[1] & 0x10000000) && (procEx != PROC_EX_CRITICAL_HIT)) + return false; + // check if we're procced by Claw, Bite or Smack (need to use the spell icon ID to detect it) + if (!(procSpell->SpellIconID == 262 || procSpell->SpellIconID == 1680 || procSpell->SpellIconID == 473)) + return false; + break; + } // Fingers of Frost, synchronise with Frostbite case 44544: - { - // Find Frostbite - if (AuraEffect* aurEff = this->GetAuraEffect(SPELL_AURA_ADD_TARGET_TRIGGER, SPELLFAMILY_MAGE, 119, EFFECT_0)) { - if (!victim) - return false; + // Find Frostbite + if (AuraEffect* aurEff = this->GetAuraEffect(SPELL_AURA_ADD_TARGET_TRIGGER, SPELLFAMILY_MAGE, 119, EFFECT_0)) + { + if (!victim) + return false; - uint8 fofRank = sSpellMgr->GetSpellRank(triggeredByAura->GetId()); - uint8 fbRank = sSpellMgr->GetSpellRank(aurEff->GetId()); - uint8 chance = uint8(ceil(fofRank * fbRank * 16.6f)); + uint8 fofRank = sSpellMgr->GetSpellRank(triggeredByAura->GetId()); + uint8 fbRank = sSpellMgr->GetSpellRank(aurEff->GetId()); + uint8 chance = uint8(ceil(fofRank * fbRank * 16.6f)); - if (roll_chance_i(chance)) - CastSpell(victim, aurEff->GetSpellInfo()->Effects[EFFECT_0].TriggerSpell, true); + if (roll_chance_i(chance)) + CastSpell(victim, aurEff->GetSpellInfo()->Effects[EFFECT_0].TriggerSpell, true); + } + break; } - break; - } } // try detect target manually if not set @@ -8999,9 +9149,9 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg } if(basepoints0) - CastCustomSpell(target,triggerEntry->Id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura); + CastCustomSpell(target, triggerEntry->Id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else - CastSpell(target,triggerEntry->Id,true,castItem,triggeredByAura); + CastSpell(target, triggerEntry->Id, true, castItem, triggeredByAura); return true; } @@ -9014,49 +9164,55 @@ bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, Au return false; Item* castItem = triggeredByAura->GetBase()->GetCastItemGUID() && GetTypeId() == TYPEID_PLAYER - ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : nullptr; + ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : nullptr; uint32 triggered_spell_id = 0; switch (scriptId) { case 836: // Improved Blizzard (Rank 1) - { - if (!procSpell || procSpell->SpellVisual[0] != 9487) - return false; - triggered_spell_id = 12484; - break; - } - case 988: // Improved Blizzard (Rank 2) - { - if (!procSpell || procSpell->SpellVisual[0] != 9487) - return false; - triggered_spell_id = 12485; - break; - } - case 989: // Improved Blizzard (Rank 3) - { - if (!procSpell || procSpell->SpellVisual[0] != 9487) - return false; - triggered_spell_id = 12486; - break; - } - case 4533: // Dreamwalker Raiment 2 pieces bonus - { - // Chance 50% - if (!roll_chance_i(50)) - return false; - - switch (victim->getPowerType()) { - case POWER_MANA: triggered_spell_id = 28722; break; - case POWER_RAGE: triggered_spell_id = 28723; break; - case POWER_ENERGY: triggered_spell_id = 28724; break; - default: + if (!procSpell || procSpell->SpellVisual[0] != 9487) return false; + triggered_spell_id = 12484; + break; + } + case 988: // Improved Blizzard (Rank 2) + { + if (!procSpell || procSpell->SpellVisual[0] != 9487) + return false; + triggered_spell_id = 12485; + break; + } + case 989: // Improved Blizzard (Rank 3) + { + if (!procSpell || procSpell->SpellVisual[0] != 9487) + return false; + triggered_spell_id = 12486; + break; + } + case 4533: // Dreamwalker Raiment 2 pieces bonus + { + // Chance 50% + if (!roll_chance_i(50)) + return false; + + switch (victim->getPowerType()) + { + case POWER_MANA: + triggered_spell_id = 28722; + break; + case POWER_RAGE: + triggered_spell_id = 28723; + break; + case POWER_ENERGY: + triggered_spell_id = 28724; + break; + default: + return false; + } + break; } - break; - } case 4537: // Dreamwalker Raiment 6 pieces bonus triggered_spell_id = 28750; // Blessing of the Claw break; @@ -9066,20 +9222,28 @@ bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, Au case 7010: // Revitalize - can proc on full hp target case 7011: case 7012: - { - if (!roll_chance_i(triggeredByAura->GetAmount())) - return false; - switch (victim->getPowerType()) { - case POWER_MANA: triggered_spell_id = 48542; break; - case POWER_RAGE: triggered_spell_id = 48541; break; - case POWER_ENERGY: triggered_spell_id = 48540; break; - case POWER_RUNIC_POWER: triggered_spell_id = 48543; break; - default: - break; + if (!roll_chance_i(triggeredByAura->GetAmount())) + return false; + switch (victim->getPowerType()) + { + case POWER_MANA: + triggered_spell_id = 48542; + break; + case POWER_RAGE: + triggered_spell_id = 48541; + break; + case POWER_ENERGY: + triggered_spell_id = 48540; + break; + case POWER_RUNIC_POWER: + triggered_spell_id = 48543; + break; + default: + break; + } + break; } - break; - } default: break; } @@ -9161,8 +9325,8 @@ void Unit::setPowerType(Powers new_powertype) if (player->NeedSendSpectatorData()) { ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "PWT", new_powertype); - ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "MPW", new_powertype == POWER_RAGE || new_powertype == POWER_RUNIC_POWER ? GetMaxPower(new_powertype)/10 : GetMaxPower(new_powertype)); - ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "CPW", new_powertype == POWER_RAGE || new_powertype == POWER_RUNIC_POWER ? GetPower(new_powertype)/10 : GetPower(new_powertype)); + ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "MPW", new_powertype == POWER_RAGE || new_powertype == POWER_RUNIC_POWER ? GetMaxPower(new_powertype) / 10 : GetMaxPower(new_powertype)); + ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "CPW", new_powertype == POWER_RAGE || new_powertype == POWER_RUNIC_POWER ? GetPower(new_powertype) / 10 : GetPower(new_powertype)); } } @@ -9241,8 +9405,8 @@ ReputationRank Unit::GetReactionTo(Unit const* target) const // same group - checks dependant only on our faction - skip FFA_PVP for example if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner)) return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work - // however client seems to allow mixed group parties, because in 13850 client it works like: - // return GetFactionReactionTo(GetFactionTemplateEntry(), target); + // however client seems to allow mixed group parties, because in 13850 client it works like: + // return GetFactionReactionTo(GetFactionTemplateEntry(), target); } // check FFA_PVP @@ -9263,7 +9427,7 @@ ReputationRank Unit::GetReactionTo(Unit const* target) const { // check contested flags if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD - && selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) + && selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) return REP_HOSTILE; // if faction has reputation, hostile state depends only from AtWar state @@ -9300,7 +9464,7 @@ ReputationRank Unit::GetFactionReactionTo(FactionTemplateEntry const* factionTem { // check contested flags if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD - && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) + && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) return REP_HOSTILE; if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(factionTemplateEntry)) return *repRank; @@ -9468,7 +9632,7 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) // delay offhand weapon attack to next attack time if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK)) - setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY); + setAttackTimer(OFF_ATTACK, ATTACK_DISPLAY_DELAY); if (meleeAttack) SendMeleeAttackStart(victim); @@ -9578,9 +9742,9 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) { if (apply) { - if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1))) + if (!HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) { - SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)); + SetFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); Unit::AuraMap& tAuras = GetOwnedAuras(); for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end(); ++itr) { @@ -9588,7 +9752,7 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) continue; if( (*itr).second->GetSpellInfo()->CasterAuraState == flag ) - if( AuraApplication *aurApp = (*itr).second->GetApplicationOfTarget(GetGUID()) ) + if( AuraApplication* aurApp = (*itr).second->GetApplicationOfTarget(GetGUID()) ) (*itr).second->HandleAllEffects(aurApp, AURA_EFFECT_HANDLE_REAL, true); } @@ -9596,9 +9760,9 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) } else { - if (HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1))) + if (HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) { - RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)); + RemoveFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras { @@ -9606,7 +9770,7 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end(); ++itr) { if( (*itr).second->GetSpellInfo()->CasterAuraState == flag ) - if( AuraApplication *aurApp = (*itr).second->GetApplicationOfTarget(GetGUID()) ) + if( AuraApplication* aurApp = (*itr).second->GetApplicationOfTarget(GetGUID()) ) (*itr).second->HandleAllEffects(aurApp, AURA_EFFECT_HANDLE_REAL, false); } } @@ -9616,11 +9780,11 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) uint32 Unit::BuildAuraStateUpdateForTarget(Unit* target) const { - uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) &~(PER_CASTER_AURA_STATE_MASK); + uint32 auraStates = GetUInt32Value(UNIT_FIELD_AURASTATE) & ~(PER_CASTER_AURA_STATE_MASK); for (AuraStateAurasMap::const_iterator itr = m_auraStateAuras.begin(); itr != m_auraStateAuras.end(); ++itr) - if ((1<<(itr->first-1)) & PER_CASTER_AURA_STATE_MASK) + if ((1 << (itr->first - 1)) & PER_CASTER_AURA_STATE_MASK) if (itr->second->GetBase()->GetCasterGUID() == target->GetGUID()) - auraStates |= (1<<(itr->first-1)); + auraStates |= (1 << (itr->first - 1)); return auraStates; } @@ -9638,7 +9802,7 @@ bool Unit::HasAuraState(AuraStateType flag, SpellInfo const* spellProto, Unit co } // Check per caster aura state // If aura with aurastate by caster not found return false - if ((1<<(flag-1)) & PER_CASTER_AURA_STATE_MASK) + if ((1 << (flag - 1)) & PER_CASTER_AURA_STATE_MASK) { AuraStateAurasMapBounds range = m_auraStateAuras.equal_range(flag); for (AuraStateAurasMap::const_iterator itr = range.first; itr != range.second; ++itr) @@ -9648,7 +9812,7 @@ bool Unit::HasAuraState(AuraStateType flag, SpellInfo const* spellProto, Unit co } } - return HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)); + return HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); } void Unit::SetOwnerGUID(uint64 owner) @@ -9714,7 +9878,7 @@ Player* Unit::GetAffectingPlayer() const return nullptr; } -Minion *Unit::GetFirstMinion() const +Minion* Unit::GetFirstMinion() const { if (uint64 pet_guid = GetMinionGUID()) { @@ -9758,7 +9922,7 @@ Unit* Unit::GetCharm() const return nullptr; } -void Unit::SetMinion(Minion *minion, bool apply) +void Unit::SetMinion(Minion* minion, bool apply) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_UNITS, "SetMinion %u for %u, apply %u", minion->GetEntry(), GetEntry(), apply); @@ -9862,14 +10026,14 @@ void Unit::SetMinion(Minion *minion, bool apply) else if (minion->IsTotem()) { // All summoned by totem minions must disappear when it is removed. - if (SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(minion->ToTotem()->GetSpell())) - for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) - { - if (spInfo->Effects[i].Effect != SPELL_EFFECT_SUMMON) - continue; + if (SpellInfo const* spInfo = sSpellMgr->GetSpellInfo(minion->ToTotem()->GetSpell())) + for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (spInfo->Effects[i].Effect != SPELL_EFFECT_SUMMON) + continue; - RemoveAllMinionsByEntry(spInfo->Effects[i].MiscValue); - } + RemoveAllMinionsByEntry(spInfo->Effects[i].MiscValue); + } } if (GetTypeId() == TYPEID_PLAYER) @@ -9933,7 +10097,7 @@ void Unit::GetAllMinionsByEntry(std::list& Minions, uint32 entry) Unit* unit = *itr; ++itr; if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT - && unit->ToCreature()->IsSummon()) // minion, actually + && unit->ToCreature()->IsSummon()) // minion, actually Minions.push_back(unit->ToCreature()); } } @@ -9945,7 +10109,7 @@ void Unit::RemoveAllMinionsByEntry(uint32 entry) Unit* unit = *itr; ++itr; if (unit->GetEntry() == entry && unit->GetTypeId() == TYPEID_UNIT - && unit->ToCreature()->IsSummon()) // minion, actually + && unit->ToCreature()->IsSummon()) // minion, actually unit->ToTempSummon()->UnSummon(); // i think this is safe because i have never heard that a despawned minion will trigger a same minion } @@ -10095,9 +10259,9 @@ Unit* Unit::GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo) { if (Unit* magnet = (*itr)->GetBase()->GetUnitOwner()) if (spellInfo->CheckExplicitTarget(this, magnet) == SPELL_CAST_OK - //&& spellInfo->CheckTarget(this, magnet, false) == SPELL_CAST_OK - && _IsValidAttackTarget(magnet, spellInfo) - /*&& IsWithinLOSInMap(magnet)*/) + //&& spellInfo->CheckTarget(this, magnet, false) == SPELL_CAST_OK + && _IsValidAttackTarget(magnet, spellInfo) + /*&& IsWithinLOSInMap(magnet)*/) { // Xinef: We should choose minimum between flight time and queue time as in reflect, however we dont know flight time at this point, use arbitrary small number magnet->m_Events.AddEvent(new RedirectSpellEvent(*magnet, victim->GetGUID(), *itr), magnet->m_Events.CalculateQueueTime(100)); @@ -10129,8 +10293,8 @@ Unit* Unit::GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo) { if (Unit* magnet = (*i)->GetBase()->GetCaster()) if (_IsValidAttackTarget(magnet, spellInfo) && magnet->IsWithinLOSInMap(this) - && (!spellInfo || (spellInfo->CheckExplicitTarget(this, magnet) == SPELL_CAST_OK - && spellInfo->CheckTarget(this, magnet, false) == SPELL_CAST_OK))) + && (!spellInfo || (spellInfo->CheckExplicitTarget(this, magnet) == SPELL_CAST_OK + && spellInfo->CheckTarget(this, magnet, false) == SPELL_CAST_OK))) if (roll_chance_i((*i)->GetAmount())) { (*i)->GetBase()->DropCharge(AURA_REMOVE_BY_EXPIRE); @@ -10216,16 +10380,16 @@ Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) if (Target != this && Target->IsAlive() && !IsHostileTo(Target)) nearMembers.push_back(Target); - // Push player's pet to vector - if (Unit* pet = Target->GetGuardianPet()) - if (pet != this && pet->IsAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet)) - nearMembers.push_back(pet); + // Push player's pet to vector + if (Unit* pet = Target->GetGuardianPet()) + if (pet != this && pet->IsAlive() && IsWithinDistInMap(pet, radius) && !IsHostileTo(pet)) + nearMembers.push_back(pet); } if (nearMembers.empty()) return nullptr; - uint32 randTarget = urand(0, nearMembers.size()-1); + uint32 randTarget = urand(0, nearMembers.size() - 1); return nearMembers[randTarget]; } @@ -10283,7 +10447,7 @@ void Unit::UnsummonAllTotems() void Unit::SendHealSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical) { // we guess size - WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+4+4+1+1)); + WorldPacket data(SMSG_SPELLHEALLOG, (8 + 8 + 4 + 4 + 4 + 4 + 1 + 1)); data.append(victim->GetPackGUID()); data.append(GetPackGUID()); data << uint32(SpellID); @@ -10310,7 +10474,7 @@ int32 Unit::HealBySpell(Unit* victim, SpellInfo const* spellInfo, uint32 addHeal void Unit::SendEnergizeSpellLog(Unit* victim, uint32 spellID, uint32 damage, Powers powerType) { - WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1)); + WorldPacket data(SMSG_SPELLENERGIZELOG, (8 + 8 + 4 + 4 + 4 + 1)); data.append(victim->GetPackGUID()); data.append(GetPackGUID()); data << uint32(spellID); @@ -10391,7 +10555,7 @@ float Unit::SpellPctDamageModsDone(Unit* victim, SpellInfo const* spellProto, Da // done scripted mod (take it from owner) Unit* owner = GetOwner() ? GetOwner() : this; - AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + AuraEffectList const& mOverrideClassScript = owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { // Xinef: self cast is ommited (because of Rage of Rivendare) @@ -10416,38 +10580,38 @@ float Unit::SpellPctDamageModsDone(Unit* victim, SpellInfo const* spellProto, Da case 6917: // Death's Embrace case 6926: case 6928: - { - if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } + { + if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } // Soul Siphon case 4992: case 4993: - { - // effect 1 m_amount - int32 maxPercent = (*i)->GetAmount(); - // effect 0 m_amount - int32 stepPercent = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 0); - // count affliction effects and calc additional damage in percentage - int32 modPercent = 0; - AuraApplicationMap const& victimAuras = victim->GetAppliedAuras(); - for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr) { - Aura const* aura = itr->second->GetBase(); - SpellInfo const* m_spell = aura->GetSpellInfo(); - if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags[1] & 0x0004071B || m_spell->SpellFamilyFlags[0] & 0x8044C402)) - continue; - modPercent += stepPercent * aura->GetStackAmount(); - if (modPercent >= maxPercent) + // effect 1 m_amount + int32 maxPercent = (*i)->GetAmount(); + // effect 0 m_amount + int32 stepPercent = CalculateSpellDamage(this, (*i)->GetSpellInfo(), 0); + // count affliction effects and calc additional damage in percentage + int32 modPercent = 0; + AuraApplicationMap const& victimAuras = victim->GetAppliedAuras(); + for (AuraApplicationMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr) { - modPercent = maxPercent; - break; + Aura const* aura = itr->second->GetBase(); + SpellInfo const* m_spell = aura->GetSpellInfo(); + if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags[1] & 0x0004071B || m_spell->SpellFamilyFlags[0] & 0x8044C402)) + continue; + modPercent += stepPercent * aura->GetStackAmount(); + if (modPercent >= maxPercent) + { + modPercent = maxPercent; + break; + } } + AddPct(DoneTotalMod, modPercent); + break; } - AddPct(DoneTotalMod, modPercent); - break; - } case 6916: // Death's Embrace case 6925: case 6927: @@ -10455,71 +10619,71 @@ float Unit::SpellPctDamageModsDone(Unit* victim, SpellInfo const* spellProto, Da AddPct(DoneTotalMod, (*i)->GetAmount()); break; case 5481: // Starfire Bonus - { - if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } - // Tundra Stalker - // Merciless Combat - case 7277: - { - // Merciless Combat - if ((*i)->GetSpellInfo()->SpellIconID == 2656) { - if( (spellProto && spellProto->SpellFamilyFlags[0] & 0x2) || spellProto->SpellFamilyFlags[1] & 0x2 ) - if (!victim->HealthAbovePct(35)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - } - // Tundra Stalker - else - { - // Frost Fever (target debuff) - if (victim->HasAura(55095)) + if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0)) AddPct(DoneTotalMod, (*i)->GetAmount()); break; } - break; - } + // Tundra Stalker + // Merciless Combat + case 7277: + { + // Merciless Combat + if ((*i)->GetSpellInfo()->SpellIconID == 2656) + { + if( (spellProto && spellProto->SpellFamilyFlags[0] & 0x2) || spellProto->SpellFamilyFlags[1] & 0x2 ) + if (!victim->HealthAbovePct(35)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + } + // Tundra Stalker + else + { + // Frost Fever (target debuff) + if (victim->HasAura(55095)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } + break; + } // Rage of Rivendare case 7293: - { - if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0)) - AddPct(DoneTotalMod, (*i)->GetSpellInfo()->GetRank() * 2.0f); - break; - } + { + if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0)) + AddPct(DoneTotalMod, (*i)->GetSpellInfo()->GetRank() * 2.0f); + break; + } // Twisted Faith case 7377: - { - if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID())) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } + { + if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0, 0, GetGUID())) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } // Marked for Death case 7598: case 7599: case 7600: case 7601: case 7602: - { - if (victim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } + { + if (victim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } // Dirty Deeds case 6427: case 6428: case 6579: case 6580: - { - if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) { - // effect 0 has expected value but in negative state - int32 bonus = -(*i)->GetBase()->GetEffect(0)->GetAmount(); - AddPct(DoneTotalMod, bonus); + if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) + { + // effect 0 has expected value but in negative state + int32 bonus = -(*i)->GetBase()->GetEffect(0)->GetAmount(); + AddPct(DoneTotalMod, bonus); + } + break; } - break; - } } } @@ -10542,8 +10706,8 @@ float Unit::SpellPctDamageModsDone(Unit* victim, SpellInfo const* spellProto, Da // Torment the weak if (spellProto->SpellFamilyFlags[0] & 0x20600021 || spellProto->SpellFamilyFlags[1] & 0x9000) - if (victim->HasAuraWithMechanic((1<HasAuraWithMechanic((1 << MECHANIC_SNARE) | (1 << MECHANIC_SLOW_ATTACK))) + if (AuraEffect* aurEff = GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_GENERIC, 3263, EFFECT_0)) AddPct(DoneTotalMod, aurEff->GetAmount()); break; case SPELLFAMILY_PRIEST: @@ -10697,7 +10861,7 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin // done scripted mod (take it from owner) Unit* owner = GetOwner() ? GetOwner() : this; - AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + AuraEffectList const& mOverrideClassScript = owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spellProto)) @@ -10713,10 +10877,10 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin case 5148: // Idol of the Shooting Star case 6008: // Increased Lightning Damage case 8627: // Totem of Hex - { - DoneTotal += (*i)->GetAmount(); - break; - } + { + DoneTotal += (*i)->GetAmount(); + break; + } } } @@ -10729,7 +10893,7 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin AddPct(DoneTotal, aurEff->GetAmount()); // Impurity - if (AuraEffect *aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 1986, 0)) + if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 1986, 0)) AddPct(ApCoeffMod, aurEff->GetAmount()); // Blood Boil - bonus for diseased targets @@ -10933,10 +11097,10 @@ int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) AuraEffectList const& mDamageDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE); for (AuraEffectList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i) if (((*i)->GetMiscValue() & schoolMask) != 0 && - (*i)->GetSpellInfo()->EquippedItemClass == -1 && - // -1 == any item class (not wand then) - (*i)->GetSpellInfo()->EquippedItemInventoryTypeMask == 0) - // 0 == any inventory type (not wand then) + (*i)->GetSpellInfo()->EquippedItemClass == -1 && + // -1 == any item class (not wand then) + (*i)->GetSpellInfo()->EquippedItemInventoryTypeMask == 0) + // 0 == any inventory type (not wand then) DoneAdvertisedBenefit += (*i)->GetAmount(); if (GetTypeId() == TYPEID_PLAYER) @@ -10957,7 +11121,7 @@ int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) } // ... and attack power AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER); - for (AuraEffectList::const_iterator i =mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i) + for (AuraEffectList::const_iterator i = mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i) if ((*i)->GetMiscValue() & schoolMask) DoneAdvertisedBenefit += int32(CalculatePct(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount())); @@ -11002,42 +11166,48 @@ float Unit::SpellDoneCritChance(Unit const* /*victim*/, SpellInfo const* spellPr switch (spellProto->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: - { - if (schoolMask & SPELL_SCHOOL_MASK_NORMAL) - crit_chance = 0.0f; - // For other schools - else if (GetTypeId() == TYPEID_PLAYER) - crit_chance = GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask)); - else { - crit_chance = (float)m_baseSpellCritChance; - crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); + if (schoolMask & SPELL_SCHOOL_MASK_NORMAL) + crit_chance = 0.0f; + // For other schools + else if (GetTypeId() == TYPEID_PLAYER) + crit_chance = GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask)); + else + { + crit_chance = (float)m_baseSpellCritChance; + crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); + } + break; } - break; - } case SPELL_DAMAGE_CLASS_MELEE: case SPELL_DAMAGE_CLASS_RANGED: - { - if (GetTypeId() == TYPEID_PLAYER) { - switch (attackType) + if (GetTypeId() == TYPEID_PLAYER) { - case BASE_ATTACK: crit_chance = GetFloatValue(PLAYER_CRIT_PERCENTAGE); break; - case OFF_ATTACK: crit_chance = GetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE); break; - case RANGED_ATTACK: crit_chance = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE); break; - default: - break; + switch (attackType) + { + case BASE_ATTACK: + crit_chance = GetFloatValue(PLAYER_CRIT_PERCENTAGE); + break; + case OFF_ATTACK: + crit_chance = GetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE); + break; + case RANGED_ATTACK: + crit_chance = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE); + break; + default: + break; + } } + else + { + crit_chance = 5.0f; + crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); + crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); + } + crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); + break; } - else - { - crit_chance = 5.0f; - crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); - crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); - } - crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); - break; - } // values overridden in spellmgr for lifebloom and earth shield case SPELL_DAMAGE_CLASS_NONE: default: @@ -11067,115 +11237,120 @@ float Unit::SpellTakenCritChance(Unit const* caster, SpellInfo const* spellProto switch (spellProto->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: - { - if (!spellProto->IsPositive()) { - // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE - // xinef: apply max and min only - if (HasAuraType(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE)) + if (!spellProto->IsPositive()) { - crit_chance += GetMaxNegativeAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); - crit_chance += GetMaxPositiveAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); - } - - Unit::ApplyResilience(this, &crit_chance, NULL, false, CR_CRIT_TAKEN_SPELL); - } - // scripted (increase crit chance ... against ... target by x% - if (caster) - { - AuraEffectList const& mOverrideClassScript = caster->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); - for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) - { - if (!((*i)->IsAffectedOnSpell(spellProto))) - continue; - int32 modChance = 0; - switch ((*i)->GetMiscValue()) + // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE + // xinef: apply max and min only + if (HasAuraType(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE)) { - // Shatter - case 911: modChance+= 16; [[fallthrough]]; - case 910: modChance+= 17; [[fallthrough]]; - case 849: modChance+= 17; - if (!HasAuraState(AURA_STATE_FROZEN, spellProto, caster)) + crit_chance += GetMaxNegativeAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); + crit_chance += GetMaxPositiveAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); + } + + Unit::ApplyResilience(this, &crit_chance, NULL, false, CR_CRIT_TAKEN_SPELL); + } + // scripted (increase crit chance ... against ... target by x% + if (caster) + { + AuraEffectList const& mOverrideClassScript = caster->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) + { + if (!((*i)->IsAffectedOnSpell(spellProto))) + continue; + int32 modChance = 0; + switch ((*i)->GetMiscValue()) + { + // Shatter + case 911: + modChance += 16; + [[fallthrough]]; + case 910: + modChance += 17; + [[fallthrough]]; + case 849: + modChance += 17; + if (!HasAuraState(AURA_STATE_FROZEN, spellProto, caster)) + break; + crit_chance += modChance; break; - crit_chance+=modChance; + case 7917: // Glyph of Shadowburn + if (HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, caster)) + crit_chance += (*i)->GetAmount(); + break; + case 7997: // Renewed Hope + case 7998: + if (HasAura(6788)) + crit_chance += (*i)->GetAmount(); + break; + default: + break; + } + } + // Custom crit by class + switch (spellProto->SpellFamilyName) + { + case SPELLFAMILY_MAGE: + // Glyph of Fire Blast + if (spellProto->SpellFamilyFlags[0] == 0x2 && spellProto->SpellIconID == 12) + if (HasAuraWithMechanic((1 << MECHANIC_STUN) | (1 << MECHANIC_KNOCKOUT))) + if (AuraEffect const* aurEff = caster->GetAuraEffect(56369, EFFECT_0)) + crit_chance += aurEff->GetAmount(); break; - case 7917: // Glyph of Shadowburn - if (HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, caster)) - crit_chance+=(*i)->GetAmount(); + case SPELLFAMILY_DRUID: + // Improved Faerie Fire + if (HasAuraState(AURA_STATE_FAERIE_FIRE)) + if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 109, 0)) + crit_chance += aurEff->GetAmount(); + + // cumulative effect - don't break + + // Starfire + if (spellProto->SpellFamilyFlags[0] & 0x4 && spellProto->SpellIconID == 1485) + { + // Improved Insect Swarm + if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) + if (GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0)) + crit_chance += aurEff->GetAmount(); + break; + } break; - case 7997: // Renewed Hope - case 7998: - if (HasAura(6788)) - crit_chance+=(*i)->GetAmount(); + case SPELLFAMILY_ROGUE: + // Shiv-applied poisons can't crit + if (caster->FindCurrentSpellBySpellId(5938)) + crit_chance = 0.0f; break; - default: + case SPELLFAMILY_PALADIN: + // Flash of light + if (spellProto->SpellFamilyFlags[0] & 0x40000000) + { + // Sacred Shield + if (AuraEffect const* aura = GetAuraEffect(58597, 1, GetGUID())) + crit_chance += aura->GetAmount(); + break; + } + // Exorcism + else if (spellProto->GetCategory() == 19) + { + if (GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD) + return 100.0f; + break; + } + break; + case SPELLFAMILY_SHAMAN: + // Lava Burst + if (spellProto->SpellFamilyFlags[1] & 0x00001000) + { + if (GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0, 0, caster->GetGUID())) + if (GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE) > -100) + return 100.0f; + break; + } break; } } - // Custom crit by class - switch (spellProto->SpellFamilyName) - { - case SPELLFAMILY_MAGE: - // Glyph of Fire Blast - if (spellProto->SpellFamilyFlags[0] == 0x2 && spellProto->SpellIconID == 12) - if (HasAuraWithMechanic((1<GetAuraEffect(56369, EFFECT_0)) - crit_chance += aurEff->GetAmount(); - break; - case SPELLFAMILY_DRUID: - // Improved Faerie Fire - if (HasAuraState(AURA_STATE_FAERIE_FIRE)) - if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 109, 0)) - crit_chance += aurEff->GetAmount(); - - // cumulative effect - don't break - - // Starfire - if (spellProto->SpellFamilyFlags[0] & 0x4 && spellProto->SpellIconID == 1485) - { - // Improved Insect Swarm - if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) - if (GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0)) - crit_chance += aurEff->GetAmount(); - break; - } - break; - case SPELLFAMILY_ROGUE: - // Shiv-applied poisons can't crit - if (caster->FindCurrentSpellBySpellId(5938)) - crit_chance = 0.0f; - break; - case SPELLFAMILY_PALADIN: - // Flash of light - if (spellProto->SpellFamilyFlags[0] & 0x40000000) - { - // Sacred Shield - if (AuraEffect const* aura = GetAuraEffect(58597, 1, GetGUID())) - crit_chance += aura->GetAmount(); - break; - } - // Exorcism - else if (spellProto->GetCategory() == 19) - { - if (GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD) - return 100.0f; - break; - } - break; - case SPELLFAMILY_SHAMAN: - // Lava Burst - if (spellProto->SpellFamilyFlags[1] & 0x00001000) - { - if (GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x10000000, 0, 0, caster->GetGUID())) - if (GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE) > -100) - return 100.0f; - break; - } - break; - } + break; } - break; - } case SPELL_DAMAGE_CLASS_MELEE: // Custom crit by class if (caster) @@ -11184,49 +11359,49 @@ float Unit::SpellTakenCritChance(Unit const* caster, SpellInfo const* spellProto case SPELLFAMILY_DRUID: // Rend and Tear - bonus crit chance for Ferocious Bite on bleeding targets if (spellProto->SpellFamilyFlags[0] & 0x00800000 - && spellProto->SpellIconID == 1680 - && HasAuraState(AURA_STATE_BLEEDING)) + && spellProto->SpellIconID == 1680 + && HasAuraState(AURA_STATE_BLEEDING)) { if (AuraEffect const* rendAndTear = caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 1)) crit_chance += rendAndTear->GetAmount(); break; } - break; + break; case SPELLFAMILY_WARRIOR: - // Victory Rush - if (spellProto->SpellFamilyFlags[1] & 0x100) - { - // Glyph of Victory Rush - if (AuraEffect const* aurEff = caster->GetAuraEffect(58382, 0)) - crit_chance += aurEff->GetAmount(); - break; - } - break; + // Victory Rush + if (spellProto->SpellFamilyFlags[1] & 0x100) + { + // Glyph of Victory Rush + if (AuraEffect const* aurEff = caster->GetAuraEffect(58382, 0)) + crit_chance += aurEff->GetAmount(); + break; + } + break; } [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. case SPELL_DAMAGE_CLASS_RANGED: - { - // flat aura mods - if (attackType == RANGED_ATTACK) - crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE); - else - crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); - - // reduce crit chance from Rating for players - if (attackType != RANGED_ATTACK) { - // xinef: little hack, crit chance dont require caster to calculate, pass victim - Unit::ApplyResilience(this, &crit_chance, NULL, false, CR_CRIT_TAKEN_MELEE); + // flat aura mods + if (attackType == RANGED_ATTACK) + crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE); + else + crit_chance += GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); + + // reduce crit chance from Rating for players + if (attackType != RANGED_ATTACK) + { + // xinef: little hack, crit chance dont require caster to calculate, pass victim + Unit::ApplyResilience(this, &crit_chance, NULL, false, CR_CRIT_TAKEN_MELEE); + } + else + Unit::ApplyResilience(this, &crit_chance, NULL, false, CR_CRIT_TAKEN_RANGED); + + // Apply crit chance from defence skill + if (caster) + crit_chance += (int32(caster->GetMaxSkillValueForLevel(this)) - int32(GetDefenseSkillValue(caster))) * 0.04f; + + break; } - else - Unit::ApplyResilience(this, &crit_chance, NULL, false, CR_CRIT_TAKEN_RANGED); - - // Apply crit chance from defence skill - if (caster) - crit_chance += (int32(caster->GetMaxSkillValueForLevel(this)) - int32(GetDefenseSkillValue(caster))) * 0.04f; - - break; - } // values overridden in spellmgr for lifebloom and earth shield case SPELL_DAMAGE_CLASS_NONE: default: @@ -11364,7 +11539,7 @@ float Unit::SpellPctHealingModsDone(Unit* victim, SpellInfo const* spellProto, D // done scripted mod (take it from owner) Unit* owner = GetOwner() ? GetOwner() : this; - AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + AuraEffectList const& mOverrideClassScript = owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spellProto)) @@ -11379,19 +11554,19 @@ float Unit::SpellPctHealingModsDone(Unit* victim, SpellInfo const* spellProto, D AddPct(DoneTotalMod, (*i)->GetAmount()); break; case 7798: // Glyph of Regrowth - { - if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } + { + if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } case 7871: // Glyph of Lesser Healing Wave - { - // xinef: affected by any earth shield - if (victim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0, 0x00000400, 0)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } + { + // xinef: affected by any earth shield + if (victim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0, 0x00000400, 0)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } default: break; } @@ -11404,18 +11579,18 @@ float Unit::SpellPctHealingModsDone(Unit* victim, SpellInfo const* spellProto, D if (spellProto->Id == 52042) { // Glyph of Healing Stream Totem - if (AuraEffect *dummy = owner->GetAuraEffect(55456, EFFECT_0)) + if (AuraEffect* dummy = owner->GetAuraEffect(55456, EFFECT_0)) AddPct(DoneTotalMod, dummy->GetAmount()); // Healing Stream totem - Restorative Totems - if (AuraEffect *aurEff = GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 338, 1)) + if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 338, 1)) AddPct(DoneTotalMod, aurEff->GetAmount()); } break; case SPELLFAMILY_PRIEST: // T9 HEALING 4P, empowered renew instant heal if (spellProto->Id == 63544) - if (AuraEffect *aurEff = GetAuraEffect(67202, EFFECT_0)) + if (AuraEffect* aurEff = GetAuraEffect(67202, EFFECT_0)) AddPct(DoneTotalMod, aurEff->GetAmount()); break; } @@ -11440,7 +11615,7 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui // done scripted mod (take it from owner) Unit* owner = GetOwner() ? GetOwner() : this; - AuraEffectList const& mOverrideClassScript= owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + AuraEffectList const& mOverrideClassScript = owner->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraEffectList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->IsAffectedOnSpell(spellProto)) @@ -11463,7 +11638,7 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui { case SPELLFAMILY_DEATHKNIGHT: // Impurity - if (AuraEffect *aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 1986, 0)) + if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 1986, 0)) AddPct(ApCoeffMod, aurEff->GetAmount()); break; @@ -11478,14 +11653,14 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui coeff = bonus->dot_damage; if (bonus->ap_dot_bonus > 0) DoneTotal += int32(bonus->ap_dot_bonus * ApCoeffMod * stack * GetTotalAttackPowerValue( - (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK)); + (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK)); } else { coeff = bonus->direct_damage; if (bonus->ap_bonus > 0) DoneTotal += int32(bonus->ap_bonus * ApCoeffMod * stack * GetTotalAttackPowerValue( - (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass !=SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK)); + (spellProto->IsRangedWeaponSpell() && spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE) ? RANGED_ATTACK : BASE_ATTACK)); } } else @@ -11561,11 +11736,11 @@ uint32 Unit::SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, u bool any = false; bool hasglyph = caster->GetAuraEffectDummy(62971); AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); - for (AuraEffectList::const_iterator i = auras.begin();i != auras.end(); ++i) + for (AuraEffectList::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (((*i)->GetCasterGUID() == caster->GetGUID())) { - SpellInfo const *spell = (*i)->GetSpellInfo(); + SpellInfo const* spell = (*i)->GetSpellInfo(); // Rejuvenation, Regrowth, Lifebloom, or Wild Growth if (!any && spell->SpellFamilyFlags.HasFlag(0x50, 0x4000010, 0)) { @@ -11627,7 +11802,7 @@ uint32 Unit::SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, u if (caster) { - AuraEffectList const& mHealingGet= GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED); + AuraEffectList const& mHealingGet = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED); for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i) if (caster->GetGUID() == (*i)->GetCasterGUID() && (*i)->IsAffectedOnSpell(spellProto)) AddPct(TakenTotalMod, (*i)->GetAmount()); @@ -11839,8 +12014,8 @@ bool Unit::IsImmunedToSpell(SpellInfo const* spellInfo) { SpellInfo const* immuneSpellInfo = sSpellMgr->GetSpellInfo(itr->spellId); if (((itr->type & spellInfo->GetSchoolMask()) == spellInfo->GetSchoolMask()) - && !(immuneSpellInfo && immuneSpellInfo->IsPositive() && spellInfo->IsPositive()) - && !spellInfo->CanPierceImmuneAura(immuneSpellInfo)) + && !(immuneSpellInfo && immuneSpellInfo->IsPositive() && spellInfo->IsPositive()) + && !spellInfo->CanPierceImmuneAura(immuneSpellInfo)) return true; } } @@ -11960,7 +12135,7 @@ uint32 Unit::MeleeDamageBonusDone(Unit* victim, uint32 pdamage, WeaponAttackType normalized = true; break; } - DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType, normalized)); + DoneFlatBenefit += int32(APbonus / 14.0f * GetAPMultiplier(attType, normalized)); } // Done total percent damage auras @@ -12016,52 +12191,52 @@ uint32 Unit::MeleeDamageBonusDone(Unit* victim, uint32 pdamage, WeaponAttackType // Tundra Stalker // Merciless Combat case 7277: - { - // Merciless Combat - if ((*i)->GetSpellInfo()->SpellIconID == 2656) { - if (!victim->HealthAbovePct(35)) - AddPct(DoneTotalMod, (*i)->GetAmount()); + // Merciless Combat + if ((*i)->GetSpellInfo()->SpellIconID == 2656) + { + if (!victim->HealthAbovePct(35)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + } + // Tundra Stalker + else + { + // Frost Fever (target debuff) + if (victim->HasAura(55095)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + } + break; } - // Tundra Stalker - else - { - // Frost Fever (target debuff) - if (victim->HasAura(55095)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - } - break; - } // Rage of Rivendare case 7293: - { - if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0)) - AddPct(DoneTotalMod, (*i)->GetSpellInfo()->GetRank() * 2.0f); - break; - } + { + if (victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0x02000000, 0)) + AddPct(DoneTotalMod, (*i)->GetSpellInfo()->GetRank() * 2.0f); + break; + } // Marked for Death case 7598: case 7599: case 7600: case 7601: case 7602: - { - if (victim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0)) - AddPct(DoneTotalMod, (*i)->GetAmount()); - break; - } + { + if (victim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0)) + AddPct(DoneTotalMod, (*i)->GetAmount()); + break; + } // Dirty Deeds case 6427: case 6428: - { - if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) { - // effect 0 has expected value but in negative state - int32 bonus = -(*i)->GetBase()->GetEffect(0)->GetAmount(); - AddPct(DoneTotalMod, bonus); + if (victim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) + { + // effect 0 has expected value but in negative state + int32 bonus = -(*i)->GetBase()->GetEffect(0)->GetAmount(); + AddPct(DoneTotalMod, bonus); + } + break; } - break; - } } } @@ -12075,7 +12250,7 @@ uint32 Unit::MeleeDamageBonusDone(Unit* victim, uint32 pdamage, WeaponAttackType if (AuraEffect* aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0)) if (victim->GetDiseasesByCaster(owner->GetGUID()) > 0) AddPct(DoneTotalMod, aurEff->GetAmount()); - break; + break; } // Some spells don't benefit from done mods @@ -12134,13 +12309,13 @@ uint32 Unit::MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackT // Shred, Maul - "Effects which increase Bleed damage also increase Shred damage" if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags[0] & 0x00008800) - mechanicMask |= (1<GetMiscValue()))) + if (mechanicMask & uint32(1 << ((*i)->GetMiscValue()))) AddPct(TakenTotalMod, (*i)->GetAmount()); } } @@ -12220,12 +12395,12 @@ uint32 Unit::MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackT class spellIdImmunityPredicate { - public: - spellIdImmunityPredicate(uint32 type) : _type(type) {} - bool operator()(SpellImmune const& spellImmune) { return spellImmune.spellId == 0 && spellImmune.type == _type; } +public: + spellIdImmunityPredicate(uint32 type) : _type(type) {} + bool operator()(SpellImmune const& spellImmune) { return spellImmune.spellId == 0 && spellImmune.type == _type; } - private: - uint32 _type; +private: + uint32 _type; }; void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply, SpellImmuneBlockType blockType) @@ -12321,7 +12496,7 @@ void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry) GetVehicleKit()->Reset(); // Send others that we now have a vehicle - WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size()+4); + WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, GetPackGUID().size() + 4); data.appendPackGUID(GetGUID()); data << uint32(VehicleId); SendMessageToSet(&data, true); @@ -12386,7 +12561,7 @@ void Unit::Dismount() if (GetTypeId() == TYPEID_PLAYER && GetVehicleKit()) { // Send other players that we are no longer a vehicle - data.Initialize(SMSG_PLAYER_VEHICLE_DATA, 8+4); + data.Initialize(SMSG_PLAYER_VEHICLE_DATA, 8 + 4); data.appendPackGUID(GetGUID()); data << uint32(0); ToPlayer()->SendMessageToSet(&data, true); @@ -12476,7 +12651,7 @@ void Unit::CombatStart(Unit* target, bool initialAggro) Unit* who = target->GetCharmerOrOwnerOrSelf(); if (who->GetTypeId() == TYPEID_PLAYER) - SetContestedPvP(who->ToPlayer()); + SetContestedPvP(who->ToPlayer()); Player* me = GetCharmerOrOwnerPlayerOrPlayerItself(); if (me && who->IsPvP() && (who->GetTypeId() != TYPEID_PLAYER || !me->duel || me->duel->opponent != who)) @@ -12503,7 +12678,7 @@ void Unit::CombatStartOnCast(Unit* target, bool initialAggro, uint32 duration) Unit* who = target->GetCharmerOrOwnerOrSelf(); if (who->GetTypeId() == TYPEID_PLAYER) - SetContestedPvP(who->ToPlayer()); + SetContestedPvP(who->ToPlayer()); Player* me = GetCharmerOrOwnerPlayerOrPlayerItself(); if (me && who->IsPvP() && (who->GetTypeId() != TYPEID_PLAYER || !me->duel || me->duel->opponent != who)) @@ -12543,8 +12718,8 @@ void Unit::SetInCombatState(bool PvP, Unit* enemy, uint32 duration) // Set home position at place of engaging combat for escorted creatures if ((IsAIEnabled && creature->AI()->IsEscorted()) || - GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE || - GetMotionMaster()->GetCurrentMovementGeneratorType() == ESCORT_MOTION_TYPE) + GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE || + GetMotionMaster()->GetCurrentMovementGeneratorType() == ESCORT_MOTION_TYPE) creature->SetHomePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); if (enemy) @@ -12658,7 +12833,7 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo // can't attack unattackable units or GMs if (target->HasUnitState(UNIT_STATE_UNATTACKABLE) - || (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->IsGameMaster())) + || (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->IsGameMaster())) return false; // can't attack own vehicle or passenger @@ -12674,11 +12849,11 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo // can't attack dead if ((!bySpell || !bySpell->IsAllowingDeadTarget()) && !target->IsAlive()) - return false; + return false; // can't attack untargetable if ((!bySpell || !bySpell->HasAttribute(SPELL_ATTR6_CAN_TARGET_UNTARGETABLE)) - && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) + && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) return false; if (Player const* playerAttacker = ToPlayer()) @@ -12688,11 +12863,11 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo } // check flags if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_TAXI_FLIGHT | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_UNK_16) - || (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC)) - || (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC)) - || (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC)) - // check if this is a world trigger cast - GOs are using world triggers to cast their spells, so we need to ignore their immunity flag here, this is a temp workaround, needs removal when go cast is implemented properly - || (GetEntry() != WORLD_TRIGGER && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC))) + || (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC)) + || (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC)) + || (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC)) + // check if this is a world trigger cast - GOs are using world triggers to cast their spells, so we need to ignore their immunity flag here, this is a temp workaround, needs removal when go cast is implemented properly + || (GetEntry() != WORLD_TRIGGER && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC))) return false; // CvC case - can attack each other only when one of them is hostile @@ -12705,17 +12880,17 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo ReputationRank repTargetToThis; if (repThisToTarget > REP_NEUTRAL - || (repTargetToThis = target->GetReactionTo(this)) > REP_NEUTRAL) + || (repTargetToThis = target->GetReactionTo(this)) > REP_NEUTRAL) return false; // Not all neutral creatures can be attacked (even some unfriendly faction does not react aggresive to you, like Sporaggar) if (repThisToTarget == REP_NEUTRAL && - repTargetToThis <= REP_NEUTRAL) + repTargetToThis <= REP_NEUTRAL) { Player* owner = GetAffectingPlayer(); - const Unit *const thisUnit = owner ? owner : this; + const Unit* const thisUnit = owner ? owner : this; if (!(target->GetTypeId() == TYPEID_PLAYER && thisUnit->GetTypeId() == TYPEID_PLAYER) && - !(target->GetTypeId() == TYPEID_UNIT && thisUnit->GetTypeId() == TYPEID_UNIT)) + !(target->GetTypeId() == TYPEID_UNIT && thisUnit->GetTypeId() == TYPEID_UNIT)) { Player const* player = target->GetTypeId() == TYPEID_PLAYER ? target->ToPlayer() : thisUnit->ToPlayer(); Unit const* creature = target->GetTypeId() == TYPEID_UNIT ? target : thisUnit; @@ -12779,7 +12954,7 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co // can't assist unattackable units or GMs if (target->HasUnitState(UNIT_STATE_UNATTACKABLE) - || (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->IsGameMaster())) + || (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->IsGameMaster())) return false; // can't assist own vehicle or passenger @@ -12793,11 +12968,11 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co // can't assist dead if ((!bySpell || !bySpell->IsAllowingDeadTarget()) && !target->IsAlive()) - return false; + return false; // can't assist untargetable if ((!bySpell || !bySpell->HasAttribute(SPELL_ATTR6_CAN_TARGET_UNTARGETABLE)) - && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) + && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) return false; if (!bySpell || !bySpell->HasAttribute(SPELL_ATTR6_ASSIST_IGNORE_IMMUNE_FLAG)) @@ -12820,8 +12995,8 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co // can't assist non-friendly targets if (GetReactionTo(target) < REP_NEUTRAL - && target->GetReactionTo(this) < REP_NEUTRAL - && (!ToCreature() || !(ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT))) + && target->GetReactionTo(this) < REP_NEUTRAL + && (!ToCreature() || !(ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT))) return false; // PvP case @@ -12835,7 +13010,7 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co { // can't assist player which is dueling someone if (selfPlayerOwner != targetPlayerOwner - && targetPlayerOwner->duel) + && targetPlayerOwner->duel) return false; } // can't assist player in ffa_pvp zone from outside @@ -12851,8 +13026,8 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co // PvC case - player can assist creature only if has specific type flags // !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && else if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) - && (!bySpell || !bySpell->HasAttribute(SPELL_ATTR6_ASSIST_IGNORE_IMMUNE_FLAG)) - && !target->IsPvP()) + && (!bySpell || !bySpell->HasAttribute(SPELL_ATTR6_ASSIST_IGNORE_IMMUNE_FLAG)) + && !target->IsPvP()) { if (Creature const* creatureTarget = target->ToCreature()) return creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT || creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_ASSIST; @@ -12986,7 +13161,7 @@ bool Unit::IsAlwaysDetectableFor(WorldObject const* seer) const if (HasAuraTypeWithCaster(SPELL_AURA_MOD_STALKED, seer->GetGUID())) return true; - if (Player *ownerPlayer = GetSpellModOwner()) + if (Player* ownerPlayer = GetSpellModOwner()) if (const Player* seerPlayer = seer->ToPlayer()) { if (ownerPlayer->IsGroupVisibleFor(seerPlayer)) @@ -13030,68 +13205,68 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) case MOVE_WALK: return; case MOVE_RUN: - { - if (IsMounted()) // Use on mount auras { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED); - stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS); - non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK) / 100.0f; - } - else - { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED); - stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS); - non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK) / 100.0f; - } - break; - } - case MOVE_SWIM: - { - // xinef: check for forced_speed_mod of sea turtle - Unit::AuraEffectList const& swimAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INCREASE_SWIM_SPEED); - for (Unit::AuraEffectList::const_iterator itr = swimAuras.begin(); itr != swimAuras.end(); ++itr) - { - // xinef: sea turtle only, it is not affected by any increasing / decreasing effects - if ((*itr)->GetId() == 64731 /*SPELL_SEA_TURTLE*/) + if (IsMounted()) // Use on mount auras { - SetSpeed(mtype, AddPct(non_stack_bonus, (*itr)->GetAmount()), forced); - return; + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED); + stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS); + non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK) / 100.0f; } - else if ((*itr)->GetAmount() > main_speed_mod) - main_speed_mod = (*itr)->GetAmount(); + else + { + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED); + stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS); + non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK) / 100.0f; + } + break; + } + case MOVE_SWIM: + { + // xinef: check for forced_speed_mod of sea turtle + Unit::AuraEffectList const& swimAuras = GetAuraEffectsByType(SPELL_AURA_MOD_INCREASE_SWIM_SPEED); + for (Unit::AuraEffectList::const_iterator itr = swimAuras.begin(); itr != swimAuras.end(); ++itr) + { + // xinef: sea turtle only, it is not affected by any increasing / decreasing effects + if ((*itr)->GetId() == 64731 /*SPELL_SEA_TURTLE*/) + { + SetSpeed(mtype, AddPct(non_stack_bonus, (*itr)->GetAmount()), forced); + return; + } + else if ((*itr)->GetAmount() > main_speed_mod) + main_speed_mod = (*itr)->GetAmount(); + } + break; } - break; - } case MOVE_FLIGHT: - { - if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); - stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS); + if (GetTypeId() == TYPEID_UNIT && IsControlledByPlayer()) // not sure if good for pet + { + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); + stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS); - // for some spells this mod is applied on vehicle owner - int32 owner_speed_mod = 0; + // for some spells this mod is applied on vehicle owner + int32 owner_speed_mod = 0; - if (Unit* owner = GetCharmer()) - owner_speed_mod = owner->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); + if (Unit* owner = GetCharmer()) + owner_speed_mod = owner->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); - main_speed_mod = std::max(main_speed_mod, owner_speed_mod); + main_speed_mod = std::max(main_speed_mod, owner_speed_mod); + } + else if (IsMounted()) + { + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED); + stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS); + } + else // Use not mount (shapeshift for example) auras (should stack) + main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); + + non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK) / 100.0f; + + // Update speed for vehicle if available + if (GetTypeId() == TYPEID_PLAYER && GetVehicle()) + GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true); + break; } - else if (IsMounted()) - { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED); - stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS); - } - else // Use not mount (shapeshift for example) auras (should stack) - main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); - - non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK) / 100.0f; - - // Update speed for vehicle if available - if (GetTypeId() == TYPEID_PLAYER && GetVehicle()) - GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true); - break; - } default: sLog->outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype); return; @@ -13107,67 +13282,67 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) case MOVE_RUN: case MOVE_SWIM: case MOVE_FLIGHT: - { - if (GetTypeId() == TYPEID_UNIT) { - Unit* pOwner = GetCharmerOrOwner(); - if (pOwner && !IsInCombat() && !IsVehicle() && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED) && (IsPet() || IsGuardian() || GetGUID() == pOwner->GetCritterGUID() || GetCharmerGUID() == pOwner->GetGUID())) + if (GetTypeId() == TYPEID_UNIT) { - if (pOwner->GetTypeId() != TYPEID_PLAYER) + Unit* pOwner = GetCharmerOrOwner(); + if (pOwner && !IsInCombat() && !IsVehicle() && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED) && (IsPet() || IsGuardian() || GetGUID() == pOwner->GetCritterGUID() || GetCharmerGUID() == pOwner->GetGUID())) { - if (speed < pOwner->GetSpeedRate(mtype)+0.1f) - speed = pOwner->GetSpeedRate(mtype)+0.1f; // pets derive speed from owner when not in combat + if (pOwner->GetTypeId() != TYPEID_PLAYER) + { + if (speed < pOwner->GetSpeedRate(mtype) + 0.1f) + speed = pOwner->GetSpeedRate(mtype) + 0.1f; // pets derive speed from owner when not in combat + } + else + { + // special treatment for player pets in order to avoid stuttering + float ownerSpeed = pOwner->GetSpeedRate(mtype); + float distOwner = GetDistance(pOwner); + float minDist = 2.5f; + + if (ToCreature()->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) + { + // different minimum distance for vanity pets + minDist = 5.0f; + + if (mtype == MOVE_FLIGHT) + mtype = MOVE_RUN; // vanity pets use run speed for flight + } + + float maxDist = ownerSpeed >= 1.0f ? minDist * ownerSpeed * 1.5f : minDist * 1.5f; + + if (distOwner < minDist && m_petCatchUp) + m_petCatchUp = false; + + if (distOwner > maxDist && !m_petCatchUp) + m_petCatchUp = true; + + if (m_petCatchUp) + speed = ownerSpeed * 1.05f; + else + speed = ownerSpeed * 0.95f; + } } else - { - // special treatment for player pets in order to avoid stuttering - float ownerSpeed = pOwner->GetSpeedRate(mtype); - float distOwner = GetDistance(pOwner); - float minDist = 2.5f; - - if (ToCreature()->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) - { - // different minimum distance for vanity pets - minDist = 5.0f; - - if (mtype == MOVE_FLIGHT) - mtype = MOVE_RUN; // vanity pets use run speed for flight - } - - float maxDist = ownerSpeed >= 1.0f ? minDist * ownerSpeed * 1.5f : minDist * 1.5f; - - if (distOwner < minDist && m_petCatchUp) - m_petCatchUp = false; - - if (distOwner > maxDist && !m_petCatchUp) - m_petCatchUp = true; - - if (m_petCatchUp) - speed = ownerSpeed * 1.05f; - else - speed = ownerSpeed * 0.95f; - } + speed *= ToCreature()->GetCreatureTemplate()->speed_run; // at this point, MOVE_WALK is never reached } - else - speed *= ToCreature()->GetCreatureTemplate()->speed_run; // at this point, MOVE_WALK is never reached + + // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need + // TODO: possible affect only on MOVE_RUN + if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED)) + { + // Use speed from aura + float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]); + + // Xinef: normal movement speed - multiply by creature db modifer + if (GetTypeId() == TYPEID_UNIT) + max_speed *= ToCreature()->GetCreatureTemplate()->speed_run; + + if (speed > max_speed) + speed = max_speed; + } + break; } - - // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need - // TODO: possible affect only on MOVE_RUN - if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED)) - { - // Use speed from aura - float max_speed = normalization / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]); - - // Xinef: normal movement speed - multiply by creature db modifer - if (GetTypeId() == TYPEID_UNIT) - max_speed *= ToCreature()->GetCreatureTemplate()->speed_run; - - if (speed > max_speed) - speed = max_speed; - } - break; - } default: break; } @@ -13197,7 +13372,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) float Unit::GetSpeed(UnitMoveType mtype) const { - return m_speed_rate[mtype]*(IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]); + return m_speed_rate[mtype] * (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]); } void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced) @@ -13219,31 +13394,31 @@ void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced) switch (mtype) { case MOVE_WALK: - data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_RUN: - data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_RUN_BACK: - data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_SWIM: - data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_SWIM_BACK: - data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_TURN_RATE: - data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_TURN_RATE, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_FLIGHT: - data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_FLIGHT_BACK: - data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; case MOVE_PITCH_RATE: - data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4); + data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8 + 4 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 4); break; default: sLog->outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype); @@ -13567,7 +13742,7 @@ Unit* Creature::SelectVictim() { if (m_mmapNotAcceptableStartTime) { - if (sWorld->GetGameTime() <= m_mmapNotAcceptableStartTime+4) + if (sWorld->GetGameTime() <= m_mmapNotAcceptableStartTime + 4) return nullptr; } else @@ -13684,7 +13859,7 @@ int32 Unit::ModSpellDuration(SpellInfo const* spellProto, Unit const* target, in for (uint8 i = 1; i <= MECHANIC_ENRAGED; ++i) { - if (!(mechanic & 1<DmgClass) { - case SPELL_DAMAGE_CLASS_NONE: - if (spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) // required double check + case SPELL_DAMAGE_CLASS_NONE: + if (spellInfo->AttributesEx5 & SPELL_ATTR5_HASTE_AFFECT_DURATION) // required double check + castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED)); + else if (spellInfo->SpellVisual[0] == 3881 && HasAura(67556)) // cooking with Chef Hat. + castTime = 500; + break; + case SPELL_DAMAGE_CLASS_MELEE: + break; // no known cases + case SPELL_DAMAGE_CLASS_MAGIC: castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED)); - else if (spellInfo->SpellVisual[0] == 3881 && HasAura(67556)) // cooking with Chef Hat. - castTime = 500; - break; - case SPELL_DAMAGE_CLASS_MELEE: - break; // no known cases - case SPELL_DAMAGE_CLASS_MAGIC: - castTime = int32(float(castTime) * GetFloatValue(UNIT_MOD_CAST_SPEED)); - break; - case SPELL_DAMAGE_CLASS_RANGED: - castTime = int32(float(castTime) * m_modAttackSpeedPct[RANGED_ATTACK]); - break; - default: - break; + break; + case SPELL_DAMAGE_CLASS_RANGED: + castTime = int32(float(castTime) * m_modAttackSpeedPct[RANGED_ATTACK]); + break; + default: + break; } } @@ -13837,7 +14012,7 @@ void Unit::IncrDiminishing(DiminishingGroup group) m_Diminishing.push_back(DiminishingReturn(group, World::GetGameTimeMS(), DIMINISHING_LEVEL_2)); } -float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, int32 limitduration) +float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32& duration, Unit* caster, DiminishingLevels Level, int32 limitduration) { // xinef: dont apply diminish to self casts if (duration == -1 || group == DIMINISHING_NONE) @@ -13854,8 +14029,8 @@ float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit const* source = casterOwner ? casterOwner : caster; if ((target->GetTypeId() == TYPEID_PLAYER - || target->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH) - && source->GetTypeId() == TYPEID_PLAYER) + || target->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH) + && source->GetTypeId() == TYPEID_PLAYER) duration = limitduration; } @@ -13868,29 +14043,47 @@ float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, DiminishingLevels diminish = Level; switch (diminish) { - case DIMINISHING_LEVEL_1: break; - case DIMINISHING_LEVEL_2: mod = 0.65f; break; - case DIMINISHING_LEVEL_3: mod = 0.4225f; break; - case DIMINISHING_LEVEL_4: mod = 0.274625f; break; - case DIMINISHING_LEVEL_TAUNT_IMMUNE: mod = 0.0f; break; - default: break; + case DIMINISHING_LEVEL_1: + break; + case DIMINISHING_LEVEL_2: + mod = 0.65f; + break; + case DIMINISHING_LEVEL_3: + mod = 0.4225f; + break; + case DIMINISHING_LEVEL_4: + mod = 0.274625f; + break; + case DIMINISHING_LEVEL_TAUNT_IMMUNE: + mod = 0.0f; + break; + default: + break; } } } // Some diminishings applies to mobs too (for example, Stun) else if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER - && ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER)) - || (GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH))) - || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL) + && ((targetOwner ? (targetOwner->GetTypeId() == TYPEID_PLAYER) : (GetTypeId() == TYPEID_PLAYER)) + || (GetTypeId() == TYPEID_UNIT && ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH))) + || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL) { DiminishingLevels diminish = Level; switch (diminish) { - case DIMINISHING_LEVEL_1: break; - case DIMINISHING_LEVEL_2: mod = 0.5f; break; - case DIMINISHING_LEVEL_3: mod = 0.25f; break; - case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f; break; - default: break; + case DIMINISHING_LEVEL_1: + break; + case DIMINISHING_LEVEL_2: + mod = 0.5f; + break; + case DIMINISHING_LEVEL_3: + mod = 0.25f; + break; + case DIMINISHING_LEVEL_IMMUNE: + mod = 0.0f; + break; + default: + break; } } @@ -13992,10 +14185,16 @@ bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, f case UNIT_MOD_STAT_AGILITY: case UNIT_MOD_STAT_STAMINA: case UNIT_MOD_STAT_INTELLECT: - case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break; + case UNIT_MOD_STAT_SPIRIT: + UpdateStats(GetStatByAuraGroup(unitMod)); + break; - case UNIT_MOD_ARMOR: UpdateArmor(); break; - case UNIT_MOD_HEALTH: UpdateMaxHealth(); break; + case UNIT_MOD_ARMOR: + UpdateArmor(); + break; + case UNIT_MOD_HEALTH: + UpdateMaxHealth(); + break; case UNIT_MOD_MANA: case UNIT_MOD_RAGE: @@ -14003,21 +14202,35 @@ bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, f case UNIT_MOD_ENERGY: case UNIT_MOD_HAPPINESS: case UNIT_MOD_RUNE: - case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break; + case UNIT_MOD_RUNIC_POWER: + UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); + break; case UNIT_MOD_RESISTANCE_HOLY: case UNIT_MOD_RESISTANCE_FIRE: case UNIT_MOD_RESISTANCE_NATURE: case UNIT_MOD_RESISTANCE_FROST: case UNIT_MOD_RESISTANCE_SHADOW: - case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break; + case UNIT_MOD_RESISTANCE_ARCANE: + UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); + break; - case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break; - case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break; + case UNIT_MOD_ATTACK_POWER: + UpdateAttackPowerAndDamage(); + break; + case UNIT_MOD_ATTACK_POWER_RANGED: + UpdateAttackPowerAndDamage(true); + break; - case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break; - case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break; - case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break; + case UNIT_MOD_DAMAGE_MAINHAND: + UpdateDamagePhysical(BASE_ATTACK); + break; + case UNIT_MOD_DAMAGE_OFFHAND: + UpdateDamagePhysical(OFF_ATTACK); + break; + case UNIT_MOD_DAMAGE_RANGED: + UpdateDamagePhysical(RANGED_ATTACK); + break; default: break; @@ -14079,8 +14292,8 @@ void Unit::ApplyStatPercentBuffMod(Stats stat, float val, bool apply) { if (val == -100.0f) // prevent set var to zero val = -99.99f; - float var = GetStat(stat)*val/100.0f; - ApplyModSignedFloatValue((var > 0 ? UNIT_FIELD_POSSTAT0+stat : UNIT_FIELD_NEGSTAT0+stat), var, apply); + float var = GetStat(stat) * val / 100.0f; + ApplyModSignedFloatValue((var > 0 ? UNIT_FIELD_POSSTAT0 + stat : UNIT_FIELD_NEGSTAT0 + stat), var, apply); } SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const @@ -14089,12 +14302,24 @@ SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const switch (unitMod) { - case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break; - case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break; - case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break; - case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break; - case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break; - case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break; + case UNIT_MOD_RESISTANCE_HOLY: + school = SPELL_SCHOOL_HOLY; + break; + case UNIT_MOD_RESISTANCE_FIRE: + school = SPELL_SCHOOL_FIRE; + break; + case UNIT_MOD_RESISTANCE_NATURE: + school = SPELL_SCHOOL_NATURE; + break; + case UNIT_MOD_RESISTANCE_FROST: + school = SPELL_SCHOOL_FROST; + break; + case UNIT_MOD_RESISTANCE_SHADOW: + school = SPELL_SCHOOL_SHADOW; + break; + case UNIT_MOD_RESISTANCE_ARCANE: + school = SPELL_SCHOOL_ARCANE; + break; default: break; @@ -14109,11 +14334,21 @@ Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const switch (unitMod) { - case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break; - case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break; - case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break; - case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break; - case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break; + case UNIT_MOD_STAT_STRENGTH: + stat = STAT_STRENGTH; + break; + case UNIT_MOD_STAT_AGILITY: + stat = STAT_AGILITY; + break; + case UNIT_MOD_STAT_STAMINA: + stat = STAT_STAMINA; + break; + case UNIT_MOD_STAT_INTELLECT: + stat = STAT_INTELLECT; + break; + case UNIT_MOD_STAT_SPIRIT: + stat = STAT_SPIRIT; + break; default: break; @@ -14126,18 +14361,25 @@ Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const { switch (unitMod) { - case UNIT_MOD_RAGE: return POWER_RAGE; - case UNIT_MOD_FOCUS: return POWER_FOCUS; - case UNIT_MOD_ENERGY: return POWER_ENERGY; - case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS; - case UNIT_MOD_RUNE: return POWER_RUNE; - case UNIT_MOD_RUNIC_POWER: return POWER_RUNIC_POWER; + case UNIT_MOD_RAGE: + return POWER_RAGE; + case UNIT_MOD_FOCUS: + return POWER_FOCUS; + case UNIT_MOD_ENERGY: + return POWER_ENERGY; + case UNIT_MOD_HAPPINESS: + return POWER_HAPPINESS; + case UNIT_MOD_RUNE: + return POWER_RUNE; + case UNIT_MOD_RUNIC_POWER: + return POWER_RUNIC_POWER; default: - case UNIT_MOD_MANA: return POWER_MANA; + case UNIT_MOD_MANA: + return POWER_MANA; } } -float Unit::GetTotalAttackPowerValue(WeaponAttackType attType, Unit *victim) const +float Unit::GetTotalAttackPowerValue(WeaponAttackType attType, Unit* victim) const { if (attType == RANGED_ATTACK) { @@ -14288,7 +14530,7 @@ void Unit::SetPower(Powers power, uint32 val) { Player* player = ToPlayer(); if (getPowerType() == power && player->NeedSendSpectatorData()) - ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "CPW", power == POWER_RAGE || power == POWER_RUNIC_POWER ? val/10 : val); + ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "CPW", power == POWER_RAGE || power == POWER_RUNIC_POWER ? val / 10 : val); if (player->GetGroup()) player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); @@ -14318,7 +14560,7 @@ void Unit::SetMaxPower(Powers power, uint32 val) { Player* player = ToPlayer(); if (getPowerType() == power && player->NeedSendSpectatorData()) - ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "MPW", power == POWER_RAGE || power == POWER_RUNIC_POWER ? val/10 : val); + ArenaSpectator::SendCommand_UInt32Value(FindMap(), GetGUID(), "MPW", power == POWER_RAGE || power == POWER_RUNIC_POWER ? val / 10 : val); if (player->GetGroup()) player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); @@ -14342,14 +14584,22 @@ uint32 Unit::GetCreatePowers(Powers power) const // Only hunter pets have POWER_FOCUS and POWER_HAPPINESS switch (power) { - case POWER_MANA: return GetCreateMana(); - case POWER_RAGE: return 1000; - case POWER_FOCUS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 100); - case POWER_ENERGY: return 100; - case POWER_HAPPINESS: return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 1050000); - case POWER_RUNIC_POWER: return 1000; - case POWER_RUNE: return 0; - case POWER_HEALTH: return 0; + case POWER_MANA: + return GetCreateMana(); + case POWER_RAGE: + return 1000; + case POWER_FOCUS: + return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 100); + case POWER_ENERGY: + return 100; + case POWER_HAPPINESS: + return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 1050000); + case POWER_RUNIC_POWER: + return 1000; + case POWER_RUNE: + return 0; + case POWER_HEALTH: + return 0; default: break; } @@ -14399,7 +14649,7 @@ void Unit::RemoveFromWorld() { if (owner->m_Controlled.find(this) != owner->m_Controlled.end()) { - if (HasUnitTypeMask(UNIT_MASK_MINION|UNIT_MASK_GUARDIAN)) + if (HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_GUARDIAN)) owner->SetMinion((Minion*)this, false); sLog->outString("Unit %u is in controlled list of %u when removed from world", GetEntry(), owner->GetEntry()); //ABORT(); @@ -14499,9 +14749,9 @@ void Unit::DeleteCharmInfo() } CharmInfo::CharmInfo(Unit* unit) -: _unit(unit), _CommandState(COMMAND_FOLLOW), _petnumber(0), _oldReactState(REACT_PASSIVE), - _isCommandAttack(false), _isCommandFollow(false), _isAtStay(false), _isFollowing(false), _isReturning(false), - _forcedSpellId(0), _forcedTargetGUID(0), _stayX(0.0f), _stayY(0.0f), _stayZ(0.0f) + : _unit(unit), _CommandState(COMMAND_FOLLOW), _petnumber(0), _oldReactState(REACT_PASSIVE), + _isCommandAttack(false), _isCommandFollow(false), _isAtStay(false), _isFollowing(false), _isReturning(false), + _forcedSpellId(0), _forcedTargetGUID(0), _stayX(0.0f), _stayY(0.0f), _stayZ(0.0f) { for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i) _charmspells[i].SetActionAndType(0, ACT_DISABLED); @@ -14530,7 +14780,7 @@ void CharmInfo::InitPetActionBar() SetActionBar(ACTION_BAR_INDEX_START + i, COMMAND_ATTACK - i, ACT_COMMAND); // middle 4 SpellOrActions are spells/special attacks/abilities - for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i) + for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END - ACTION_BAR_INDEX_PET_SPELL_START; ++i) SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i, 0, ACT_PASSIVE); // last 3 SpellOrActions are reactions @@ -14544,7 +14794,7 @@ void CharmInfo::InitEmptyActionBar(bool withAttack) SetActionBar(ACTION_BAR_INDEX_START, COMMAND_ATTACK, ACT_COMMAND); else SetActionBar(ACTION_BAR_INDEX_START, 0, ACT_PASSIVE); - for (uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x) + for (uint32 x = ACTION_BAR_INDEX_START + 1; x < ACTION_BAR_INDEX_END; ++x) SetActionBar(x, 0, ACT_PASSIVE); } @@ -14708,7 +14958,7 @@ void CharmInfo::LoadPetActionBar(const std::string& data) { Tokenizer tokens(data, ' '); - if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START) * 2) + if (tokens.size() != (ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_START) * 2) return; // non critical, will reset to default uint8 index = ACTION_BAR_INDEX_START; @@ -14889,8 +15139,8 @@ void createProcFlags(const SpellInfo* spellInfo, WeaponAttackType attackType, bo break; default: if (spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && - spellInfo->EquippedItemSubClassMask & (1<HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) // Wands auto attack + spellInfo->EquippedItemSubClassMask & (1 << ITEM_SUBCLASS_WEAPON_WAND) + && spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) // Wands auto attack { procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; @@ -14905,8 +15155,8 @@ void createProcFlags(const SpellInfo* spellInfo, WeaponAttackType attackType, bo } else if (attackType == OFF_ATTACK) { - procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK; - procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK; + procAttacker = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK; + procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK; } } @@ -14917,17 +15167,39 @@ uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missC if (missCondition != SPELL_MISS_NONE) switch (missCondition) { - case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break; - case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break; - case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break; - case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break; - case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break; - case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break; - case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break; - case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break; - case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break; - case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break; - case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break; + case SPELL_MISS_MISS: + procEx |= PROC_EX_MISS; + break; + case SPELL_MISS_RESIST: + procEx |= PROC_EX_RESIST; + break; + case SPELL_MISS_DODGE: + procEx |= PROC_EX_DODGE; + break; + case SPELL_MISS_PARRY: + procEx |= PROC_EX_PARRY; + break; + case SPELL_MISS_BLOCK: + procEx |= PROC_EX_BLOCK; + break; + case SPELL_MISS_EVADE: + procEx |= PROC_EX_EVADE; + break; + case SPELL_MISS_IMMUNE: + procEx |= PROC_EX_IMMUNE; + break; + case SPELL_MISS_IMMUNE2: + procEx |= PROC_EX_IMMUNE; + break; + case SPELL_MISS_DEFLECT: + procEx |= PROC_EX_DEFLECT; + break; + case SPELL_MISS_ABSORB: + procEx |= PROC_EX_ABSORB; + break; + case SPELL_MISS_REFLECT: + procEx |= PROC_EX_REFLECT; + break; default: break; } @@ -14935,15 +15207,15 @@ uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missC { // On block if (damageInfo->blocked) - procEx|=PROC_EX_BLOCK; + procEx |= PROC_EX_BLOCK; // On absorb if (damageInfo->absorb) - procEx|=PROC_EX_ABSORB; + procEx |= PROC_EX_ABSORB; // On crit if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT) - procEx|=PROC_EX_CRITICAL_HIT; + procEx |= PROC_EX_CRITICAL_HIT; else - procEx|=PROC_EX_NORMAL_HIT; + procEx |= PROC_EX_NORMAL_HIT; } return procEx; } @@ -14964,17 +15236,17 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u if (GetTypeId() == TYPEID_PLAYER) { // On melee based hit/miss/resist need update skill (for victim and attacker) - if (procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST)) + if (procExtra & (PROC_EX_NORMAL_HIT | PROC_EX_MISS | PROC_EX_RESIST)) { if (target->GetTypeId() != TYPEID_PLAYER && !target->IsCritter()) ToPlayer()->UpdateCombatSkills(target, attType, isVictim); } // Update defence if player is victim and parry/dodge/block - else if (isVictim && procExtra & (PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK)) + else if (isVictim && procExtra & (PROC_EX_DODGE | PROC_EX_PARRY | PROC_EX_BLOCK)) ToPlayer()->UpdateCombatSkills(target, attType, true); } // If exist crit/parry/dodge/block need update aura state (for victim and attacker) - if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK)) + if (procExtra & (PROC_EX_CRITICAL_HIT | PROC_EX_PARRY | PROC_EX_DODGE | PROC_EX_BLOCK)) { // for victim if (isVictim) @@ -15044,7 +15316,7 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u ProcTriggeredList procTriggered; // Fill procTriggered list - for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr) + for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr != GetAppliedAuras().end(); ++itr) { // Do not allow auras to proc from effect triggered by itself if (procAura && procAura->Id == itr->first) @@ -15102,7 +15374,7 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u continue; // Some spells must always trigger //if (isAlwaysTriggeredAura[aurEff->GetAuraType()]) - triggerData.effMask |= 1<aura->GetId(); - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), Id); + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), Id); #endif takeCharges = true; } if (!handled) - for (uint8 effIndex = 0; effIndexeffMask & (1<aura->GetEffect(effIndex); - ASSERT(triggeredByAura); - - bool prevented = i->aura->CallScriptEffectProcHandlers(triggeredByAura, aurApp, eventInfo); - if (prevented) + for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { - takeCharges = true; - continue; - } + if (!(i->effMask & (1 << effIndex))) + continue; - switch(triggeredByAura->GetAuraType()) - { - case SPELL_AURA_PROC_TRIGGER_SPELL: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); -#endif - // Don`t drop charge or add cooldown for not started trigger - if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) - takeCharges = true; - break; - } - case SPELL_AURA_PROC_TRIGGER_DAMAGE: - { - // target has to be valid - if (!eventInfo.GetProcTarget()) - break; + AuraEffect* triggeredByAura = i->aura->GetEffect(effIndex); + ASSERT(triggeredByAura); - triggeredByAura->HandleProcTriggerDamageAuraProc(aurApp, eventInfo); // this function is part of the new proc system + bool prevented = i->aura->CallScriptEffectProcHandlers(triggeredByAura, aurApp, eventInfo); + if (prevented) + { takeCharges = true; - break; + continue; } - case SPELL_AURA_MANA_SHIELD: - case SPELL_AURA_DUMMY: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); -#endif - if (HandleDummyAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) - takeCharges = true; - break; - } - case SPELL_AURA_OBS_MOD_POWER: - case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: - case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN: - case SPELL_AURA_MOD_MELEE_HASTE: - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, isVictim ? "a victim's" : "an attacker's", triggeredByAura->GetId()); - takeCharges = true; - break; - case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); -#endif - if (HandleOverrideClassScriptAuraProc(target, damage, triggeredByAura, procSpell, cooldown)) - takeCharges = true; - break; - } - case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", - (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); -#endif - if (damage > 0) - { - HandleAuraRaidProcFromChargeWithValue(triggeredByAura); - takeCharges = true; - } - break; - } - case SPELL_AURA_RAID_PROC_FROM_CHARGE: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", - (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); -#endif - HandleAuraRaidProcFromCharge(triggeredByAura); - takeCharges = true; - break; - } - case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE: - { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); -#endif - if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) - takeCharges = true; - break; - } - case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK: - // Skip melee hits or instant cast spells - // xinef: check channeled spells which are affected by haste also - if (procSpell && (procSpell->SpellFamilyName || GetTypeId() != TYPEID_PLAYER) && - (procSpell->CalcCastTime() > 0 /*|| - (procSpell->IsChanneled() && procSpell->GetDuration() > 0 && (HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, procSpell) || procSpell->HasAttribute(SPELL_ATTR5_HASTE_AFFECT_DURATION)))*/)) - takeCharges = true; - break; - case SPELL_AURA_REFLECT_SPELLS_SCHOOL: - // Skip Melee hits and spells ws wrong school - if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check - takeCharges = true; - break; - case SPELL_AURA_SPELL_MAGNET: - // Skip Melee hits and targets with magnet aura - if (procSpell && (triggeredByAura->GetBase()->GetUnitOwner()->ToUnit() == ToUnit())) // Magnet - takeCharges = true; - break; - case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT: - case SPELL_AURA_MOD_POWER_COST_SCHOOL: - // Skip melee hits and spells ws wrong school or zero cost - if (procSpell && - (procSpell->ManaCost != 0 || procSpell->ManaCostPercentage != 0 || (procSpell->SpellFamilyFlags[1] & 0x2)) && // Cost check, mutilate include - (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check - takeCharges = true; - break; - case SPELL_AURA_MECHANIC_IMMUNITY: - case SPELL_AURA_MOD_MECHANIC_RESISTANCE: - // Compare mechanic - if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue())) - takeCharges = true; - break; - case SPELL_AURA_MOD_DAMAGE_FROM_CASTER: - // Compare casters - if (target && triggeredByAura->GetCasterGUID() == target->GetGUID()) - takeCharges = true; - break; - // CC Auras which use their amount amount to drop - // Are there any more auras which need this? - case SPELL_AURA_MOD_CONFUSE: - case SPELL_AURA_MOD_FEAR: - case SPELL_AURA_MOD_STUN: - case SPELL_AURA_MOD_ROOT: - case SPELL_AURA_TRANSFORM: + switch(triggeredByAura->GetAuraType()) { - // Spell own direct damage at apply wont break the CC - // Xinef: Or when the aura is at full duration (assume that such auras should be added at the end, skipping all damage procs etc.) - if (procSpell) - if ((!i->aura->IsPermanent() && i->aura->GetDuration() == i->aura->GetMaxDuration()) || procSpell->Id == triggeredByAura->GetId() || procSpell->HasAttribute(SPELL_ATTR4_DAMAGE_DOESNT_BREAK_AURAS)) + case SPELL_AURA_PROC_TRIGGER_SPELL: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); +#endif + // Don`t drop charge or add cooldown for not started trigger + if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) + takeCharges = true; break; + } + case SPELL_AURA_PROC_TRIGGER_DAMAGE: + { + // target has to be valid + if (!eventInfo.GetProcTarget()) + break; - // chargeable mods are breaking on hit - if (useCharges) + triggeredByAura->HandleProcTriggerDamageAuraProc(aurApp, eventInfo); // this function is part of the new proc system + takeCharges = true; + break; + } + case SPELL_AURA_MANA_SHIELD: + case SPELL_AURA_DUMMY: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); +#endif + if (HandleDummyAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) + takeCharges = true; + break; + } + case SPELL_AURA_OBS_MOD_POWER: + case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: + case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN: + case SPELL_AURA_MOD_MELEE_HASTE: + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, isVictim ? "a victim's" : "an attacker's", triggeredByAura->GetId()); takeCharges = true; - else if (triggeredByAura->GetAmount()) // aura must have amount - { - - int32 damageLeft = triggeredByAura->GetAmount(); - // No damage left - if (damageLeft < int32(damage)) - i->aura->Remove(); - else - triggeredByAura->SetAmount(damageLeft - damage); - } - break; - } - case SPELL_AURA_ABILITY_IGNORE_AURASTATE: - if (procSpell && procSpell->Id == 20647) // hack for warriors execute, both dummy and damage spell are affected by ignore aurastate aura break; - takeCharges = true; - break; - default: - takeCharges = true; - break; + case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); +#endif + if (HandleOverrideClassScriptAuraProc(target, damage, triggeredByAura, procSpell, cooldown)) + takeCharges = true; + break; + } + case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", + (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); +#endif + if (damage > 0) + { + HandleAuraRaidProcFromChargeWithValue(triggeredByAura); + takeCharges = true; + } + break; + } + case SPELL_AURA_RAID_PROC_FROM_CHARGE: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", + (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); +#endif + HandleAuraRaidProcFromCharge(triggeredByAura); + takeCharges = true; + break; + } + case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE: + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); +#endif + + if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) + takeCharges = true; + break; + } + case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK: + // Skip melee hits or instant cast spells + // xinef: check channeled spells which are affected by haste also + if (procSpell && (procSpell->SpellFamilyName || GetTypeId() != TYPEID_PLAYER) && + (procSpell->CalcCastTime() > 0 /*|| + (procSpell->IsChanneled() && procSpell->GetDuration() > 0 && (HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, procSpell) || procSpell->HasAttribute(SPELL_ATTR5_HASTE_AFFECT_DURATION)))*/)) + takeCharges = true; + break; + case SPELL_AURA_REFLECT_SPELLS_SCHOOL: + // Skip Melee hits and spells ws wrong school + if (procSpell && (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check + takeCharges = true; + break; + case SPELL_AURA_SPELL_MAGNET: + // Skip Melee hits and targets with magnet aura + if (procSpell && (triggeredByAura->GetBase()->GetUnitOwner()->ToUnit() == ToUnit())) // Magnet + takeCharges = true; + break; + case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT: + case SPELL_AURA_MOD_POWER_COST_SCHOOL: + // Skip melee hits and spells ws wrong school or zero cost + if (procSpell && + (procSpell->ManaCost != 0 || procSpell->ManaCostPercentage != 0 || (procSpell->SpellFamilyFlags[1] & 0x2)) && // Cost check, mutilate include + (triggeredByAura->GetMiscValue() & procSpell->SchoolMask)) // School check + takeCharges = true; + break; + case SPELL_AURA_MECHANIC_IMMUNITY: + case SPELL_AURA_MOD_MECHANIC_RESISTANCE: + // Compare mechanic + if (procSpell && procSpell->Mechanic == uint32(triggeredByAura->GetMiscValue())) + takeCharges = true; + break; + case SPELL_AURA_MOD_DAMAGE_FROM_CASTER: + // Compare casters + if (target && triggeredByAura->GetCasterGUID() == target->GetGUID()) + takeCharges = true; + break; + // CC Auras which use their amount amount to drop + // Are there any more auras which need this? + case SPELL_AURA_MOD_CONFUSE: + case SPELL_AURA_MOD_FEAR: + case SPELL_AURA_MOD_STUN: + case SPELL_AURA_MOD_ROOT: + case SPELL_AURA_TRANSFORM: + { + // Spell own direct damage at apply wont break the CC + // Xinef: Or when the aura is at full duration (assume that such auras should be added at the end, skipping all damage procs etc.) + if (procSpell) + if ((!i->aura->IsPermanent() && i->aura->GetDuration() == i->aura->GetMaxDuration()) || procSpell->Id == triggeredByAura->GetId() || procSpell->HasAttribute(SPELL_ATTR4_DAMAGE_DOESNT_BREAK_AURAS)) + break; + + // chargeable mods are breaking on hit + if (useCharges) + takeCharges = true; + else if (triggeredByAura->GetAmount()) // aura must have amount + { + + int32 damageLeft = triggeredByAura->GetAmount(); + // No damage left + if (damageLeft < int32(damage)) + i->aura->Remove(); + else + triggeredByAura->SetAmount(damageLeft - damage); + } + break; + } + case SPELL_AURA_ABILITY_IGNORE_AURASTATE: + if (procSpell && procSpell->Id == 20647) // hack for warriors execute, both dummy and damage spell are affected by ignore aurastate aura + break; + takeCharges = true; + break; + default: + takeCharges = true; + break; + } + i->aura->CallScriptAfterEffectProcHandlers(triggeredByAura, aurApp, eventInfo); } - i->aura->CallScriptAfterEffectProcHandlers(triggeredByAura, aurApp, eventInfo); - } // Remove charge (aura can be removed by triggers) // xinef: take into account attribute6 of proc spell if (prepare && useCharges && takeCharges) @@ -15356,7 +15628,7 @@ void Unit::GetProcAurasTriggeredOnEvent(std::list& aurasTrigge // use provided list of auras which can proc if (procAuras) { - for (std::list::iterator itr = procAuras->begin(); itr!= procAuras->end(); ++itr) + for (std::list::iterator itr = procAuras->begin(); itr != procAuras->end(); ++itr) { ASSERT((*itr)->GetTarget() == this); if (!(*itr)->GetRemoveMode()) @@ -15370,7 +15642,7 @@ void Unit::GetProcAurasTriggeredOnEvent(std::list& aurasTrigge // or generate one on our own else { - for (AuraApplicationMap::iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr) + for (AuraApplicationMap::iterator itr = GetAppliedAuras().begin(); itr != GetAppliedAuras().end(); ++itr) { if (itr->second->GetBase()->IsProcTriggeredOnEvent(itr->second, eventInfo)) { @@ -15527,7 +15799,7 @@ void Unit::SetStandState(uint8 state) SetByteValue(UNIT_FIELD_BYTES_1, 0, state); if (IsStandState()) - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED); + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED); if (GetTypeId() == TYPEID_PLAYER) { @@ -15691,7 +15963,7 @@ Unit* Unit::SelectNearbyTarget(Unit* exclude, float dist) const { if (!IsWithinLOSInMap(*tIter) || !IsValidAttackTarget(*tIter)) { - std::list::iterator tIter2 = tIter; + std::list::iterator tIter2 = tIter; ++tIter; targets.erase(tIter2); } @@ -15726,7 +15998,7 @@ Unit* Unit::SelectNearbyNoTotemTarget(Unit* exclude, float dist) const { if (!IsWithinLOSInMap(*tIter) || !IsValidAttackTarget(*tIter)) { - std::list::iterator tIter2 = tIter; + std::list::iterator tIter2 = tIter; ++tIter; targets.erase(tIter2); } @@ -15748,12 +16020,12 @@ void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply if (val > 0) { ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply); - ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att, val, !apply); + ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, val, !apply); } else { ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply); - ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att, -val, apply); + ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, -val, apply); } m_attackTimer[att] = uint32(GetAttackTime(att) * m_modAttackSpeedPct[att] * remainingTimePct); } @@ -15843,7 +16115,7 @@ uint32 Unit::GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectTyp for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellProto->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH || - (spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH)) + (spellProto->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && spellProto->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH)) { CastingTime /= 2; break; @@ -15884,7 +16156,7 @@ void Unit::UpdateAuraForGroup(uint8 slot) } } -float Unit::CalculateDefaultCoefficient(SpellInfo const *spellInfo, DamageEffectType damagetype) const +float Unit::CalculateDefaultCoefficient(SpellInfo const* spellInfo, DamageEffectType damagetype) const { // Damage over Time spells bonus calculation float DotFactor = 1.0f; @@ -16077,7 +16349,7 @@ bool Unit::InitTamedPet(Pet* pet, uint8 level, uint32 spell_id) return true; } -bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const* & spellProcEvent, ProcEventInfo const& eventInfo) +bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent, ProcEventInfo const& eventInfo) { SpellInfo const* spellProto = aura->GetSpellInfo(); @@ -16108,7 +16380,7 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const // Xinef: additional check for player auras - only player spells can trigger player proc auras // Xinef: skip victim auras if (!isVictim && GetTypeId() == TYPEID_PLAYER) //spellProto->SpellFamilyName != SPELLFAMILY_GENERIC) - if (!(EventProcFlag & (PROC_FLAG_KILL|PROC_FLAG_DEATH)) && procSpell && procSpell->SpellFamilyName == SPELLFAMILY_GENERIC && (!eventInfo.GetTriggerAuraSpell() || eventInfo.GetTriggerAuraSpell()->SpellFamilyName == SPELLFAMILY_GENERIC)) + if (!(EventProcFlag & (PROC_FLAG_KILL | PROC_FLAG_DEATH)) && procSpell && procSpell->SpellFamilyName == SPELLFAMILY_GENERIC && (!eventInfo.GetTriggerAuraSpell() || eventInfo.GetTriggerAuraSpell()->SpellFamilyName == SPELLFAMILY_GENERIC)) return false; // Check spellProcEvent data requirements @@ -16131,7 +16403,7 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const // Aura added by spell can`t trigger from self (prevent drop charges/do triggers) // But except periodic and kill triggers (can triggered from self) if (procSpell && procSpell->Id == spellProto->Id - && !(spellProto->ProcFlags&(PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL))) + && !(spellProto->ProcFlags & (PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL))) return false; // Check if current equipment allows aura to proc @@ -16151,14 +16423,14 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const if (player->IsInFeralForm()) return false; - if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1<GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask)) + if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1 << item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask)) return false; } else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR) { // Check if player is wearing shield Item* item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); - if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1<GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask)) + if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1 << item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask)) return false; } } @@ -16186,21 +16458,21 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const switch (spellProto->SpellFamilyName) { case SPELLFAMILY_SHAMAN: - { - // Blessing of the Eternals, Earthliving proc - if (spellProto->SpellIconID == 1929) { - if (victim && (float(victim->GetHealth() * 100.0f / victim->GetMaxHealth()) > 35.0f)) - return roll_chance_f(chance); + // Blessing of the Eternals, Earthliving proc + if (spellProto->SpellIconID == 1929) + { + if (victim && (float(victim->GetHealth() * 100.0f / victim->GetMaxHealth()) > 35.0f)) + return roll_chance_f(chance); + } + break; } - break; - } case SPELLFAMILY_WARRIOR: - { - // Recklessness, allow to proc only once for whirlwind - if (spellProto->Id == 1719 && procSpell && procSpell->Id == 44949) - return false; - } + { + // Recklessness, allow to proc only once for whirlwind + if (spellProto->Id == 1719 && procSpell && procSpell->Id == 44949) + return false; + } } // Apply chance modifer aura @@ -16228,7 +16500,7 @@ bool Unit::HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura) } // jumps - int32 jumps = triggeredByAura->GetBase()->GetCharges()-1; + int32 jumps = triggeredByAura->GetBase()->GetCharges() - 1; // current aura expire triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease @@ -16329,7 +16601,7 @@ bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura) uint64 caster_guid = triggeredByAura->GetCasterGUID(); // jumps - int32 jumps = triggeredByAura->GetBase()->GetCharges()-1; + int32 jumps = triggeredByAura->GetBase()->GetCharges() - 1; // current aura expire triggeredByAura->GetBase()->SetCharges(1); // will removed at next charges decrease @@ -16340,7 +16612,7 @@ bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura) if (Unit* caster = triggeredByAura->GetCaster()) { float radius = triggeredByAura->GetSpellInfo()->Effects[triggeredByAura->GetEffIndex()].CalcRadius(caster); - if (Unit* target= GetNextRandomRaidMemberOrPet(radius)) + if (Unit* target = GetNextRandomRaidMemberOrPet(radius)) { CastSpell(target, spellProto, true, NULL, triggeredByAura, caster_guid); if (Aura* aura = target->GetAura(spellProto->Id, caster->GetGUID())) @@ -16354,7 +16626,7 @@ bool Unit::HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura) return true; } -void Unit::Kill(Unit* killer, Unit* victim, bool durabilityLoss, WeaponAttackType attackType, SpellInfo const *spellProto) +void Unit::Kill(Unit* killer, Unit* victim, bool durabilityLoss, WeaponAttackType attackType, SpellInfo const* spellProto) { // Prevent killing unit twice (and giving reward from kill twice) if (!victim->GetHealth()) @@ -16399,7 +16671,7 @@ void Unit::Kill(Unit* killer, Unit* victim, bool durabilityLoss, WeaponAttackTyp // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop) if (isRewardAllowed && player && player != victim) { - WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); // send event PARTY_KILL + WorldPacket data(SMSG_PARTYKILLLOG, (8 + 8)); // send event PARTY_KILL data << uint64(player->GetGUID()); // player with killing blow data << uint64(victim->GetGUID()); // victim @@ -16492,7 +16764,7 @@ void Unit::Kill(Unit* killer, Unit* victim, bool durabilityLoss, WeaponAttackTyp bool spiritOfRedemption = false; if (victim->GetTypeId() == TYPEID_PLAYER && victim->getClass() == CLASS_PRIEST) { - if (AuraEffect *aurEff = victim->GetAuraEffectDummy(20711)) + if (AuraEffect* aurEff = victim->GetAuraEffectDummy(20711)) { // Xinef: aura_spirit_of_redemption is triggered by 27827 shapeshift if (victim->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION) || victim->HasAura(27827)) @@ -16506,24 +16778,24 @@ void Unit::Kill(Unit* killer, Unit* victim, bool durabilityLoss, WeaponAttackTyp } else { - // save value before aura remove - uint32 ressSpellId = victim->GetUInt32Value(PLAYER_SELF_RES_SPELL); - if (!ressSpellId) - ressSpellId = victim->ToPlayer()->GetResurrectionSpellId(); + // save value before aura remove + uint32 ressSpellId = victim->GetUInt32Value(PLAYER_SELF_RES_SPELL); + if (!ressSpellId) + ressSpellId = victim->ToPlayer()->GetResurrectionSpellId(); - //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers) - victim->RemoveAllAurasOnDeath(); + //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers) + victim->RemoveAllAurasOnDeath(); - // Stop attacks - victim->CombatStop(); - victim->getHostileRefManager().deleteReferences(); + // Stop attacks + victim->CombatStop(); + victim->getHostileRefManager().deleteReferences(); - // restore for use at real death - victim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId); + // restore for use at real death + victim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); - // FORM_SPIRITOFREDEMPTION and related auras - victim->CastSpell(victim, 27827, true, NULL, aurEff); - spiritOfRedemption = true; + // FORM_SPIRITOFREDEMPTION and related auras + victim->CastSpell(victim, 27827, true, NULL, aurEff); + spiritOfRedemption = true; } } } @@ -17181,9 +17453,9 @@ void Unit::RemoveCharmedBy(Unit* charmer) charmer = GetCharmer(); if (charmer != GetCharmer()) // one aura overrides another? { -// sLog->outCrash("Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD, -// GetGUID(), GetCharmerGUID(), charmer->GetGUID()); -// ABORT(); + // sLog->outCrash("Unit::RemoveCharmedBy: this: " UI64FMTD " true charmer: " UI64FMTD " false charmer: " UI64FMTD, + // GetGUID(), GetCharmerGUID(), charmer->GetGUID()); + // ABORT(); return; } @@ -17406,7 +17678,7 @@ bool Unit::IsInPartyWith(Unit const* unit) const return u1->getFaction() == u2->getFaction(); // Xinef: creature type_flag should work for party check only if player group is not a raid else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && (u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) && u2->ToPlayer()->GetGroup() && !u2->ToPlayer()->GetGroup()->isRaidGroup()) || - (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && (u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) && u1->ToPlayer()->GetGroup() && !u1->ToPlayer()->GetGroup()->isRaidGroup())) + (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && (u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) && u1->ToPlayer()->GetGroup() && !u1->ToPlayer()->GetGroup()->isRaidGroup())) return true; else return false; @@ -17428,14 +17700,14 @@ bool Unit::IsInRaidWith(Unit const* unit) const else if (u1->GetTypeId() == TYPEID_UNIT && u2->GetTypeId() == TYPEID_UNIT && !u1->IsControlledByPlayer() && !u2->IsControlledByPlayer()) return u1->getFaction() == u2->getFaction(); else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) || - (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT)) + (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT)) return true; else return false; } -void Unit::GetPartyMembers(std::list &TagUnitMap) +void Unit::GetPartyMembers(std::list& TagUnitMap) { Unit* owner = GetCharmerOrOwnerOrSelf(); Group* group = nullptr; @@ -17504,10 +17776,10 @@ Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target) for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - if (!(effMask & (1<IsImmunedToSpellEffect(spellInfo, i)) - effMask &= ~(1<MoveJumpTo(angle, speedXY, speedZ); else { - float vcos = cos(angle+GetOrientation()); - float vsin = sin(angle+GetOrientation()); + float vcos = cos(angle + GetOrientation()); + float vsin = sin(angle + GetOrientation()); - WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4)); + WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8 + 4 + 4 + 4 + 4 + 4)); data.append(GetPackGUID()); data << uint32(0); // Sequence data << float(vcos); // x direction @@ -18173,7 +18445,7 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) } if (IsInMap(caster)) - caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId+1, target, GetVehicleKit() ? TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE : TRIGGERED_NONE, nullptr, nullptr, origCasterGUID); + caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0 + i), seatId + 1, target, GetVehicleKit() ? TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE : TRIGGERED_NONE, nullptr, nullptr, origCasterGUID); else // This can happen during Player::_LoadAuras { int32 bp0[MAX_SPELL_EFFECTS]; @@ -18204,12 +18476,12 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) void Unit::EnterVehicle(Unit* base, int8 seatId) { - CastCustomSpell(VEHICLE_SPELL_RIDE_HARDCODED, SPELLVALUE_BASE_POINT0, seatId+1, base, TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE); + CastCustomSpell(VEHICLE_SPELL_RIDE_HARDCODED, SPELLVALUE_BASE_POINT0, seatId + 1, base, TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE); } -void Unit::EnterVehicleUnattackable(Unit *base, int8 seatId) +void Unit::EnterVehicleUnattackable(Unit* base, int8 seatId) { - CastCustomSpell(67830, SPELLVALUE_BASE_POINT0, seatId+1, base, true); + CastCustomSpell(67830, SPELLVALUE_BASE_POINT0, seatId + 1, base, true); } void Unit::_EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp) @@ -18273,7 +18545,7 @@ void Unit::_EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* a } // Xinef: remove movement auras when entering vehicle (food buffs etc) - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING|AURA_INTERRUPT_FLAG_MOVE); + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING | AURA_INTERRUPT_FLAG_MOVE); } void Unit::ChangeSeat(int8 seatId, bool next) @@ -18346,7 +18618,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) Position pos; if (!exitPosition) // Exit position not specified vehicleBase->GetPosition(&pos); // This should use passenger's current position, leaving it as it is now - // because we calculate positions incorrect (sometimes under map) + // because we calculate positions incorrect (sometimes under map) else pos = *exitPosition; @@ -18359,7 +18631,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) { float x = pos.GetPositionX() + 2.0f * cos(pos.GetOrientation() - M_PI / 2.0f); float y = pos.GetPositionY() + 2.0f * sin(pos.GetOrientation() - M_PI / 2.0f); - float z = GetMap()->GetHeight(GetPhaseMask(), x, y, pos.GetPositionZ())+0.1f; + float z = GetMap()->GetHeight(GetPhaseMask(), x, y, pos.GetPositionZ()) + 0.1f; if (z > INVALID_HEIGHT) pos.Relocate(x, y, z); } @@ -18388,7 +18660,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) { float o = pos.GetAngle(this); Movement::MoveSplineInit init(this); - init.MoveTo(pos.GetPositionX()+8*cos(o), pos.GetPositionY()+8*sin(o), pos.GetPositionZ()+16.0f); + init.MoveTo(pos.GetPositionX() + 8 * cos(o), pos.GetPositionY() + 8 * sin(o), pos.GetPositionZ() + 16.0f); init.SetFacing(GetOrientation()); init.SetTransportExit(); init.Launch(); @@ -18399,7 +18671,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) // xinef: move fall, should we support all creatures that exited vehicle in air? Currently Quest Drag and Drop only, Air Assault quest if (GetTypeId() == TYPEID_UNIT && !CanFly() && - (vehicle->GetVehicleInfo()->m_ID == 113 || vehicle->GetVehicleInfo()->m_ID == 8 || vehicle->GetVehicleInfo()->m_ID == 290 || vehicle->GetVehicleInfo()->m_ID == 298)) + (vehicle->GetVehicleInfo()->m_ID == 113 || vehicle->GetVehicleInfo()->m_ID == 8 || vehicle->GetVehicleInfo()->m_ID == 290 || vehicle->GetVehicleInfo()->m_ID == 298)) GetMotionMaster()->MoveFall(); //GetMotionMaster()->MoveFall(); // Enable this once passenger positions are calculater properly (see above) @@ -18441,7 +18713,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) player->ResummonPetTemporaryUnSummonedIfAny(); } -void Unit::BuildMovementPacket(ByteBuffer *data) const +void Unit::BuildMovementPacket(ByteBuffer* data) const { if (GetTypeId() == TYPEID_UNIT && GetHoverHeight() >= 2.0f && !HasUnitMovementFlag(MOVEMENTFLAG_FALLING) && !movespline->isFalling()) // pussywizard: add disable gravity to hover (artifically, not to spoil speed and other things) *data << uint32(GetUnitMovementFlags() | MOVEMENTFLAG_DISABLE_GRAVITY); // movement flags @@ -18477,7 +18749,7 @@ void Unit::BuildMovementPacket(ByteBuffer *data) const // 0x02200000 if ((GetUnitMovementFlags() & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) - || (m_movementInfo.flags2 & MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING)) + || (m_movementInfo.flags2 & MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING)) *data << (float)m_movementInfo.pitch; *data << (uint32)m_movementInfo.fallTime; @@ -18611,11 +18883,11 @@ void Unit::SendThreatListUpdate() WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8); data.append(GetPackGUID()); data << uint32(count); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data.appendPackGUID((*itr)->getUnitGuid()); - data << uint32((*itr)->getThreat()*100); + data << uint32((*itr)->getThreat() * 100); } SendMessageToSet(&data, false); } @@ -18634,11 +18906,11 @@ void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference) data.append(GetPackGUID()); data.appendPackGUID(pHostileReference->getUnitGuid()); data << uint32(count); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data.appendPackGUID((*itr)->getUnitGuid()); - data << uint32((*itr)->getThreat()*100); + data << uint32((*itr)->getThreat() * 100); } SendMessageToSet(&data, false); } @@ -18727,14 +18999,14 @@ void Unit::StopAttackFaction(uint32 faction_id) getHostileRefManager().deleteReferencesForFaction(faction_id); for (ControlSet::const_iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr) - (*itr)->StopAttackFaction(faction_id); + (*itr)->StopAttackFaction(faction_id); } void Unit::OutDebugInfo() const { sLog->outError("Unit::OutDebugInfo"); sLog->outString("GUID " UI64FMTD ", entry %u, type %u, name %s", GetGUID(), GetEntry(), (uint32)GetTypeId(), GetName().c_str()); - sLog->outString("OwnerGUID " UI64FMTD ", MinionGUID " UI64FMTD ", CharmerGUID " UI64FMTD ", CharmedGUID " UI64FMTD , GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID()); + sLog->outString("OwnerGUID " UI64FMTD ", MinionGUID " UI64FMTD ", CharmerGUID " UI64FMTD ", CharmedGUID " UI64FMTD, GetOwnerGUID(), GetMinionGUID(), GetCharmerGUID(), GetCharmGUID()); sLog->outString("In world %u, unit type mask %u", (uint32)(IsInWorld() ? 1 : 0), m_unitTypeMask); if (IsInWorld()) sLog->outString("Mapid %u", GetMapId()); @@ -18769,23 +19041,23 @@ void Unit::OutDebugInfo() const class AuraMunchingQueue : public BasicEvent { - public: - AuraMunchingQueue(Unit& owner, uint64 targetGUID, int32 basePoints, uint32 spellId) : _owner(owner), _targetGUID(targetGUID), _basePoints(basePoints), _spellId(spellId) { } +public: + AuraMunchingQueue(Unit& owner, uint64 targetGUID, int32 basePoints, uint32 spellId) : _owner(owner), _targetGUID(targetGUID), _basePoints(basePoints), _spellId(spellId) { } - bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) - { - if (_owner.IsInWorld() && _owner.FindMap()) - if (Unit* target = ObjectAccessor::GetUnit(_owner, _targetGUID)) - _owner.CastCustomSpell(_spellId, SPELLVALUE_BASE_POINT0, _basePoints, target, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_NO_PERIODIC_RESET), nullptr, nullptr, _owner.GetGUID()); + bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) + { + if (_owner.IsInWorld() && _owner.FindMap()) + if (Unit* target = ObjectAccessor::GetUnit(_owner, _targetGUID)) + _owner.CastCustomSpell(_spellId, SPELLVALUE_BASE_POINT0, _basePoints, target, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_NO_PERIODIC_RESET), nullptr, nullptr, _owner.GetGUID()); - return true; - } + return true; + } - private: - Unit& _owner; - uint64 _targetGUID; - int32 _basePoints; - uint32 _spellId; +private: + Unit& _owner; + uint64 _targetGUID; + int32 _basePoints; + uint32 _spellId; }; void Unit::CastDelayedSpellWithPeriodicAmount(Unit* caster, uint32 spellId, AuraType auraType, int32 addAmount, uint8 effectIndex) @@ -18802,7 +19074,7 @@ void Unit::CastDelayedSpellWithPeriodicAmount(Unit* caster, uint32 spellId, Aura // xinef: delay only for casting on different unit if (this == caster) - caster->CastCustomSpell(spellId, SPELLVALUE_BASE_POINT0, addAmount, this, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_NO_PERIODIC_RESET), nullptr, nullptr, caster->GetGUID()); + caster->CastCustomSpell(spellId, SPELLVALUE_BASE_POINT0, addAmount, this, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_NO_PERIODIC_RESET), nullptr, nullptr, caster->GetGUID()); else caster->m_Events.AddEvent(new AuraMunchingQueue(*caster, GetGUID(), addAmount, spellId), caster->m_Events.CalculateQueueTime(400)); } @@ -18868,7 +19140,7 @@ void CharmInfo::SaveStayPosition(bool atCurrentPos) _stayZ = stayPos.z; } -void CharmInfo::GetStayPosition(float &x, float &y, float &z) +void CharmInfo::GetStayPosition(float& x, float& y, float& z) { x = _stayX; y = _stayY; @@ -18926,7 +19198,7 @@ void Unit::PetSpellFail(const SpellInfo* spellInfo, Unit* target, uint32 result) if ((MMAP::MMapFactory::IsPathfindingEnabled(GetMap()) || result != SPELL_FAILED_LINE_OF_SIGHT) && target) { if ((result == SPELL_FAILED_LINE_OF_SIGHT || result == SPELL_FAILED_OUT_OF_RANGE) || !ToCreature()->HasReactState(REACT_PASSIVE)) - if (Unit *owner = GetOwner()) + if (Unit* owner = GetOwner()) { if (spellInfo->IsPositive() && IsFriendlyTo(target)) { @@ -18936,7 +19208,7 @@ void Unit::PetSpellFail(const SpellInfo* spellInfo, Unit* target, uint32 result) charmInfo->SetIsReturning(false); charmInfo->SetIsFollowing(false); - GetMotionMaster()->MoveFollow(target, PET_FOLLOW_DIST, rand_norm()*2*M_PI); + GetMotionMaster()->MoveFollow(target, PET_FOLLOW_DIST, rand_norm() * 2 * M_PI); } else if (owner->IsValidAttackTarget(target)) { @@ -18979,10 +19251,10 @@ int32 Unit::CalculateAOEDamageReduction(int32 damage, uint32 schoolMask, Unit* c bool ConflagrateAuraStateDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) { if (Unit* owner = ObjectAccessor::FindUnit(m_owner)) - if (owner && m_caster && owner->IsInWorld()) - if (owner->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0, m_caster) || // immolate + if (owner && m_caster && owner->IsInWorld()) + if (owner->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0, m_caster) || // immolate owner->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0, 0, 0x2, m_caster)) // shadowflame - owner->ModifyAuraState(AURA_STATE_CONFLAGRATE, true); + owner->ModifyAuraState(AURA_STATE_CONFLAGRATE, true); return true; } @@ -18990,7 +19262,7 @@ bool ConflagrateAuraStateDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_tim uint32 Unit::GetZoneId(bool forceRecalc) const { // xinef: optimization, zone calculated every few yards - if (!forceRecalc && GetExactDistSq(&m_last_zone_position) < 4.0f*4.0f) + if (!forceRecalc && GetExactDistSq(&m_last_zone_position) < 4.0f * 4.0f) return m_last_zone_id; else { @@ -19003,7 +19275,7 @@ uint32 Unit::GetZoneId(bool forceRecalc) const uint32 Unit::GetAreaId(bool forceRecalc) const { // xinef: optimization, area calculated every few yards - if (!forceRecalc && GetExactDistSq(&m_last_area_position) < 4.0f*4.0f) + if (!forceRecalc && GetExactDistSq(&m_last_area_position) < 4.0f * 4.0f) return m_last_area_id; else { @@ -19016,7 +19288,7 @@ uint32 Unit::GetAreaId(bool forceRecalc) const void Unit::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc) const { // xinef: optimization, zone and area calculated every few yards - if (!forceRecalc && GetExactDistSq(&m_last_area_position) < 4.0f*4.0f && GetExactDistSq(&m_last_zone_position) < 4.0f*4.0f) + if (!forceRecalc && GetExactDistSq(&m_last_area_position) < 4.0f * 4.0f && GetExactDistSq(&m_last_zone_position) < 4.0f * 4.0f) { zoneid = m_last_zone_id; areaid = m_last_area_id; @@ -19033,7 +19305,7 @@ void Unit::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc) co bool Unit::IsOutdoors() const { // xinef: optimization, outdoor status calculated every few yards - if (GetExactDistSq(&m_last_outdoors_position) < 4.0f*4.0f) + if (GetExactDistSq(&m_last_outdoors_position) < 4.0f * 4.0f) return m_last_outdoors_status; else { @@ -19069,7 +19341,7 @@ void Unit::ExecuteDelayedUnitRelocationEvent() float dx = active->m_last_notify_position.GetPositionX() - active->GetPositionX(); float dy = active->m_last_notify_position.GetPositionY() - active->GetPositionY(); float dz = active->m_last_notify_position.GetPositionZ() - active->GetPositionZ(); - float distsq = dx*dx+dy*dy+dz*dz; + float distsq = dx * dx + dy * dy + dz * dz; float mindistsq = DynamicVisibilityMgr::GetReqMoveDistSq(active->FindMap()->GetEntry()->map_type); if (distsq < mindistsq) continue; @@ -19079,7 +19351,7 @@ void Unit::ExecuteDelayedUnitRelocationEvent() } acore::PlayerRelocationNotifier relocateNoLarge(*player, false); // visit only objects which are not large; default distance - viewPoint->VisitNearbyObject(player->GetSightRange()+VISIBILITY_INC_FOR_GOBJECTS, relocateNoLarge); + viewPoint->VisitNearbyObject(player->GetSightRange() + VISIBILITY_INC_FOR_GOBJECTS, relocateNoLarge); relocateNoLarge.SendToSelf(); acore::PlayerRelocationNotifier relocateLarge(*player, true); // visit only large objects; maximum distance viewPoint->VisitNearbyObject(MAX_VISIBILITY_DISTANCE, relocateLarge); @@ -19103,7 +19375,7 @@ void Unit::ExecuteDelayedUnitRelocationEvent() float dx = active->m_last_notify_position.GetPositionX() - active->GetPositionX(); float dy = active->m_last_notify_position.GetPositionY() - active->GetPositionY(); float dz = active->m_last_notify_position.GetPositionZ() - active->GetPositionZ(); - float distsq = dx*dx+dy*dy+dz*dz; + float distsq = dx * dx + dy * dy + dz * dz; float mindistsq = DynamicVisibilityMgr::GetReqMoveDistSq(active->FindMap()->GetEntry()->map_type); if (distsq < mindistsq) @@ -19113,7 +19385,7 @@ void Unit::ExecuteDelayedUnitRelocationEvent() } acore::PlayerRelocationNotifier relocateNoLarge(*player, false); // visit only objects which are not large; default distance - viewPoint->VisitNearbyObject(player->GetSightRange()+VISIBILITY_INC_FOR_GOBJECTS, relocateNoLarge); + viewPoint->VisitNearbyObject(player->GetSightRange() + VISIBILITY_INC_FOR_GOBJECTS, relocateNoLarge); relocateNoLarge.SendToSelf(); acore::PlayerRelocationNotifier relocateLarge(*player, true); // visit only large objects; maximum distance viewPoint->VisitNearbyObject(MAX_VISIBILITY_DISTANCE, relocateLarge); @@ -19129,7 +19401,7 @@ void Unit::ExecuteDelayedUnitRelocationEvent() float dx = unit->m_last_notify_position.GetPositionX() - unit->GetPositionX(); float dy = unit->m_last_notify_position.GetPositionY() - unit->GetPositionY(); float dz = unit->m_last_notify_position.GetPositionZ() - unit->GetPositionZ(); - float distsq = dx*dx+dy*dy+dz*dz; + float distsq = dx * dx + dy * dy + dz * dz; float mindistsq = DynamicVisibilityMgr::GetReqMoveDistSq(unit->FindMap()->GetEntry()->map_type); if (distsq < mindistsq) return; @@ -19137,7 +19409,7 @@ void Unit::ExecuteDelayedUnitRelocationEvent() unit->m_last_notify_position.Relocate(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ()); acore::CreatureRelocationNotifier relocate(*unit); - unit->VisitNearbyObject(unit->GetVisibilityRange()+VISIBILITY_COMPENSATION, relocate); + unit->VisitNearbyObject(unit->GetVisibilityRange() + VISIBILITY_COMPENSATION, relocate); this->AddToNotify(NOTIFY_AI_RELOCATION); } @@ -19358,9 +19630,9 @@ void Unit::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) for (uint16 index = 0; index < m_valuesCount; ++index) { if (_fieldNotifyFlags & flags[index] || - ((flags[index] & visibleFlag) & UF_FLAG_SPECIAL_INFO) || - ((updateType == UPDATETYPE_VALUES ? _changesMask.GetBit(index) : m_uint32Values[index]) && (flags[index] & visibleFlag)) || - (index == UNIT_FIELD_AURASTATE && HasFlag(UNIT_FIELD_AURASTATE, PER_CASTER_AURA_STATE_MASK))) + ((flags[index] & visibleFlag) & UF_FLAG_SPECIAL_INFO) || + ((updateType == UPDATETYPE_VALUES ? _changesMask.GetBit(index) : m_uint32Values[index]) && (flags[index] & visibleFlag)) || + (index == UNIT_FIELD_AURASTATE && HasFlag(UNIT_FIELD_AURASTATE, PER_CASTER_AURA_STATE_MASK))) { updateMask.SetBit(index); @@ -19392,9 +19664,9 @@ void Unit::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) } // there are some float values which may be negative or can't get negative due to other checks else if ((index >= UNIT_FIELD_NEGSTAT0 && index <= UNIT_FIELD_NEGSTAT4) || - (index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) || - (index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) || - (index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4)) + (index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) || + (index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) || + (index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4)) { fieldBuffer << uint32(m_floatValues[index]); } @@ -19491,7 +19763,7 @@ void Unit::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) fieldBuffer << m_uint32Values[index]; }// pussywizard / Callmephil else if (target->IsSpectator() && target->FindMap() && target->FindMap()->IsBattleArena() && - (this->GetTypeId() == TYPEID_PLAYER || this->GetTypeId() == TYPEID_UNIT || this->GetTypeId() == TYPEID_DYNAMICOBJECT)) + (this->GetTypeId() == TYPEID_PLAYER || this->GetTypeId() == TYPEID_UNIT || this->GetTypeId() == TYPEID_DYNAMICOBJECT)) { if (index == UNIT_FIELD_BYTES_2) fieldBuffer << (m_uint32Values[index] & 0xFFFFF2FF); // clear UNIT_BYTE2_FLAG_PVP, UNIT_BYTE2_FLAG_FFA_PVP, UNIT_BYTE2_FLAG_SANCTUARY diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index 5a9c06f68..30d2d4d96 100644 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -118,11 +118,11 @@ enum SpellValueMod typedef std::pair CustomSpellValueMod; class CustomSpellValues : public std::vector { - public: - void AddSpellMod(SpellValueMod mod, int32 value) - { - push_back(std::make_pair(mod, value)); - } +public: + void AddSpellMod(SpellValueMod mod, int32 value) + { + push_back(std::make_pair(mod, value)); + } }; enum SpellFacingFlags @@ -481,15 +481,15 @@ enum UnitState UNIT_STATE_NO_ENVIRONMENT_UPD = 0x20000000, // pussywizard UNIT_STATE_ALL_STATE_SUPPORTED = UNIT_STATE_DIED | UNIT_STATE_MELEE_ATTACKING | UNIT_STATE_STUNNED | UNIT_STATE_ROAMING | UNIT_STATE_CHASE - | UNIT_STATE_FLEEING | UNIT_STATE_IN_FLIGHT | UNIT_STATE_FOLLOW | UNIT_STATE_ROOT | UNIT_STATE_CONFUSED - | UNIT_STATE_DISTRACTED | UNIT_STATE_ISOLATED | UNIT_STATE_ATTACK_PLAYER | UNIT_STATE_CASTING - | UNIT_STATE_POSSESSED | UNIT_STATE_CHARGING | UNIT_STATE_JUMPING | UNIT_STATE_MOVE | UNIT_STATE_ROTATING - | UNIT_STATE_EVADE | UNIT_STATE_ROAMING_MOVE | UNIT_STATE_CONFUSED_MOVE | UNIT_STATE_FLEEING_MOVE - | UNIT_STATE_CHASE_MOVE | UNIT_STATE_FOLLOW_MOVE | UNIT_STATE_IGNORE_PATHFINDING | UNIT_STATE_NO_ENVIRONMENT_UPD, + | UNIT_STATE_FLEEING | UNIT_STATE_IN_FLIGHT | UNIT_STATE_FOLLOW | UNIT_STATE_ROOT | UNIT_STATE_CONFUSED + | UNIT_STATE_DISTRACTED | UNIT_STATE_ISOLATED | UNIT_STATE_ATTACK_PLAYER | UNIT_STATE_CASTING + | UNIT_STATE_POSSESSED | UNIT_STATE_CHARGING | UNIT_STATE_JUMPING | UNIT_STATE_MOVE | UNIT_STATE_ROTATING + | UNIT_STATE_EVADE | UNIT_STATE_ROAMING_MOVE | UNIT_STATE_CONFUSED_MOVE | UNIT_STATE_FLEEING_MOVE + | UNIT_STATE_CHASE_MOVE | UNIT_STATE_FOLLOW_MOVE | UNIT_STATE_IGNORE_PATHFINDING | UNIT_STATE_NO_ENVIRONMENT_UPD, UNIT_STATE_UNATTACKABLE = UNIT_STATE_IN_FLIGHT, // for real move using movegen check and stop (except unstoppable flight) - UNIT_STATE_MOVING = UNIT_STATE_ROAMING_MOVE | UNIT_STATE_CONFUSED_MOVE | UNIT_STATE_FLEEING_MOVE | UNIT_STATE_CHASE_MOVE | UNIT_STATE_FOLLOW_MOVE , + UNIT_STATE_MOVING = UNIT_STATE_ROAMING_MOVE | UNIT_STATE_CONFUSED_MOVE | UNIT_STATE_FLEEING_MOVE | UNIT_STATE_CHASE_MOVE | UNIT_STATE_FOLLOW_MOVE, UNIT_STATE_CONTROLLED = (UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING), UNIT_STATE_LOST_CONTROL = (UNIT_STATE_CONTROLLED | UNIT_STATE_JUMPING | UNIT_STATE_CHARGING), UNIT_STATE_SIGHTLESS = (UNIT_STATE_LOST_CONTROL | UNIT_STATE_EVADE), @@ -713,7 +713,7 @@ enum MovementFlags /// Movement flags that have change status opcodes associated for players MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE = MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | - MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER + MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER }; enum MovementFlags2 @@ -798,7 +798,8 @@ enum UnitTypeMask UNIT_MASK_ACCESSORY = 0x00000200, }; -namespace Movement{ +namespace Movement +{ class MoveSpline; } @@ -818,8 +819,8 @@ struct DiminishingReturn : DRGroup(group), stack(0), hitTime(t), hitCount(count) {} - DiminishingGroup DRGroup:16; - uint16 stack:16; + DiminishingGroup DRGroup: 16; + uint16 stack: 16; uint32 hitTime; uint32 hitCount; }; @@ -834,7 +835,7 @@ class DispelInfo { public: explicit DispelInfo(Unit* dispeller, uint32 dispellerSpellId, uint8 chargesRemoved) : - _dispellerUnit(dispeller), _dispellerSpell(dispellerSpellId), _chargesRemoved(chargesRemoved) {} + _dispellerUnit(dispeller), _dispellerSpell(dispellerSpellId), _chargesRemoved(chargesRemoved) {} Unit* GetDispeller() const { return _dispellerUnit; } uint32 GetDispellerSpellId() const { return _dispellerSpell; } @@ -852,7 +853,7 @@ private: struct CleanDamage { CleanDamage(uint32 mitigated, uint32 absorbed, WeaponAttackType _attackType, MeleeHitOutcome _hitOutCome) : - absorbed_damage(absorbed), mitigated_damage(mitigated), attackType(_attackType), hitOutCome(_hitOutCome) {} + absorbed_damage(absorbed), mitigated_damage(mitigated), attackType(_attackType), hitOutCome(_hitOutCome) {} uint32 absorbed_damage; uint32 mitigated_damage; @@ -963,8 +964,8 @@ public: // Need create structure like in SMSG_ATTACKERSTATEUPDATE opcode struct CalcDamageInfo { - Unit *attacker; // Attacker - Unit *target; // Target for damage + Unit* attacker; // Attacker + Unit* target; // Target for damage uint32 damageSchoolMask; uint32 damage; uint32 absorb; @@ -972,7 +973,7 @@ struct CalcDamageInfo uint32 blocked_amount; uint32 HitInfo; uint32 TargetState; -// Helper + // Helper WeaponAttackType attackType; // uint32 procAttacker; uint32 procVictim; @@ -986,11 +987,11 @@ struct SpellNonMeleeDamage { SpellNonMeleeDamage(Unit* _attacker, Unit* _target, uint32 _SpellID, uint32 _schoolMask) : target(_target), attacker(_attacker), SpellID(_SpellID), damage(0), overkill(0), schoolMask(_schoolMask), - absorb(0), resist(0), physicalLog(false), unused(false), blocked(0), HitInfo(0), cleanDamage(0) + absorb(0), resist(0), physicalLog(false), unused(false), blocked(0), HitInfo(0), cleanDamage(0) {} - Unit *target; - Unit *attacker; + Unit* target; + Unit* attacker; uint32 SpellID; uint32 damage; uint32 overkill; @@ -1008,7 +1009,7 @@ struct SpellNonMeleeDamage struct SpellPeriodicAuraLogInfo { SpellPeriodicAuraLogInfo(AuraEffect const* _auraEff, uint32 _damage, uint32 _overDamage, uint32 _absorb, uint32 _resist, float _multiplier, bool _critical) - : auraEff(_auraEff), damage(_damage), overDamage(_overDamage), absorb(_absorb), resist(_resist), multiplier(_multiplier), critical(_critical){} + : auraEff(_auraEff), damage(_damage), overDamage(_overDamage), absorb(_absorb), resist(_resist), multiplier(_multiplier), critical(_critical) {} AuraEffect const* auraEff; uint32 damage; @@ -1170,87 +1171,87 @@ enum ActionBarIndex struct CharmInfo { - public: - explicit CharmInfo(Unit* unit); - ~CharmInfo(); - void RestoreState(); - uint32 GetPetNumber() const { return _petnumber; } - void SetPetNumber(uint32 petnumber, bool statwindow); +public: + explicit CharmInfo(Unit* unit); + ~CharmInfo(); + void RestoreState(); + uint32 GetPetNumber() const { return _petnumber; } + void SetPetNumber(uint32 petnumber, bool statwindow); - void SetCommandState(CommandStates st) { _CommandState = st; } - CommandStates GetCommandState() const { return _CommandState; } - bool HasCommandState(CommandStates state) const { return (_CommandState == state); } + void SetCommandState(CommandStates st) { _CommandState = st; } + CommandStates GetCommandState() const { return _CommandState; } + bool HasCommandState(CommandStates state) const { return (_CommandState == state); } - void InitPossessCreateSpells(); - void InitCharmCreateSpells(); - void InitPetActionBar(); - void InitEmptyActionBar(bool withAttack = true); + void InitPossessCreateSpells(); + void InitCharmCreateSpells(); + void InitPetActionBar(); + void InitEmptyActionBar(bool withAttack = true); - //return true if successful - bool AddSpellToActionBar(SpellInfo const* spellInfo, ActiveStates newstate = ACT_DECIDE); - bool RemoveSpellFromActionBar(uint32 spell_id); - void LoadPetActionBar(const std::string& data); - void BuildActionBar(WorldPacket* data); - void SetSpellAutocast(SpellInfo const* spellInfo, bool state); - void SetActionBar(uint8 index, uint32 spellOrAction, ActiveStates type) - { - PetActionBar[index].SetActionAndType(spellOrAction, type); - } - UnitActionBarEntry const* GetActionBarEntry(uint8 index) const { return &(PetActionBar[index]); } + //return true if successful + bool AddSpellToActionBar(SpellInfo const* spellInfo, ActiveStates newstate = ACT_DECIDE); + bool RemoveSpellFromActionBar(uint32 spell_id); + void LoadPetActionBar(const std::string& data); + void BuildActionBar(WorldPacket* data); + void SetSpellAutocast(SpellInfo const* spellInfo, bool state); + void SetActionBar(uint8 index, uint32 spellOrAction, ActiveStates type) + { + PetActionBar[index].SetActionAndType(spellOrAction, type); + } + UnitActionBarEntry const* GetActionBarEntry(uint8 index) const { return &(PetActionBar[index]); } - void ToggleCreatureAutocast(SpellInfo const* spellInfo, bool apply); + void ToggleCreatureAutocast(SpellInfo const* spellInfo, bool apply); - CharmSpellInfo* GetCharmSpell(uint8 index) { return &(_charmspells[index]); } + CharmSpellInfo* GetCharmSpell(uint8 index) { return &(_charmspells[index]); } - GlobalCooldownMgr& GetGlobalCooldownMgr() { return _GlobalCooldownMgr; } + GlobalCooldownMgr& GetGlobalCooldownMgr() { return _GlobalCooldownMgr; } - void SetIsCommandAttack(bool val); - bool IsCommandAttack(); - void SetIsCommandFollow(bool val); - bool IsCommandFollow(); - void SetIsAtStay(bool val); - bool IsAtStay(); - void SetIsFollowing(bool val); - bool IsFollowing(); - void SetIsReturning(bool val); - bool IsReturning(); - void SaveStayPosition(bool atCurrentPos); - void GetStayPosition(float &x, float &y, float &z); - void RemoveStayPosition(); - bool HasStayPosition(); + void SetIsCommandAttack(bool val); + bool IsCommandAttack(); + void SetIsCommandFollow(bool val); + bool IsCommandFollow(); + void SetIsAtStay(bool val); + bool IsAtStay(); + void SetIsFollowing(bool val); + bool IsFollowing(); + void SetIsReturning(bool val); + bool IsReturning(); + void SaveStayPosition(bool atCurrentPos); + void GetStayPosition(float& x, float& y, float& z); + void RemoveStayPosition(); + bool HasStayPosition(); - void SetForcedSpell(uint32 id) { _forcedSpellId = id; } - int32 GetForcedSpell() { return _forcedSpellId; } - void SetForcedTargetGUID(uint64 guid) { _forcedTargetGUID = guid; } - uint64 GetForcedTarget() { return _forcedTargetGUID; } + void SetForcedSpell(uint32 id) { _forcedSpellId = id; } + int32 GetForcedSpell() { return _forcedSpellId; } + void SetForcedTargetGUID(uint64 guid) { _forcedTargetGUID = guid; } + uint64 GetForcedTarget() { return _forcedTargetGUID; } - // Player react states - void SetPlayerReactState(ReactStates s) { _oldReactState = s; } - ReactStates GetPlayerReactState() const { return _oldReactState; } + // Player react states + void SetPlayerReactState(ReactStates s) { _oldReactState = s; } + ReactStates GetPlayerReactState() const { return _oldReactState; } - private: +private: - Unit* _unit; - UnitActionBarEntry PetActionBar[MAX_UNIT_ACTION_BAR_INDEX]; - CharmSpellInfo _charmspells[4]; - CommandStates _CommandState; - uint32 _petnumber; + Unit* _unit; + UnitActionBarEntry PetActionBar[MAX_UNIT_ACTION_BAR_INDEX]; + CharmSpellInfo _charmspells[4]; + CommandStates _CommandState; + uint32 _petnumber; - //for restoration after charmed - ReactStates _oldReactState; + //for restoration after charmed + ReactStates _oldReactState; - bool _isCommandAttack; - bool _isCommandFollow; - bool _isAtStay; - bool _isFollowing; - bool _isReturning; - int32 _forcedSpellId; - uint64 _forcedTargetGUID; - float _stayX; - float _stayY; - float _stayZ; + bool _isCommandAttack; + bool _isCommandFollow; + bool _isAtStay; + bool _isFollowing; + bool _isReturning; + int32 _forcedSpellId; + uint64 _forcedTargetGUID; + float _stayX; + float _stayY; + float _stayZ; - GlobalCooldownMgr _GlobalCooldownMgr; + GlobalCooldownMgr _GlobalCooldownMgr; }; // for clearing special attacks @@ -1315,14 +1316,14 @@ public: _posTarget.Relocate(c._posTarget); } /* requried as of C++ 11 */ - #if __cplusplus >= 201103L +#if __cplusplus >= 201103L MMapTargetData(MMapTargetData&&) = default; MMapTargetData& operator=(const MMapTargetData&) = default; MMapTargetData& operator=(MMapTargetData&&) = default; - #endif +#endif bool PosChanged(const Position& o, const Position& t) const { - return _posOwner.GetExactDistSq(&o) > 0.5f*0.5f || _posTarget.GetExactDistSq(&t) > 0.5f*0.5f; + return _posOwner.GetExactDistSq(&o) > 0.5f * 0.5f || _posTarget.GetExactDistSq(&t) > 0.5f * 0.5f; } uint32 _endTime; Position _posOwner; @@ -1340,7 +1341,7 @@ public: void UnitDeleted(); Unit* operator->() const { return ptr; } void operator=(Unit* u) { SetPointedTo(u); } - operator Unit*() const { return ptr; } + operator Unit* () const { return ptr; } private: Unit* ptr; Unit* defaultValue; @@ -1348,1228 +1349,1232 @@ private: class Unit : public WorldObject { - public: - typedef std::unordered_set AttackerSet; - typedef std::set ControlSet; +public: + typedef std::unordered_set AttackerSet; + typedef std::set ControlSet; - typedef std::multimap AuraMap; - typedef std::pair AuraMapBounds; - typedef std::pair AuraMapBoundsNonConst; + typedef std::multimap AuraMap; + typedef std::pair AuraMapBounds; + typedef std::pair AuraMapBoundsNonConst; - typedef std::multimap AuraApplicationMap; - typedef std::pair AuraApplicationMapBounds; - typedef std::pair AuraApplicationMapBoundsNonConst; + typedef std::multimap AuraApplicationMap; + typedef std::pair AuraApplicationMapBounds; + typedef std::pair AuraApplicationMapBoundsNonConst; - typedef std::multimap AuraStateAurasMap; - typedef std::pair AuraStateAurasMapBounds; + typedef std::multimap AuraStateAurasMap; + typedef std::pair AuraStateAurasMapBounds; - typedef std::list AuraEffectList; - typedef std::list AuraList; - typedef std::list AuraApplicationList; - typedef std::list Diminishing; - typedef std::unordered_set ComboPointHolderSet; + typedef std::list AuraEffectList; + typedef std::list AuraList; + typedef std::list AuraApplicationList; + typedef std::list Diminishing; + typedef std::unordered_set ComboPointHolderSet; - typedef std::map VisibleAuraMap; + typedef std::map VisibleAuraMap; - virtual ~Unit(); + virtual ~Unit(); - UnitAI* GetAI() { return i_AI; } - void SetAI(UnitAI* newAI) { i_AI = newAI; } + UnitAI* GetAI() { return i_AI; } + void SetAI(UnitAI* newAI) { i_AI = newAI; } - void AddToWorld() override; - void RemoveFromWorld() override; + void AddToWorld() override; + void RemoveFromWorld() override; - void CleanupBeforeRemoveFromMap(bool finalCleanup); - void CleanupsBeforeDelete(bool finalCleanup = true) override; // used in ~Creature/~Player (or before mass creature delete to remove cross-references to already deleted units) + void CleanupBeforeRemoveFromMap(bool finalCleanup); + void CleanupsBeforeDelete(bool finalCleanup = true) override; // used in ~Creature/~Player (or before mass creature delete to remove cross-references to already deleted units) - DiminishingLevels GetDiminishing(DiminishingGroup group); - void IncrDiminishing(DiminishingGroup group); - float ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, int32 limitduration); - void ApplyDiminishingAura(DiminishingGroup group, bool apply); - void ClearDiminishings() { m_Diminishing.clear(); } + DiminishingLevels GetDiminishing(DiminishingGroup group); + void IncrDiminishing(DiminishingGroup group); + float ApplyDiminishingToDuration(DiminishingGroup group, int32& duration, Unit* caster, DiminishingLevels Level, int32 limitduration); + void ApplyDiminishingAura(DiminishingGroup group, bool apply); + void ClearDiminishings() { m_Diminishing.clear(); } - // target dependent range checks - float GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const; - float GetSpellMinRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const; + // target dependent range checks + float GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const; + float GetSpellMinRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const; - virtual void Update(uint32 time) override; + virtual void Update(uint32 time) override; - void setAttackTimer(WeaponAttackType type, int32 time) { m_attackTimer[type] = time; } - void resetAttackTimer(WeaponAttackType type = BASE_ATTACK); - int32 getAttackTimer(WeaponAttackType type) const { return m_attackTimer[type]; } - bool isAttackReady(WeaponAttackType type = BASE_ATTACK) const { return m_attackTimer[type] <= 0; } - bool haveOffhandWeapon() const; - bool CanDualWield() const { return m_canDualWield; } - virtual void SetCanDualWield(bool value) { m_canDualWield = value; } - float GetCombatReach() const override { return m_floatValues[UNIT_FIELD_COMBATREACH]; } - float GetMeleeReach() const { float reach = m_floatValues[UNIT_FIELD_COMBATREACH]; return reach > MIN_MELEE_REACH ? reach : MIN_MELEE_REACH; } - bool IsWithinCombatRange(const Unit* obj, float dist2compare) const; - bool IsWithinMeleeRange(const Unit* obj, float dist = MELEE_RANGE) const; - bool GetRandomContactPoint(const Unit* target, float &x, float &y, float &z, bool force = false) const; - uint32 m_extraAttacks; - bool m_canDualWield; + void setAttackTimer(WeaponAttackType type, int32 time) { m_attackTimer[type] = time; } + void resetAttackTimer(WeaponAttackType type = BASE_ATTACK); + int32 getAttackTimer(WeaponAttackType type) const { return m_attackTimer[type]; } + bool isAttackReady(WeaponAttackType type = BASE_ATTACK) const { return m_attackTimer[type] <= 0; } + bool haveOffhandWeapon() const; + bool CanDualWield() const { return m_canDualWield; } + virtual void SetCanDualWield(bool value) { m_canDualWield = value; } + float GetCombatReach() const override { return m_floatValues[UNIT_FIELD_COMBATREACH]; } + float GetMeleeReach() const { float reach = m_floatValues[UNIT_FIELD_COMBATREACH]; return reach > MIN_MELEE_REACH ? reach : MIN_MELEE_REACH; } + bool IsWithinCombatRange(const Unit* obj, float dist2compare) const; + bool IsWithinMeleeRange(const Unit* obj, float dist = MELEE_RANGE) const; + bool GetRandomContactPoint(const Unit* target, float& x, float& y, float& z, bool force = false) const; + uint32 m_extraAttacks; + bool m_canDualWield; - void _addAttacker(Unit* pAttacker) // must be called only from Unit::Attack(Unit*) + void _addAttacker(Unit* pAttacker) // must be called only from Unit::Attack(Unit*) + { + m_attackers.insert(pAttacker); + } + void _removeAttacker(Unit* pAttacker) // must be called only from Unit::AttackStop() + { + m_attackers.erase(pAttacker); + } + Unit* getAttackerForHelper() const // If someone wants to help, who to give them + { + if (GetVictim() != nullptr) + return GetVictim(); + + if (!m_attackers.empty()) + return *(m_attackers.begin()); + + return nullptr; + } + bool Attack(Unit* victim, bool meleeAttack); + void CastStop(uint32 except_spellid = 0, bool withInstant = true); + bool AttackStop(); + void RemoveAllAttackers(); + AttackerSet const& getAttackers() const { return m_attackers; } + bool isAttackingPlayer() const; + Unit* GetVictim() const { return m_attacking; } + + void CombatStop(bool includingCast = false); + void CombatStopWithPets(bool includingCast = false); + void StopAttackFaction(uint32 faction_id); + Unit* SelectNearbyTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const; + Unit* SelectNearbyNoTotemTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const; + void SendMeleeAttackStop(Unit* victim = nullptr); + void SendMeleeAttackStart(Unit* victim, Player* sendTo = nullptr); + + void AddUnitState(uint32 f) { m_state |= f; } + bool HasUnitState(const uint32 f) const { return (m_state & f); } + void ClearUnitState(uint32 f) { m_state &= ~f; } + uint32 GetUnitState() const { return m_state; } + bool CanFreeMove() const + { + return !HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_FLEEING | UNIT_STATE_IN_FLIGHT | + UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_DISTRACTED) && GetOwnerGUID() == 0; + } + + uint32 HasUnitTypeMask(uint32 mask) const { return mask & m_unitTypeMask; } + void AddUnitTypeMask(uint32 mask) { m_unitTypeMask |= mask; } + uint32 GetUnitTypeMask() const { return m_unitTypeMask; } + bool IsSummon() const { return m_unitTypeMask & UNIT_MASK_SUMMON; } + bool IsGuardian() const { return m_unitTypeMask & UNIT_MASK_GUARDIAN; } + bool IsPet() const { return m_unitTypeMask & UNIT_MASK_PET; } + bool IsHunterPet() const { return m_unitTypeMask & UNIT_MASK_HUNTER_PET; } + bool IsTotem() const { return m_unitTypeMask & UNIT_MASK_TOTEM; } + bool IsVehicle() const { return m_unitTypeMask & UNIT_MASK_VEHICLE; } + + uint8 getLevel() const { return uint8(GetUInt32Value(UNIT_FIELD_LEVEL)); } + uint8 getLevelForTarget(WorldObject const* /*target*/) const override { return getLevel(); } + void SetLevel(uint8 lvl, bool showLevelChange = true); + uint8 getRace(bool original = false) const; + void setRace(uint8 race); + uint32 getRaceMask() const { return 1 << (getRace(true) - 1); } + uint8 getClass() const { return GetByteValue(UNIT_FIELD_BYTES_0, 1); } + uint32 getClassMask() const { return 1 << (getClass() - 1); } + uint8 getGender() const { return GetByteValue(UNIT_FIELD_BYTES_0, 2); } + + float GetStat(Stats stat) const { return float(GetUInt32Value(UNIT_FIELD_STAT0 + stat)); } + void SetStat(Stats stat, int32 val) { SetStatInt32Value(UNIT_FIELD_STAT0 + stat, val); } + uint32 GetArmor() const { return GetResistance(SPELL_SCHOOL_NORMAL); } + void SetArmor(int32 val) { SetResistance(SPELL_SCHOOL_NORMAL, val); } + + uint32 GetResistance(SpellSchools school) const { return GetUInt32Value(UNIT_FIELD_RESISTANCES + school); } + uint32 GetResistance(SpellSchoolMask mask) const; + void SetResistance(SpellSchools school, int32 val) { SetStatInt32Value(UNIT_FIELD_RESISTANCES + school, val); } + static float GetEffectiveResistChance(Unit const* owner, SpellSchoolMask schoolMask, Unit const* victim, SpellInfo const* spellInfo = nullptr); + + uint32 GetHealth() const { return GetUInt32Value(UNIT_FIELD_HEALTH); } + uint32 GetMaxHealth() const { return GetUInt32Value(UNIT_FIELD_MAXHEALTH); } + + bool IsFullHealth() const { return GetHealth() == GetMaxHealth(); } + bool HealthBelowPct(int32 pct) const { return GetHealth() < CountPctFromMaxHealth(pct); } + bool HealthBelowPctDamaged(int32 pct, uint32 damage) const { return int64(GetHealth()) - int64(damage) < int64(CountPctFromMaxHealth(pct)); } + bool HealthAbovePct(int32 pct) const { return GetHealth() > CountPctFromMaxHealth(pct); } + bool HealthAbovePctHealed(int32 pct, uint32 heal) const { return uint64(GetHealth()) + uint64(heal) > CountPctFromMaxHealth(pct); } + float GetHealthPct() const { return GetMaxHealth() ? 100.f * GetHealth() / GetMaxHealth() : 0.0f; } + uint32 CountPctFromMaxHealth(int32 pct) const { return CalculatePct(GetMaxHealth(), pct); } + uint32 CountPctFromCurHealth(int32 pct) const { return CalculatePct(GetHealth(), pct); } + float GetPowerPct(Powers power) const { return GetMaxPower(power) ? 100.f * GetPower(power) / GetMaxPower(power) : 0.0f; } + + void SetHealth(uint32 val); + void SetMaxHealth(uint32 val); + inline void SetFullHealth() { SetHealth(GetMaxHealth()); } + int32 ModifyHealth(int32 val); + int32 GetHealthGain(int32 dVal); + + Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, 3)); } + void setPowerType(Powers power); + uint32 GetPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_POWER1 + power); } + uint32 GetMaxPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_MAXPOWER1 + power); } + void SetPower(Powers power, uint32 val); + void SetMaxPower(Powers power, uint32 val); + // returns the change in power + int32 ModifyPower(Powers power, int32 val); + int32 ModifyPowerPct(Powers power, float pct, bool apply = true); + + uint32 GetAttackTime(WeaponAttackType att) const + { + float f_BaseAttackTime = GetFloatValue(UNIT_FIELD_BASEATTACKTIME + att) / m_modAttackSpeedPct[att]; + return (uint32)f_BaseAttackTime; + } + + void SetAttackTime(WeaponAttackType att, uint32 val) { SetFloatValue(UNIT_FIELD_BASEATTACKTIME + att, val * m_modAttackSpeedPct[att]); } + void ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply); + void ApplyCastTimePercentMod(float val, bool apply); + + SheathState GetSheath() const { return SheathState(GetByteValue(UNIT_FIELD_BYTES_2, 0)); } + virtual void SetSheath(SheathState sheathed) { SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); } + + // faction template id + uint32 getFaction() const { return GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE); } + void setFaction(uint32 faction); + FactionTemplateEntry const* GetFactionTemplateEntry() const; + + ReputationRank GetReactionTo(Unit const* target) const; + ReputationRank GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target) const; + + bool IsHostileTo(Unit const* unit) const; + bool IsHostileToPlayers() const; + bool IsFriendlyTo(Unit const* unit) const; + bool IsNeutralToAll() const; + bool IsInPartyWith(Unit const* unit) const; + bool IsInRaidWith(Unit const* unit) const; + void GetPartyMembers(std::list& units); + bool IsContestedGuard() const + { + if (FactionTemplateEntry const* entry = GetFactionTemplateEntry()) + return entry->IsContestedGuardFaction(); + + return false; + } + bool IsInSanctuary() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY); } + bool IsPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); } + bool IsFFAPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); } + void SetPvP(bool state) + { + if (state) + SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); + else + RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); + } + uint32 GetCreatureType() const; + uint32 GetCreatureTypeMask() const + { + uint32 creatureType = GetCreatureType(); + return (creatureType >= 1) ? (1 << (creatureType - 1)) : 0; + } + + uint8 getStandState() const { return GetByteValue(UNIT_FIELD_BYTES_1, 0); } + bool IsSitState() const; + bool IsStandState() const; + void SetStandState(uint8 state); + + void SetStandFlags(uint8 flags) { SetByteFlag(UNIT_FIELD_BYTES_1, 2, flags); } + void RemoveStandFlags(uint8 flags) { RemoveByteFlag(UNIT_FIELD_BYTES_1, 2, flags); } + + bool IsMounted() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT); } + uint32 GetMountID() const { return GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID); } + void Mount(uint32 mount, uint32 vehicleId = 0, uint32 creatureEntry = 0); + void Dismount(); + + uint16 GetMaxSkillValueForLevel(Unit const* target = nullptr) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } + static void DealDamageMods(Unit const* victim, uint32& damage, uint32* absorb); + static uint32 DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage const* cleanDamage = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = NULL, bool durabilityLoss = true, bool allowGM = false); + static void Kill(Unit* killer, Unit* victim, bool durabilityLoss = true, WeaponAttackType attackType = BASE_ATTACK, SpellInfo const* spellProto = nullptr); + static int32 DealHeal(Unit* healer, Unit* victim, uint32 addhealth); + + void ProcDamageAndSpell(Unit* victim, uint32 procAttacker, uint32 procVictim, uint32 procEx, uint32 amount, WeaponAttackType attType = BASE_ATTACK, SpellInfo const* procSpell = NULL, SpellInfo const* procAura = nullptr); + void ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellInfo const* procSpell, uint32 damage, SpellInfo const* procAura = nullptr); + + void GetProcAurasTriggeredOnEvent(std::list& aurasTriggeringProc, std::list* procAuras, ProcEventInfo eventInfo); + void TriggerAurasProcOnEvent(CalcDamageInfo& damageInfo); + void TriggerAurasProcOnEvent(std::list* myProcAuras, std::list* targetProcAuras, Unit* actionTarget, uint32 typeMaskActor, uint32 typeMaskActionTarget, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo); + void TriggerAurasProcOnEvent(ProcEventInfo& eventInfo, std::list& procAuras); + + void HandleEmoteCommand(uint32 anim_id); + void AttackerStateUpdate (Unit* victim, WeaponAttackType attType = BASE_ATTACK, bool extra = false); + + void CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* damageInfo, WeaponAttackType attackType = BASE_ATTACK); + void DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss); + void HandleProcExtraAttackFor(Unit* victim); + + void CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType = BASE_ATTACK, bool crit = false); + void DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss); + + // player or player's pet resilience (-1%) + float GetMeleeCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_MELEE); } + float GetRangedCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_RANGED); } + float GetSpellCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_SPELL); } + + // player or player's pet resilience (-1%) + uint32 GetMeleeCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.2f, 33.0f, damage); } + uint32 GetRangedCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_RANGED, 2.2f, 33.0f, damage); } + uint32 GetSpellCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_SPELL, 2.2f, 33.0f, damage); } + + // player or player's pet resilience (-1%), cap 100% + uint32 GetMeleeDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); } + uint32 GetRangedDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_RANGED, 2.0f, 100.0f, damage); } + uint32 GetSpellDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_SPELL, 2.0f, 100.0f, damage); } + + static void ApplyResilience(const Unit* victim, float* crit, int32* damage, bool isCrit, CombatRating type); + + float MeleeSpellMissChance(const Unit* victim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const; + SpellMissInfo MeleeSpellHitResult(Unit* victim, SpellInfo const* spell); + SpellMissInfo MagicSpellHitResult(Unit* victim, SpellInfo const* spell); + SpellMissInfo SpellHitResult(Unit* victim, SpellInfo const* spell, bool canReflect = false); + + float GetUnitDodgeChance() const; + float GetUnitParryChance() const; + float GetUnitBlockChance() const; + float GetUnitMissChance(WeaponAttackType attType) const; + float GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victim) const; + int32 GetMechanicResistChance(const SpellInfo* spell); + bool CanUseAttackType(uint8 attacktype) const + { + switch (attacktype) { - m_attackers.insert(pAttacker); + case BASE_ATTACK: + return !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED); + case OFF_ATTACK: + return !HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_DISARM_OFFHAND); + case RANGED_ATTACK: + return !HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_DISARM_RANGED); } - void _removeAttacker(Unit* pAttacker) // must be called only from Unit::AttackStop() + return true; + } + + virtual uint32 GetShieldBlockValue() const = 0; + uint32 GetShieldBlockValue(uint32 soft_cap, uint32 hard_cap) const + { + uint32 value = GetShieldBlockValue(); + if (value >= hard_cap) { - m_attackers.erase(pAttacker); + value = (soft_cap + hard_cap) / 2; } - Unit* getAttackerForHelper() const // If someone wants to help, who to give them + else if (value > soft_cap) { - if (GetVictim() != nullptr) - return GetVictim(); - - if (!m_attackers.empty()) - return *(m_attackers.begin()); - - return nullptr; - } - bool Attack(Unit* victim, bool meleeAttack); - void CastStop(uint32 except_spellid = 0, bool withInstant = true); - bool AttackStop(); - void RemoveAllAttackers(); - AttackerSet const& getAttackers() const { return m_attackers; } - bool isAttackingPlayer() const; - Unit* GetVictim() const { return m_attacking; } - - void CombatStop(bool includingCast = false); - void CombatStopWithPets(bool includingCast = false); - void StopAttackFaction(uint32 faction_id); - Unit* SelectNearbyTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const; - Unit* SelectNearbyNoTotemTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const; - void SendMeleeAttackStop(Unit* victim = nullptr); - void SendMeleeAttackStart(Unit* victim, Player* sendTo = nullptr); - - void AddUnitState(uint32 f) { m_state |= f; } - bool HasUnitState(const uint32 f) const { return (m_state & f); } - void ClearUnitState(uint32 f) { m_state &= ~f; } - uint32 GetUnitState() const { return m_state; } - bool CanFreeMove() const - { - return !HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_FLEEING | UNIT_STATE_IN_FLIGHT | - UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_DISTRACTED) && GetOwnerGUID() == 0; + value = soft_cap + ((value - soft_cap) / 2); } - uint32 HasUnitTypeMask(uint32 mask) const { return mask & m_unitTypeMask; } - void AddUnitTypeMask(uint32 mask) { m_unitTypeMask |= mask; } - uint32 GetUnitTypeMask() const { return m_unitTypeMask; } - bool IsSummon() const { return m_unitTypeMask & UNIT_MASK_SUMMON; } - bool IsGuardian() const { return m_unitTypeMask & UNIT_MASK_GUARDIAN; } - bool IsPet() const { return m_unitTypeMask & UNIT_MASK_PET; } - bool IsHunterPet() const{ return m_unitTypeMask & UNIT_MASK_HUNTER_PET; } - bool IsTotem() const { return m_unitTypeMask & UNIT_MASK_TOTEM; } - bool IsVehicle() const { return m_unitTypeMask & UNIT_MASK_VEHICLE; } + return value; + } + uint32 GetUnitMeleeSkill(Unit const* target = nullptr) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } + uint32 GetDefenseSkillValue(Unit const* target = nullptr) const; + uint32 GetWeaponSkillValue(WeaponAttackType attType, Unit const* target = nullptr) const; + float GetWeaponProcChance() const; + float GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const; - uint8 getLevel() const { return uint8(GetUInt32Value(UNIT_FIELD_LEVEL)); } - uint8 getLevelForTarget(WorldObject const* /*target*/) const override { return getLevel(); } - void SetLevel(uint8 lvl, bool showLevelChange = true); - uint8 getRace(bool original = false) const; - void setRace(uint8 race); - uint32 getRaceMask() const { return 1 << (getRace(true)-1); } - uint8 getClass() const { return GetByteValue(UNIT_FIELD_BYTES_0, 1); } - uint32 getClassMask() const { return 1 << (getClass()-1); } - uint8 getGender() const { return GetByteValue(UNIT_FIELD_BYTES_0, 2); } + MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType) const; + MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const; - float GetStat(Stats stat) const { return float(GetUInt32Value(UNIT_FIELD_STAT0+stat)); } - void SetStat(Stats stat, int32 val) { SetStatInt32Value(UNIT_FIELD_STAT0+stat, val); } - uint32 GetArmor() const { return GetResistance(SPELL_SCHOOL_NORMAL); } - void SetArmor(int32 val) { SetResistance(SPELL_SCHOOL_NORMAL, val); } + bool IsVendor() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_VENDOR); } + bool IsTrainer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TRAINER); } + bool IsQuestGiver() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); } + bool IsGossip() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); } + bool IsTaxi() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_FLIGHTMASTER); } + bool IsGuildMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PETITIONER); } + bool IsBattleMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BATTLEMASTER); } + bool IsBanker() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BANKER); } + bool IsInnkeeper() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_INNKEEPER); } + bool IsSpiritHealer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER); } + bool IsSpiritGuide() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITGUIDE); } + bool IsTabardDesigner()const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TABARDDESIGNER); } + bool IsAuctioner() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_AUCTIONEER); } + bool IsArmorer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_REPAIR); } + bool IsServiceProvider() const + { + return HasFlag(UNIT_NPC_FLAGS, + UNIT_NPC_FLAG_VENDOR | UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_FLIGHTMASTER | + UNIT_NPC_FLAG_PETITIONER | UNIT_NPC_FLAG_BATTLEMASTER | UNIT_NPC_FLAG_BANKER | + UNIT_NPC_FLAG_INNKEEPER | UNIT_NPC_FLAG_SPIRITHEALER | + UNIT_NPC_FLAG_SPIRITGUIDE | UNIT_NPC_FLAG_TABARDDESIGNER | UNIT_NPC_FLAG_AUCTIONEER); + } + bool IsSpiritService() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER | UNIT_NPC_FLAG_SPIRITGUIDE); } + bool IsCritter() const { return GetCreatureType() == CREATURE_TYPE_CRITTER; } - uint32 GetResistance(SpellSchools school) const { return GetUInt32Value(UNIT_FIELD_RESISTANCES+school); } - uint32 GetResistance(SpellSchoolMask mask) const; - void SetResistance(SpellSchools school, int32 val) { SetStatInt32Value(UNIT_FIELD_RESISTANCES+school, val); } - static float GetEffectiveResistChance(Unit const* owner, SpellSchoolMask schoolMask, Unit const* victim, SpellInfo const* spellInfo = nullptr); + bool IsInFlight() const { return HasUnitState(UNIT_STATE_IN_FLIGHT); } - uint32 GetHealth() const { return GetUInt32Value(UNIT_FIELD_HEALTH); } - uint32 GetMaxHealth() const { return GetUInt32Value(UNIT_FIELD_MAXHEALTH); } + bool IsInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); } + bool IsInCombatWith(Unit const* who) const; - bool IsFullHealth() const { return GetHealth() == GetMaxHealth(); } - bool HealthBelowPct(int32 pct) const { return GetHealth() < CountPctFromMaxHealth(pct); } - bool HealthBelowPctDamaged(int32 pct, uint32 damage) const { return int64(GetHealth()) - int64(damage) < int64(CountPctFromMaxHealth(pct)); } - bool HealthAbovePct(int32 pct) const { return GetHealth() > CountPctFromMaxHealth(pct); } - bool HealthAbovePctHealed(int32 pct, uint32 heal) const { return uint64(GetHealth()) + uint64(heal) > CountPctFromMaxHealth(pct); } - float GetHealthPct() const { return GetMaxHealth() ? 100.f * GetHealth() / GetMaxHealth() : 0.0f; } - uint32 CountPctFromMaxHealth(int32 pct) const { return CalculatePct(GetMaxHealth(), pct); } - uint32 CountPctFromCurHealth(int32 pct) const { return CalculatePct(GetHealth(), pct); } - float GetPowerPct(Powers power) const { return GetMaxPower(power) ? 100.f * GetPower(power) / GetMaxPower(power) : 0.0f; } + bool IsPetInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); } + void CombatStart(Unit* target, bool initialAggro = true); + void CombatStartOnCast(Unit* target, bool initialAggro = true, uint32 duration = 0); + void SetInCombatState(bool PvP, Unit* enemy = NULL, uint32 duration = 0); + void SetInCombatWith(Unit* enemy, uint32 duration = 0); + void ClearInCombat(); + void ClearInPetCombat(); + uint32 GetCombatTimer() const { return m_CombatTimer; } - void SetHealth(uint32 val); - void SetMaxHealth(uint32 val); - inline void SetFullHealth() { SetHealth(GetMaxHealth()); } - int32 ModifyHealth(int32 val); - int32 GetHealthGain(int32 dVal); + bool HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const; + bool virtual HasSpell(uint32 /*spellID*/) const { return false; } + bool HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura = 0) const; + bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = nullptr) const; - Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, 3)); } - void setPowerType(Powers power); - uint32 GetPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_POWER1 +power); } - uint32 GetMaxPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_MAXPOWER1+power); } - void SetPower(Powers power, uint32 val); - void SetMaxPower(Powers power, uint32 val); - // returns the change in power - int32 ModifyPower(Powers power, int32 val); - int32 ModifyPowerPct(Powers power, float pct, bool apply = true); + bool HasStealthAura() const { return HasAuraType(SPELL_AURA_MOD_STEALTH); } + bool HasInvisibilityAura() const { return HasAuraType(SPELL_AURA_MOD_INVISIBILITY); } + bool isFeared() const { return HasAuraType(SPELL_AURA_MOD_FEAR); } + bool isInRoots() const { return HasAuraType(SPELL_AURA_MOD_ROOT); } + bool IsPolymorphed() const; - uint32 GetAttackTime(WeaponAttackType att) const - { - float f_BaseAttackTime = GetFloatValue(UNIT_FIELD_BASEATTACKTIME+att) / m_modAttackSpeedPct[att]; - return (uint32)f_BaseAttackTime; - } + bool isFrozen() const; - void SetAttackTime(WeaponAttackType att, uint32 val) { SetFloatValue(UNIT_FIELD_BASEATTACKTIME+att, val*m_modAttackSpeedPct[att]); } - void ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply); - void ApplyCastTimePercentMod(float val, bool apply); + bool isTargetableForAttack(bool checkFakeDeath = true, Unit const* byWho = nullptr) const; - SheathState GetSheath() const { return SheathState(GetByteValue(UNIT_FIELD_BYTES_2, 0)); } - virtual void SetSheath(SheathState sheathed) { SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); } + bool IsValidAttackTarget(Unit const* target) const; + bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = nullptr) const; - // faction template id - uint32 getFaction() const { return GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE); } - void setFaction(uint32 faction); - FactionTemplateEntry const* GetFactionTemplateEntry() const; + bool IsValidAssistTarget(Unit const* target) const; + bool _IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const; - ReputationRank GetReactionTo(Unit const* target) const; - ReputationRank GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target) const; + void UpdateEnvironmentIfNeeded(const uint8 option); + virtual bool IsInWater(bool allowAbove = false) const; + virtual bool IsUnderWater() const; + virtual void UpdateUnderwaterState(Map* m, float x, float y, float z); + bool isInAccessiblePlaceFor(Creature const* c) const; - bool IsHostileTo(Unit const* unit) const; - bool IsHostileToPlayers() const; - bool IsFriendlyTo(Unit const* unit) const; - bool IsNeutralToAll() const; - bool IsInPartyWith(Unit const* unit) const; - bool IsInRaidWith(Unit const* unit) const; - void GetPartyMembers(std::list &units); - bool IsContestedGuard() const - { - if (FactionTemplateEntry const* entry = GetFactionTemplateEntry()) - return entry->IsContestedGuardFaction(); + void SendHealSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical = false); + int32 HealBySpell(Unit* victim, SpellInfo const* spellInfo, uint32 addHealth, bool critical = false); + void SendEnergizeSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, Powers powertype); + void EnergizeBySpell(Unit* victim, uint32 SpellID, uint32 Damage, Powers powertype); + void CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastSpell(Unit* victim, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastSpell(Unit* victim, uint32 spellId, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastSpell(Unit* victim, SpellInfo const* spellInfo, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastSpell(Unit* victim, SpellInfo const* spellInfo, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastSpell(GameObject* go, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastCustomSpell(Unit* victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim = NULL, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + void CastCustomSpell(uint32 spellId, CustomSpellValues const& value, Unit* victim = NULL, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); + Aura* AddAura(uint32 spellId, Unit* target); + Aura* AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target); + void SetAuraStack(uint32 spellId, Unit* target, uint32 stack); + void SendPlaySpellVisual(uint32 id); + void SendPlaySpellImpact(uint64 guid, uint32 id); + void BuildCooldownPacket(WorldPacket& data, uint8 flags, uint32 spellId, uint32 cooldown); + void BuildCooldownPacket(WorldPacket& data, uint8 flags, PacketCooldowns const& cooldowns); + + void DeMorph(); + + void SendAttackStateUpdate(CalcDamageInfo* damageInfo); + void SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount); + void SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log); + void SendSpellNonMeleeReflectLog(SpellNonMeleeDamage* log, Unit* attacker); + void SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit = false); + void SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo); + void SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo); + void SendSpellDamageResist(Unit* target, uint32 spellId); + void SendSpellDamageImmune(Unit* target, uint32 spellId); + + void NearTeleportTo(float x, float y, float z, float orientation, bool casting = false, bool vehicleTeleport = false, bool withPet = false, bool removeTransport = false); + void SendTameFailure(uint8 result); + void SendTeleportPacket(Position& pos); + virtual bool UpdatePosition(float x, float y, float z, float ang, bool teleport = false); + // returns true if unit's position really changed + bool UpdatePosition(const Position& pos, bool teleport = false) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } + void UpdateOrientation(float orientation); + void UpdateHeight(float newZ); + + void KnockbackFrom(float x, float y, float speedXY, float speedZ); + void JumpTo(float speedXY, float speedZ, bool forward = true); + void JumpTo(WorldObject* obj, float speedZ); + + void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 TransitTime, SplineFlags sf = SPLINEFLAG_WALK_MODE); // pussywizard: need to just send packet, with no shitty movement/spline + void MonsterMoveWithSpeed(float x, float y, float z, float speed); + //void SetFacing(float ori, WorldObject* obj = nullptr); + //void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player = nullptr); + void SendMovementFlagUpdate(bool self = false); + + bool IsLevitating() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY); } + bool IsWalking() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_WALKING); } + virtual bool SetWalk(bool enable); + virtual bool SetDisableGravity(bool disable, bool packetOnly = false); + virtual bool SetSwim(bool enable); + virtual bool SetCanFly(bool enable, bool packetOnly = false); + virtual bool SetWaterWalking(bool enable, bool packetOnly = false); + virtual bool SetFeatherFall(bool enable, bool packetOnly = false); + virtual bool SetHover(bool enable, bool packetOnly = false); + + // pussywizard: + void SendMovementWaterWalking(Player* sendTo); + void SendMovementFeatherFall(Player* sendTo); + void SendMovementHover(Player* sendTo); + + void SetInFront(WorldObject const* target); + void SetFacingTo(float ori); + void SetFacingToObject(WorldObject* object); + + void SendChangeCurrentVictimOpcode(HostileReference* pHostileReference); + void SendClearThreatListOpcode(); + void SendRemoveFromThreatListOpcode(HostileReference* pHostileReference); + void SendThreatListUpdate(); + + void SendClearTarget(); + + void BuildHeartBeatMsg(WorldPacket* data) const; + + bool IsAlive() const { return (m_deathState == ALIVE); }; + bool isDying() const { return (m_deathState == JUST_DIED); }; + bool isDead() const { return (m_deathState == DEAD || m_deathState == CORPSE); }; + DeathState getDeathState() { return m_deathState; }; + virtual void setDeathState(DeathState s, bool despawn = false); // overwrited in Creature/Player/Pet + + uint64 GetOwnerGUID() const { return GetUInt64Value(UNIT_FIELD_SUMMONEDBY); } + void SetOwnerGUID(uint64 owner); + uint64 GetCreatorGUID() const { return GetUInt64Value(UNIT_FIELD_CREATEDBY); } + void SetCreatorGUID(uint64 creator) { SetUInt64Value(UNIT_FIELD_CREATEDBY, creator); } + uint64 GetMinionGUID() const { return GetUInt64Value(UNIT_FIELD_SUMMON); } + void SetMinionGUID(uint64 guid) { SetUInt64Value(UNIT_FIELD_SUMMON, guid); } + uint64 GetCharmerGUID() const { return GetUInt64Value(UNIT_FIELD_CHARMEDBY); } + void SetCharmerGUID(uint64 owner) { SetUInt64Value(UNIT_FIELD_CHARMEDBY, owner); } + uint64 GetCharmGUID() const { return GetUInt64Value(UNIT_FIELD_CHARM); } + void SetPetGUID(uint64 guid) { m_SummonSlot[SUMMON_SLOT_PET] = guid; } + uint64 GetPetGUID() const { return m_SummonSlot[SUMMON_SLOT_PET]; } + void SetCritterGUID(uint64 guid) { SetUInt64Value(UNIT_FIELD_CRITTER, guid); } + uint64 GetCritterGUID() const { return GetUInt64Value(UNIT_FIELD_CRITTER); } + + bool IsControlledByPlayer() const { return m_ControlledByPlayer; } + bool IsCreatedByPlayer() const { return m_CreatedByPlayer; } + uint64 GetCharmerOrOwnerGUID() const { return GetCharmerGUID() ? GetCharmerGUID() : GetOwnerGUID(); } + uint64 GetCharmerOrOwnerOrOwnGUID() const + { + if (uint64 guid = GetCharmerOrOwnerGUID()) + return guid; + return GetGUID(); + } + bool IsCharmedOwnedByPlayerOrPlayer() const { return IS_PLAYER_GUID(GetCharmerOrOwnerOrOwnGUID()); } + + Player* GetSpellModOwner() const; + + Unit* GetOwner() const; + Guardian* GetGuardianPet() const; + Minion* GetFirstMinion() const; + Unit* GetCharmer() const; + Unit* GetCharm() const; + Unit* GetCharmerOrOwner() const { return GetCharmerGUID() ? GetCharmer() : GetOwner(); } + Unit* GetCharmerOrOwnerOrSelf() const + { + if (Unit* u = GetCharmerOrOwner()) + return u; + + return (Unit*)this; + } + Player* GetCharmerOrOwnerPlayerOrPlayerItself() const; + Player* GetAffectingPlayer() const; + + void SetMinion(Minion* minion, bool apply); + void GetAllMinionsByEntry(std::list& Minions, uint32 entry); + void RemoveAllMinionsByEntry(uint32 entry); + void SetCharm(Unit* target, bool apply); + Unit* GetNextRandomRaidMemberOrPet(float radius); + bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = nullptr); + void RemoveCharmedBy(Unit* charmer); + void RestoreFaction(); + + ControlSet m_Controlled; + Unit* GetFirstControlled() const; + void RemoveAllControlled(); + + bool IsCharmed() const { return GetCharmerGUID() != 0; } + bool isPossessed() const { return HasUnitState(UNIT_STATE_POSSESSED); } + bool isPossessedByPlayer() const { return HasUnitState(UNIT_STATE_POSSESSED) && IS_PLAYER_GUID(GetCharmerGUID()); } + bool isPossessing() const + { + if (Unit* u = GetCharm()) + return u->isPossessed(); + else return false; - } - bool IsInSanctuary() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY); } - bool IsPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); } - bool IsFFAPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); } - void SetPvP(bool state) + } + bool isPossessing(Unit* u) const { return u->isPossessed() && GetCharmGUID() == u->GetGUID(); } + + CharmInfo* GetCharmInfo() { return m_charmInfo; } + CharmInfo* InitCharmInfo(); + void DeleteCharmInfo(); + void UpdateCharmAI(); + //Player* GetMoverSource() const; + SafeUnitPointer m_movedByPlayer; + SharedVisionList const& GetSharedVisionList() { return m_sharedVision; } + void AddPlayerToVision(Player* player); + void RemovePlayerFromVision(Player* player); + bool HasSharedVision() const { return !m_sharedVision.empty(); } + void RemoveBindSightAuras(); + void RemoveCharmAuras(); + + Pet* CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id = 0); + Pet* CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id = 0); + bool InitTamedPet(Pet* pet, uint8 level, uint32 spell_id); + + // aura apply/remove helpers - you should better not use these + Aura* _TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0, bool periodicReset = false); + void _AddAura(UnitAura* aura, Unit* caster); + AuraApplication* _CreateAuraApplication(Aura* aura, uint8 effMask); + void _ApplyAuraEffect(Aura* aura, uint8 effIndex); + void _ApplyAura(AuraApplication* aurApp, uint8 effMask); + void _UnapplyAura(AuraApplicationMap::iterator& i, AuraRemoveMode removeMode); + void _UnapplyAura(AuraApplication* aurApp, AuraRemoveMode removeMode); + void _RemoveNoStackAuraApplicationsDueToAura(Aura* aura); + void _RemoveNoStackAurasDueToAura(Aura* aura); + bool _IsNoStackAuraDueToAura(Aura* appliedAura, Aura* existingAura) const; + void _RegisterAuraEffect(AuraEffect* aurEff, bool apply); + + // m_ownedAuras container management + AuraMap& GetOwnedAuras() { return m_ownedAuras; } + AuraMap const& GetOwnedAuras() const { return m_ownedAuras; } + + void RemoveOwnedAura(AuraMap::iterator& i, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + void RemoveOwnedAura(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + void RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + + Aura* GetOwnedAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, Aura* except = nullptr) const; + + // m_appliedAuras container management + AuraApplicationMap& GetAppliedAuras() { return m_appliedAuras; } + AuraApplicationMap const& GetAppliedAuras() const { return m_appliedAuras; } + + void RemoveAura(AuraApplicationMap::iterator& i, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); + void RemoveAura(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + void RemoveAura(AuraApplication* aurApp, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); + void RemoveAura(Aura* aur, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); + + void RemoveAurasDueToSpell(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + void RemoveAuraFromStack(uint32 spellId, uint64 casterGUID = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + void RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, uint64 casterGUID, Unit* dispeller, uint8 chargesRemoved = 1); + void RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit* stealer); + void RemoveAurasDueToItemSpell(uint32 spellId, uint64 castItemGuid); + void RemoveAurasByType(AuraType auraType, uint64 casterGUID = 0, Aura* except = NULL, bool negative = true, bool positive = true); + void RemoveNotOwnSingleTargetAuras(); + void RemoveAurasWithInterruptFlags(uint32 flag, uint32 except = 0); + void RemoveAurasWithAttribute(uint32 flags); + void RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID); + void RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode = AURA_REMOVE_BY_DEFAULT, uint32 except = 0); + void RemoveMovementImpairingAuras(bool withRoot); + void RemoveAurasByShapeShift(); + + void RemoveAreaAurasDueToLeaveWorld(); + void RemoveAllAuras(); + void RemoveArenaAuras(); + void RemoveAllAurasOnDeath(); + void RemoveAllAurasRequiringDeadTarget(); + void RemoveAllAurasExceptType(AuraType type); + //void RemoveAllAurasExceptType(AuraType type1, AuraType type2); // pussywizard: replaced with RemoveEvadeAuras() + void RemoveEvadeAuras(); + void DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime); + + void _RemoveAllAuraStatMods(); + void _ApplyAllAuraStatMods(); + + AuraEffectList const& GetAuraEffectsByType(AuraType type) const { return m_modAuras[type]; } + AuraList& GetSingleCastAuras() { return m_scAuras; } + AuraList const& GetSingleCastAuras() const { return m_scAuras; } + + AuraEffect* GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 casterGUID = 0) const; + AuraEffect* GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 casterGUID = 0) const; + AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const; // spell mustn't have familyflags + AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID = 0) const; + AuraEffect* GetAuraEffectDummy(uint32 spellid) const; + inline AuraEffect* GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const { return GetAuraEffect(SPELL_AURA_DUMMY, name, iconId, effIndex);} + + AuraApplication* GetAuraApplication(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, AuraApplication* except = nullptr) const; + Aura* GetAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const; + + AuraApplication* GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, AuraApplication* except = nullptr) const; + Aura* GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const; + + void GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList); + + bool HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster = 0) const; + uint32 GetAuraCount(uint32 spellId) const; + bool HasAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const; + bool HasAuraType(AuraType auraType) const; + bool HasAuraTypeWithCaster(AuraType auratype, uint64 caster) const; + bool HasAuraTypeWithMiscvalue(AuraType auratype, int32 miscvalue) const; + bool HasAuraTypeWithAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; + bool HasAuraTypeWithValue(AuraType auratype, int32 value) const; + bool HasNegativeAuraWithInterruptFlag(uint32 flag, uint64 guid = 0); + bool HasVisibleAuraType(AuraType auraType) const; + bool HasNegativeAuraWithAttribute(uint32 flag, uint64 guid = 0); + bool HasAuraWithMechanic(uint32 mechanicMask) const; + + AuraEffect* IsScriptOverriden(SpellInfo const* spell, int32 script) const; + uint32 GetDiseasesByCaster(uint64 casterGUID, uint8 mode = 0); + uint32 GetDoTsByCaster(uint64 casterGUID) const; + + int32 GetTotalAuraModifierAreaExclusive(AuraType auratype) const; + int32 GetTotalAuraModifier(AuraType auratype) const; + float GetTotalAuraMultiplier(AuraType auratype) const; + int32 GetMaxPositiveAuraModifier(AuraType auratype); + int32 GetMaxNegativeAuraModifier(AuraType auratype) const; + + int32 GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const; + float GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const; + int32 GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask, const AuraEffect* except = nullptr) const; + int32 GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const; + + int32 GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const; + float GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const; + int32 GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const; + int32 GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const; + + int32 GetTotalAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; + float GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; + int32 GetMaxPositiveAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; + int32 GetMaxNegativeAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; + + float GetResistanceBuffMods(SpellSchools school, bool positive) const { return GetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + school); } + void SetResistanceBuffMods(SpellSchools school, bool positive, float val) { SetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + school, val); } + void ApplyResistanceBuffModsMod(SpellSchools school, bool positive, float val, bool apply) { ApplyModSignedFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + school, val, apply); } + void ApplyResistanceBuffModsPercentMod(SpellSchools school, bool positive, float val, bool apply) { ApplyPercentModFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + school, val, apply); } + void InitStatBuffMods() + { + for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_POSSTAT0 + i, 0); + for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_NEGSTAT0 + i, 0); + } + void ApplyStatBuffMod(Stats stat, float val, bool apply) { ApplyModSignedFloatValue((val > 0 ? UNIT_FIELD_POSSTAT0 + stat : UNIT_FIELD_NEGSTAT0 + stat), val, apply); } + void ApplyStatPercentBuffMod(Stats stat, float val, bool apply); + + void SetCreateStat(Stats stat, float val) { m_createStats[stat] = val; } + void SetCreateHealth(uint32 val) { SetUInt32Value(UNIT_FIELD_BASE_HEALTH, val); } + uint32 GetCreateHealth() const { return GetUInt32Value(UNIT_FIELD_BASE_HEALTH); } + void SetCreateMana(uint32 val) { SetUInt32Value(UNIT_FIELD_BASE_MANA, val); } + uint32 GetCreateMana() const { return GetUInt32Value(UNIT_FIELD_BASE_MANA); } + uint32 GetCreatePowers(Powers power) const; + float GetPosStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_POSSTAT0 + stat); } + float GetNegStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_NEGSTAT0 + stat); } + float GetCreateStat(Stats stat) const { return m_createStats[stat]; } + + void SetCurrentCastedSpell(Spell* pSpell); + virtual void ProhibitSpellSchool(SpellSchoolMask /*idSchoolMask*/, uint32 /*unTimeMs*/) { } + void InterruptSpell(CurrentSpellTypes spellType, bool withDelayed = true, bool withInstant = true, bool bySelf = false); + void FinishSpell(CurrentSpellTypes spellType, bool ok = true); + + // set withDelayed to true to account delayed spells as casted + // delayed+channeled spells are always accounted as casted + // we can skip channeled or delayed checks using flags + bool IsNonMeleeSpellCast(bool withDelayed, bool skipChanneled = false, bool skipAutorepeat = false, bool isAutoshoot = false, bool skipInstant = true) const; + + // set withDelayed to true to interrupt delayed spells too + // delayed+channeled spells are always interrupted + void InterruptNonMeleeSpells(bool withDelayed, uint32 spellid = 0, bool withInstant = true, bool bySelf = false); + + // Check if our current channel spell has attribute SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING + bool CanMoveDuringChannel() const; + + Spell* GetCurrentSpell(CurrentSpellTypes spellType) const { return m_currentSpells[spellType]; } + Spell* GetCurrentSpell(uint32 spellType) const { return m_currentSpells[spellType]; } + Spell* FindCurrentSpellBySpellId(uint32 spell_id) const; + int32 GetCurrentSpellCastTime(uint32 spell_id) const; + + uint64 m_SummonSlot[MAX_SUMMON_SLOT]; + uint64 m_ObjectSlot[MAX_GAMEOBJECT_SLOT]; + + ShapeshiftForm GetShapeshiftForm() const { return ShapeshiftForm(GetByteValue(UNIT_FIELD_BYTES_2, 3)); } + void SetShapeshiftForm(ShapeshiftForm form) + { + SetByteValue(UNIT_FIELD_BYTES_2, 3, form); + } + + inline bool IsInFeralForm() const + { + ShapeshiftForm form = GetShapeshiftForm(); + return form == FORM_CAT || form == FORM_BEAR || form == FORM_DIREBEAR || form == FORM_GHOSTWOLF; // Xinef: added shamans Ghost Wolf, should behave exactly like druid forms + } + + inline bool IsInDisallowedMountForm() const + { + ShapeshiftForm form = GetShapeshiftForm(); + return form != FORM_NONE && form != FORM_BATTLESTANCE && form != FORM_BERSERKERSTANCE && form != FORM_DEFENSIVESTANCE && + form != FORM_SHADOW && form != FORM_STEALTH && form != FORM_UNDEAD; + } + + float m_modMeleeHitChance; + float m_modRangedHitChance; + float m_modSpellHitChance; + int32 m_baseSpellCritChance; + + float m_threatModifier[MAX_SPELL_SCHOOL]; + float m_modAttackSpeedPct[3]; + + // Event handler + EventProcessor m_Events; + + // stat system + bool HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply); + void SetModifierValue(UnitMods unitMod, UnitModifierType modifierType, float value) { m_auraModifiersGroup[unitMod][modifierType] = value; } + float GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const; + float GetTotalStatValue(Stats stat, float additionalValue = 0.0f) const; + float GetTotalAuraModValue(UnitMods unitMod) const; + SpellSchools GetSpellSchoolByAuraGroup(UnitMods unitMod) const; + Stats GetStatByAuraGroup(UnitMods unitMod) const; + Powers GetPowerTypeByAuraGroup(UnitMods unitMod) const; + bool CanModifyStats() const { return m_canModifyStats; } + void SetCanModifyStats(bool modifyStats) { m_canModifyStats = modifyStats; } + virtual bool UpdateStats(Stats stat) = 0; + virtual bool UpdateAllStats() = 0; + virtual void UpdateResistances(uint32 school) = 0; + virtual void UpdateAllResistances(); + virtual void UpdateArmor() = 0; + virtual void UpdateMaxHealth() = 0; + virtual void UpdateMaxPower(Powers power) = 0; + virtual void UpdateAttackPowerAndDamage(bool ranged = false) = 0; + virtual void UpdateDamagePhysical(WeaponAttackType attType); + float GetTotalAttackPowerValue(WeaponAttackType attType, Unit* pVictim = nullptr) const; + float GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange type) const; + void SetBaseWeaponDamage(WeaponAttackType attType, WeaponDamageRange damageRange, float value) { m_weaponDamage[attType][damageRange] = value; } + virtual void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) = 0; + uint32 CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct); + float GetAPMultiplier(WeaponAttackType attType, bool normalized); + + bool isInFrontInMap(Unit const* target, float distance, float arc = M_PI) const; + bool isInBackInMap(Unit const* target, float distance, float arc = M_PI) const; + + // Visibility system + bool IsVisible() const { return (m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GM) > SEC_PLAYER) ? false : true; } + void SetVisible(bool x); + void SetModelVisible(bool on); + + // common function for visibility checks for player/creatures with detection code + uint32 GetPhaseByAuras() const; + void SetPhaseMask(uint32 newPhaseMask, bool update) override;// overwrite WorldObject::SetPhaseMask + void UpdateObjectVisibility(bool forced = true, bool fromUpdate = false) override; + + SpellImmuneList m_spellImmune[MAX_SPELL_IMMUNITY]; + uint32 m_lastSanctuaryTime; + + // Threat related methods + bool CanHaveThreatList() const; + void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); + float ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL); + void DeleteThreatList(); + void TauntApply(Unit* victim); + void TauntFadeOut(Unit* taunter); + ThreatManager& getThreatManager() { return m_ThreatManager; } + void addHatedBy(HostileReference* pHostileReference) { m_HostileRefManager.insertFirst(pHostileReference); }; + void removeHatedBy(HostileReference* /*pHostileReference*/) { /* nothing to do yet */ } + HostileRefManager& getHostileRefManager() { return m_HostileRefManager; } + + VisibleAuraMap const* GetVisibleAuras() { return &m_visibleAuras; } + AuraApplication* GetVisibleAura(uint8 slot) + { + VisibleAuraMap::iterator itr = m_visibleAuras.find(slot); + if (itr != m_visibleAuras.end()) + return itr->second; + return 0; + } + void SetVisibleAura(uint8 slot, AuraApplication* aur) { m_visibleAuras[slot] = aur; UpdateAuraForGroup(slot);} + void RemoveVisibleAura(uint8 slot) { m_visibleAuras.erase(slot); UpdateAuraForGroup(slot);} + + uint32 GetInterruptMask() const { return m_interruptMask; } + void AddInterruptMask(uint32 mask) { m_interruptMask |= mask; } + void UpdateInterruptMask(); + + uint32 GetDisplayId() { return GetUInt32Value(UNIT_FIELD_DISPLAYID); } + virtual void SetDisplayId(uint32 modelId); + uint32 GetNativeDisplayId() { return GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID); } + void RestoreDisplayId(); + void SetNativeDisplayId(uint32 modelId) { SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, modelId); } + void setTransForm(uint32 spellid) { m_transform = spellid;} + uint32 getTransForm() const { return m_transform;} + + // DynamicObject management + void _RegisterDynObject(DynamicObject* dynObj); + void _UnregisterDynObject(DynamicObject* dynObj); + DynamicObject* GetDynObject(uint32 spellId); + void RemoveDynObject(uint32 spellId); + void RemoveAllDynObjects(); + + GameObject* GetGameObject(uint32 spellId) const; + void AddGameObject(GameObject* gameObj); + void RemoveGameObject(GameObject* gameObj, bool del); + void RemoveGameObject(uint32 spellid, bool del); + void RemoveAllGameObjects(); + + void ModifyAuraState(AuraStateType flag, bool apply); + uint32 BuildAuraStateUpdateForTarget(Unit* target) const; + bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = NULL, Unit const* Caster = nullptr) const; + void UnsummonAllTotems(); + Unit* GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo); + Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = nullptr); + + int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask); + int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask, bool isDoT = false); + float SpellPctDamageModsDone(Unit* victim, SpellInfo const* spellProto, DamageEffectType damagetype); + uint32 SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, float TotalMod = 0.0f, uint32 stack = 1); + uint32 SpellDamageBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1); + int32 SpellBaseHealingBonusDone(SpellSchoolMask schoolMask); + int32 SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask); + float SpellPctHealingModsDone(Unit* victim, SpellInfo const* spellProto, DamageEffectType damagetype); + uint32 SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, float TotalMod = 0.0f, uint32 stack = 1); + uint32 SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack = 1); + + uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const* spellProto = nullptr); + uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto = nullptr); + + bool isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType attackType = BASE_ATTACK); + bool isBlockCritical(); + float SpellDoneCritChance(Unit const* /*victim*/, SpellInfo const* spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType, bool skipEffectCheck) const; + float SpellTakenCritChance(Unit const* caster, SpellInfo const* spellProto, SpellSchoolMask schoolMask, float doneChance, WeaponAttackType attackType, bool skipEffectCheck) const; + static uint32 SpellCriticalDamageBonus(Unit const* caster, SpellInfo const* spellProto, uint32 damage, Unit const* victim); + static uint32 SpellCriticalHealingBonus(Unit const* caster, SpellInfo const* spellProto, uint32 damage, Unit const* victim); + + void SetLastManaUse(uint32 spellCastTime) { m_lastManaUse = spellCastTime; } + bool IsUnderLastManaUseEffect() const; + + void SetContestedPvP(Player* attackedPlayer = nullptr); + + uint32 GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime) const; + float CalculateDefaultCoefficient(SpellInfo const* spellInfo, DamageEffectType damagetype) const; + + void CastDelayedSpellWithPeriodicAmount(Unit* caster, uint32 spellId, AuraType auraType, int32 addAmount, uint8 effectIndex = 0); + + void ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply, SpellImmuneBlockType blockType = SPELL_BLOCK_TYPE_ALL); + void ApplySpellDispelImmunity(const SpellInfo* spellProto, DispelType type, bool apply); + virtual bool IsImmunedToSpell(SpellInfo const* spellInfo); + // redefined in Creature + bool IsImmunedToDamage(SpellSchoolMask meleeSchoolMask) const; + bool IsImmunedToDamage(SpellInfo const* spellInfo) const; + bool IsImmunedToSchool(SpellSchoolMask meleeSchoolMask) const; + bool IsImmunedToSchool(SpellInfo const* spellInfo) const; + bool IsImmunedToDamageOrSchool(SpellSchoolMask meleeSchoolMask) const; + bool IsImmunedToDamageOrSchool(SpellInfo const* spellInfo) const; + virtual bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const; + // redefined in Creature + static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = NULL, uint8 effIndex = MAX_SPELL_EFFECTS); + static uint32 CalcArmorReducedDamage(Unit const* attacker, Unit const* victim, const uint32 damage, SpellInfo const* spellInfo, uint8 attackerLevel = 0, WeaponAttackType attackType = MAX_ATTACK); + static void CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32* absorb, uint32* resist, SpellInfo const* spellInfo = NULL, bool Splited = false); + static void CalcHealAbsorb(Unit const* victim, const SpellInfo* spellProto, uint32& healAmount, uint32& absorb); + + void UpdateSpeed(UnitMoveType mtype, bool forced); + float GetSpeed(UnitMoveType mtype) const; + float GetSpeedRate(UnitMoveType mtype) const { return m_speed_rate[mtype]; } + void SetSpeed(UnitMoveType mtype, float rate, bool forced = false); + void SetSpeedRate(UnitMoveType mtype, float rate) { m_speed_rate[mtype] = rate; } + + float ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const; + int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = nullptr) const; + int32 CalcSpellDuration(SpellInfo const* spellProto); + int32 ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask); + void ModSpellCastTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = NULL); + float CalculateLevelPenalty(SpellInfo const* spellProto) const; + + void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); } + void removeFollower(FollowerReference* /*pRef*/) { /* nothing to do yet */ } + + MotionMaster* GetMotionMaster() { return i_motionMaster; } + const MotionMaster* GetMotionMaster() const { return i_motionMaster; } + + bool IsStopped() const { return !(HasUnitState(UNIT_STATE_MOVING)); } + void StopMoving(); + void StopMovingOnCurrentPos(); + + void AddUnitMovementFlag(uint32 f) { m_movementInfo.flags |= f; } + void RemoveUnitMovementFlag(uint32 f) { m_movementInfo.flags &= ~f; } + bool HasUnitMovementFlag(uint32 f) const { return (m_movementInfo.flags & f) == f; } + uint32 GetUnitMovementFlags() const { return m_movementInfo.flags; } + void SetUnitMovementFlags(uint32 f) { m_movementInfo.flags = f; } + + void AddExtraUnitMovementFlag(uint16 f) { m_movementInfo.flags2 |= f; } + void RemoveExtraUnitMovementFlag(uint16 f) { m_movementInfo.flags2 &= ~f; } + uint16 HasExtraUnitMovementFlag(uint16 f) const { return m_movementInfo.flags2 & f; } + uint16 GetExtraUnitMovementFlags() const { return m_movementInfo.flags2; } + void SetExtraUnitMovementFlags(uint16 f) { m_movementInfo.flags2 = f; } + + void SetControlled(bool apply, UnitState state); + void DisableRotate(bool apply); + void DisableSpline(); + + void AddComboPointHolder(uint32 lowguid) { m_ComboPointHolders.insert(lowguid); } + void RemoveComboPointHolder(uint32 lowguid) { m_ComboPointHolders.erase(lowguid); } + void ClearComboPointHolders(); + + ///----------Pet responses methods----------------- + void SendPetActionFeedback (uint8 msg); + void SendPetTalk (uint32 pettalk); + void SendPetAIReaction(uint64 guid); + ///----------End of Pet responses methods---------- + + void propagateSpeedChange() { GetMotionMaster()->propagateSpeedChange(); } + + // reactive attacks + void ClearAllReactives(); + void StartReactiveTimer(ReactiveType reactive) { m_reactiveTimer[reactive] = REACTIVE_TIMER_START;} + void UpdateReactives(uint32 p_time); + + // group updates + void UpdateAuraForGroup(uint8 slot); + + // proc trigger system + bool CanProc() {return !m_procDeep;} + void SetCantProc(bool apply) + { + if (apply) + ++m_procDeep; + else { - if (state) - SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); - else - RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); + ASSERT(m_procDeep); + --m_procDeep; } - uint32 GetCreatureType() const; - uint32 GetCreatureTypeMask() const - { - uint32 creatureType = GetCreatureType(); - return (creatureType >= 1) ? (1 << (creatureType - 1)) : 0; - } - - uint8 getStandState() const { return GetByteValue(UNIT_FIELD_BYTES_1, 0); } - bool IsSitState() const; - bool IsStandState() const; - void SetStandState(uint8 state); - - void SetStandFlags(uint8 flags) { SetByteFlag(UNIT_FIELD_BYTES_1, 2, flags); } - void RemoveStandFlags(uint8 flags) { RemoveByteFlag(UNIT_FIELD_BYTES_1, 2, flags); } - - bool IsMounted() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT); } - uint32 GetMountID() const { return GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID); } - void Mount(uint32 mount, uint32 vehicleId = 0, uint32 creatureEntry = 0); - void Dismount(); - - uint16 GetMaxSkillValueForLevel(Unit const* target = nullptr) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } - static void DealDamageMods(Unit const* victim, uint32 &damage, uint32* absorb); - static uint32 DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage const* cleanDamage = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = NULL, bool durabilityLoss = true, bool allowGM = false); - static void Kill(Unit* killer, Unit* victim, bool durabilityLoss = true, WeaponAttackType attackType = BASE_ATTACK, SpellInfo const *spellProto = nullptr); - static int32 DealHeal(Unit* healer, Unit* victim, uint32 addhealth); - - void ProcDamageAndSpell(Unit* victim, uint32 procAttacker, uint32 procVictim, uint32 procEx, uint32 amount, WeaponAttackType attType = BASE_ATTACK, SpellInfo const* procSpell = NULL, SpellInfo const* procAura = nullptr); - void ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellInfo const* procSpell, uint32 damage, SpellInfo const* procAura = nullptr); - - void GetProcAurasTriggeredOnEvent(std::list& aurasTriggeringProc, std::list* procAuras, ProcEventInfo eventInfo); - void TriggerAurasProcOnEvent(CalcDamageInfo& damageInfo); - void TriggerAurasProcOnEvent(std::list* myProcAuras, std::list* targetProcAuras, Unit* actionTarget, uint32 typeMaskActor, uint32 typeMaskActionTarget, uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo); - void TriggerAurasProcOnEvent(ProcEventInfo& eventInfo, std::list& procAuras); - - void HandleEmoteCommand(uint32 anim_id); - void AttackerStateUpdate (Unit* victim, WeaponAttackType attType = BASE_ATTACK, bool extra = false); - - void CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* damageInfo, WeaponAttackType attackType = BASE_ATTACK); - void DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss); - void HandleProcExtraAttackFor(Unit* victim); - - void CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType = BASE_ATTACK, bool crit = false); - void DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss); - - // player or player's pet resilience (-1%) - float GetMeleeCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_MELEE); } - float GetRangedCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_RANGED); } - float GetSpellCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_SPELL); } - - // player or player's pet resilience (-1%) - uint32 GetMeleeCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.2f, 33.0f, damage); } - uint32 GetRangedCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_RANGED, 2.2f, 33.0f, damage); } - uint32 GetSpellCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_SPELL, 2.2f, 33.0f, damage); } - - // player or player's pet resilience (-1%), cap 100% - uint32 GetMeleeDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); } - uint32 GetRangedDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_RANGED, 2.0f, 100.0f, damage); } - uint32 GetSpellDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_SPELL, 2.0f, 100.0f, damage); } - - static void ApplyResilience(const Unit* victim, float * crit, int32 * damage, bool isCrit, CombatRating type); - - float MeleeSpellMissChance(const Unit* victim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const; - SpellMissInfo MeleeSpellHitResult(Unit* victim, SpellInfo const* spell); - SpellMissInfo MagicSpellHitResult(Unit* victim, SpellInfo const* spell); - SpellMissInfo SpellHitResult(Unit* victim, SpellInfo const* spell, bool canReflect = false); - - float GetUnitDodgeChance() const; - float GetUnitParryChance() const; - float GetUnitBlockChance() const; - float GetUnitMissChance(WeaponAttackType attType) const; - float GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victim) const; - int32 GetMechanicResistChance(const SpellInfo* spell); - bool CanUseAttackType(uint8 attacktype) const - { - switch (attacktype) - { - case BASE_ATTACK: return !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED); - case OFF_ATTACK: return !HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_DISARM_OFFHAND); - case RANGED_ATTACK: return !HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_DISARM_RANGED); - } - return true; - } - - virtual uint32 GetShieldBlockValue() const =0; - uint32 GetShieldBlockValue(uint32 soft_cap, uint32 hard_cap) const - { - uint32 value = GetShieldBlockValue(); - if (value >= hard_cap) - { - value = (soft_cap + hard_cap) / 2; - } - else if (value > soft_cap) - { - value = soft_cap + ((value - soft_cap) / 2); - } - - return value; - } - uint32 GetUnitMeleeSkill(Unit const* target = nullptr) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } - uint32 GetDefenseSkillValue(Unit const* target = nullptr) const; - uint32 GetWeaponSkillValue(WeaponAttackType attType, Unit const* target = nullptr) const; - float GetWeaponProcChance() const; - float GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const; - - MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType) const; - MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const; - - bool IsVendor() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_VENDOR); } - bool IsTrainer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TRAINER); } - bool IsQuestGiver() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); } - bool IsGossip() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); } - bool IsTaxi() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_FLIGHTMASTER); } - bool IsGuildMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PETITIONER); } - bool IsBattleMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BATTLEMASTER); } - bool IsBanker() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BANKER); } - bool IsInnkeeper() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_INNKEEPER); } - bool IsSpiritHealer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER); } - bool IsSpiritGuide() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITGUIDE); } - bool IsTabardDesigner()const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TABARDDESIGNER); } - bool IsAuctioner() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_AUCTIONEER); } - bool IsArmorer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_REPAIR); } - bool IsServiceProvider() const - { - return HasFlag(UNIT_NPC_FLAGS, - UNIT_NPC_FLAG_VENDOR | UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_FLIGHTMASTER | - UNIT_NPC_FLAG_PETITIONER | UNIT_NPC_FLAG_BATTLEMASTER | UNIT_NPC_FLAG_BANKER | - UNIT_NPC_FLAG_INNKEEPER | UNIT_NPC_FLAG_SPIRITHEALER | - UNIT_NPC_FLAG_SPIRITGUIDE | UNIT_NPC_FLAG_TABARDDESIGNER | UNIT_NPC_FLAG_AUCTIONEER); - } - bool IsSpiritService() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER | UNIT_NPC_FLAG_SPIRITGUIDE); } - bool IsCritter() const { return GetCreatureType() == CREATURE_TYPE_CRITTER; } - - bool IsInFlight() const { return HasUnitState(UNIT_STATE_IN_FLIGHT); } - - bool IsInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); } - bool IsInCombatWith(Unit const* who) const; - - bool IsPetInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); } - void CombatStart(Unit* target, bool initialAggro = true); - void CombatStartOnCast(Unit* target, bool initialAggro = true, uint32 duration = 0); - void SetInCombatState(bool PvP, Unit* enemy = NULL, uint32 duration = 0); - void SetInCombatWith(Unit* enemy, uint32 duration = 0); - void ClearInCombat(); - void ClearInPetCombat(); - uint32 GetCombatTimer() const { return m_CombatTimer; } - - bool HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const; - bool virtual HasSpell(uint32 /*spellID*/) const { return false; } - bool HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura = 0) const; - bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = nullptr) const; - - bool HasStealthAura() const { return HasAuraType(SPELL_AURA_MOD_STEALTH); } - bool HasInvisibilityAura() const { return HasAuraType(SPELL_AURA_MOD_INVISIBILITY); } - bool isFeared() const { return HasAuraType(SPELL_AURA_MOD_FEAR); } - bool isInRoots() const { return HasAuraType(SPELL_AURA_MOD_ROOT); } - bool IsPolymorphed() const; - - bool isFrozen() const; - - bool isTargetableForAttack(bool checkFakeDeath = true, Unit const* byWho = nullptr) const; - - bool IsValidAttackTarget(Unit const* target) const; - bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = nullptr) const; - - bool IsValidAssistTarget(Unit const* target) const; - bool _IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const; - - void UpdateEnvironmentIfNeeded(const uint8 option); - virtual bool IsInWater(bool allowAbove = false) const; - virtual bool IsUnderWater() const; - virtual void UpdateUnderwaterState(Map* m, float x, float y, float z); - bool isInAccessiblePlaceFor(Creature const* c) const; - - void SendHealSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical = false); - int32 HealBySpell(Unit* victim, SpellInfo const* spellInfo, uint32 addHealth, bool critical = false); - void SendEnergizeSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, Powers powertype); - void EnergizeBySpell(Unit* victim, uint32 SpellID, uint32 Damage, Powers powertype); - - void CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastSpell(Unit* victim, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastSpell(Unit* victim, uint32 spellId, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastSpell(Unit* victim, SpellInfo const* spellInfo, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastSpell(Unit* victim, SpellInfo const* spellInfo, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastSpell(GameObject* go, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastCustomSpell(Unit* victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim = NULL, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - void CastCustomSpell(uint32 spellId, CustomSpellValues const &value, Unit* victim = NULL, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0); - Aura* AddAura(uint32 spellId, Unit* target); - Aura* AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target); - void SetAuraStack(uint32 spellId, Unit* target, uint32 stack); - void SendPlaySpellVisual(uint32 id); - void SendPlaySpellImpact(uint64 guid, uint32 id); - void BuildCooldownPacket(WorldPacket& data, uint8 flags, uint32 spellId, uint32 cooldown); - void BuildCooldownPacket(WorldPacket& data, uint8 flags, PacketCooldowns const& cooldowns); - - void DeMorph(); - - void SendAttackStateUpdate(CalcDamageInfo* damageInfo); - void SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount); - void SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log); - void SendSpellNonMeleeReflectLog(SpellNonMeleeDamage* log, Unit* attacker); - void SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit = false); - void SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo); - void SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo); - void SendSpellDamageResist(Unit* target, uint32 spellId); - void SendSpellDamageImmune(Unit* target, uint32 spellId); - - void NearTeleportTo(float x, float y, float z, float orientation, bool casting = false, bool vehicleTeleport = false, bool withPet = false, bool removeTransport = false); - void SendTameFailure(uint8 result); - void SendTeleportPacket(Position& pos); - virtual bool UpdatePosition(float x, float y, float z, float ang, bool teleport = false); - // returns true if unit's position really changed - bool UpdatePosition(const Position &pos, bool teleport = false) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } - void UpdateOrientation(float orientation); - void UpdateHeight(float newZ); - - void KnockbackFrom(float x, float y, float speedXY, float speedZ); - void JumpTo(float speedXY, float speedZ, bool forward = true); - void JumpTo(WorldObject* obj, float speedZ); - - void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 TransitTime, SplineFlags sf = SPLINEFLAG_WALK_MODE); // pussywizard: need to just send packet, with no shitty movement/spline - void MonsterMoveWithSpeed(float x, float y, float z, float speed); - //void SetFacing(float ori, WorldObject* obj = nullptr); - //void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player = nullptr); - void SendMovementFlagUpdate(bool self = false); - - bool IsLevitating() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY); } - bool IsWalking() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_WALKING); } - virtual bool SetWalk(bool enable); - virtual bool SetDisableGravity(bool disable, bool packetOnly = false); - virtual bool SetSwim(bool enable); - virtual bool SetCanFly(bool enable, bool packetOnly = false); - virtual bool SetWaterWalking(bool enable, bool packetOnly = false); - virtual bool SetFeatherFall(bool enable, bool packetOnly = false); - virtual bool SetHover(bool enable, bool packetOnly = false); - - // pussywizard: - void SendMovementWaterWalking(Player* sendTo); - void SendMovementFeatherFall(Player* sendTo); - void SendMovementHover(Player* sendTo); - - void SetInFront(WorldObject const* target); - void SetFacingTo(float ori); - void SetFacingToObject(WorldObject* object); - - void SendChangeCurrentVictimOpcode(HostileReference* pHostileReference); - void SendClearThreatListOpcode(); - void SendRemoveFromThreatListOpcode(HostileReference* pHostileReference); - void SendThreatListUpdate(); - - void SendClearTarget(); - - void BuildHeartBeatMsg(WorldPacket* data) const; - - bool IsAlive() const { return (m_deathState == ALIVE); }; - bool isDying() const { return (m_deathState == JUST_DIED); }; - bool isDead() const { return (m_deathState == DEAD || m_deathState == CORPSE); }; - DeathState getDeathState() { return m_deathState; }; - virtual void setDeathState(DeathState s, bool despawn = false); // overwrited in Creature/Player/Pet - - uint64 GetOwnerGUID() const { return GetUInt64Value(UNIT_FIELD_SUMMONEDBY); } - void SetOwnerGUID(uint64 owner); - uint64 GetCreatorGUID() const { return GetUInt64Value(UNIT_FIELD_CREATEDBY); } - void SetCreatorGUID(uint64 creator) { SetUInt64Value(UNIT_FIELD_CREATEDBY, creator); } - uint64 GetMinionGUID() const { return GetUInt64Value(UNIT_FIELD_SUMMON); } - void SetMinionGUID(uint64 guid) { SetUInt64Value(UNIT_FIELD_SUMMON, guid); } - uint64 GetCharmerGUID() const { return GetUInt64Value(UNIT_FIELD_CHARMEDBY); } - void SetCharmerGUID(uint64 owner) { SetUInt64Value(UNIT_FIELD_CHARMEDBY, owner); } - uint64 GetCharmGUID() const { return GetUInt64Value(UNIT_FIELD_CHARM); } - void SetPetGUID(uint64 guid) { m_SummonSlot[SUMMON_SLOT_PET] = guid; } - uint64 GetPetGUID() const { return m_SummonSlot[SUMMON_SLOT_PET]; } - void SetCritterGUID(uint64 guid) { SetUInt64Value(UNIT_FIELD_CRITTER, guid); } - uint64 GetCritterGUID() const { return GetUInt64Value(UNIT_FIELD_CRITTER); } - - bool IsControlledByPlayer() const { return m_ControlledByPlayer; } - bool IsCreatedByPlayer() const { return m_CreatedByPlayer; } - uint64 GetCharmerOrOwnerGUID() const { return GetCharmerGUID() ? GetCharmerGUID() : GetOwnerGUID(); } - uint64 GetCharmerOrOwnerOrOwnGUID() const - { - if (uint64 guid = GetCharmerOrOwnerGUID()) - return guid; - return GetGUID(); - } - bool IsCharmedOwnedByPlayerOrPlayer() const { return IS_PLAYER_GUID(GetCharmerOrOwnerOrOwnGUID()); } - - Player* GetSpellModOwner() const; - - Unit* GetOwner() const; - Guardian *GetGuardianPet() const; - Minion *GetFirstMinion() const; - Unit* GetCharmer() const; - Unit* GetCharm() const; - Unit* GetCharmerOrOwner() const { return GetCharmerGUID() ? GetCharmer() : GetOwner(); } - Unit* GetCharmerOrOwnerOrSelf() const - { - if (Unit* u = GetCharmerOrOwner()) - return u; - - return (Unit*)this; - } - Player* GetCharmerOrOwnerPlayerOrPlayerItself() const; - Player* GetAffectingPlayer() const; - - void SetMinion(Minion *minion, bool apply); - void GetAllMinionsByEntry(std::list& Minions, uint32 entry); - void RemoveAllMinionsByEntry(uint32 entry); - void SetCharm(Unit* target, bool apply); - Unit* GetNextRandomRaidMemberOrPet(float radius); - bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = nullptr); - void RemoveCharmedBy(Unit* charmer); - void RestoreFaction(); - - ControlSet m_Controlled; - Unit* GetFirstControlled() const; - void RemoveAllControlled(); - - bool IsCharmed() const { return GetCharmerGUID() != 0; } - bool isPossessed() const { return HasUnitState(UNIT_STATE_POSSESSED); } - bool isPossessedByPlayer() const { return HasUnitState(UNIT_STATE_POSSESSED) && IS_PLAYER_GUID(GetCharmerGUID()); } - bool isPossessing() const - { - if (Unit* u = GetCharm()) - return u->isPossessed(); - else - return false; - } - bool isPossessing(Unit* u) const { return u->isPossessed() && GetCharmGUID() == u->GetGUID(); } - - CharmInfo* GetCharmInfo() { return m_charmInfo; } - CharmInfo* InitCharmInfo(); - void DeleteCharmInfo(); - void UpdateCharmAI(); - //Player* GetMoverSource() const; - SafeUnitPointer m_movedByPlayer; - SharedVisionList const& GetSharedVisionList() { return m_sharedVision; } - void AddPlayerToVision(Player* player); - void RemovePlayerFromVision(Player* player); - bool HasSharedVision() const { return !m_sharedVision.empty(); } - void RemoveBindSightAuras(); - void RemoveCharmAuras(); - - Pet* CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id = 0); - Pet* CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id = 0); - bool InitTamedPet(Pet* pet, uint8 level, uint32 spell_id); - - // aura apply/remove helpers - you should better not use these - Aura* _TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0, bool periodicReset = false); - void _AddAura(UnitAura* aura, Unit* caster); - AuraApplication * _CreateAuraApplication(Aura* aura, uint8 effMask); - void _ApplyAuraEffect(Aura* aura, uint8 effIndex); - void _ApplyAura(AuraApplication * aurApp, uint8 effMask); - void _UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode); - void _UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode); - void _RemoveNoStackAuraApplicationsDueToAura(Aura* aura); - void _RemoveNoStackAurasDueToAura(Aura* aura); - bool _IsNoStackAuraDueToAura(Aura* appliedAura, Aura* existingAura) const; - void _RegisterAuraEffect(AuraEffect* aurEff, bool apply); - - // m_ownedAuras container management - AuraMap & GetOwnedAuras() { return m_ownedAuras; } - AuraMap const& GetOwnedAuras() const { return m_ownedAuras; } - - void RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void RemoveOwnedAura(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - - Aura* GetOwnedAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, Aura* except = nullptr) const; - - // m_appliedAuras container management - AuraApplicationMap & GetAppliedAuras() { return m_appliedAuras; } - AuraApplicationMap const& GetAppliedAuras() const { return m_appliedAuras; } - - void RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); - void RemoveAura(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); - void RemoveAura(Aura* aur, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); - - void RemoveAurasDueToSpell(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void RemoveAuraFromStack(uint32 spellId, uint64 casterGUID = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, uint64 casterGUID, Unit* dispeller, uint8 chargesRemoved = 1); - void RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit* stealer); - void RemoveAurasDueToItemSpell(uint32 spellId, uint64 castItemGuid); - void RemoveAurasByType(AuraType auraType, uint64 casterGUID = 0, Aura* except = NULL, bool negative = true, bool positive = true); - void RemoveNotOwnSingleTargetAuras(); - void RemoveAurasWithInterruptFlags(uint32 flag, uint32 except = 0); - void RemoveAurasWithAttribute(uint32 flags); - void RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID); - void RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode = AURA_REMOVE_BY_DEFAULT, uint32 except=0); - void RemoveMovementImpairingAuras(bool withRoot); - void RemoveAurasByShapeShift(); - - void RemoveAreaAurasDueToLeaveWorld(); - void RemoveAllAuras(); - void RemoveArenaAuras(); - void RemoveAllAurasOnDeath(); - void RemoveAllAurasRequiringDeadTarget(); - void RemoveAllAurasExceptType(AuraType type); - //void RemoveAllAurasExceptType(AuraType type1, AuraType type2); // pussywizard: replaced with RemoveEvadeAuras() - void RemoveEvadeAuras(); - void DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime); - - void _RemoveAllAuraStatMods(); - void _ApplyAllAuraStatMods(); - - AuraEffectList const& GetAuraEffectsByType(AuraType type) const { return m_modAuras[type]; } - AuraList & GetSingleCastAuras() { return m_scAuras; } - AuraList const& GetSingleCastAuras() const { return m_scAuras; } - - AuraEffect* GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 casterGUID = 0) const; - AuraEffect* GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 casterGUID = 0) const; - AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const; // spell mustn't have familyflags - AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID =0) const; - AuraEffect * GetAuraEffectDummy(uint32 spellid) const; - inline AuraEffect* GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const { return GetAuraEffect(SPELL_AURA_DUMMY, name, iconId, effIndex);} - - AuraApplication * GetAuraApplication(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, AuraApplication * except = nullptr) const; - Aura* GetAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const; - - AuraApplication * GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, AuraApplication * except = nullptr) const; - Aura* GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const; - - void GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList); - - bool HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster = 0) const; - uint32 GetAuraCount(uint32 spellId) const; - bool HasAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const; - bool HasAuraType(AuraType auraType) const; - bool HasAuraTypeWithCaster(AuraType auratype, uint64 caster) const; - bool HasAuraTypeWithMiscvalue(AuraType auratype, int32 miscvalue) const; - bool HasAuraTypeWithAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; - bool HasAuraTypeWithValue(AuraType auratype, int32 value) const; - bool HasNegativeAuraWithInterruptFlag(uint32 flag, uint64 guid = 0); - bool HasVisibleAuraType(AuraType auraType) const; - bool HasNegativeAuraWithAttribute(uint32 flag, uint64 guid = 0); - bool HasAuraWithMechanic(uint32 mechanicMask) const; - - AuraEffect* IsScriptOverriden(SpellInfo const* spell, int32 script) const; - uint32 GetDiseasesByCaster(uint64 casterGUID, uint8 mode = 0); - uint32 GetDoTsByCaster(uint64 casterGUID) const; - - int32 GetTotalAuraModifierAreaExclusive(AuraType auratype) const; - int32 GetTotalAuraModifier(AuraType auratype) const; - float GetTotalAuraMultiplier(AuraType auratype) const; - int32 GetMaxPositiveAuraModifier(AuraType auratype); - int32 GetMaxNegativeAuraModifier(AuraType auratype) const; - - int32 GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const; - float GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const; - int32 GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask, const AuraEffect* except = nullptr) const; - int32 GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const; - - int32 GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const; - float GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const; - int32 GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const; - int32 GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const; - - int32 GetTotalAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; - float GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; - int32 GetMaxPositiveAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; - int32 GetMaxNegativeAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const; - - float GetResistanceBuffMods(SpellSchools school, bool positive) const { return GetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school); } - void SetResistanceBuffMods(SpellSchools school, bool positive, float val) { SetFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val); } - void ApplyResistanceBuffModsMod(SpellSchools school, bool positive, float val, bool apply) { ApplyModSignedFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val, apply); } - void ApplyResistanceBuffModsPercentMod(SpellSchools school, bool positive, float val, bool apply) { ApplyPercentModFloatValue(positive ? UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+school : UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+school, val, apply); } - void InitStatBuffMods() - { - for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_POSSTAT0+i, 0); - for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) SetFloatValue(UNIT_FIELD_NEGSTAT0+i, 0); - } - void ApplyStatBuffMod(Stats stat, float val, bool apply) { ApplyModSignedFloatValue((val > 0 ? UNIT_FIELD_POSSTAT0+stat : UNIT_FIELD_NEGSTAT0+stat), val, apply); } - void ApplyStatPercentBuffMod(Stats stat, float val, bool apply); - - void SetCreateStat(Stats stat, float val) { m_createStats[stat] = val; } - void SetCreateHealth(uint32 val) { SetUInt32Value(UNIT_FIELD_BASE_HEALTH, val); } - uint32 GetCreateHealth() const { return GetUInt32Value(UNIT_FIELD_BASE_HEALTH); } - void SetCreateMana(uint32 val) { SetUInt32Value(UNIT_FIELD_BASE_MANA, val); } - uint32 GetCreateMana() const { return GetUInt32Value(UNIT_FIELD_BASE_MANA); } - uint32 GetCreatePowers(Powers power) const; - float GetPosStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_POSSTAT0+stat); } - float GetNegStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_NEGSTAT0+stat); } - float GetCreateStat(Stats stat) const { return m_createStats[stat]; } - - void SetCurrentCastedSpell(Spell* pSpell); - virtual void ProhibitSpellSchool(SpellSchoolMask /*idSchoolMask*/, uint32 /*unTimeMs*/) { } - void InterruptSpell(CurrentSpellTypes spellType, bool withDelayed = true, bool withInstant = true, bool bySelf = false); - void FinishSpell(CurrentSpellTypes spellType, bool ok = true); - - // set withDelayed to true to account delayed spells as casted - // delayed+channeled spells are always accounted as casted - // we can skip channeled or delayed checks using flags - bool IsNonMeleeSpellCast(bool withDelayed, bool skipChanneled = false, bool skipAutorepeat = false, bool isAutoshoot = false, bool skipInstant = true) const; - - // set withDelayed to true to interrupt delayed spells too - // delayed+channeled spells are always interrupted - void InterruptNonMeleeSpells(bool withDelayed, uint32 spellid = 0, bool withInstant = true, bool bySelf = false); - - // Check if our current channel spell has attribute SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING - bool CanMoveDuringChannel() const; - - Spell* GetCurrentSpell(CurrentSpellTypes spellType) const { return m_currentSpells[spellType]; } - Spell* GetCurrentSpell(uint32 spellType) const { return m_currentSpells[spellType]; } - Spell* FindCurrentSpellBySpellId(uint32 spell_id) const; - int32 GetCurrentSpellCastTime(uint32 spell_id) const; - - uint64 m_SummonSlot[MAX_SUMMON_SLOT]; - uint64 m_ObjectSlot[MAX_GAMEOBJECT_SLOT]; - - ShapeshiftForm GetShapeshiftForm() const { return ShapeshiftForm(GetByteValue(UNIT_FIELD_BYTES_2, 3)); } - void SetShapeshiftForm(ShapeshiftForm form) - { - SetByteValue(UNIT_FIELD_BYTES_2, 3, form); - } - - inline bool IsInFeralForm() const - { - ShapeshiftForm form = GetShapeshiftForm(); - return form == FORM_CAT || form == FORM_BEAR || form == FORM_DIREBEAR || form == FORM_GHOSTWOLF; // Xinef: added shamans Ghost Wolf, should behave exactly like druid forms - } - - inline bool IsInDisallowedMountForm() const - { - ShapeshiftForm form = GetShapeshiftForm(); - return form != FORM_NONE && form != FORM_BATTLESTANCE && form != FORM_BERSERKERSTANCE && form != FORM_DEFENSIVESTANCE && - form != FORM_SHADOW && form != FORM_STEALTH && form != FORM_UNDEAD; - } - - float m_modMeleeHitChance; - float m_modRangedHitChance; - float m_modSpellHitChance; - int32 m_baseSpellCritChance; - - float m_threatModifier[MAX_SPELL_SCHOOL]; - float m_modAttackSpeedPct[3]; - - // Event handler - EventProcessor m_Events; - - // stat system - bool HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply); - void SetModifierValue(UnitMods unitMod, UnitModifierType modifierType, float value) { m_auraModifiersGroup[unitMod][modifierType] = value; } - float GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const; - float GetTotalStatValue(Stats stat, float additionalValue = 0.0f) const; - float GetTotalAuraModValue(UnitMods unitMod) const; - SpellSchools GetSpellSchoolByAuraGroup(UnitMods unitMod) const; - Stats GetStatByAuraGroup(UnitMods unitMod) const; - Powers GetPowerTypeByAuraGroup(UnitMods unitMod) const; - bool CanModifyStats() const { return m_canModifyStats; } - void SetCanModifyStats(bool modifyStats) { m_canModifyStats = modifyStats; } - virtual bool UpdateStats(Stats stat) = 0; - virtual bool UpdateAllStats() = 0; - virtual void UpdateResistances(uint32 school) = 0; - virtual void UpdateAllResistances(); - virtual void UpdateArmor() = 0; - virtual void UpdateMaxHealth() = 0; - virtual void UpdateMaxPower(Powers power) = 0; - virtual void UpdateAttackPowerAndDamage(bool ranged = false) = 0; - virtual void UpdateDamagePhysical(WeaponAttackType attType); - float GetTotalAttackPowerValue(WeaponAttackType attType, Unit *pVictim = nullptr) const; - float GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange type) const; - void SetBaseWeaponDamage(WeaponAttackType attType, WeaponDamageRange damageRange, float value) { m_weaponDamage[attType][damageRange] = value; } - virtual void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) = 0; - uint32 CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct); - float GetAPMultiplier(WeaponAttackType attType, bool normalized); - - bool isInFrontInMap(Unit const* target, float distance, float arc = M_PI) const; - bool isInBackInMap(Unit const* target, float distance, float arc = M_PI) const; - - // Visibility system - bool IsVisible() const { return (m_serverSideVisibility.GetValue(SERVERSIDE_VISIBILITY_GM) > SEC_PLAYER) ? false : true; } - void SetVisible(bool x); - void SetModelVisible(bool on); - - // common function for visibility checks for player/creatures with detection code - uint32 GetPhaseByAuras() const; - void SetPhaseMask(uint32 newPhaseMask, bool update) override;// overwrite WorldObject::SetPhaseMask - void UpdateObjectVisibility(bool forced = true, bool fromUpdate = false) override; - - SpellImmuneList m_spellImmune[MAX_SPELL_IMMUNITY]; - uint32 m_lastSanctuaryTime; - - // Threat related methods - bool CanHaveThreatList() const; - void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); - float ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL); - void DeleteThreatList(); - void TauntApply(Unit* victim); - void TauntFadeOut(Unit* taunter); - ThreatManager& getThreatManager() { return m_ThreatManager; } - void addHatedBy(HostileReference* pHostileReference) { m_HostileRefManager.insertFirst(pHostileReference); }; - void removeHatedBy(HostileReference* /*pHostileReference*/) { /* nothing to do yet */ } - HostileRefManager& getHostileRefManager() { return m_HostileRefManager; } - - VisibleAuraMap const* GetVisibleAuras() { return &m_visibleAuras; } - AuraApplication * GetVisibleAura(uint8 slot) - { - VisibleAuraMap::iterator itr = m_visibleAuras.find(slot); - if (itr != m_visibleAuras.end()) - return itr->second; - return 0; - } - void SetVisibleAura(uint8 slot, AuraApplication * aur){ m_visibleAuras[slot]=aur; UpdateAuraForGroup(slot);} - void RemoveVisibleAura(uint8 slot){ m_visibleAuras.erase(slot); UpdateAuraForGroup(slot);} - - uint32 GetInterruptMask() const { return m_interruptMask; } - void AddInterruptMask(uint32 mask) { m_interruptMask |= mask; } - void UpdateInterruptMask(); - - uint32 GetDisplayId() { return GetUInt32Value(UNIT_FIELD_DISPLAYID); } - virtual void SetDisplayId(uint32 modelId); - uint32 GetNativeDisplayId() { return GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID); } - void RestoreDisplayId(); - void SetNativeDisplayId(uint32 modelId) { SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, modelId); } - void setTransForm(uint32 spellid) { m_transform = spellid;} - uint32 getTransForm() const { return m_transform;} - - // DynamicObject management - void _RegisterDynObject(DynamicObject* dynObj); - void _UnregisterDynObject(DynamicObject* dynObj); - DynamicObject* GetDynObject(uint32 spellId); - void RemoveDynObject(uint32 spellId); - void RemoveAllDynObjects(); - - GameObject* GetGameObject(uint32 spellId) const; - void AddGameObject(GameObject* gameObj); - void RemoveGameObject(GameObject* gameObj, bool del); - void RemoveGameObject(uint32 spellid, bool del); - void RemoveAllGameObjects(); - - void ModifyAuraState(AuraStateType flag, bool apply); - uint32 BuildAuraStateUpdateForTarget(Unit* target) const; - bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = NULL, Unit const* Caster = nullptr) const; - void UnsummonAllTotems(); - Unit* GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo); - Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = nullptr); - - int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask); - int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask, bool isDoT = false); - float SpellPctDamageModsDone(Unit* victim, SpellInfo const *spellProto, DamageEffectType damagetype); - uint32 SpellDamageBonusDone(Unit* victim, SpellInfo const *spellProto, uint32 pdamage, DamageEffectType damagetype, float TotalMod = 0.0f, uint32 stack = 1); - uint32 SpellDamageBonusTaken(Unit* caster, SpellInfo const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1); - int32 SpellBaseHealingBonusDone(SpellSchoolMask schoolMask); - int32 SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask); - float SpellPctHealingModsDone(Unit* victim, SpellInfo const *spellProto, DamageEffectType damagetype); - uint32 SpellHealingBonusDone(Unit* victim, SpellInfo const *spellProto, uint32 healamount, DamageEffectType damagetype, float TotalMod = 0.0f, uint32 stack = 1); - uint32 SpellHealingBonusTaken(Unit* caster, SpellInfo const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack = 1); - - uint32 MeleeDamageBonusDone(Unit *pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const *spellProto = nullptr); - uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage,WeaponAttackType attType, SpellInfo const *spellProto = nullptr); - - bool isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType attackType = BASE_ATTACK); - bool isBlockCritical(); - float SpellDoneCritChance(Unit const* /*victim*/, SpellInfo const* spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType, bool skipEffectCheck) const; - float SpellTakenCritChance(Unit const* caster, SpellInfo const* spellProto, SpellSchoolMask schoolMask, float doneChance, WeaponAttackType attackType, bool skipEffectCheck) const; - static uint32 SpellCriticalDamageBonus(Unit const* caster, SpellInfo const* spellProto, uint32 damage, Unit const* victim); - static uint32 SpellCriticalHealingBonus(Unit const* caster, SpellInfo const* spellProto, uint32 damage, Unit const* victim); - - void SetLastManaUse(uint32 spellCastTime) { m_lastManaUse = spellCastTime; } - bool IsUnderLastManaUseEffect() const; - - void SetContestedPvP(Player* attackedPlayer = nullptr); - - uint32 GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime) const; - float CalculateDefaultCoefficient(SpellInfo const *spellInfo, DamageEffectType damagetype) const; - - void CastDelayedSpellWithPeriodicAmount(Unit* caster, uint32 spellId, AuraType auraType, int32 addAmount, uint8 effectIndex = 0); - - void ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply, SpellImmuneBlockType blockType = SPELL_BLOCK_TYPE_ALL); - void ApplySpellDispelImmunity(const SpellInfo* spellProto, DispelType type, bool apply); - virtual bool IsImmunedToSpell(SpellInfo const* spellInfo); - // redefined in Creature - bool IsImmunedToDamage(SpellSchoolMask meleeSchoolMask) const; - bool IsImmunedToDamage(SpellInfo const* spellInfo) const; - bool IsImmunedToSchool(SpellSchoolMask meleeSchoolMask) const; - bool IsImmunedToSchool(SpellInfo const* spellInfo) const; - bool IsImmunedToDamageOrSchool(SpellSchoolMask meleeSchoolMask) const; - bool IsImmunedToDamageOrSchool(SpellInfo const* spellInfo) const; - virtual bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const; - // redefined in Creature - static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = NULL, uint8 effIndex = MAX_SPELL_EFFECTS); - static uint32 CalcArmorReducedDamage(Unit const* attacker, Unit const* victim, const uint32 damage, SpellInfo const* spellInfo, uint8 attackerLevel = 0, WeaponAttackType attackType=MAX_ATTACK); - static void CalcAbsorbResist(Unit* attacker, Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellInfo const* spellInfo = NULL, bool Splited = false); - static void CalcHealAbsorb(Unit const* victim, const SpellInfo* spellProto, uint32 &healAmount, uint32 &absorb); - - void UpdateSpeed(UnitMoveType mtype, bool forced); - float GetSpeed(UnitMoveType mtype) const; - float GetSpeedRate(UnitMoveType mtype) const { return m_speed_rate[mtype]; } - void SetSpeed(UnitMoveType mtype, float rate, bool forced = false); - void SetSpeedRate(UnitMoveType mtype, float rate) { m_speed_rate[mtype] = rate; } - - float ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const; - int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = nullptr) const; - int32 CalcSpellDuration(SpellInfo const* spellProto); - int32 ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask); - void ModSpellCastTime(SpellInfo const* spellProto, int32 & castTime, Spell * spell=NULL); - float CalculateLevelPenalty(SpellInfo const* spellProto) const; - - void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); } - void removeFollower(FollowerReference* /*pRef*/) { /* nothing to do yet */ } - - MotionMaster* GetMotionMaster() { return i_motionMaster; } - const MotionMaster* GetMotionMaster() const { return i_motionMaster; } - - bool IsStopped() const { return !(HasUnitState(UNIT_STATE_MOVING)); } - void StopMoving(); - void StopMovingOnCurrentPos(); - - void AddUnitMovementFlag(uint32 f) { m_movementInfo.flags |= f; } - void RemoveUnitMovementFlag(uint32 f) { m_movementInfo.flags &= ~f; } - bool HasUnitMovementFlag(uint32 f) const { return (m_movementInfo.flags & f) == f; } - uint32 GetUnitMovementFlags() const { return m_movementInfo.flags; } - void SetUnitMovementFlags(uint32 f) { m_movementInfo.flags = f; } - - void AddExtraUnitMovementFlag(uint16 f) { m_movementInfo.flags2 |= f; } - void RemoveExtraUnitMovementFlag(uint16 f) { m_movementInfo.flags2 &= ~f; } - uint16 HasExtraUnitMovementFlag(uint16 f) const { return m_movementInfo.flags2 & f; } - uint16 GetExtraUnitMovementFlags() const { return m_movementInfo.flags2; } - void SetExtraUnitMovementFlags(uint16 f) { m_movementInfo.flags2 = f; } - - void SetControlled(bool apply, UnitState state); - void DisableRotate(bool apply); - void DisableSpline(); - - void AddComboPointHolder(uint32 lowguid) { m_ComboPointHolders.insert(lowguid); } - void RemoveComboPointHolder(uint32 lowguid) { m_ComboPointHolders.erase(lowguid); } - void ClearComboPointHolders(); - - ///----------Pet responses methods----------------- - void SendPetActionFeedback (uint8 msg); - void SendPetTalk (uint32 pettalk); - void SendPetAIReaction(uint64 guid); - ///----------End of Pet responses methods---------- - - void propagateSpeedChange() { GetMotionMaster()->propagateSpeedChange(); } - - // reactive attacks - void ClearAllReactives(); - void StartReactiveTimer(ReactiveType reactive) { m_reactiveTimer[reactive] = REACTIVE_TIMER_START;} - void UpdateReactives(uint32 p_time); - - // group updates - void UpdateAuraForGroup(uint8 slot); - - // proc trigger system - bool CanProc(){return !m_procDeep;} - void SetCantProc(bool apply) - { - if (apply) - ++m_procDeep; - else - { - ASSERT(m_procDeep); - --m_procDeep; - } - } - - // pet auras - typedef std::set PetAuraSet; - PetAuraSet m_petAuras; - void AddPetAura(PetAura const* petSpell); - void RemovePetAura(PetAura const* petSpell); - void CastPetAura(PetAura const* aura); - bool IsPetAura(Aura const* aura); - - uint32 GetModelForForm(ShapeshiftForm form) const; - uint32 GetModelForTotem(PlayerTotemType totemType); - - // Redirect Threat - void SetRedirectThreat(uint64 guid, uint32 pct) { _redirectThreatInfo.Set(guid, pct); } - void ResetRedirectThreat() { SetRedirectThreat(0, 0); } - void ModifyRedirectThreat(int32 amount) { _redirectThreatInfo.ModifyThreatPct(amount); } - uint32 GetRedirectThreatPercent() { return _redirectThreatInfo.GetThreatPct(); } - Unit* GetRedirectThreatTarget() const; - - bool IsAIEnabled, NeedChangeAI; - bool CreateVehicleKit(uint32 id, uint32 creatureEntry); - void RemoveVehicleKit(); - Vehicle* GetVehicleKit()const { return m_vehicleKit; } - Vehicle* GetVehicle() const { return m_vehicle; } - bool IsOnVehicle(const Unit* vehicle) const { return m_vehicle && m_vehicle == vehicle->GetVehicleKit(); } - Unit* GetVehicleBase() const; - Creature* GetVehicleCreatureBase() const; - uint64 GetTransGUID() const override; - /// Returns the transport this unit is on directly (if on vehicle and transport, return vehicle) - TransportBase* GetDirectTransport() const; - - bool m_ControlledByPlayer; - bool m_CreatedByPlayer; - - bool HandleSpellClick(Unit* clicker, int8 seatId = -1); - void EnterVehicle(Unit* base, int8 seatId = -1); - void EnterVehicleUnattackable(Unit *base, int8 seatId = -1); - void ExitVehicle(Position const* exitPosition = nullptr); - void ChangeSeat(int8 seatId, bool next = true); - - // Should only be called by AuraEffect::HandleAuraControlVehicle(AuraApplication const* auraApp, uint8 mode, bool apply) const; - void _ExitVehicle(Position const* exitPosition = nullptr); - void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = nullptr); - - void BuildMovementPacket(ByteBuffer *data) const; - - virtual bool CanSwim() const; - bool isMoving() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_MOVING); } - bool isTurning() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_TURNING); } - bool IsHovering() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_HOVER); } - bool isSwimming() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_SWIMMING); } - virtual bool CanFly() const = 0; - bool IsFlying() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_DISABLE_GRAVITY); } - bool IsFalling() const; - float GetHoverHeight() const { return IsHovering() ? GetFloatValue(UNIT_FIELD_HOVERHEIGHT) : 0.0f; } - - void RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker); - - virtual float GetFollowAngle() const { return static_cast(M_PI/2); } - - void OutDebugInfo() const; - virtual bool isBeingLoaded() const { return false;} - bool IsDuringRemoveFromWorld() const {return m_duringRemoveFromWorld;} - - Pet* ToPet(){ if (IsPet()) return reinterpret_cast(this); else return nullptr; } - Totem* ToTotem(){ if (IsTotem()) return reinterpret_cast(this); else return nullptr; } - TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } - const TempSummon* ToTempSummon() const { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } - - // pussywizard: - // MMaps - std::map m_targetsNotAcceptable; - bool isTargetNotAcceptableByMMaps(uint64 guid, uint32 currTime, const Position* t = nullptr) const { std::map::const_iterator itr = m_targetsNotAcceptable.find(guid); if (itr != m_targetsNotAcceptable.end() && (itr->second._endTime >= currTime || (t && !itr->second.PosChanged(*this, *t)))) return true; return false; } - uint32 m_mmapNotAcceptableStartTime; - // Safe mover - std::set SafeUnitPointerSet; - void AddPointedBy(SafeUnitPointer* sup) { SafeUnitPointerSet.insert(sup); } - void RemovePointedBy(SafeUnitPointer* sup) { SafeUnitPointerSet.erase(sup); } - static void HandleSafeUnitPointersOnDelete(Unit* thisUnit); - // Relocation Nofier optimization - Position m_last_notify_position; - uint32 m_last_notify_mstime; - uint16 m_delayed_unit_relocation_timer; - uint16 m_delayed_unit_ai_notify_timer; - bool bRequestForcedVisibilityUpdate; - void ExecuteDelayedUnitRelocationEvent(); - void ExecuteDelayedUnitAINotifyEvent(); - // IsInWater, UpdateUnderwaterState, etc. optimizations - Position m_last_underwaterstate_position; - Position m_last_environment_position; - bool m_last_isinwater_status; - bool m_last_islittleabovewater_status; - bool m_last_isunderwater_status; - bool m_is_updating_environment; - // GetZone / GetArea optimization - Position m_last_area_position; - Position m_last_zone_position; - uint32 m_last_area_id; - uint32 m_last_zone_id; - Position m_last_outdoors_position; - bool m_last_outdoors_status; - bool IsOutdoors() const; - - uint32 GetZoneId(bool forceRecalc = false) const override; - uint32 GetAreaId(bool forceRecalc = false) const override; - void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc = false) const override; - - // cooldowns - virtual bool HasSpellCooldown(uint32 /*spell_id*/) const { return false; } - virtual bool HasSpellItemCooldown(uint32 /*spell_id*/, uint32 /*itemid*/) const { return false; } - virtual void AddSpellCooldown(uint32 /*spell_id*/, uint32 /*itemid*/, uint32 /*end_time*/, bool needSendToClient = false, bool forceSendToSpectator = false) { - // workaround for unused parameters - (void)needSendToClient; - (void)forceSendToSpectator; - } - - bool CanApplyResilience() const { return m_applyResilience; } - - void PetSpellFail(const SpellInfo* spellInfo, Unit* target, uint32 result); - - int32 CalculateAOEDamageReduction(int32 damage, uint32 schoolMask, Unit* caster) const; - - uint64 GetTarget() const { return GetUInt64Value(UNIT_FIELD_TARGET); } - virtual void SetTarget(uint64 /*guid*/) = 0; - - void SetInstantCast(bool set) { _instantCast = set; } - bool CanInstantCast() const { return _instantCast; } - - // Movement info - Movement::MoveSpline * movespline; - - protected: - explicit Unit (bool isWorldObject); - - void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const override; - - UnitAI* i_AI, *i_disabledAI; - - void _UpdateSpells(uint32 time); - void _DeleteRemovedAuras(); - - void _UpdateAutoRepeatSpell(); - - uint8 m_realRace; - uint8 m_race; - - bool m_AutoRepeatFirstCast; - - int32 m_attackTimer[MAX_ATTACK]; + } + + // pet auras + typedef std::set PetAuraSet; + PetAuraSet m_petAuras; + void AddPetAura(PetAura const* petSpell); + void RemovePetAura(PetAura const* petSpell); + void CastPetAura(PetAura const* aura); + bool IsPetAura(Aura const* aura); + + uint32 GetModelForForm(ShapeshiftForm form) const; + uint32 GetModelForTotem(PlayerTotemType totemType); + + // Redirect Threat + void SetRedirectThreat(uint64 guid, uint32 pct) { _redirectThreatInfo.Set(guid, pct); } + void ResetRedirectThreat() { SetRedirectThreat(0, 0); } + void ModifyRedirectThreat(int32 amount) { _redirectThreatInfo.ModifyThreatPct(amount); } + uint32 GetRedirectThreatPercent() { return _redirectThreatInfo.GetThreatPct(); } + Unit* GetRedirectThreatTarget() const; + + bool IsAIEnabled, NeedChangeAI; + bool CreateVehicleKit(uint32 id, uint32 creatureEntry); + void RemoveVehicleKit(); + Vehicle* GetVehicleKit()const { return m_vehicleKit; } + Vehicle* GetVehicle() const { return m_vehicle; } + bool IsOnVehicle(const Unit* vehicle) const { return m_vehicle && m_vehicle == vehicle->GetVehicleKit(); } + Unit* GetVehicleBase() const; + Creature* GetVehicleCreatureBase() const; + uint64 GetTransGUID() const override; + /// Returns the transport this unit is on directly (if on vehicle and transport, return vehicle) + TransportBase* GetDirectTransport() const; + + bool m_ControlledByPlayer; + bool m_CreatedByPlayer; + + bool HandleSpellClick(Unit* clicker, int8 seatId = -1); + void EnterVehicle(Unit* base, int8 seatId = -1); + void EnterVehicleUnattackable(Unit* base, int8 seatId = -1); + void ExitVehicle(Position const* exitPosition = nullptr); + void ChangeSeat(int8 seatId, bool next = true); + + // Should only be called by AuraEffect::HandleAuraControlVehicle(AuraApplication const* auraApp, uint8 mode, bool apply) const; + void _ExitVehicle(Position const* exitPosition = nullptr); + void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = nullptr); + + void BuildMovementPacket(ByteBuffer* data) const; + + virtual bool CanSwim() const; + bool isMoving() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_MOVING); } + bool isTurning() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_TURNING); } + bool IsHovering() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_HOVER); } + bool isSwimming() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_SWIMMING); } + virtual bool CanFly() const = 0; + bool IsFlying() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_DISABLE_GRAVITY); } + bool IsFalling() const; + float GetHoverHeight() const { return IsHovering() ? GetFloatValue(UNIT_FIELD_HOVERHEIGHT) : 0.0f; } + + void RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker); + + virtual float GetFollowAngle() const { return static_cast(M_PI / 2); } + + void OutDebugInfo() const; + virtual bool isBeingLoaded() const { return false;} + bool IsDuringRemoveFromWorld() const {return m_duringRemoveFromWorld;} + + Pet* ToPet() { if (IsPet()) return reinterpret_cast(this); else return nullptr; } + Totem* ToTotem() { if (IsTotem()) return reinterpret_cast(this); else return nullptr; } + TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } + const TempSummon* ToTempSummon() const { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } + + // pussywizard: + // MMaps + std::map m_targetsNotAcceptable; + bool isTargetNotAcceptableByMMaps(uint64 guid, uint32 currTime, const Position* t = nullptr) const { std::map::const_iterator itr = m_targetsNotAcceptable.find(guid); if (itr != m_targetsNotAcceptable.end() && (itr->second._endTime >= currTime || (t && !itr->second.PosChanged(*this, *t)))) return true; return false; } + uint32 m_mmapNotAcceptableStartTime; + // Safe mover + std::set SafeUnitPointerSet; + void AddPointedBy(SafeUnitPointer* sup) { SafeUnitPointerSet.insert(sup); } + void RemovePointedBy(SafeUnitPointer* sup) { SafeUnitPointerSet.erase(sup); } + static void HandleSafeUnitPointersOnDelete(Unit* thisUnit); + // Relocation Nofier optimization + Position m_last_notify_position; + uint32 m_last_notify_mstime; + uint16 m_delayed_unit_relocation_timer; + uint16 m_delayed_unit_ai_notify_timer; + bool bRequestForcedVisibilityUpdate; + void ExecuteDelayedUnitRelocationEvent(); + void ExecuteDelayedUnitAINotifyEvent(); + // IsInWater, UpdateUnderwaterState, etc. optimizations + Position m_last_underwaterstate_position; + Position m_last_environment_position; + bool m_last_isinwater_status; + bool m_last_islittleabovewater_status; + bool m_last_isunderwater_status; + bool m_is_updating_environment; + // GetZone / GetArea optimization + Position m_last_area_position; + Position m_last_zone_position; + uint32 m_last_area_id; + uint32 m_last_zone_id; + Position m_last_outdoors_position; + bool m_last_outdoors_status; + bool IsOutdoors() const; + + uint32 GetZoneId(bool forceRecalc = false) const override; + uint32 GetAreaId(bool forceRecalc = false) const override; + void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, bool forceRecalc = false) const override; + + // cooldowns + virtual bool HasSpellCooldown(uint32 /*spell_id*/) const { return false; } + virtual bool HasSpellItemCooldown(uint32 /*spell_id*/, uint32 /*itemid*/) const { return false; } + virtual void AddSpellCooldown(uint32 /*spell_id*/, uint32 /*itemid*/, uint32 /*end_time*/, bool needSendToClient = false, bool forceSendToSpectator = false) + { + // workaround for unused parameters + (void)needSendToClient; + (void)forceSendToSpectator; + } + + bool CanApplyResilience() const { return m_applyResilience; } + + void PetSpellFail(const SpellInfo* spellInfo, Unit* target, uint32 result); + + int32 CalculateAOEDamageReduction(int32 damage, uint32 schoolMask, Unit* caster) const; + + uint64 GetTarget() const { return GetUInt64Value(UNIT_FIELD_TARGET); } + virtual void SetTarget(uint64 /*guid*/) = 0; + + void SetInstantCast(bool set) { _instantCast = set; } + bool CanInstantCast() const { return _instantCast; } + + // Movement info + Movement::MoveSpline* movespline; + +protected: + explicit Unit (bool isWorldObject); + + void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const override; + + UnitAI* i_AI, *i_disabledAI; + + void _UpdateSpells(uint32 time); + void _DeleteRemovedAuras(); + + void _UpdateAutoRepeatSpell(); + + uint8 m_realRace; + uint8 m_race; + + bool m_AutoRepeatFirstCast; + + int32 m_attackTimer[MAX_ATTACK]; - float m_createStats[MAX_STATS]; + float m_createStats[MAX_STATS]; - AttackerSet m_attackers; - Unit* m_attacking; + AttackerSet m_attackers; + Unit* m_attacking; - DeathState m_deathState; + DeathState m_deathState; - int32 m_procDeep; + int32 m_procDeep; - typedef std::list DynObjectList; - DynObjectList m_dynObj; + typedef std::list DynObjectList; + DynObjectList m_dynObj; - typedef std::list GameObjectList; - GameObjectList m_gameObj; - uint32 m_transform; + typedef std::list GameObjectList; + GameObjectList m_gameObj; + uint32 m_transform; - Spell* m_currentSpells[CURRENT_MAX_SPELL]; + Spell* m_currentSpells[CURRENT_MAX_SPELL]; - AuraMap m_ownedAuras; - AuraApplicationMap m_appliedAuras; - AuraList m_removedAuras; - AuraMap::iterator m_auraUpdateIterator; - uint32 m_removedAurasCount; + AuraMap m_ownedAuras; + AuraApplicationMap m_appliedAuras; + AuraList m_removedAuras; + AuraMap::iterator m_auraUpdateIterator; + uint32 m_removedAurasCount; - AuraEffectList m_modAuras[TOTAL_AURAS]; - AuraList m_scAuras; // casted singlecast auras - AuraApplicationList m_interruptableAuras; // auras which have interrupt mask applied on unit - AuraStateAurasMap m_auraStateAuras; // Used for improve performance of aura state checks on aura apply/remove - uint32 m_interruptMask; + AuraEffectList m_modAuras[TOTAL_AURAS]; + AuraList m_scAuras; // casted singlecast auras + AuraApplicationList m_interruptableAuras; // auras which have interrupt mask applied on unit + AuraStateAurasMap m_auraStateAuras; // Used for improve performance of aura state checks on aura apply/remove + uint32 m_interruptMask; - float m_auraModifiersGroup[UNIT_MOD_END][MODIFIER_TYPE_END]; - float m_weaponDamage[MAX_ATTACK][2]; - bool m_canModifyStats; - VisibleAuraMap m_visibleAuras; + float m_auraModifiersGroup[UNIT_MOD_END][MODIFIER_TYPE_END]; + float m_weaponDamage[MAX_ATTACK][2]; + bool m_canModifyStats; + VisibleAuraMap m_visibleAuras; - float m_speed_rate[MAX_MOVE_TYPE]; + float m_speed_rate[MAX_MOVE_TYPE]; - CharmInfo* m_charmInfo; - SharedVisionList m_sharedVision; + CharmInfo* m_charmInfo; + SharedVisionList m_sharedVision; - virtual SpellSchoolMask GetMeleeDamageSchoolMask() const; + virtual SpellSchoolMask GetMeleeDamageSchoolMask() const; - MotionMaster* i_motionMaster; + MotionMaster* i_motionMaster; - uint32 m_reactiveTimer[MAX_REACTIVE]; - int32 m_regenTimer; + uint32 m_reactiveTimer[MAX_REACTIVE]; + int32 m_regenTimer; - ThreatManager m_ThreatManager; - typedef std::map CharmThreatMap; - CharmThreatMap _charmThreatInfo; + ThreatManager m_ThreatManager; + typedef std::map CharmThreatMap; + CharmThreatMap _charmThreatInfo; - Vehicle* m_vehicle; - Vehicle* m_vehicleKit; + Vehicle* m_vehicle; + Vehicle* m_vehicleKit; - uint32 m_unitTypeMask; - LiquidTypeEntry const* _lastLiquid; + uint32 m_unitTypeMask; + LiquidTypeEntry const* _lastLiquid; - // xinef: apply resilience - bool m_applyResilience; - bool IsAlwaysVisibleFor(WorldObject const* seer) const override; - bool IsAlwaysDetectableFor(WorldObject const* seer) const override; - bool _instantCast; + // xinef: apply resilience + bool m_applyResilience; + bool IsAlwaysVisibleFor(WorldObject const* seer) const override; + bool IsAlwaysDetectableFor(WorldObject const* seer) const override; + bool _instantCast; - private: - bool IsTriggeredAtSpellProcEvent(Unit* victim, Aura * aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const *& spellProcEvent, ProcEventInfo const& eventInfo); - bool HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); - bool HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown, bool * handled); - bool HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); - bool HandleOverrideClassScriptAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const *procSpell, uint32 cooldown); - bool HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura); - bool HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura); +private: + bool IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent, ProcEventInfo const& eventInfo); + bool HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); + bool HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown, bool* handled); + bool HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); + bool HandleOverrideClassScriptAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 cooldown); + bool HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura); + bool HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura); - void UpdateSplineMovement(uint32 t_diff); - void UpdateSplinePosition(); + void UpdateSplineMovement(uint32 t_diff); + void UpdateSplinePosition(); - // player or player's pet - float GetCombatRatingReduction(CombatRating cr) const; - uint32 GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const; + // player or player's pet + float GetCombatRatingReduction(CombatRating cr) const; + uint32 GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const; - void SetFeared(bool apply); - void SetConfused(bool apply); - void SetStunned(bool apply); - void SetRooted(bool apply); + void SetFeared(bool apply); + void SetConfused(bool apply); + void SetStunned(bool apply); + void SetRooted(bool apply); - uint32 m_rootTimes; + uint32 m_rootTimes; - uint32 m_state; // Even derived shouldn't modify - uint32 m_CombatTimer; - uint32 m_lastManaUse; // msecs - //TimeTrackerSmall m_movesplineTimer; + uint32 m_state; // Even derived shouldn't modify + uint32 m_CombatTimer; + uint32 m_lastManaUse; // msecs + //TimeTrackerSmall m_movesplineTimer; - Diminishing m_Diminishing; - // Manage all Units that are threatened by us - HostileRefManager m_HostileRefManager; + Diminishing m_Diminishing; + // Manage all Units that are threatened by us + HostileRefManager m_HostileRefManager; - FollowerRefManager m_FollowingRefManager; + FollowerRefManager m_FollowingRefManager; - ComboPointHolderSet m_ComboPointHolders; + ComboPointHolderSet m_ComboPointHolders; - RedirectThreatInfo _redirectThreatInfo; + RedirectThreatInfo _redirectThreatInfo; - bool m_cleanupDone; // lock made to not add stuff after cleanup before delete - bool m_duringRemoveFromWorld; // lock made to not add stuff after begining removing from world + bool m_cleanupDone; // lock made to not add stuff after cleanup before delete + bool m_duringRemoveFromWorld; // lock made to not add stuff after begining removing from world - uint32 _oldFactionId; ///< faction before charm - bool m_petCatchUp; + uint32 _oldFactionId; ///< faction before charm + bool m_petCatchUp; }; namespace acore @@ -2577,89 +2582,89 @@ namespace acore // Binary predicate for sorting Units based on percent value of a power class PowerPctOrderPred { - public: - PowerPctOrderPred(Powers power, bool ascending = true) : _power(power), _ascending(ascending) { } + public: + PowerPctOrderPred(Powers power, bool ascending = true) : _power(power), _ascending(ascending) { } - bool operator()(WorldObject const* objA, WorldObject const* objB) const - { - Unit const* a = objA->ToUnit(); - Unit const* b = objB->ToUnit(); - float rA = (a && a->GetMaxPower(_power)) ? float(a->GetPower(_power)) / float(a->GetMaxPower(_power)) : 0.0f; - float rB = (b && b->GetMaxPower(_power)) ? float(b->GetPower(_power)) / float(b->GetMaxPower(_power)) : 0.0f; - return _ascending ? rA < rB : rA > rB; - } + bool operator()(WorldObject const* objA, WorldObject const* objB) const + { + Unit const* a = objA->ToUnit(); + Unit const* b = objB->ToUnit(); + float rA = (a && a->GetMaxPower(_power)) ? float(a->GetPower(_power)) / float(a->GetMaxPower(_power)) : 0.0f; + float rB = (b && b->GetMaxPower(_power)) ? float(b->GetPower(_power)) / float(b->GetMaxPower(_power)) : 0.0f; + return _ascending ? rA < rB : rA > rB; + } - bool operator()(Unit const* a, Unit const* b) const - { - float rA = a->GetMaxPower(_power) ? float(a->GetPower(_power)) / float(a->GetMaxPower(_power)) : 0.0f; - float rB = b->GetMaxPower(_power) ? float(b->GetPower(_power)) / float(b->GetMaxPower(_power)) : 0.0f; - return _ascending ? rA < rB : rA > rB; - } + bool operator()(Unit const* a, Unit const* b) const + { + float rA = a->GetMaxPower(_power) ? float(a->GetPower(_power)) / float(a->GetMaxPower(_power)) : 0.0f; + float rB = b->GetMaxPower(_power) ? float(b->GetPower(_power)) / float(b->GetMaxPower(_power)) : 0.0f; + return _ascending ? rA < rB : rA > rB; + } - private: - Powers const _power; - bool const _ascending; + private: + Powers const _power; + bool const _ascending; }; // Binary predicate for sorting Units based on percent value of health class HealthPctOrderPred { - public: - HealthPctOrderPred(bool ascending = true) : _ascending(ascending) { } + public: + HealthPctOrderPred(bool ascending = true) : _ascending(ascending) { } - bool operator()(WorldObject const* objA, WorldObject const* objB) const - { - Unit const* a = objA->ToUnit(); - Unit const* b = objB->ToUnit(); - float rA = (a && a->GetMaxHealth()) ? float(a->GetHealth()) / float(a->GetMaxHealth()) : 0.0f; - float rB = (b && b->GetMaxHealth()) ? float(b->GetHealth()) / float(b->GetMaxHealth()) : 0.0f; - return _ascending ? rA < rB : rA > rB; - } + bool operator()(WorldObject const* objA, WorldObject const* objB) const + { + Unit const* a = objA->ToUnit(); + Unit const* b = objB->ToUnit(); + float rA = (a && a->GetMaxHealth()) ? float(a->GetHealth()) / float(a->GetMaxHealth()) : 0.0f; + float rB = (b && b->GetMaxHealth()) ? float(b->GetHealth()) / float(b->GetMaxHealth()) : 0.0f; + return _ascending ? rA < rB : rA > rB; + } - bool operator() (Unit const* a, Unit const* b) const - { - float rA = a->GetMaxHealth() ? float(a->GetHealth()) / float(a->GetMaxHealth()) : 0.0f; - float rB = b->GetMaxHealth() ? float(b->GetHealth()) / float(b->GetMaxHealth()) : 0.0f; - return _ascending ? rA < rB : rA > rB; - } + bool operator() (Unit const* a, Unit const* b) const + { + float rA = a->GetMaxHealth() ? float(a->GetHealth()) / float(a->GetMaxHealth()) : 0.0f; + float rB = b->GetMaxHealth() ? float(b->GetHealth()) / float(b->GetMaxHealth()) : 0.0f; + return _ascending ? rA < rB : rA > rB; + } - private: - bool const _ascending; + private: + bool const _ascending; }; } class ConflagrateAuraStateDelayEvent : public BasicEvent { - public: - ConflagrateAuraStateDelayEvent(uint64 ownerGUID, uint64 casterGUID) : BasicEvent(), m_owner(ownerGUID), m_caster(casterGUID) { } - bool Execute(uint64 e_time, uint32 p_time); +public: + ConflagrateAuraStateDelayEvent(uint64 ownerGUID, uint64 casterGUID) : BasicEvent(), m_owner(ownerGUID), m_caster(casterGUID) { } + bool Execute(uint64 e_time, uint32 p_time); - private: - uint64 m_owner; - uint64 m_caster; +private: + uint64 m_owner; + uint64 m_caster; }; class RedirectSpellEvent : public BasicEvent { - public: - RedirectSpellEvent(Unit& self, uint64 auraOwnerGUID, AuraEffect* auraEffect) : _self(self), _auraOwnerGUID(auraOwnerGUID), _auraEffect(auraEffect) { } - bool Execute(uint64 e_time, uint32 p_time); +public: + RedirectSpellEvent(Unit& self, uint64 auraOwnerGUID, AuraEffect* auraEffect) : _self(self), _auraOwnerGUID(auraOwnerGUID), _auraEffect(auraEffect) { } + bool Execute(uint64 e_time, uint32 p_time); - protected: - Unit& _self; - uint64 _auraOwnerGUID; - AuraEffect* _auraEffect; +protected: + Unit& _self; + uint64 _auraOwnerGUID; + AuraEffect* _auraEffect; }; class VehicleDespawnEvent : public BasicEvent { - public: - VehicleDespawnEvent(Unit& self, uint32 duration) : _self(self), _duration(duration) { } - bool Execute(uint64 e_time, uint32 p_time); +public: + VehicleDespawnEvent(Unit& self, uint32 duration) : _self(self), _duration(duration) { } + bool Execute(uint64 e_time, uint32 p_time); - protected: - Unit& _self; - uint32 _duration; +protected: + Unit& _self; + uint32 _duration; }; #endif diff --git a/src/server/game/Entities/Vehicle/Vehicle.cpp b/src/server/game/Entities/Vehicle/Vehicle.cpp index c3495fe7f..b1debf734 100644 --- a/src/server/game/Entities/Vehicle/Vehicle.cpp +++ b/src/server/game/Entities/Vehicle/Vehicle.cpp @@ -22,7 +22,7 @@ #include "BattlefieldWG.h" Vehicle::Vehicle(Unit* unit, VehicleEntry const* vehInfo, uint32 creatureEntry) : -_me(unit), _vehicleInfo(vehInfo), _usableSeatNum(0), _creatureEntry(creatureEntry), _status(STATUS_NONE) + _me(unit), _vehicleInfo(vehInfo), _usableSeatNum(0), _creatureEntry(creatureEntry), _status(STATUS_NONE) { for (uint32 i = 0; i < MAX_VEHICLE_SEATS; ++i) { @@ -58,7 +58,7 @@ Vehicle::~Vehicle() else sLog->outString("ZOMG! ~Vehicle(), unknown guid!"); } - //ASSERT(!itr->second.IsEmpty()); + //ASSERT(!itr->second.IsEmpty()); } void Vehicle::Install() @@ -96,7 +96,7 @@ void Vehicle::Uninstall() if (_status == STATUS_UNINSTALLING && !GetBase()->HasUnitTypeMask(UNIT_MASK_MINION)) { sLog->outError("Vehicle GuidLow: %u, Entry: %u attempts to uninstall, but already has STATUS_UNINSTALLING! " - "Check Uninstall/PassengerBoarded script hooks for errors.", _me->GetGUIDLow(), _me->GetEntry()); + "Check Uninstall/PassengerBoarded script hooks for errors.", _me->GetGUIDLow(), _me->GetEntry()); return; } _status = STATUS_UNINSTALLING; @@ -264,7 +264,7 @@ void Vehicle::InstallAccessory(uint32 entry, int8 seatId, bool minion, uint8 typ if (_status == STATUS_UNINSTALLING) { sLog->outError("Vehicle GuidLow: %u, Entry: %u attempts to install accessory Entry: %u on seat %d with STATUS_UNINSTALLING! " - "Check Uninstall/PassengerBoarded script hooks for errors.", _me->GetGUIDLow(), _me->GetEntry(), entry, (int32)seatId); + "Check Uninstall/PassengerBoarded script hooks for errors.", _me->GetGUIDLow(), _me->GetEntry(), entry, (int32)seatId); return; } @@ -351,7 +351,7 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) seat->second.Passenger.Guid = unit->GetGUID(); seat->second.Passenger.IsUnselectable = unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - + if (seat->second.SeatInfo->CanEnterOrExit()) { ASSERT(_usableSeatNum); @@ -384,13 +384,13 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) // xinef: removed retarded seat->first == 0 check... if (_me->GetTypeId() == TYPEID_UNIT - && unit->GetTypeId() == TYPEID_PLAYER - && seat->second.SeatInfo->m_flags & VEHICLE_SEAT_FLAG_CAN_CONTROL) + && unit->GetTypeId() == TYPEID_PLAYER + && seat->second.SeatInfo->m_flags & VEHICLE_SEAT_FLAG_CAN_CONTROL) { try { - if (!_me->SetCharmedBy(unit, CHARM_TYPE_VEHICLE)) - ABORT(); + if (!_me->SetCharmedBy(unit, CHARM_TYPE_VEHICLE)) + ABORT(); } catch (...) { @@ -411,7 +411,7 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) { unit->SendClearTarget(); // SMSG_BREAK_TARGET unit->SetControlled(true, UNIT_STATE_ROOT); // SMSG_FORCE_ROOT - In some cases we send SMSG_SPLINE_MOVE_ROOT here (for creatures) - // also adds MOVEMENTFLAG_ROOT + // also adds MOVEMENTFLAG_ROOT Movement::MoveSplineInit init(unit); init.DisableTransportPathTransformations(); init.MoveTo(veSeat->m_attachmentOffsetX, veSeat->m_attachmentOffsetY, veSeat->m_attachmentOffsetZ); @@ -549,7 +549,7 @@ void Vehicle::TeleportVehicle(float x, float y, float z, float ang) { _me->GetMap()->LoadGrid(x, y); _me->NearTeleportTo(x, y, z, ang, true); - + for (SeatMap::const_iterator itr = Seats.begin(); itr != Seats.end(); ++itr) if (Unit* passenger = ObjectAccessor::GetUnit(*GetBase(), itr->second.Passenger.Guid)) { diff --git a/src/server/game/Entities/Vehicle/Vehicle.h b/src/server/game/Entities/Vehicle/Vehicle.h index 04e96f979..048006019 100644 --- a/src/server/game/Entities/Vehicle/Vehicle.h +++ b/src/server/game/Entities/Vehicle/Vehicle.h @@ -17,74 +17,74 @@ class Unit; class Vehicle : public TransportBase { - public: - void Install(); - void Uninstall(); - void Reset(bool evading = false); - void InstallAllAccessories(bool evading); - void ApplyAllImmunities(); - void InstallAccessory(uint32 entry, int8 seatId, bool minion, uint8 type, uint32 summonTime); //! May be called from scripts +public: + void Install(); + void Uninstall(); + void Reset(bool evading = false); + void InstallAllAccessories(bool evading); + void ApplyAllImmunities(); + void InstallAccessory(uint32 entry, int8 seatId, bool minion, uint8 type, uint32 summonTime); //! May be called from scripts - Unit* GetBase() const { return _me; } - VehicleEntry const* GetVehicleInfo() const { return _vehicleInfo; } - uint32 GetCreatureEntry() const { return _creatureEntry; } + Unit* GetBase() const { return _me; } + VehicleEntry const* GetVehicleInfo() const { return _vehicleInfo; } + uint32 GetCreatureEntry() const { return _creatureEntry; } - bool HasEmptySeat(int8 seatId) const; - Unit* GetPassenger(int8 seatId) const; - int8 GetNextEmptySeat(int8 seatId, bool next) const; - uint8 GetAvailableSeatCount() const; + bool HasEmptySeat(int8 seatId) const; + Unit* GetPassenger(int8 seatId) const; + int8 GetNextEmptySeat(int8 seatId, bool next) const; + uint8 GetAvailableSeatCount() const; - bool AddPassenger(Unit* passenger, int8 seatId = -1); - void EjectPassenger(Unit* passenger, Unit* controller); - void RemovePassenger(Unit* passenger); - void RelocatePassengers(); - void RemoveAllPassengers(); - void Dismiss(); - bool IsVehicleInUse(); - void TeleportVehicle(float x, float y, float z, float ang); + bool AddPassenger(Unit* passenger, int8 seatId = -1); + void EjectPassenger(Unit* passenger, Unit* controller); + void RemovePassenger(Unit* passenger); + void RelocatePassengers(); + void RemoveAllPassengers(); + void Dismiss(); + bool IsVehicleInUse(); + void TeleportVehicle(float x, float y, float z, float ang); - SeatMap Seats; + SeatMap Seats; - VehicleSeatEntry const* GetSeatForPassenger(Unit const* passenger); - SeatMap::iterator GetSeatIteratorForPassenger(Unit* passenger); + VehicleSeatEntry const* GetSeatForPassenger(Unit const* passenger); + SeatMap::iterator GetSeatIteratorForPassenger(Unit* passenger); - protected: - friend bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry); - Vehicle(Unit* unit, VehicleEntry const* vehInfo, uint32 creatureEntry); - friend void Unit::RemoveVehicleKit(); - ~Vehicle(); +protected: + friend bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry); + Vehicle(Unit* unit, VehicleEntry const* vehInfo, uint32 creatureEntry); + friend void Unit::RemoveVehicleKit(); + ~Vehicle(); - private: - enum Status - { - STATUS_NONE, - STATUS_INSTALLED, - STATUS_UNINSTALLING, - }; +private: + enum Status + { + STATUS_NONE, + STATUS_INSTALLED, + STATUS_UNINSTALLING, + }; - void InitMovementInfoForBase(); + void InitMovementInfoForBase(); - /// This method transforms supplied transport offsets into global coordinates - void CalculatePassengerPosition(float& x, float& y, float& z, float* o /*= NULL*/) const - { - TransportBase::CalculatePassengerPosition(x, y, z, o, + /// This method transforms supplied transport offsets into global coordinates + void CalculatePassengerPosition(float& x, float& y, float& z, float* o /*= NULL*/) const + { + TransportBase::CalculatePassengerPosition(x, y, z, o, GetBase()->GetPositionX(), GetBase()->GetPositionY(), GetBase()->GetPositionZ(), GetBase()->GetOrientation()); - } + } - /// This method transforms supplied global coordinates into local offsets - void CalculatePassengerOffset(float& x, float& y, float& z, float* o /*= NULL*/) const - { - TransportBase::CalculatePassengerOffset(x, y, z, o, - GetBase()->GetPositionX(), GetBase()->GetPositionY(), - GetBase()->GetPositionZ(), GetBase()->GetOrientation()); - } + /// This method transforms supplied global coordinates into local offsets + void CalculatePassengerOffset(float& x, float& y, float& z, float* o /*= NULL*/) const + { + TransportBase::CalculatePassengerOffset(x, y, z, o, + GetBase()->GetPositionX(), GetBase()->GetPositionY(), + GetBase()->GetPositionZ(), GetBase()->GetOrientation()); + } - Unit* _me; - VehicleEntry const* _vehicleInfo; - uint32 _usableSeatNum; // Number of seats that match VehicleSeatEntry::UsableByPlayer, used for proper display flags - uint32 _creatureEntry; // Can be different than me->GetBase()->GetEntry() in case of players - Status _status; + Unit* _me; + VehicleEntry const* _vehicleInfo; + uint32 _usableSeatNum; // Number of seats that match VehicleSeatEntry::UsableByPlayer, used for proper display flags + uint32 _creatureEntry; // Can be different than me->GetBase()->GetEntry() in case of players + Status _status; }; #endif diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index 75645c0d2..be1e3d00b 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -37,13 +37,13 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const { default: case GAMEEVENT_NORMAL: - { - time_t currenttime = time(nullptr); - // Get the event information - return mGameEvent[entry].start < currenttime - && currenttime < mGameEvent[entry].end - && (currenttime - mGameEvent[entry].start) % (mGameEvent[entry].occurence * MINUTE) < mGameEvent[entry].length * MINUTE; - } + { + time_t currenttime = time(nullptr); + // Get the event information + return mGameEvent[entry].start < currenttime + && currenttime < mGameEvent[entry].end + && (currenttime - mGameEvent[entry].start) % (mGameEvent[entry].occurence * MINUTE) < mGameEvent[entry].length * MINUTE; + } // if the state is conditions or nextphase, then the event should be active case GAMEEVENT_WORLD_CONDITIONS: case GAMEEVENT_WORLD_NEXTPHASE: @@ -54,18 +54,18 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const return false; // if inactive world event, check the prerequisite events case GAMEEVENT_WORLD_INACTIVE: - { - time_t currenttime = time(nullptr); - for (std::set::const_iterator itr = mGameEvent[entry].prerequisite_events.begin(); itr != mGameEvent[entry].prerequisite_events.end(); ++itr) { - if ((mGameEvent[*itr].state != GAMEEVENT_WORLD_NEXTPHASE && mGameEvent[*itr].state != GAMEEVENT_WORLD_FINISHED) || // if prereq not in nextphase or finished state, then can't start this one - mGameEvent[*itr].nextstart > currenttime) // if not in nextphase state for long enough, can't start this one - return false; + time_t currenttime = time(nullptr); + for (std::set::const_iterator itr = mGameEvent[entry].prerequisite_events.begin(); itr != mGameEvent[entry].prerequisite_events.end(); ++itr) + { + if ((mGameEvent[*itr].state != GAMEEVENT_WORLD_NEXTPHASE && mGameEvent[*itr].state != GAMEEVENT_WORLD_FINISHED) || // if prereq not in nextphase or finished state, then can't start this one + mGameEvent[*itr].nextstart > currenttime) // if not in nextphase state for long enough, can't start this one + return false; + } + // all prerequisite events are met + // but if there are no prerequisites, this can be only activated through gm command + return !(mGameEvent[entry].prerequisite_events.empty()); } - // all prerequisite events are met - // but if there are no prerequisites, this can be only activated through gm command - return !(mGameEvent[entry].prerequisite_events.empty()); - } } } @@ -124,7 +124,7 @@ void GameEventMgr::StartInternalEvent(uint16 event_id) bool GameEventMgr::StartEvent(uint16 event_id, bool overwrite) { - GameEventData &data = mGameEvent[event_id]; + GameEventData& data = mGameEvent[event_id]; if (data.state == GAMEEVENT_NORMAL || data.state == GAMEEVENT_INTERNAL) { AddActiveEvent(event_id); @@ -171,7 +171,7 @@ bool GameEventMgr::StartEvent(uint16 event_id, bool overwrite) void GameEventMgr::StopEvent(uint16 event_id, bool overwrite) { - GameEventData &data = mGameEvent[event_id]; + GameEventData& data = mGameEvent[event_id]; bool serverwide_evt = data.state != GAMEEVENT_NORMAL && data.state != GAMEEVENT_INTERNAL; RemoveActiveEvent(event_id); @@ -216,7 +216,7 @@ void GameEventMgr::LoadFromDB() { { uint32 oldMSTime = getMSTime(); - // 1 2 3 4 5 6 7 8 9 10 + // 1 2 3 4 5 6 7 8 9 10 QueryResult result = WorldDatabase.Query("SELECT eventEntry, UNIX_TIMESTAMP(start_time), UNIX_TIMESTAMP(end_time), occurence, length, holiday, holidayStage, description, world_event, announce FROM game_event"); if (!result) { @@ -274,8 +274,7 @@ void GameEventMgr::LoadFromDB() SetHolidayEventTime(pGameEvent); } - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -320,8 +319,7 @@ void GameEventMgr::LoadFromDB() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u game event saves in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -371,8 +369,7 @@ void GameEventMgr::LoadFromDB() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u game event prerequisites in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -385,7 +382,7 @@ void GameEventMgr::LoadFromDB() // 1 2 QueryResult result = WorldDatabase.Query("SELECT creature.guid, game_event_creature.eventEntry FROM creature" - " JOIN game_event_creature ON creature.guid = game_event_creature.guid"); + " JOIN game_event_creature ON creature.guid = game_event_creature.guid"); if (!result) { @@ -414,8 +411,7 @@ void GameEventMgr::LoadFromDB() crelist.push_back(guid); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creatures in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -428,7 +424,7 @@ void GameEventMgr::LoadFromDB() // 0 1 QueryResult result = WorldDatabase.Query("SELECT gameobject.guid, game_event_gameobject.eventEntry FROM gameobject" - " JOIN game_event_gameobject ON gameobject.guid=game_event_gameobject.guid"); + " JOIN game_event_gameobject ON gameobject.guid=game_event_gameobject.guid"); if (!result) { @@ -457,8 +453,7 @@ void GameEventMgr::LoadFromDB() golist.push_back(guid); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u gameobjects in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -471,7 +466,7 @@ void GameEventMgr::LoadFromDB() // 0 1 2 3 4 QueryResult result = WorldDatabase.Query("SELECT creature.guid, creature.id, game_event_model_equip.eventEntry, game_event_model_equip.modelid, game_event_model_equip.equipment_id " - "FROM creature JOIN game_event_model_equip ON creature.guid=game_event_model_equip.guid"); + "FROM creature JOIN game_event_model_equip ON creature.guid=game_event_model_equip.guid"); if (!result) { @@ -516,8 +511,7 @@ void GameEventMgr::LoadFromDB() equiplist.push_back(std::pair(guid, newModelEquipSet)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u model/equipment changes in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -557,8 +551,7 @@ void GameEventMgr::LoadFromDB() questlist.push_back(QuestRelation(id, quest)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u quests additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -598,8 +591,7 @@ void GameEventMgr::LoadFromDB() questlist.push_back(QuestRelation(id, quest)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u quests additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -641,8 +633,7 @@ void GameEventMgr::LoadFromDB() mQuestToEventConditions[quest].num = num; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u quest event conditions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -683,8 +674,7 @@ void GameEventMgr::LoadFromDB() mGameEvent[event_id].conditions[condition].done_world_state = fields[4].GetUInt16(); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u conditions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -731,8 +721,7 @@ void GameEventMgr::LoadFromDB() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u condition saves in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -771,8 +760,7 @@ void GameEventMgr::LoadFromDB() mGameEventNPCFlags[event_id].push_back(GuidNPCFlagPair(guid, npcflag)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u npcflags in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -817,8 +805,7 @@ void GameEventMgr::LoadFromDB() questTemplate->SetEventIdForQuest((uint16)eventEntry); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u quests additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -883,8 +870,7 @@ void GameEventMgr::LoadFromDB() vendors.push_back(newEntry); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u vendor additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -921,8 +907,7 @@ void GameEventMgr::LoadFromDB() mGameEventBattlegroundHolidays[event_id] = fields[1].GetUInt32(); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u battleground holidays in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -935,7 +920,7 @@ void GameEventMgr::LoadFromDB() // 0 1 QueryResult result = WorldDatabase.Query("SELECT pool_template.entry, game_event_pool.eventEntry FROM pool_template" - " JOIN game_event_pool ON pool_template.entry = game_event_pool.pool_entry"); + " JOIN game_event_pool ON pool_template.entry = game_event_pool.pool_entry"); if (!result) { @@ -970,8 +955,7 @@ void GameEventMgr::LoadFromDB() poollist.push_back(entry); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u pools for game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1037,8 +1021,8 @@ uint32 GameEventMgr::GetNPCFlag(Creature* cr) for (ActiveEvents::iterator e_itr = m_ActiveEvents.begin(); e_itr != m_ActiveEvents.end(); ++e_itr) { for (NPCFlagList::iterator itr = mGameEventNPCFlags[*e_itr].begin(); - itr != mGameEventNPCFlags[*e_itr].end(); - ++ itr) + itr != mGameEventNPCFlags[*e_itr].end(); + ++ itr) if (itr->first == guid) mask |= itr->second; } @@ -1289,7 +1273,7 @@ void GameEventMgr::GameEventSpawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventCreatureGuids.size())) { sLog->outError("GameEventMgr::GameEventSpawn attempt access to out of range mGameEventCreatureGuids element %i (size: " SZFMTD ")", - internal_event_id, mGameEventCreatureGuids.size()); + internal_event_id, mGameEventCreatureGuids.size()); return; } @@ -1316,7 +1300,7 @@ void GameEventMgr::GameEventSpawn(int16 event_id) if (internal_event_id >= int32(mGameEventGameobjectGuids.size())) { sLog->outError("GameEventMgr::GameEventSpawn attempt access to out of range mGameEventGameobjectGuids element %i (size: " SZFMTD ")", - internal_event_id, mGameEventGameobjectGuids.size()); + internal_event_id, mGameEventGameobjectGuids.size()); return; } @@ -1349,7 +1333,7 @@ void GameEventMgr::GameEventSpawn(int16 event_id) if (internal_event_id >= int32(mGameEventPoolIds.size())) { sLog->outError("GameEventMgr::GameEventSpawn attempt access to out of range mGameEventPoolIds element %u (size: " SZFMTD ")", - internal_event_id, mGameEventPoolIds.size()); + internal_event_id, mGameEventPoolIds.size()); return; } @@ -1364,7 +1348,7 @@ void GameEventMgr::GameEventUnspawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventCreatureGuids.size())) { sLog->outError("GameEventMgr::GameEventUnspawn attempt access to out of range mGameEventCreatureGuids element %i (size: " SZFMTD ")", - internal_event_id, mGameEventCreatureGuids.size()); + internal_event_id, mGameEventCreatureGuids.size()); return; } @@ -1386,14 +1370,14 @@ void GameEventMgr::GameEventUnspawn(int16 event_id) if (internal_event_id >= int32(mGameEventGameobjectGuids.size())) { sLog->outError("GameEventMgr::GameEventUnspawn attempt access to out of range mGameEventGameobjectGuids element %i (size: " SZFMTD ")", - internal_event_id, mGameEventGameobjectGuids.size()); + internal_event_id, mGameEventGameobjectGuids.size()); return; } for (GuidList::iterator itr = mGameEventGameobjectGuids[internal_event_id].begin(); itr != mGameEventGameobjectGuids[internal_event_id].end(); ++itr) { // check if it's needed by another event, if so, don't remove - if (event_id >0 && hasGameObjectActiveEventExcept(*itr, event_id)) + if (event_id > 0 && hasGameObjectActiveEventExcept(*itr, event_id)) continue; // Remove the gameobject from grid if (GameObjectData const* data = sObjectMgr->GetGOData(*itr)) @@ -1435,7 +1419,7 @@ void GameEventMgr::ChangeEquipOrModel(int16 event_id, bool activate) itr->second.modelid_prev = creature->GetDisplayId(); creature->LoadEquipment(itr->second.equipment_id, true); if (itr->second.modelid > 0 && itr->second.modelid_prev != itr->second.modelid && - sObjectMgr->GetCreatureModelInfo(itr->second.modelid)) + sObjectMgr->GetCreatureModelInfo(itr->second.modelid)) { creature->SetDisplayId(itr->second.modelid); creature->SetNativeDisplayId(itr->second.modelid); @@ -1445,7 +1429,7 @@ void GameEventMgr::ChangeEquipOrModel(int16 event_id, bool activate) { creature->LoadEquipment(itr->second.equipement_id_prev, true); if (itr->second.modelid_prev > 0 && itr->second.modelid_prev != itr->second.modelid && - sObjectMgr->GetCreatureModelInfo(itr->second.modelid_prev)) + sObjectMgr->GetCreatureModelInfo(itr->second.modelid_prev)) { creature->SetDisplayId(itr->second.modelid_prev); creature->SetNativeDisplayId(itr->second.modelid_prev); @@ -1469,7 +1453,7 @@ void GameEventMgr::ChangeEquipOrModel(int16 event_id, bool activate) } } // now last step: put in data - // just to have write access to it + // just to have write access to it CreatureData& data2 = sObjectMgr->NewOrExistCreatureData(itr->first); if (activate) { @@ -1490,8 +1474,8 @@ bool GameEventMgr::hasCreatureQuestActiveEventExcept(uint32 quest_id, uint16 eve { if ((*e_itr) != event_id) for (QuestRelList::iterator itr = mGameEventCreatureQuests[*e_itr].begin(); - itr != mGameEventCreatureQuests[*e_itr].end(); - ++ itr) + itr != mGameEventCreatureQuests[*e_itr].end(); + ++ itr) if (itr->second == quest_id) return true; } @@ -1504,8 +1488,8 @@ bool GameEventMgr::hasGameObjectQuestActiveEventExcept(uint32 quest_id, uint16 e { if ((*e_itr) != event_id) for (QuestRelList::iterator itr = mGameEventGameObjectQuests[*e_itr].begin(); - itr != mGameEventGameObjectQuests[*e_itr].end(); - ++ itr) + itr != mGameEventGameObjectQuests[*e_itr].end(); + ++ itr) if (itr->second == quest_id) return true; } @@ -1519,8 +1503,8 @@ bool GameEventMgr::hasCreatureActiveEventExcept(uint32 creature_id, uint16 event { int32 internal_event_id = mGameEvent.size() + (*e_itr) - 1; for (GuidList::iterator itr = mGameEventCreatureGuids[internal_event_id].begin(); - itr != mGameEventCreatureGuids[internal_event_id].end(); - ++ itr) + itr != mGameEventCreatureGuids[internal_event_id].end(); + ++ itr) if (*itr == creature_id) return true; } @@ -1535,8 +1519,8 @@ bool GameEventMgr::hasGameObjectActiveEventExcept(uint32 go_id, uint16 event_id) { int32 internal_event_id = mGameEvent.size() + (*e_itr) - 1; for (GuidList::iterator itr = mGameEventGameobjectGuids[internal_event_id].begin(); - itr != mGameEventGameobjectGuids[internal_event_id].end(); - ++ itr) + itr != mGameEventGameobjectGuids[internal_event_id].end(); + ++ itr) if (*itr == go_id) return true; } @@ -1713,7 +1697,7 @@ void GameEventMgr::SaveWorldEventStateToDB(uint16 event_id) void GameEventMgr::SendWorldStateUpdate(Player* player, uint16 event_id) { GameEventConditionMap::const_iterator itr; - for (itr = mGameEvent[event_id].conditions.begin(); itr !=mGameEvent[event_id].conditions.end(); ++itr) + for (itr = mGameEvent[event_id].conditions.begin(); itr != mGameEvent[event_id].conditions.end(); ++itr) { if (itr->second.done_world_state) player->SendUpdateWorldState(itr->second.done_world_state, (uint32)(itr->second.done)); @@ -1766,16 +1750,16 @@ void GameEventMgr::SetHolidayEventTime(GameEventData& event) switch (holiday->CalendarFilterType) { - case -1: // Yearly - event.occurence = YEAR / MINUTE; // Not all too useful - break; - case 0: // Weekly - event.occurence = WEEK / MINUTE; - break; - case 1: // Defined dates only (Darkmoon Faire) - break; - case 2: // Only used for looping events (Call to Arms) - break; + case -1: // Yearly + event.occurence = YEAR / MINUTE; // Not all too useful + break; + case 0: // Weekly + event.occurence = WEEK / MINUTE; + break; + case 1: // Defined dates only (Darkmoon Faire) + break; + case 2: // Only used for looping events (Call to Arms) + break; } if (holiday->Looping) diff --git a/src/server/game/Events/GameEventMgr.h b/src/server/game/Events/GameEventMgr.h index 6124bbb42..0025682b0 100644 --- a/src/server/game/Events/GameEventMgr.h +++ b/src/server/game/Events/GameEventMgr.h @@ -81,88 +81,88 @@ class Quest; class GameEventMgr { - private: - GameEventMgr(); - ~GameEventMgr() {}; +private: + GameEventMgr(); + ~GameEventMgr() {}; - public: - static GameEventMgr* instance(); +public: + static GameEventMgr* instance(); - typedef std::set ActiveEvents; - typedef std::vector GameEventDataMap; - ActiveEvents const& GetActiveEventList() const { return m_ActiveEvents; } - GameEventDataMap const& GetEventMap() const { return mGameEvent; } - bool CheckOneGameEvent(uint16 entry) const; - uint32 NextCheck(uint16 entry) const; - void LoadFromDB(); - void LoadHolidayDates(); - uint32 Update(); - bool IsActiveEvent(uint16 event_id) { return (m_ActiveEvents.find(event_id) != m_ActiveEvents.end()); } - uint32 StartSystem(); - void Initialize(); - void StartArenaSeason(); - void StartInternalEvent(uint16 event_id); - bool StartEvent(uint16 event_id, bool overwrite = false); - void StopEvent(uint16 event_id, bool overwrite = false); - void HandleQuestComplete(uint32 quest_id); // called on world event type quest completions - uint32 GetNPCFlag(Creature* cr); - private: - void SendWorldStateUpdate(Player* player, uint16 event_id); - void AddActiveEvent(uint16 event_id) { m_ActiveEvents.insert(event_id); } - void RemoveActiveEvent(uint16 event_id) { m_ActiveEvents.erase(event_id); } - void ApplyNewEvent(uint16 event_id); - void UnApplyEvent(uint16 event_id); - void GameEventSpawn(int16 event_id); - void GameEventUnspawn(int16 event_id); - void ChangeEquipOrModel(int16 event_id, bool activate); - void UpdateEventQuests(uint16 event_id, bool activate); - void UpdateWorldStates(uint16 event_id, bool Activate); - void UpdateEventNPCFlags(uint16 event_id); - void UpdateEventNPCVendor(uint16 event_id, bool activate); - void UpdateBattlegroundSettings(); - void RunSmartAIScripts(uint16 event_id, bool activate); //! Runs SMART_EVENT_GAME_EVENT_START/_END SAI - bool CheckOneGameEventConditions(uint16 event_id); - void SaveWorldEventStateToDB(uint16 event_id); - bool hasCreatureQuestActiveEventExcept(uint32 quest_id, uint16 event_id); - bool hasGameObjectQuestActiveEventExcept(uint32 quest_id, uint16 event_id); - bool hasCreatureActiveEventExcept(uint32 creature_guid, uint16 event_id); - bool hasGameObjectActiveEventExcept(uint32 go_guid, uint16 event_id); - void SetHolidayEventTime(GameEventData& event); + typedef std::set ActiveEvents; + typedef std::vector GameEventDataMap; + ActiveEvents const& GetActiveEventList() const { return m_ActiveEvents; } + GameEventDataMap const& GetEventMap() const { return mGameEvent; } + bool CheckOneGameEvent(uint16 entry) const; + uint32 NextCheck(uint16 entry) const; + void LoadFromDB(); + void LoadHolidayDates(); + uint32 Update(); + bool IsActiveEvent(uint16 event_id) { return (m_ActiveEvents.find(event_id) != m_ActiveEvents.end()); } + uint32 StartSystem(); + void Initialize(); + void StartArenaSeason(); + void StartInternalEvent(uint16 event_id); + bool StartEvent(uint16 event_id, bool overwrite = false); + void StopEvent(uint16 event_id, bool overwrite = false); + void HandleQuestComplete(uint32 quest_id); // called on world event type quest completions + uint32 GetNPCFlag(Creature* cr); +private: + void SendWorldStateUpdate(Player* player, uint16 event_id); + void AddActiveEvent(uint16 event_id) { m_ActiveEvents.insert(event_id); } + void RemoveActiveEvent(uint16 event_id) { m_ActiveEvents.erase(event_id); } + void ApplyNewEvent(uint16 event_id); + void UnApplyEvent(uint16 event_id); + void GameEventSpawn(int16 event_id); + void GameEventUnspawn(int16 event_id); + void ChangeEquipOrModel(int16 event_id, bool activate); + void UpdateEventQuests(uint16 event_id, bool activate); + void UpdateWorldStates(uint16 event_id, bool Activate); + void UpdateEventNPCFlags(uint16 event_id); + void UpdateEventNPCVendor(uint16 event_id, bool activate); + void UpdateBattlegroundSettings(); + void RunSmartAIScripts(uint16 event_id, bool activate); //! Runs SMART_EVENT_GAME_EVENT_START/_END SAI + bool CheckOneGameEventConditions(uint16 event_id); + void SaveWorldEventStateToDB(uint16 event_id); + bool hasCreatureQuestActiveEventExcept(uint32 quest_id, uint16 event_id); + bool hasGameObjectQuestActiveEventExcept(uint32 quest_id, uint16 event_id); + bool hasCreatureActiveEventExcept(uint32 creature_guid, uint16 event_id); + bool hasGameObjectActiveEventExcept(uint32 go_guid, uint16 event_id); + void SetHolidayEventTime(GameEventData& event); - typedef std::list GuidList; - typedef std::list IdList; - typedef std::vector GameEventGuidMap; - typedef std::vector GameEventIdMap; - typedef std::pair ModelEquipPair; - typedef std::list ModelEquipList; - typedef std::vector GameEventModelEquipMap; - typedef std::pair QuestRelation; - typedef std::list QuestRelList; - typedef std::vector GameEventQuestMap; - typedef std::list NPCVendorList; - typedef std::vector GameEventNPCVendorMap; - typedef std::map QuestIdToEventConditionMap; - typedef std::pair GuidNPCFlagPair; - typedef std::list NPCFlagList; - typedef std::vector GameEventNPCFlagMap; - typedef std::vector GameEventBitmask; - GameEventQuestMap mGameEventCreatureQuests; - GameEventQuestMap mGameEventGameObjectQuests; - GameEventNPCVendorMap mGameEventVendors; - GameEventModelEquipMap mGameEventModelEquip; - //GameEventGuidMap mGameEventCreatureGuids; - //GameEventGuidMap mGameEventGameobjectGuids; - GameEventIdMap mGameEventPoolIds; - GameEventDataMap mGameEvent; - GameEventBitmask mGameEventBattlegroundHolidays; - QuestIdToEventConditionMap mQuestToEventConditions; - GameEventNPCFlagMap mGameEventNPCFlags; - ActiveEvents m_ActiveEvents; - bool isSystemInit; - public: - GameEventGuidMap mGameEventCreatureGuids; - GameEventGuidMap mGameEventGameobjectGuids; - std::vector modifiedHolidays; + typedef std::list GuidList; + typedef std::list IdList; + typedef std::vector GameEventGuidMap; + typedef std::vector GameEventIdMap; + typedef std::pair ModelEquipPair; + typedef std::list ModelEquipList; + typedef std::vector GameEventModelEquipMap; + typedef std::pair QuestRelation; + typedef std::list QuestRelList; + typedef std::vector GameEventQuestMap; + typedef std::list NPCVendorList; + typedef std::vector GameEventNPCVendorMap; + typedef std::map QuestIdToEventConditionMap; + typedef std::pair GuidNPCFlagPair; + typedef std::list NPCFlagList; + typedef std::vector GameEventNPCFlagMap; + typedef std::vector GameEventBitmask; + GameEventQuestMap mGameEventCreatureQuests; + GameEventQuestMap mGameEventGameObjectQuests; + GameEventNPCVendorMap mGameEventVendors; + GameEventModelEquipMap mGameEventModelEquip; + //GameEventGuidMap mGameEventCreatureGuids; + //GameEventGuidMap mGameEventGameobjectGuids; + GameEventIdMap mGameEventPoolIds; + GameEventDataMap mGameEvent; + GameEventBitmask mGameEventBattlegroundHolidays; + QuestIdToEventConditionMap mQuestToEventConditions; + GameEventNPCFlagMap mGameEventNPCFlags; + ActiveEvents m_ActiveEvents; + bool isSystemInit; +public: + GameEventGuidMap mGameEventCreatureGuids; + GameEventGuidMap mGameEventGameobjectGuids; + std::vector modifiedHolidays; }; #define sGameEventMgr GameEventMgr::instance() diff --git a/src/server/game/Globals/ObjectAccessor.cpp b/src/server/game/Globals/ObjectAccessor.cpp index efaaa310c..8a6dc6d6a 100644 --- a/src/server/game/Globals/ObjectAccessor.cpp +++ b/src/server/game/Globals/ObjectAccessor.cpp @@ -51,16 +51,23 @@ WorldObject* ObjectAccessor::GetWorldObject(WorldObject const& p, uint64 guid) { switch (GUID_HIPART(guid)) { - case HIGHGUID_PLAYER: return GetPlayer(p, guid); + case HIGHGUID_PLAYER: + return GetPlayer(p, guid); case HIGHGUID_TRANSPORT: case HIGHGUID_MO_TRANSPORT: - case HIGHGUID_GAMEOBJECT: return GetGameObject(p, guid); + case HIGHGUID_GAMEOBJECT: + return GetGameObject(p, guid); case HIGHGUID_VEHICLE: - case HIGHGUID_UNIT: return GetCreature(p, guid); - case HIGHGUID_PET: return GetPet(p, guid); - case HIGHGUID_DYNAMICOBJECT: return GetDynamicObject(p, guid); - case HIGHGUID_CORPSE: return GetCorpse(p, guid); - default: return nullptr; + case HIGHGUID_UNIT: + return GetCreature(p, guid); + case HIGHGUID_PET: + return GetPet(p, guid); + case HIGHGUID_DYNAMICOBJECT: + return GetDynamicObject(p, guid); + case HIGHGUID_CORPSE: + return GetCorpse(p, guid); + default: + return nullptr; } } @@ -345,8 +352,8 @@ Corpse* ObjectAccessor::ConvertCorpseForPlayer(uint64 player_guid, bool insignia // ignore bones creating option in case insignia if (map && corpse->IsPositionValid() && inWorld && (insignia || - (map->IsBattlegroundOrArena() ? sWorld->getBoolConfig(CONFIG_DEATH_BONES_BG_OR_ARENA) : sWorld->getBoolConfig(CONFIG_DEATH_BONES_WORLD))) && - !map->IsRemovalGrid(corpse->GetPositionX(), corpse->GetPositionY())) + (map->IsBattlegroundOrArena() ? sWorld->getBoolConfig(CONFIG_DEATH_BONES_BG_OR_ARENA) : sWorld->getBoolConfig(CONFIG_DEATH_BONES_WORLD))) && + !map->IsRemovalGrid(corpse->GetPositionX(), corpse->GetPositionY())) { // Create bones, don't change Corpse bones = new Corpse; diff --git a/src/server/game/Globals/ObjectAccessor.h b/src/server/game/Globals/ObjectAccessor.h index da6f1400f..eee74d7c4 100644 --- a/src/server/game/Globals/ObjectAccessor.h +++ b/src/server/game/Globals/ObjectAccessor.h @@ -31,41 +31,41 @@ class MotionTransport; template class HashMapHolder { - public: +public: - typedef std::unordered_map MapType; - typedef ACE_RW_Thread_Mutex LockType; + typedef std::unordered_map MapType; + typedef ACE_RW_Thread_Mutex LockType; - static void Insert(T* o) - { - ACORE_WRITE_GUARD(LockType, i_lock); - m_objectMap[o->GetGUID()] = o; - } + static void Insert(T* o) + { + ACORE_WRITE_GUARD(LockType, i_lock); + m_objectMap[o->GetGUID()] = o; + } - static void Remove(T* o) - { - ACORE_WRITE_GUARD(LockType, i_lock); - m_objectMap.erase(o->GetGUID()); - } + static void Remove(T* o) + { + ACORE_WRITE_GUARD(LockType, i_lock); + m_objectMap.erase(o->GetGUID()); + } - static T* Find(uint64 guid) - { - ACORE_READ_GUARD(LockType, i_lock); - typename MapType::iterator itr = m_objectMap.find(guid); - return (itr != m_objectMap.end()) ? itr->second : nullptr; - } + static T* Find(uint64 guid) + { + ACORE_READ_GUARD(LockType, i_lock); + typename MapType::iterator itr = m_objectMap.find(guid); + return (itr != m_objectMap.end()) ? itr->second : nullptr; + } - static MapType& GetContainer() { return m_objectMap; } + static MapType& GetContainer() { return m_objectMap; } - static LockType* GetLock() { return &i_lock; } + static LockType* GetLock() { return &i_lock; } - private: +private: - //Non instanceable only static - HashMapHolder() {} + //Non instanceable only static + HashMapHolder() {} - static LockType i_lock; - static MapType m_objectMap; + static LockType i_lock; + static MapType m_objectMap; }; /// Define the static members of HashMapHolder @@ -86,196 +86,196 @@ public: class ObjectAccessor { - private: - ObjectAccessor(); - ~ObjectAccessor(); - ObjectAccessor(const ObjectAccessor&); - ObjectAccessor& operator=(const ObjectAccessor&); +private: + ObjectAccessor(); + ~ObjectAccessor(); + ObjectAccessor(const ObjectAccessor&); + ObjectAccessor& operator=(const ObjectAccessor&); - public: - static ObjectAccessor* instance(); - // TODO: override these template functions for each holder type and add assertions +public: + static ObjectAccessor* instance(); + // TODO: override these template functions for each holder type and add assertions - template static T* GetObjectInOrOutOfWorld(uint64 guid, T* /*typeSpecifier*/) + template static T* GetObjectInOrOutOfWorld(uint64 guid, T* /*typeSpecifier*/) + { + return HashMapHolder::Find(guid); + } + + static Unit* GetObjectInOrOutOfWorld(uint64 guid, Unit* /*typeSpecifier*/) + { + if (IS_PLAYER_GUID(guid)) + return (Unit*)GetObjectInOrOutOfWorld(guid, (Player*)NULL); + + if (IS_PET_GUID(guid)) + return (Unit*)GetObjectInOrOutOfWorld(guid, (Pet*)NULL); + + return (Unit*)GetObjectInOrOutOfWorld(guid, (Creature*)NULL); + } + + // returns object if is in world + template static T* GetObjectInWorld(uint64 guid, T* /*typeSpecifier*/) + { + return HashMapHolder::Find(guid); + } + + // Player may be not in world while in ObjectAccessor + static Player* GetObjectInWorld(uint64 guid, Player* /*typeSpecifier*/); + + static Unit* GetObjectInWorld(uint64 guid, Unit* /*typeSpecifier*/) + { + if (IS_PLAYER_GUID(guid)) + return (Unit*)GetObjectInWorld(guid, (Player*)NULL); + + if (IS_PET_GUID(guid)) + return (Unit*)GetObjectInWorld(guid, (Pet*)NULL); + + return (Unit*)GetObjectInWorld(guid, (Creature*)NULL); + } + + // returns object if is in map + template static T* GetObjectInMap(uint64 guid, Map* map, T* /*typeSpecifier*/) + { + ASSERT(map); + if (T* obj = GetObjectInWorld(guid, (T*)NULL)) + if (obj->GetMap() == map) + return obj; + return nullptr; + } + + template static T* GetObjectInWorld(uint32 mapid, float x, float y, uint64 guid, T* /*fake*/) + { + T* obj = HashMapHolder::Find(guid); + if (!obj || obj->GetMapId() != mapid) + return nullptr; + + CellCoord p = acore::ComputeCellCoord(x, y); + if (!p.IsCoordValid()) { - return HashMapHolder::Find(guid); - } - - static Unit* GetObjectInOrOutOfWorld(uint64 guid, Unit* /*typeSpecifier*/) - { - if (IS_PLAYER_GUID(guid)) - return (Unit*)GetObjectInOrOutOfWorld(guid, (Player*)NULL); - - if (IS_PET_GUID(guid)) - return (Unit*)GetObjectInOrOutOfWorld(guid, (Pet*)NULL); - - return (Unit*)GetObjectInOrOutOfWorld(guid, (Creature*)NULL); - } - - // returns object if is in world - template static T* GetObjectInWorld(uint64 guid, T* /*typeSpecifier*/) - { - return HashMapHolder::Find(guid); - } - - // Player may be not in world while in ObjectAccessor - static Player* GetObjectInWorld(uint64 guid, Player* /*typeSpecifier*/); - - static Unit* GetObjectInWorld(uint64 guid, Unit* /*typeSpecifier*/) - { - if (IS_PLAYER_GUID(guid)) - return (Unit*)GetObjectInWorld(guid, (Player*)NULL); - - if (IS_PET_GUID(guid)) - return (Unit*)GetObjectInWorld(guid, (Pet*)NULL); - - return (Unit*)GetObjectInWorld(guid, (Creature*)NULL); - } - - // returns object if is in map - template static T* GetObjectInMap(uint64 guid, Map* map, T* /*typeSpecifier*/) - { - ASSERT(map); - if (T * obj = GetObjectInWorld(guid, (T*)NULL)) - if (obj->GetMap() == map) - return obj; + sLog->outError("ObjectAccessor::GetObjectInWorld: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord); return nullptr; } - template static T* GetObjectInWorld(uint32 mapid, float x, float y, uint64 guid, T* /*fake*/) + CellCoord q = acore::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY()); + if (!q.IsCoordValid()) { - T* obj = HashMapHolder::Find(guid); - if (!obj || obj->GetMapId() != mapid) - return nullptr; - - CellCoord p = acore::ComputeCellCoord(x, y); - if (!p.IsCoordValid()) - { - sLog->outError("ObjectAccessor::GetObjectInWorld: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord); - return nullptr; - } - - CellCoord q = acore::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY()); - if (!q.IsCoordValid()) - { - sLog->outError("ObjectAccessor::GetObjecInWorld: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), q.x_coord, q.y_coord); - return nullptr; - } - - int32 dx = int32(p.x_coord) - int32(q.x_coord); - int32 dy = int32(p.y_coord) - int32(q.y_coord); - - if (dx > -2 && dx < 2 && dy > -2 && dy < 2) - return obj; - else - return nullptr; + sLog->outError("ObjectAccessor::GetObjecInWorld: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), q.x_coord, q.y_coord); + return nullptr; } - // these functions return objects only if in map of specified object - static WorldObject* GetWorldObject(WorldObject const&, uint64); - static Object* GetObjectByTypeMask(WorldObject const&, uint64, uint32 typemask); - static Corpse* GetCorpse(WorldObject const& u, uint64 guid); - static GameObject* GetGameObject(WorldObject const& u, uint64 guid); - static Transport* GetTransport(WorldObject const& u, uint64 guid); - static DynamicObject* GetDynamicObject(WorldObject const& u, uint64 guid); - static Unit* GetUnit(WorldObject const&, uint64 guid); - static Creature* GetCreature(WorldObject const& u, uint64 guid); - static Pet* GetPet(WorldObject const&, uint64 guid); - static Player* GetPlayer(WorldObject const&, uint64 guid); - static Creature* GetCreatureOrPetOrVehicle(WorldObject const&, uint64); + int32 dx = int32(p.x_coord) - int32(q.x_coord); + int32 dy = int32(p.y_coord) - int32(q.y_coord); - // these functions return objects if found in whole world - // ACCESS LIKE THAT IS NOT THREAD SAFE - static Pet* FindPet(uint64); - static Player* FindPlayer(uint64); - static Player* FindPlayerInOrOutOfWorld(uint64 m_guid); + if (dx > -2 && dx < 2 && dy > -2 && dy < 2) + return obj; + else + return nullptr; + } - static Unit* FindUnit(uint64); - static Player* FindConnectedPlayer(uint64 const&); - static Player* FindPlayerByName(std::string const& name, bool checkInWorld = true); - static std::map playerNameToPlayerPointer; // pussywizard: optimization + // these functions return objects only if in map of specified object + static WorldObject* GetWorldObject(WorldObject const&, uint64); + static Object* GetObjectByTypeMask(WorldObject const&, uint64, uint32 typemask); + static Corpse* GetCorpse(WorldObject const& u, uint64 guid); + static GameObject* GetGameObject(WorldObject const& u, uint64 guid); + static Transport* GetTransport(WorldObject const& u, uint64 guid); + static DynamicObject* GetDynamicObject(WorldObject const& u, uint64 guid); + static Unit* GetUnit(WorldObject const&, uint64 guid); + static Creature* GetCreature(WorldObject const& u, uint64 guid); + static Pet* GetPet(WorldObject const&, uint64 guid); + static Player* GetPlayer(WorldObject const&, uint64 guid); + static Creature* GetCreatureOrPetOrVehicle(WorldObject const&, uint64); - // when using this, you must use the hashmapholder's lock - static HashMapHolder::MapType const& GetPlayers() - { - return HashMapHolder::GetContainer(); - } + // these functions return objects if found in whole world + // ACCESS LIKE THAT IS NOT THREAD SAFE + static Pet* FindPet(uint64); + static Player* FindPlayer(uint64); + static Player* FindPlayerInOrOutOfWorld(uint64 m_guid); - // when using this, you must use the hashmapholder's lock - static HashMapHolder::MapType const& GetCreatures() - { - return HashMapHolder::GetContainer(); - } + static Unit* FindUnit(uint64); + static Player* FindConnectedPlayer(uint64 const&); + static Player* FindPlayerByName(std::string const& name, bool checkInWorld = true); + static std::map playerNameToPlayerPointer; // pussywizard: optimization - // when using this, you must use the hashmapholder's lock - static HashMapHolder::MapType const& GetGameObjects() - { - return HashMapHolder::GetContainer(); - } + // when using this, you must use the hashmapholder's lock + static HashMapHolder::MapType const& GetPlayers() + { + return HashMapHolder::GetContainer(); + } - template static void AddObject(T* object) - { - HashMapHolder::Insert(object); - } + // when using this, you must use the hashmapholder's lock + static HashMapHolder::MapType const& GetCreatures() + { + return HashMapHolder::GetContainer(); + } - template static void RemoveObject(T* object) - { - HashMapHolder::Remove(object); - } + // when using this, you must use the hashmapholder's lock + static HashMapHolder::MapType const& GetGameObjects() + { + return HashMapHolder::GetContainer(); + } - static void SaveAllPlayers(); + template static void AddObject(T* object) + { + HashMapHolder::Insert(object); + } - //non-static functions - void AddUpdateObject(Object* obj) - { - ACORE_GUARD(ACE_Thread_Mutex, i_objectLock); - if (obj->GetTypeId() < TYPEID_UNIT) // these are not in map: TYPEID_OBJECT, TYPEID_ITEM, TYPEID_CONTAINER - i_objects.insert(obj); - else - ((WorldObject*)obj)->FindMap()->i_objectsToUpdate.insert(obj); - } + template static void RemoveObject(T* object) + { + HashMapHolder::Remove(object); + } - void RemoveUpdateObject(Object* obj) - { - ACORE_GUARD(ACE_Thread_Mutex, i_objectLock); - if (obj->GetTypeId() < TYPEID_UNIT) // these are not in map: TYPEID_OBJECT, TYPEID_ITEM, TYPEID_CONTAINER - i_objects.erase(obj); - else - ((WorldObject*)obj)->FindMap()->i_objectsToUpdate.erase(obj); - } + static void SaveAllPlayers(); - //Thread safe - Corpse* GetCorpseForPlayerGUID(uint64 guid); - void RemoveCorpse(Corpse* corpse, bool final = false); - void AddCorpse(Corpse* corpse); - void AddCorpsesToGrid(GridCoord const& gridpair, GridType& grid, Map* map); - Corpse* ConvertCorpseForPlayer(uint64 player_guid, bool insignia = false); + //non-static functions + void AddUpdateObject(Object* obj) + { + ACORE_GUARD(ACE_Thread_Mutex, i_objectLock); + if (obj->GetTypeId() < TYPEID_UNIT) // these are not in map: TYPEID_OBJECT, TYPEID_ITEM, TYPEID_CONTAINER + i_objects.insert(obj); + else + ((WorldObject*)obj)->FindMap()->i_objectsToUpdate.insert(obj); + } - //Thread unsafe - void Update(uint32 diff); - void RemoveOldCorpses(); - void UnloadAll(); + void RemoveUpdateObject(Object* obj) + { + ACORE_GUARD(ACE_Thread_Mutex, i_objectLock); + if (obj->GetTypeId() < TYPEID_UNIT) // these are not in map: TYPEID_OBJECT, TYPEID_ITEM, TYPEID_CONTAINER + i_objects.erase(obj); + else + ((WorldObject*)obj)->FindMap()->i_objectsToUpdate.erase(obj); + } - // pussywizard: crashfix for corpses - void AddDelayedCorpseAction(Corpse* corpse, uint8 action, uint32 mapId = 0, uint32 instanceId = 0); - void ProcessDelayedCorpseActions(); + //Thread safe + Corpse* GetCorpseForPlayerGUID(uint64 guid); + void RemoveCorpse(Corpse* corpse, bool final = false); + void AddCorpse(Corpse* corpse); + void AddCorpsesToGrid(GridCoord const& gridpair, GridType& grid, Map* map); + Corpse* ConvertCorpseForPlayer(uint64 player_guid, bool insignia = false); - private: - static void _buildChangeObjectForPlayer(WorldObject*, UpdateDataMapType&); - static void _buildPacket(Player*, Object*, UpdateDataMapType&); - void _update(); + //Thread unsafe + void Update(uint32 diff); + void RemoveOldCorpses(); + void UnloadAll(); - typedef std::unordered_map Player2CorpsesMapType; - typedef std::unordered_map::value_type UpdateDataValueType; + // pussywizard: crashfix for corpses + void AddDelayedCorpseAction(Corpse* corpse, uint8 action, uint32 mapId = 0, uint32 instanceId = 0); + void ProcessDelayedCorpseActions(); - std::unordered_set i_objects; - Player2CorpsesMapType i_player2corpse; - std::list i_playerBones; +private: + static void _buildChangeObjectForPlayer(WorldObject*, UpdateDataMapType&); + static void _buildPacket(Player*, Object*, UpdateDataMapType&); + void _update(); - ACE_Thread_Mutex i_objectLock; - ACE_RW_Thread_Mutex i_corpseLock; - std::list i_delayedCorpseActions; - mutable ACE_Thread_Mutex DelayedCorpseLock; + typedef std::unordered_map Player2CorpsesMapType; + typedef std::unordered_map::value_type UpdateDataValueType; + + std::unordered_set i_objects; + Player2CorpsesMapType i_player2corpse; + std::list i_playerBones; + + ACE_Thread_Mutex i_objectLock; + ACE_RW_Thread_Mutex i_corpseLock; + std::list i_delayedCorpseActions; + mutable ACE_Thread_Mutex DelayedCorpseLock; }; #define sObjectAccessor ObjectAccessor::instance() diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index f90b835de..e90a81b6e 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -46,10 +46,17 @@ std::string GetScriptsTableNameByType(ScriptsType type) std::string res = ""; switch (type) { - case SCRIPTS_SPELL: res = "spell_scripts"; break; - case SCRIPTS_EVENT: res = "event_scripts"; break; - case SCRIPTS_WAYPOINT: res = "waypoint_scripts"; break; - default: break; + case SCRIPTS_SPELL: + res = "spell_scripts"; + break; + case SCRIPTS_EVENT: + res = "event_scripts"; + break; + case SCRIPTS_WAYPOINT: + res = "waypoint_scripts"; + break; + default: + break; } return res; } @@ -59,10 +66,17 @@ ScriptMapMap* GetScriptsMapByType(ScriptsType type) ScriptMapMap* res = nullptr; switch (type) { - case SCRIPTS_SPELL: res = &sSpellScripts; break; - case SCRIPTS_EVENT: res = &sEventScripts; break; - case SCRIPTS_WAYPOINT: res = &sWaypointScripts; break; - default: break; + case SCRIPTS_SPELL: + res = &sSpellScripts; + break; + case SCRIPTS_EVENT: + res = &sEventScripts; + break; + case SCRIPTS_WAYPOINT: + res = &sWaypointScripts; + break; + default: + break; } return res; } @@ -72,41 +86,95 @@ std::string GetScriptCommandName(ScriptCommands command) std::string res = ""; switch (command) { - case SCRIPT_COMMAND_TALK: res = "SCRIPT_COMMAND_TALK"; break; - case SCRIPT_COMMAND_EMOTE: res = "SCRIPT_COMMAND_EMOTE"; break; - case SCRIPT_COMMAND_FIELD_SET: res = "SCRIPT_COMMAND_FIELD_SET"; break; - case SCRIPT_COMMAND_MOVE_TO: res = "SCRIPT_COMMAND_MOVE_TO"; break; - case SCRIPT_COMMAND_FLAG_SET: res = "SCRIPT_COMMAND_FLAG_SET"; break; - case SCRIPT_COMMAND_FLAG_REMOVE: res = "SCRIPT_COMMAND_FLAG_REMOVE"; break; - case SCRIPT_COMMAND_TELEPORT_TO: res = "SCRIPT_COMMAND_TELEPORT_TO"; break; - case SCRIPT_COMMAND_QUEST_EXPLORED: res = "SCRIPT_COMMAND_QUEST_EXPLORED"; break; - case SCRIPT_COMMAND_KILL_CREDIT: res = "SCRIPT_COMMAND_KILL_CREDIT"; break; - case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT: res = "SCRIPT_COMMAND_RESPAWN_GAMEOBJECT"; break; - case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE: res = "SCRIPT_COMMAND_TEMP_SUMMON_CREATURE"; break; - case SCRIPT_COMMAND_OPEN_DOOR: res = "SCRIPT_COMMAND_OPEN_DOOR"; break; - case SCRIPT_COMMAND_CLOSE_DOOR: res = "SCRIPT_COMMAND_CLOSE_DOOR"; break; - case SCRIPT_COMMAND_ACTIVATE_OBJECT: res = "SCRIPT_COMMAND_ACTIVATE_OBJECT"; break; - case SCRIPT_COMMAND_REMOVE_AURA: res = "SCRIPT_COMMAND_REMOVE_AURA"; break; - case SCRIPT_COMMAND_CAST_SPELL: res = "SCRIPT_COMMAND_CAST_SPELL"; break; - case SCRIPT_COMMAND_PLAY_SOUND: res = "SCRIPT_COMMAND_PLAY_SOUND"; break; - case SCRIPT_COMMAND_CREATE_ITEM: res = "SCRIPT_COMMAND_CREATE_ITEM"; break; - case SCRIPT_COMMAND_DESPAWN_SELF: res = "SCRIPT_COMMAND_DESPAWN_SELF"; break; - case SCRIPT_COMMAND_LOAD_PATH: res = "SCRIPT_COMMAND_LOAD_PATH"; break; - case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT: res = "SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT"; break; - case SCRIPT_COMMAND_KILL: res = "SCRIPT_COMMAND_KILL"; break; - // AzerothCore only - case SCRIPT_COMMAND_ORIENTATION: res = "SCRIPT_COMMAND_ORIENTATION"; break; - case SCRIPT_COMMAND_EQUIP: res = "SCRIPT_COMMAND_EQUIP"; break; - case SCRIPT_COMMAND_MODEL: res = "SCRIPT_COMMAND_MODEL"; break; - case SCRIPT_COMMAND_CLOSE_GOSSIP: res = "SCRIPT_COMMAND_CLOSE_GOSSIP"; break; - case SCRIPT_COMMAND_PLAYMOVIE: res = "SCRIPT_COMMAND_PLAYMOVIE"; break; - default: - { - char sz[32]; - sprintf(sz, "Unknown command: %d", command); - res = sz; + case SCRIPT_COMMAND_TALK: + res = "SCRIPT_COMMAND_TALK"; break; - } + case SCRIPT_COMMAND_EMOTE: + res = "SCRIPT_COMMAND_EMOTE"; + break; + case SCRIPT_COMMAND_FIELD_SET: + res = "SCRIPT_COMMAND_FIELD_SET"; + break; + case SCRIPT_COMMAND_MOVE_TO: + res = "SCRIPT_COMMAND_MOVE_TO"; + break; + case SCRIPT_COMMAND_FLAG_SET: + res = "SCRIPT_COMMAND_FLAG_SET"; + break; + case SCRIPT_COMMAND_FLAG_REMOVE: + res = "SCRIPT_COMMAND_FLAG_REMOVE"; + break; + case SCRIPT_COMMAND_TELEPORT_TO: + res = "SCRIPT_COMMAND_TELEPORT_TO"; + break; + case SCRIPT_COMMAND_QUEST_EXPLORED: + res = "SCRIPT_COMMAND_QUEST_EXPLORED"; + break; + case SCRIPT_COMMAND_KILL_CREDIT: + res = "SCRIPT_COMMAND_KILL_CREDIT"; + break; + case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT: + res = "SCRIPT_COMMAND_RESPAWN_GAMEOBJECT"; + break; + case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE: + res = "SCRIPT_COMMAND_TEMP_SUMMON_CREATURE"; + break; + case SCRIPT_COMMAND_OPEN_DOOR: + res = "SCRIPT_COMMAND_OPEN_DOOR"; + break; + case SCRIPT_COMMAND_CLOSE_DOOR: + res = "SCRIPT_COMMAND_CLOSE_DOOR"; + break; + case SCRIPT_COMMAND_ACTIVATE_OBJECT: + res = "SCRIPT_COMMAND_ACTIVATE_OBJECT"; + break; + case SCRIPT_COMMAND_REMOVE_AURA: + res = "SCRIPT_COMMAND_REMOVE_AURA"; + break; + case SCRIPT_COMMAND_CAST_SPELL: + res = "SCRIPT_COMMAND_CAST_SPELL"; + break; + case SCRIPT_COMMAND_PLAY_SOUND: + res = "SCRIPT_COMMAND_PLAY_SOUND"; + break; + case SCRIPT_COMMAND_CREATE_ITEM: + res = "SCRIPT_COMMAND_CREATE_ITEM"; + break; + case SCRIPT_COMMAND_DESPAWN_SELF: + res = "SCRIPT_COMMAND_DESPAWN_SELF"; + break; + case SCRIPT_COMMAND_LOAD_PATH: + res = "SCRIPT_COMMAND_LOAD_PATH"; + break; + case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT: + res = "SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT"; + break; + case SCRIPT_COMMAND_KILL: + res = "SCRIPT_COMMAND_KILL"; + break; + // AzerothCore only + case SCRIPT_COMMAND_ORIENTATION: + res = "SCRIPT_COMMAND_ORIENTATION"; + break; + case SCRIPT_COMMAND_EQUIP: + res = "SCRIPT_COMMAND_EQUIP"; + break; + case SCRIPT_COMMAND_MODEL: + res = "SCRIPT_COMMAND_MODEL"; + break; + case SCRIPT_COMMAND_CLOSE_GOSSIP: + res = "SCRIPT_COMMAND_CLOSE_GOSSIP"; + break; + case SCRIPT_COMMAND_PLAYMOVIE: + res = "SCRIPT_COMMAND_PLAYMOVIE"; + break; + default: + { + char sz[32]; + sprintf(sz, "Unknown command: %d", command); + res = sz; + break; + } } return res; } @@ -124,8 +192,8 @@ bool normalizePlayerName(std::string& name) return false; if (name.find(" ") != std::string::npos) - return false; - + return false; + std::wstring tmp; if (!Utf8toWStr(name, tmp)) return false; @@ -265,7 +333,7 @@ ObjectMgr::~ObjectMgr() _cacheTrainerSpellStore.clear(); - for (DungeonEncounterContainer::iterator itr =_dungeonEncounterStore.begin(); itr != _dungeonEncounterStore.end(); ++itr) + for (DungeonEncounterContainer::iterator itr = _dungeonEncounterStore.begin(); itr != _dungeonEncounterStore.end(); ++itr) for (DungeonEncounterList::iterator encounterItr = itr->second.begin(); encounterItr != itr->second.end(); ++encounterItr) delete *encounterItr; @@ -396,19 +464,19 @@ void ObjectMgr::LoadCreatureTemplates() // 0 1 2 3 4 5 6 7 8 QueryResult result = WorldDatabase.Query("SELECT entry, difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, " - // 9 10 11 12 13 14 15 16 17 18 19 20 21 - "modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, faction, npcflag, speed_walk, speed_run, " - // 22 23 24 25 26 27 28 29 30 31 32 33 - "scale, `rank`, mindmg, maxdmg, dmgschool, attackpower, DamageModifier, BaseAttackTime, RangeAttackTime, unit_class, unit_flags, unit_flags2, " - // 34 35 36 37 38 39 40 41 42 43 - "dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, minrangedmg, maxrangedmg, rangedattackpower, type, " - // 44 45 46 47 48 49 50 51 52 53 54 - "type_flags, lootid, pickpocketloot, skinloot, resistance1, resistance2, resistance3, resistance4, resistance5, resistance6, spell1, " - // 55 56 57 58 59 60 61 62 63 64 65 66 67 - "spell2, spell3, spell4, spell5, spell6, spell7, spell8, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, " - // 68 69 70 71 72 73 74 75 76 77 78 - "InhabitType, HoverHeight, HealthModifier, ManaModifier, ArmorModifier, RacialLeader, movementId, RegenHealth, mechanic_immune_mask, flags_extra, ScriptName " - "FROM creature_template;"); + // 9 10 11 12 13 14 15 16 17 18 19 20 21 + "modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, faction, npcflag, speed_walk, speed_run, " + // 22 23 24 25 26 27 28 29 30 31 32 33 + "scale, `rank`, mindmg, maxdmg, dmgschool, attackpower, DamageModifier, BaseAttackTime, RangeAttackTime, unit_class, unit_flags, unit_flags2, " + // 34 35 36 37 38 39 40 41 42 43 + "dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, minrangedmg, maxrangedmg, rangedattackpower, type, " + // 44 45 46 47 48 49 50 51 52 53 54 + "type_flags, lootid, pickpocketloot, skinloot, resistance1, resistance2, resistance3, resistance4, resistance5, resistance6, spell1, " + // 55 56 57 58 59 60 61 62 63 64 65 66 67 + "spell2, spell3, spell4, spell5, spell6, spell7, spell8, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, " + // 68 69 70 71 72 73 74 75 76 77 78 + "InhabitType, HoverHeight, HealthModifier, ManaModifier, ArmorModifier, RacialLeader, movementId, RegenHealth, mechanic_immune_mask, flags_extra, ScriptName " + "FROM creature_template;"); if (!result) { @@ -478,7 +546,7 @@ void ObjectMgr::LoadCreatureTemplates() creatureTemplate.SkinLootId = fields[46].GetUInt32(); for (uint8 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) - creatureTemplate.resistance[i] = fields[47 + i -1].GetInt16(); + creatureTemplate.resistance[i] = fields[47 + i - 1].GetInt16(); for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) creatureTemplate.spells[i] = fields[53 + i].GetUInt32(); @@ -502,8 +570,7 @@ void ObjectMgr::LoadCreatureTemplates() creatureTemplate.ScriptID = GetScriptId(fields[77].GetCString()); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // pussywizard: { @@ -514,7 +581,7 @@ void ObjectMgr::LoadCreatureTemplates() if (max) { _creatureTemplateStoreFast.clear(); - _creatureTemplateStoreFast.resize(max+1, nullptr); + _creatureTemplateStoreFast.resize(max + 1, nullptr); for (CreatureTemplateContainer::iterator itr = _creatureTemplateStore.begin(); itr != _creatureTemplateStore.end(); ++itr) _creatureTemplateStoreFast[itr->first] = &(itr->second); } @@ -596,8 +663,7 @@ void ObjectMgr::LoadCreatureTemplateAddons() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creature template addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -619,7 +685,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (!difficultyInfo) { sLog->outErrorDb("Creature (Entry: %u) has `difficulty_entry_%u`=%u but creature entry %u does not exist.", - cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]); + cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]); continue; } @@ -630,7 +696,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (_difficultyEntries[diff2].find(cInfo->Entry) != _difficultyEntries[diff2].end()) { sLog->outErrorDb("Creature (Entry: %u) is listed as `difficulty_entry_%u` of another creature, but itself lists %u in `difficulty_entry_%u`.", - cInfo->Entry, diff2 + 1, cInfo->DifficultyEntry[diff], diff + 1); + cInfo->Entry, diff2 + 1, cInfo->DifficultyEntry[diff], diff + 1); continue; } @@ -643,7 +709,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (_hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != _hasDifficultyEntries[diff2].end()) { sLog->outErrorDb("Creature (Entry: %u) has `difficulty_entry_%u`=%u but creature entry %u has itself a value in `difficulty_entry_%u`.", - cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1); + cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1); continue; } ok2 = true; @@ -654,19 +720,19 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->expansion > difficultyInfo->expansion) { sLog->outErrorDb("Creature (Entry: %u, expansion %u) has different `expansion` in difficulty %u mode (Entry: %u, expansion %u).", - cInfo->Entry, cInfo->expansion, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->expansion); + cInfo->Entry, cInfo->expansion, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->expansion); } if (cInfo->faction != difficultyInfo->faction) { sLog->outErrorDb("Creature (Entry: %u, faction %u) has different `faction` in difficulty %u mode (Entry: %u, faction %u).", - cInfo->Entry, cInfo->faction, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->faction); + cInfo->Entry, cInfo->faction, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->faction); } if (cInfo->unit_class != difficultyInfo->unit_class) { sLog->outErrorDb("Creature (Entry: %u, class %u) has different `unit_class` in difficulty %u mode (Entry: %u, class %u).", - cInfo->Entry, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class); + cInfo->Entry, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class); continue; } @@ -679,7 +745,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->family != difficultyInfo->family) { sLog->outErrorDb("Creature (Entry: %u, family %u) has different `family` in difficulty %u mode (Entry: %u, family %u).", - cInfo->Entry, cInfo->family, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->family); + cInfo->Entry, cInfo->family, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->family); } if (cInfo->trainer_class != difficultyInfo->trainer_class) @@ -709,13 +775,13 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->type != difficultyInfo->type) { sLog->outErrorDb("Creature (Entry: %u, type %u) has different `type` in difficulty %u mode (Entry: %u, type %u).", - cInfo->Entry, cInfo->type, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->type); + cInfo->Entry, cInfo->type, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->type); } if (!cInfo->VehicleId && difficultyInfo->VehicleId) { sLog->outErrorDb("Creature (Entry: %u, VehicleId %u) has different `VehicleId` in difficulty %u mode (Entry: %u, VehicleId %u).", - cInfo->Entry, cInfo->VehicleId, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->VehicleId); + cInfo->Entry, cInfo->VehicleId, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->VehicleId); } // Xinef: check dmg school @@ -727,14 +793,14 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (!difficultyInfo->AIName.empty()) { sLog->outErrorDb("Creature (Entry: %u) lists difficulty %u mode entry %u with `AIName` filled in. `AIName` of difficulty 0 mode creature is always used instead.", - cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (difficultyInfo->ScriptID) { sLog->outErrorDb("Creature (Entry: %u) lists difficulty %u mode entry %u with `ScriptName` filled in. `ScriptName` of difficulty 0 mode creature is always used instead.", - cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } @@ -829,7 +895,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) } } - if (!cInfo->unit_class || ((1 << (cInfo->unit_class-1)) & CLASSMASK_ALL_CREATURES) == 0) + if (!cInfo->unit_class || ((1 << (cInfo->unit_class - 1)) & CLASSMASK_ALL_CREATURES) == 0) { sLog->outErrorDb("Creature (Entry: %u) has invalid unit_class (%u) in creature_template. Set to 1 (UNIT_CLASS_WARRIOR).", cInfo->Entry, cInfo->unit_class); const_cast(cInfo)->unit_class = UNIT_CLASS_WARRIOR; @@ -892,8 +958,8 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) VehicleEntry const* vehId = sVehicleStore.LookupEntry(cInfo->VehicleId); if (!vehId) { - sLog->outErrorDb("Creature (Entry: %u) has a non-existing VehicleId (%u). This *WILL* cause the client to freeze!", cInfo->Entry, cInfo->VehicleId); - const_cast(cInfo)->VehicleId = 0; + sLog->outErrorDb("Creature (Entry: %u) has a non-existing VehicleId (%u). This *WILL* cause the client to freeze!", cInfo->Entry, cInfo->VehicleId); + const_cast(cInfo)->VehicleId = 0; } } @@ -908,7 +974,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) { if (cInfo->spells[j] && !sSpellMgr->GetSpellInfo(cInfo->spells[j])) { - sLog->outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0.", cInfo->Entry, j+1, cInfo->spells[j]); + sLog->outErrorDb("Creature (Entry: %u) has non-existing Spell%d (%u), set to 0.", cInfo->Entry, j + 1, cInfo->spells[j]); const_cast(cInfo)->spells[j] = 0; } } @@ -1016,8 +1082,7 @@ void ObjectMgr::LoadCreatureAddons() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creature addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1069,8 +1134,7 @@ void ObjectMgr::LoadGameObjectAddons() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u gameobject addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1179,30 +1243,29 @@ void ObjectMgr::LoadEquipmentTemplates() if (!item) { sLog->outErrorDb("Unknown item (ID=%u) in creature_equip_template.ItemID%u for CreatureID = %u and ID = %u, forced to 0.", - equipmentInfo.ItemEntry[i], i+1, entry, id); + equipmentInfo.ItemEntry[i], i + 1, entry, id); equipmentInfo.ItemEntry[i] = 0; continue; } if (item->InventoryType != INVTYPE_WEAPON && - item->InventoryType != INVTYPE_SHIELD && - item->InventoryType != INVTYPE_RANGED && - item->InventoryType != INVTYPE_2HWEAPON && - item->InventoryType != INVTYPE_WEAPONMAINHAND && - item->InventoryType != INVTYPE_WEAPONOFFHAND && - item->InventoryType != INVTYPE_HOLDABLE && - item->InventoryType != INVTYPE_THROWN && - item->InventoryType != INVTYPE_RANGEDRIGHT) + item->InventoryType != INVTYPE_SHIELD && + item->InventoryType != INVTYPE_RANGED && + item->InventoryType != INVTYPE_2HWEAPON && + item->InventoryType != INVTYPE_WEAPONMAINHAND && + item->InventoryType != INVTYPE_WEAPONOFFHAND && + item->InventoryType != INVTYPE_HOLDABLE && + item->InventoryType != INVTYPE_THROWN && + item->InventoryType != INVTYPE_RANGEDRIGHT) { sLog->outErrorDb("Item (ID=%u) in creature_equip_template.ItemID%u for CreatureID = %u and ID = %u is not equipable in a hand, forced to 0.", - equipmentInfo.ItemEntry[i], i+1, entry, id); + equipmentInfo.ItemEntry[i], i + 1, entry, id); equipmentInfo.ItemEntry[i] = 0; } } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u equipment templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1319,8 +1382,7 @@ void ObjectMgr::LoadCreatureModelInfo() modelInfo.combat_reach = DEFAULT_COMBAT_REACH; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creature model based info in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1354,159 +1416,158 @@ void ObjectMgr::LoadLinkedRespawn() switch (linkType) { case CREATURE_TO_CREATURE: - { - const CreatureData* slave = GetCreatureData(guidLow); - if (!slave) { - sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", guidLow); - error = true; + const CreatureData* slave = GetCreatureData(guidLow); + if (!slave) + { + sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", guidLow); + error = true; + break; + } + + const CreatureData* master = GetCreatureData(linkedGuidLow); + if (!master) + { + sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", linkedGuidLow); + error = true; + break; + } + + const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) + { + sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); + error = true; + break; + } + + if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) + { + sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); + error = true; + break; + } + + guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_UNIT); + linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_UNIT); break; } - - const CreatureData* master = GetCreatureData(linkedGuidLow); - if (!master) - { - sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", linkedGuidLow); - error = true; - break; - } - - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); - if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) - { - sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); - error = true; - break; - } - - if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) - { - sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); - error = true; - break; - } - - guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_UNIT); - linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_UNIT); - break; - } case CREATURE_TO_GO: - { - const CreatureData* slave = GetCreatureData(guidLow); - if (!slave) { - sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", guidLow); - error = true; + const CreatureData* slave = GetCreatureData(guidLow); + if (!slave) + { + sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", guidLow); + error = true; + break; + } + + const GameObjectData* master = GetGOData(linkedGuidLow); + if (!master) + { + sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", linkedGuidLow); + error = true; + break; + } + + const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) + { + sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); + error = true; + break; + } + + if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) + { + sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); + error = true; + break; + } + + guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_UNIT); + linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_GAMEOBJECT); break; } - - const GameObjectData* master = GetGOData(linkedGuidLow); - if (!master) - { - sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", linkedGuidLow); - error = true; - break; - } - - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); - if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) - { - sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); - error = true; - break; - } - - if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) - { - sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); - error = true; - break; - } - - guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_UNIT); - linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_GAMEOBJECT); - break; - } case GO_TO_GO: - { - const GameObjectData* slave = GetGOData(guidLow); - if (!slave) { - sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", guidLow); - error = true; + const GameObjectData* slave = GetGOData(guidLow); + if (!slave) + { + sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", guidLow); + error = true; + break; + } + + const GameObjectData* master = GetGOData(linkedGuidLow); + if (!master) + { + sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", linkedGuidLow); + error = true; + break; + } + + const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) + { + sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); + error = true; + break; + } + + if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) + { + sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); + error = true; + break; + } + + guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_GAMEOBJECT); + linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_GAMEOBJECT); break; } - - const GameObjectData* master = GetGOData(linkedGuidLow); - if (!master) - { - sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", linkedGuidLow); - error = true; - break; - } - - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); - if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) - { - sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); - error = true; - break; - } - - if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) - { - sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); - error = true; - break; - } - - guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_GAMEOBJECT); - linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_GAMEOBJECT); - break; - } case GO_TO_CREATURE: - { - const GameObjectData* slave = GetGOData(guidLow); - if (!slave) { - sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", guidLow); - error = true; + const GameObjectData* slave = GetGOData(guidLow); + if (!slave) + { + sLog->outErrorDb("Couldn't get gameobject data for GUIDLow %u", guidLow); + error = true; + break; + } + + const CreatureData* master = GetCreatureData(linkedGuidLow); + if (!master) + { + sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", linkedGuidLow); + error = true; + break; + } + + const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) + { + sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); + error = true; + break; + } + + if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) + { + sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); + error = true; + break; + } + + guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_GAMEOBJECT); + linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_UNIT); break; } - - const CreatureData* master = GetCreatureData(linkedGuidLow); - if (!master) - { - sLog->outErrorDb("Couldn't get creature data for GUIDLow %u", linkedGuidLow); - error = true; - break; - } - - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); - if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) - { - sLog->outErrorDb("Creature '%u' linking to '%u' on an unpermitted map.", guidLow, linkedGuidLow); - error = true; - break; - } - - if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) - { - sLog->outErrorDb("LinkedRespawn: Creature '%u' linking to '%u' with not corresponding spawnMask", guidLow, linkedGuidLow); - error = true; - break; - } - - guid = MAKE_NEW_GUID(guidLow, slave->id, HIGHGUID_GAMEOBJECT); - linkedGuid = MAKE_NEW_GUID(linkedGuidLow, master->id, HIGHGUID_UNIT); - break; - } } if (!error) _linkedRespawnStore[guid] = linkedGuid; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded " UI64FMTD " linked respawns in %u ms", uint64(_linkedRespawnStore.size()), GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -1523,7 +1584,7 @@ bool ObjectMgr::SetCreatureLinkedRespawn(uint32 guidLow, uint32 linkedGuidLow) if (!linkedGuidLow) // we're removing the linking { _linkedRespawnStore.erase(guid); - PreparedStatement *stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CRELINKED_RESPAWN); + PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CRELINKED_RESPAWN); stmt->setUInt32(0, guidLow); WorldDatabase.Execute(stmt); return true; @@ -1552,7 +1613,7 @@ bool ObjectMgr::SetCreatureLinkedRespawn(uint32 guidLow, uint32 linkedGuidLow) uint64 linkedGuid = MAKE_NEW_GUID(linkedGuidLow, slave->id, HIGHGUID_UNIT); _linkedRespawnStore[guid] = linkedGuid; - PreparedStatement *stmt = WorldDatabase.GetPreparedStatement(WORLD_REP_CREATURE_LINKED_RESPAWN); + PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_REP_CREATURE_LINKED_RESPAWN); stmt->setUInt32(0, guidLow); stmt->setUInt32(1, linkedGuidLow); WorldDatabase.Execute(stmt); @@ -1651,11 +1712,11 @@ void ObjectMgr::LoadCreatures() // 0 1 2 3 4 5 6 7 8 9 10 QueryResult result = WorldDatabase.Query("SELECT creature.guid, id, map, modelid, equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, wander_distance, " - // 11 12 13 14 15 16 17 18 19 20 21 - "currentwaypoint, curhealth, curmana, MovementType, spawnMask, phaseMask, eventEntry, pool_entry, creature.npcflag, creature.unit_flags, creature.dynamicflags " - "FROM creature " - "LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid " - "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid"); + // 11 12 13 14 15 16 17 18 19 20 21 + "currentwaypoint, curhealth, curmana, MovementType, spawnMask, phaseMask, eventEntry, pool_entry, creature.npcflag, creature.unit_flags, creature.dynamicflags " + "FROM creature " + "LEFT OUTER JOIN game_event_creature ON creature.guid = game_event_creature.guid " + "LEFT OUTER JOIN pool_creature ON creature.guid = pool_creature.guid"); if (!result) { @@ -1719,8 +1780,8 @@ void ObjectMgr::LoadCreatures() } // pussywizard: 7 days means no reaspawn, so set it to 14 days, because manual id reset may be late - if (mapEntry->IsRaid() && data.spawntimesecs >= 7*DAY && data.spawntimesecs < 14*DAY) - data.spawntimesecs = 14*DAY; + if (mapEntry->IsRaid() && data.spawntimesecs >= 7 * DAY && data.spawntimesecs < 14 * DAY) + data.spawntimesecs = 14 * DAY; // Skip spawnMask check for transport maps if (!_transportMaps.count(data.mapid) && data.spawnMask & ~spawnMasks[data.mapid]) @@ -1732,7 +1793,7 @@ void ObjectMgr::LoadCreatures() if (_difficultyEntries[diff].find(data.id) != _difficultyEntries[diff].end()) { sLog->outErrorDb("Table `creature` have creature (GUID: %u) that listed as difficulty %u template (entry: %u) in `creature_template`, skipped.", - guid, diff + 1, data.id); + guid, diff + 1, data.id); ok = false; } } @@ -1983,10 +2044,10 @@ void ObjectMgr::LoadGameobjects() // 0 1 2 3 4 5 6 QueryResult result = WorldDatabase.Query("SELECT gameobject.guid, id, map, position_x, position_y, position_z, orientation, " - // 7 8 9 10 11 12 13 14 15 16 17 - "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, eventEntry, pool_entry " - "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid " - "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid"); + // 7 8 9 10 11 12 13 14 15 16 17 + "rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnMask, phaseMask, eventEntry, pool_entry " + "FROM gameobject LEFT OUTER JOIN game_event_gameobject ON gameobject.guid = game_event_gameobject.guid " + "LEFT OUTER JOIN pool_gameobject ON gameobject.guid = pool_gameobject.guid"); if (!result) { @@ -2180,7 +2241,7 @@ uint64 ObjectMgr::GetPlayerGUIDByName(std::string const& name) const return 0; } -bool ObjectMgr::GetPlayerNameByGUID(uint64 guid, std::string &name) const +bool ObjectMgr::GetPlayerNameByGUID(uint64 guid, std::string& name) const { // Get data from global storage if (GlobalPlayerData const* playerData = sWorld->GetGlobalPlayerData(GUID_LOPART(guid))) @@ -2258,36 +2319,36 @@ void ObjectMgr::LoadItemTemplates() // 0 1 2 3 4 5 6 7 8 9 10 11 12 QueryResult result = WorldDatabase.Query("SELECT entry, class, subclass, SoundOverrideSubclass, name, displayid, Quality, Flags, FlagsExtra, BuyCount, BuyPrice, SellPrice, InventoryType, " - // 13 14 15 16 17 18 19 20 - "AllowableClass, AllowableRace, ItemLevel, RequiredLevel, RequiredSkill, RequiredSkillRank, requiredspell, requiredhonorrank, " - // 21 22 23 24 25 26 27 28 - "RequiredCityRank, RequiredReputationFaction, RequiredReputationRank, maxcount, stackable, ContainerSlots, StatsCount, stat_type1, " - // 29 30 31 32 33 34 35 36 37 38 - "stat_value1, stat_type2, stat_value2, stat_type3, stat_value3, stat_type4, stat_value4, stat_type5, stat_value5, stat_type6, " - // 39 40 41 42 43 44 45 46 47 - "stat_value6, stat_type7, stat_value7, stat_type8, stat_value8, stat_type9, stat_value9, stat_type10, stat_value10, " - // 48 49 50 51 52 53 54 55 56 57 58 - "ScalingStatDistribution, ScalingStatValue, dmg_min1, dmg_max1, dmg_type1, dmg_min2, dmg_max2, dmg_type2, armor, holy_res, fire_res, " - // 59 60 61 62 63 64 65 66 67 68 - "nature_res, frost_res, shadow_res, arcane_res, delay, ammo_type, RangedModRange, spellid_1, spelltrigger_1, spellcharges_1, " - // 69 70 71 72 73 74 75 - "spellppmRate_1, spellcooldown_1, spellcategory_1, spellcategorycooldown_1, spellid_2, spelltrigger_2, spellcharges_2, " - // 76 77 78 79 80 81 82 - "spellppmRate_2, spellcooldown_2, spellcategory_2, spellcategorycooldown_2, spellid_3, spelltrigger_3, spellcharges_3, " - // 83 84 85 86 87 88 89 - "spellppmRate_3, spellcooldown_3, spellcategory_3, spellcategorycooldown_3, spellid_4, spelltrigger_4, spellcharges_4, " - // 90 91 92 93 94 95 96 - "spellppmRate_4, spellcooldown_4, spellcategory_4, spellcategorycooldown_4, spellid_5, spelltrigger_5, spellcharges_5, " - // 97 98 99 100 101 102 103 104 105 - "spellppmRate_5, spellcooldown_5, spellcategory_5, spellcategorycooldown_5, bonding, description, PageText, LanguageID, PageMaterial, " - // 106 107 108 109 110 111 112 113 114 115 116 117 - "startquest, lockid, Material, sheath, RandomProperty, RandomSuffix, block, itemset, MaxDurability, area, Map, BagFamily, " - // 118 119 120 121 122 123 124 125 - "TotemCategory, socketColor_1, socketContent_1, socketColor_2, socketContent_2, socketColor_3, socketContent_3, socketBonus, " - // 126 127 128 129 130 131 132 133 - "GemProperties, RequiredDisenchantSkill, ArmorDamageModifier, duration, ItemLimitCategory, HolidayId, ScriptName, DisenchantID, " - // 134 135 136 - "FoodType, minMoneyLoot, maxMoneyLoot, flagsCustom FROM item_template"); + // 13 14 15 16 17 18 19 20 + "AllowableClass, AllowableRace, ItemLevel, RequiredLevel, RequiredSkill, RequiredSkillRank, requiredspell, requiredhonorrank, " + // 21 22 23 24 25 26 27 28 + "RequiredCityRank, RequiredReputationFaction, RequiredReputationRank, maxcount, stackable, ContainerSlots, StatsCount, stat_type1, " + // 29 30 31 32 33 34 35 36 37 38 + "stat_value1, stat_type2, stat_value2, stat_type3, stat_value3, stat_type4, stat_value4, stat_type5, stat_value5, stat_type6, " + // 39 40 41 42 43 44 45 46 47 + "stat_value6, stat_type7, stat_value7, stat_type8, stat_value8, stat_type9, stat_value9, stat_type10, stat_value10, " + // 48 49 50 51 52 53 54 55 56 57 58 + "ScalingStatDistribution, ScalingStatValue, dmg_min1, dmg_max1, dmg_type1, dmg_min2, dmg_max2, dmg_type2, armor, holy_res, fire_res, " + // 59 60 61 62 63 64 65 66 67 68 + "nature_res, frost_res, shadow_res, arcane_res, delay, ammo_type, RangedModRange, spellid_1, spelltrigger_1, spellcharges_1, " + // 69 70 71 72 73 74 75 + "spellppmRate_1, spellcooldown_1, spellcategory_1, spellcategorycooldown_1, spellid_2, spelltrigger_2, spellcharges_2, " + // 76 77 78 79 80 81 82 + "spellppmRate_2, spellcooldown_2, spellcategory_2, spellcategorycooldown_2, spellid_3, spelltrigger_3, spellcharges_3, " + // 83 84 85 86 87 88 89 + "spellppmRate_3, spellcooldown_3, spellcategory_3, spellcategorycooldown_3, spellid_4, spelltrigger_4, spellcharges_4, " + // 90 91 92 93 94 95 96 + "spellppmRate_4, spellcooldown_4, spellcategory_4, spellcategorycooldown_4, spellid_5, spelltrigger_5, spellcharges_5, " + // 97 98 99 100 101 102 103 104 105 + "spellppmRate_5, spellcooldown_5, spellcategory_5, spellcategorycooldown_5, bonding, description, PageText, LanguageID, PageMaterial, " + // 106 107 108 109 110 111 112 113 114 115 116 117 + "startquest, lockid, Material, sheath, RandomProperty, RandomSuffix, block, itemset, MaxDurability, area, Map, BagFamily, " + // 118 119 120 121 122 123 124 125 + "TotemCategory, socketColor_1, socketContent_1, socketColor_2, socketContent_2, socketColor_3, socketContent_3, socketBonus, " + // 126 127 128 129 130 131 132 133 + "GemProperties, RequiredDisenchantSkill, ArmorDamageModifier, duration, ItemLimitCategory, HolidayId, ScriptName, DisenchantID, " + // 134 135 136 + "FoodType, minMoneyLoot, maxMoneyLoot, flagsCustom FROM item_template"); if (!result) { @@ -2338,8 +2399,8 @@ void ObjectMgr::LoadItemTemplates() for (uint8 i = 0; i < itemTemplate.StatsCount; ++i) { - itemTemplate.ItemStat[i].ItemStatType = uint32(fields[28 + i*2].GetUInt8()); - itemTemplate.ItemStat[i].ItemStatValue = int32(fields[29 + i*2].GetInt16()); + itemTemplate.ItemStat[i].ItemStatType = uint32(fields[28 + i * 2].GetUInt8()); + itemTemplate.ItemStat[i].ItemStatValue = int32(fields[29 + i * 2].GetInt16()); } itemTemplate.ScalingStatDistribution = uint32(fields[48].GetUInt16()); @@ -2347,9 +2408,9 @@ void ObjectMgr::LoadItemTemplates() for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) { - itemTemplate.Damage[i].DamageMin = fields[50 + i*3].GetFloat(); - itemTemplate.Damage[i].DamageMax = fields[51 + i*3].GetFloat(); - itemTemplate.Damage[i].DamageType = uint32(fields[52 + i*3].GetUInt8()); + itemTemplate.Damage[i].DamageMin = fields[50 + i * 3].GetFloat(); + itemTemplate.Damage[i].DamageMax = fields[51 + i * 3].GetFloat(); + itemTemplate.Damage[i].DamageType = uint32(fields[52 + i * 3].GetUInt8()); } itemTemplate.Armor = uint32(fields[56].GetUInt16()); @@ -2365,13 +2426,13 @@ void ObjectMgr::LoadItemTemplates() for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { - itemTemplate.Spells[i].SpellId = fields[66 + i*7 ].GetInt32(); - itemTemplate.Spells[i].SpellTrigger = uint32(fields[67 + i*7].GetUInt8()); - itemTemplate.Spells[i].SpellCharges = int32(fields[68 + i*7].GetInt16()); - itemTemplate.Spells[i].SpellPPMRate = fields[69 + i*7].GetFloat(); - itemTemplate.Spells[i].SpellCooldown = fields[70 + i*7].GetInt32(); - itemTemplate.Spells[i].SpellCategory = uint32(fields[71 + i*7].GetUInt16()); - itemTemplate.Spells[i].SpellCategoryCooldown = fields[72 + i*7].GetInt32(); + itemTemplate.Spells[i].SpellId = fields[66 + i * 7 ].GetInt32(); + itemTemplate.Spells[i].SpellTrigger = uint32(fields[67 + i * 7].GetUInt8()); + itemTemplate.Spells[i].SpellCharges = int32(fields[68 + i * 7].GetInt16()); + itemTemplate.Spells[i].SpellPPMRate = fields[69 + i * 7].GetFloat(); + itemTemplate.Spells[i].SpellCooldown = fields[70 + i * 7].GetInt32(); + itemTemplate.Spells[i].SpellCategory = uint32(fields[71 + i * 7].GetUInt16()); + itemTemplate.Spells[i].SpellCategoryCooldown = fields[72 + i * 7].GetInt32(); } itemTemplate.Bonding = uint32(fields[101].GetUInt8()); @@ -2395,8 +2456,8 @@ void ObjectMgr::LoadItemTemplates() for (uint8 i = 0; i < MAX_ITEM_PROTO_SOCKETS; ++i) { - itemTemplate.Socket[i].Color = uint32(fields[119 + i*2].GetUInt8()); - itemTemplate.Socket[i].Content = fields[120 + i*2].GetUInt32(); + itemTemplate.Socket[i].Color = uint32(fields[119 + i * 2].GetUInt8()); + itemTemplate.Socket[i].Content = fields[120 + i * 2].GetUInt32(); } itemTemplate.socketBonus = fields[125].GetUInt32(); @@ -2437,18 +2498,18 @@ void ObjectMgr::LoadItemTemplates() if (FactionEntry const* faction = sFactionStore.LookupEntry(HORDE)) if ((itemTemplate.AllowableRace & faction->BaseRepRaceMask[0]) == 0) sLog->outErrorDb("Item (Entry: %u) has value (%u) in `AllowableRace` races, not compatible with ITEM_FLAGS_EXTRA_HORDE_ONLY (%u) in Flags field, item cannot be equipped or used by these races.", - entry, itemTemplate.AllowableRace, ITEM_FLAGS_EXTRA_HORDE_ONLY); + entry, itemTemplate.AllowableRace, ITEM_FLAGS_EXTRA_HORDE_ONLY); if (itemTemplate.Flags2 & ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) sLog->outErrorDb("Item (Entry: %u) has value (%u) in `Flags2` flags (ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) and ITEM_FLAGS_EXTRA_HORDE_ONLY (%u) in Flags field, this is a wrong combination.", - entry, ITEM_FLAGS_EXTRA_ALLIANCE_ONLY, ITEM_FLAGS_EXTRA_HORDE_ONLY); + entry, ITEM_FLAGS_EXTRA_ALLIANCE_ONLY, ITEM_FLAGS_EXTRA_HORDE_ONLY); } else if (itemTemplate.Flags2 & ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) { if (FactionEntry const* faction = sFactionStore.LookupEntry(ALLIANCE)) if ((itemTemplate.AllowableRace & faction->BaseRepRaceMask[0]) == 0) sLog->outErrorDb("Item (Entry: %u) has value (%u) in `AllowableRace` races, not compatible with ITEM_FLAGS_EXTRA_ALLIANCE_ONLY (%u) in Flags field, item cannot be equipped or used by these races.", - entry, itemTemplate.AllowableRace, ITEM_FLAGS_EXTRA_ALLIANCE_ONLY); + entry, itemTemplate.AllowableRace, ITEM_FLAGS_EXTRA_ALLIANCE_ONLY); } if (itemTemplate.BuyCount <= 0) @@ -2547,7 +2608,7 @@ void ObjectMgr::LoadItemTemplates() // for ItemStatValue != 0 if (itemTemplate.ItemStat[j].ItemStatValue && itemTemplate.ItemStat[j].ItemStatType >= MAX_ITEM_MOD) { - sLog->outErrorDb("Item (Entry: %u) has wrong (non-existing?) stat_type%d (%u)", entry, j+1, itemTemplate.ItemStat[j].ItemStatType); + sLog->outErrorDb("Item (Entry: %u) has wrong (non-existing?) stat_type%d (%u)", entry, j + 1, itemTemplate.ItemStat[j].ItemStatType); itemTemplate.ItemStat[j].ItemStatType = 0; } @@ -2555,7 +2616,7 @@ void ObjectMgr::LoadItemTemplates() { case ITEM_MOD_SPELL_HEALING_DONE: case ITEM_MOD_SPELL_DAMAGE_DONE: - sLog->outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)", entry, j+1, itemTemplate.ItemStat[j].ItemStatType); + sLog->outErrorDb("Item (Entry: %u) has deprecated stat_type%d (%u)", entry, j + 1, itemTemplate.ItemStat[j].ItemStatType); break; default: break; @@ -2566,7 +2627,7 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Damage[j].DamageType >= MAX_SPELL_SCHOOL) { - sLog->outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)", entry, j+1, itemTemplate.Damage[j].DamageType); + sLog->outErrorDb("Item (Entry: %u) has wrong dmg_type%d (%u)", entry, j + 1, itemTemplate.Damage[j].DamageType); itemTemplate.Damage[j].DamageType = 0; } } @@ -2577,7 +2638,7 @@ void ObjectMgr::LoadItemTemplates() // spell_1 if (itemTemplate.Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) { - sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format", entry, 0+1, itemTemplate.Spells[0].SpellTrigger); + sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format", entry, 0 + 1, itemTemplate.Spells[0].SpellTrigger); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; itemTemplate.Spells[1].SpellId = 0; @@ -2587,14 +2648,14 @@ void ObjectMgr::LoadItemTemplates() // spell_2 have learning spell if (itemTemplate.Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID) { - sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format.", entry, 1+1, itemTemplate.Spells[1].SpellTrigger); + sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u) for special learning format.", entry, 1 + 1, itemTemplate.Spells[1].SpellTrigger); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } else if (!itemTemplate.Spells[1].SpellId) { - sLog->outErrorDb("Item (Entry: %u) does not have an expected spell in spellid_%d in special learning format.", entry, 1+1); + sLog->outErrorDb("Item (Entry: %u) does not have an expected spell in spellid_%d in special learning format.", entry, 1 + 1); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } @@ -2603,7 +2664,7 @@ void ObjectMgr::LoadItemTemplates() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itemTemplate.Spells[1].SpellId); if (!spellInfo && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, itemTemplate.Spells[1].SpellId, nullptr)) { - sLog->outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%d)", entry, 1+1, itemTemplate.Spells[1].SpellId); + sLog->outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%d)", entry, 1 + 1, itemTemplate.Spells[1].SpellId); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; @@ -2611,7 +2672,7 @@ void ObjectMgr::LoadItemTemplates() // allowed only in special format else if ((itemTemplate.Spells[1].SpellId == 483) || (itemTemplate.Spells[1].SpellId == 55884)) { - sLog->outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%d)", entry, 1+1, itemTemplate.Spells[1].SpellId); + sLog->outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%d)", entry, 1 + 1, itemTemplate.Spells[1].SpellId); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; @@ -2623,13 +2684,13 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) { - sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)", entry, j+1, itemTemplate.Spells[j].SpellTrigger); + sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)", entry, j + 1, itemTemplate.Spells[j].SpellTrigger); itemTemplate.Spells[j].SpellId = 0; itemTemplate.Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } else if (itemTemplate.Spells[j].SpellId != 0) { - sLog->outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%d) for learning special format", entry, j+1, itemTemplate.Spells[j].SpellId); + sLog->outErrorDb("Item (Entry: %u) has wrong spell in spellid_%d (%d) for learning special format", entry, j + 1, itemTemplate.Spells[j].SpellId); itemTemplate.Spells[j].SpellId = 0; } } @@ -2641,7 +2702,7 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || itemTemplate.Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID) { - sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)", entry, j+1, itemTemplate.Spells[j].SpellTrigger); + sLog->outErrorDb("Item (Entry: %u) has wrong item spell trigger value in spelltrigger_%d (%u)", entry, j + 1, itemTemplate.Spells[j].SpellTrigger); itemTemplate.Spells[j].SpellId = 0; itemTemplate.Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } @@ -2651,13 +2712,13 @@ void ObjectMgr::LoadItemTemplates() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itemTemplate.Spells[j].SpellId); if (!spellInfo && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, itemTemplate.Spells[j].SpellId, nullptr)) { - sLog->outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%d)", entry, j+1, itemTemplate.Spells[j].SpellId); + sLog->outErrorDb("Item (Entry: %u) has wrong (not existing) spell in spellid_%d (%d)", entry, j + 1, itemTemplate.Spells[j].SpellId); itemTemplate.Spells[j].SpellId = 0; } // allowed only in special format else if ((itemTemplate.Spells[j].SpellId == 483) || (itemTemplate.Spells[j].SpellId == 55884)) { - sLog->outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%d)", entry, j+1, itemTemplate.Spells[j].SpellId); + sLog->outErrorDb("Item (Entry: %u) has broken spell in spellid_%d (%d)", entry, j + 1, itemTemplate.Spells[j].SpellId); itemTemplate.Spells[j].SpellId = 0; } } @@ -2713,13 +2774,13 @@ void ObjectMgr::LoadItemTemplates() if (itemTemplate.BagFamily) { // check bits - for (uint32 j = 0; j < sizeof(itemTemplate.BagFamily)*8; ++j) + for (uint32 j = 0; j < sizeof(itemTemplate.BagFamily) * 8; ++j) { uint32 mask = 1 << j; if ((itemTemplate.BagFamily & mask) == 0) continue; - ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j+1); + ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j + 1); if (!bf) { sLog->outErrorDb("Item (Entry: %u) has bag family bit set not listed in ItemBagFamily.dbc, remove bit", entry); @@ -2746,7 +2807,7 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Socket[j].Color && (itemTemplate.Socket[j].Color & SOCKET_COLOR_ALL) != itemTemplate.Socket[j].Color) { - sLog->outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)", entry, j+1, itemTemplate.Socket[j].Color); + sLog->outErrorDb("Item (Entry: %u) has wrong socketColor_%d (%u)", entry, j + 1, itemTemplate.Socket[j].Color); itemTemplate.Socket[j].Color = 0; } } @@ -2794,8 +2855,7 @@ void ObjectMgr::LoadItemTemplates() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // pussywizard: { @@ -2806,7 +2866,7 @@ void ObjectMgr::LoadItemTemplates() if (max) { _itemTemplateStoreFast.clear(); - _itemTemplateStoreFast.resize(max+1, nullptr); + _itemTemplateStoreFast.resize(max + 1, nullptr); for (ItemTemplateContainer::iterator itr = _itemTemplateStore.begin(); itr != _itemTemplateStore.end(); ++itr) _itemTemplateStoreFast[itr->first] = &(itr->second); } @@ -2922,7 +2982,7 @@ void ObjectMgr::LoadItemSetNames() continue; } - ItemSetNameEntry &data = _itemSetNameStore[entry]; + ItemSetNameEntry& data = _itemSetNameStore[entry]; data.name = fields[1].GetString(); uint32 invType = fields[2].GetUInt8(); @@ -2948,7 +3008,7 @@ void ObjectMgr::LoadItemSetNames() if (pProto) { sLog->outErrorDb("Item set part (Entry: %u) does not have entry in `item_set_names`, adding data from `item_template`.", entry); - ItemSetNameEntry &data = _itemSetNameStore[entry]; + ItemSetNameEntry& data = _itemSetNameStore[entry]; data.name = pProto->Name1; data.InventoryType = pProto->InventoryType; ++count; @@ -2989,7 +3049,7 @@ void ObjectMgr::LoadVehicleTemplateAccessories() int8 uiSeat = int8(fields[2].GetInt8()); bool bMinion = fields[3].GetBool(); uint8 uiSummonType = fields[4].GetUInt8(); - uint32 uiSummonTimer= fields[5].GetUInt32(); + uint32 uiSummonTimer = fields[5].GetUInt32(); if (!sObjectMgr->GetCreatureTemplate(uiEntry)) { @@ -3012,8 +3072,7 @@ void ObjectMgr::LoadVehicleTemplateAccessories() _vehicleTemplateAccessoryStore[uiEntry].push_back(VehicleAccessory(uiAccessory, uiSeat, bMinion, uiSummonType, uiSummonTimer)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u Vehicle Template Accessories in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -3046,7 +3105,7 @@ void ObjectMgr::LoadVehicleAccessories() int8 uiSeat = int8(fields[2].GetInt16()); bool bMinion = fields[3].GetBool(); uint8 uiSummonType = fields[4].GetUInt8(); - uint32 uiSummonTimer= fields[5].GetUInt32(); + uint32 uiSummonTimer = fields[5].GetUInt32(); if (!sObjectMgr->GetCreatureTemplate(uiAccessory)) { @@ -3057,8 +3116,7 @@ void ObjectMgr::LoadVehicleAccessories() _vehicleAccessoryStore[uiGUID].push_back(VehicleAccessory(uiAccessory, uiSeat, bMinion, uiSummonType, uiSummonTimer)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u Vehicle Accessories in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -3117,21 +3175,20 @@ void ObjectMgr::LoadPetLevelInfo() pInfoMapEntry = new PetLevelInfo[sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)]; // data for level 1 stored in [0] array element, ... - PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level-1]; + PetLevelInfo* pLevelInfo = &pInfoMapEntry[current_level - 1]; pLevelInfo->health = fields[2].GetUInt16(); pLevelInfo->mana = fields[3].GetUInt16(); pLevelInfo->armor = fields[9].GetUInt32(); - pLevelInfo->min_dmg= fields[10].GetUInt16(); - pLevelInfo->max_dmg= fields[11].GetUInt16(); + pLevelInfo->min_dmg = fields[10].GetUInt16(); + pLevelInfo->max_dmg = fields[11].GetUInt16(); for (int i = 0; i < MAX_STATS; i++) { - pLevelInfo->stats[i] = fields[i+4].GetUInt16(); + pLevelInfo->stats[i] = fields[i + 4].GetUInt16(); } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // Fill gaps and check integrity for (PetLevelInfoContainer::iterator itr = _petInfoStore.begin(); itr != _petInfoStore.end(); ++itr) @@ -3169,7 +3226,7 @@ PetLevelInfo const* ObjectMgr::GetPetLevelInfo(uint32 creature_id, uint8 level) if (itr == _petInfoStore.end()) return nullptr; - return &itr->second[level-1]; // data for level 1 stored in [0] array element, ... + return &itr->second[level - 1]; // data for level 1 stored in [0] array element, ... } void ObjectMgr::PlayerCreateInfoAddItemHelper(uint32 race_, uint32 class_, uint32 itemId, int32 count) @@ -3287,8 +3344,7 @@ void ObjectMgr::LoadPlayerInfo() _playerInfo[current_race][current_class] = info; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u player create definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -3358,8 +3414,7 @@ void ObjectMgr::LoadPlayerInfo() PlayerCreateInfoAddItemHelper(current_race, current_class, item_id, amount); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u custom player create items in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -3422,8 +3477,7 @@ void ObjectMgr::LoadPlayerInfo() } } } - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u player create spells in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -3468,8 +3522,7 @@ void ObjectMgr::LoadPlayerInfo() info->action.push_back(PlayerCreateInfoAction(fields[2].GetUInt16(), fields[3].GetUInt32(), fields[4].GetUInt16())); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u player create actions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -3525,8 +3578,7 @@ void ObjectMgr::LoadPlayerInfo() levelInfo.basemana = fields[3].GetUInt16(); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // Fill gaps and check integrity for (int class_ = 0; class_ < MAX_CLASSES; ++class_) @@ -3620,8 +3672,7 @@ void ObjectMgr::LoadPlayerInfo() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // Fill gaps and check integrity for (int race = 0; race < MAX_RACES; ++race) @@ -3715,8 +3766,7 @@ void ObjectMgr::LoadPlayerInfo() //PlayerXPperLevel _playerXPperLevel[current_level] = current_xp; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // fill level gaps for (uint8 level = 1; level < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); ++level) @@ -3743,7 +3793,7 @@ void ObjectMgr::GetPlayerClassLevelInfo(uint32 class_, uint8 level, PlayerClassL if (level > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) level = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); - *info = pInfo->levelInfo[level-1]; + *info = pInfo->levelInfo[level - 1]; } void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, PlayerLevelInfo* info) const @@ -3756,7 +3806,7 @@ void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, Play return; if (level <= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) - *info = pInfo->levelInfo[level-1]; + *info = pInfo->levelInfo[level - 1]; else BuildPlayerLevelInfo(race, class_, level, info); } @@ -3764,75 +3814,75 @@ void ObjectMgr::GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, Play void ObjectMgr::BuildPlayerLevelInfo(uint8 race, uint8 _class, uint8 level, PlayerLevelInfo* info) const { // base data (last known level) - *info = _playerInfo[race][_class]->levelInfo[sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)-1]; + *info = _playerInfo[race][_class]->levelInfo[sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL) - 1]; // if conversion from uint32 to uint8 causes unexpected behaviour, change lvl to uint32 - for (uint8 lvl = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)-1; lvl < level; ++lvl) + for (uint8 lvl = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL) - 1; lvl < level; ++lvl) { switch (_class) { case CLASS_WARRIOR: - info->stats[STAT_STRENGTH] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_STAMINA] += (lvl > 23 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_AGILITY] += (lvl > 36 ? 1: (lvl > 6 && (lvl%2) ? 1: 0)); - info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl%2) ? 1: 0); - info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl%2) ? 1: 0); + info->stats[STAT_STRENGTH] += (lvl > 23 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_STAMINA] += (lvl > 23 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_AGILITY] += (lvl > 36 ? 1 : (lvl > 6 && (lvl % 2) ? 1 : 0)); + info->stats[STAT_INTELLECT] += (lvl > 9 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_SPIRIT] += (lvl > 9 && !(lvl % 2) ? 1 : 0); break; case CLASS_PALADIN: - info->stats[STAT_STRENGTH] += (lvl > 3 ? 1: 0); - info->stats[STAT_STAMINA] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 7 && !(lvl%2) ? 1: 0)); - info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl%2) ? 1: 0); - info->stats[STAT_SPIRIT] += (lvl > 7 ? 1: 0); + info->stats[STAT_STRENGTH] += (lvl > 3 ? 1 : 0); + info->stats[STAT_STAMINA] += (lvl > 33 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_AGILITY] += (lvl > 38 ? 1 : (lvl > 7 && !(lvl % 2) ? 1 : 0)); + info->stats[STAT_INTELLECT] += (lvl > 6 && (lvl % 2) ? 1 : 0); + info->stats[STAT_SPIRIT] += (lvl > 7 ? 1 : 0); break; case CLASS_HUNTER: - info->stats[STAT_STRENGTH] += (lvl > 4 ? 1: 0); - info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0); - info->stats[STAT_AGILITY] += (lvl > 33 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl%2) ? 1: 0); - info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0)); + info->stats[STAT_STRENGTH] += (lvl > 4 ? 1 : 0); + info->stats[STAT_STAMINA] += (lvl > 4 ? 1 : 0); + info->stats[STAT_AGILITY] += (lvl > 33 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_INTELLECT] += (lvl > 8 && (lvl % 2) ? 1 : 0); + info->stats[STAT_SPIRIT] += (lvl > 38 ? 1 : (lvl > 9 && !(lvl % 2) ? 1 : 0)); break; case CLASS_ROGUE: - info->stats[STAT_STRENGTH] += (lvl > 5 ? 1: 0); - info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0); - info->stats[STAT_AGILITY] += (lvl > 16 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl%2) ? 1: 0); - info->stats[STAT_SPIRIT] += (lvl > 38 ? 1: (lvl > 9 && !(lvl%2) ? 1: 0)); + info->stats[STAT_STRENGTH] += (lvl > 5 ? 1 : 0); + info->stats[STAT_STAMINA] += (lvl > 4 ? 1 : 0); + info->stats[STAT_AGILITY] += (lvl > 16 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_INTELLECT] += (lvl > 8 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_SPIRIT] += (lvl > 38 ? 1 : (lvl > 9 && !(lvl % 2) ? 1 : 0)); break; case CLASS_PRIEST: - info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0); - info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0); - info->stats[STAT_AGILITY] += (lvl > 38 ? 1: (lvl > 8 && (lvl%2) ? 1: 0)); - info->stats[STAT_INTELLECT] += (lvl > 22 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_SPIRIT] += (lvl > 3 ? 1: 0); + info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_STAMINA] += (lvl > 5 ? 1 : 0); + info->stats[STAT_AGILITY] += (lvl > 38 ? 1 : (lvl > 8 && (lvl % 2) ? 1 : 0)); + info->stats[STAT_INTELLECT] += (lvl > 22 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_SPIRIT] += (lvl > 3 ? 1 : 0); break; case CLASS_SHAMAN: - info->stats[STAT_STRENGTH] += (lvl > 34 ? 1: (lvl > 6 && (lvl%2) ? 1: 0)); - info->stats[STAT_STAMINA] += (lvl > 4 ? 1: 0); - info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl%2) ? 1: 0); - info->stats[STAT_INTELLECT] += (lvl > 5 ? 1: 0); - info->stats[STAT_SPIRIT] += (lvl > 4 ? 1: 0); + info->stats[STAT_STRENGTH] += (lvl > 34 ? 1 : (lvl > 6 && (lvl % 2) ? 1 : 0)); + info->stats[STAT_STAMINA] += (lvl > 4 ? 1 : 0); + info->stats[STAT_AGILITY] += (lvl > 7 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_INTELLECT] += (lvl > 5 ? 1 : 0); + info->stats[STAT_SPIRIT] += (lvl > 4 ? 1 : 0); break; case CLASS_MAGE: - info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0); - info->stats[STAT_STAMINA] += (lvl > 5 ? 1: 0); - info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0); - info->stats[STAT_INTELLECT] += (lvl > 24 ? 2: (lvl > 1 ? 1: 0)); - info->stats[STAT_SPIRIT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0)); + info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_STAMINA] += (lvl > 5 ? 1 : 0); + info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_INTELLECT] += (lvl > 24 ? 2 : (lvl > 1 ? 1 : 0)); + info->stats[STAT_SPIRIT] += (lvl > 33 ? 2 : (lvl > 2 ? 1 : 0)); break; case CLASS_WARLOCK: - info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl%2) ? 1: 0); - info->stats[STAT_STAMINA] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0)); - info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl%2) ? 1: 0); - info->stats[STAT_INTELLECT] += (lvl > 33 ? 2: (lvl > 2 ? 1: 0)); - info->stats[STAT_SPIRIT] += (lvl > 38 ? 2: (lvl > 3 ? 1: 0)); + info->stats[STAT_STRENGTH] += (lvl > 9 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_STAMINA] += (lvl > 38 ? 2 : (lvl > 3 ? 1 : 0)); + info->stats[STAT_AGILITY] += (lvl > 9 && !(lvl % 2) ? 1 : 0); + info->stats[STAT_INTELLECT] += (lvl > 33 ? 2 : (lvl > 2 ? 1 : 0)); + info->stats[STAT_SPIRIT] += (lvl > 38 ? 2 : (lvl > 3 ? 1 : 0)); break; case CLASS_DRUID: - info->stats[STAT_STRENGTH] += (lvl > 38 ? 2: (lvl > 6 && (lvl%2) ? 1: 0)); - info->stats[STAT_STAMINA] += (lvl > 32 ? 2: (lvl > 4 ? 1: 0)); - info->stats[STAT_AGILITY] += (lvl > 38 ? 2: (lvl > 8 && (lvl%2) ? 1: 0)); - info->stats[STAT_INTELLECT] += (lvl > 38 ? 3: (lvl > 4 ? 1: 0)); - info->stats[STAT_SPIRIT] += (lvl > 38 ? 3: (lvl > 5 ? 1: 0)); + info->stats[STAT_STRENGTH] += (lvl > 38 ? 2 : (lvl > 6 && (lvl % 2) ? 1 : 0)); + info->stats[STAT_STAMINA] += (lvl > 32 ? 2 : (lvl > 4 ? 1 : 0)); + info->stats[STAT_AGILITY] += (lvl > 38 ? 2 : (lvl > 8 && (lvl % 2) ? 1 : 0)); + info->stats[STAT_INTELLECT] += (lvl > 38 ? 3 : (lvl > 4 ? 1 : 0)); + info->stats[STAT_SPIRIT] += (lvl > 38 ? 3 : (lvl > 5 ? 1 : 0)); } } } @@ -3842,40 +3892,40 @@ void ObjectMgr::LoadQuests() uint32 oldMSTime = getMSTime(); // For reload case - for (QuestMap::const_iterator itr=_questTemplates.begin(); itr != _questTemplates.end(); ++itr) + for (QuestMap::const_iterator itr = _questTemplates.begin(); itr != _questTemplates.end(); ++itr) delete itr->second; _questTemplates.clear(); mExclusiveQuestGroups.clear(); QueryResult result = WorldDatabase.Query("SELECT " - //0 1 2 3 4 5 6 7 8 - "ID, QuestType, QuestLevel, MinLevel, QuestSortID, QuestInfoID, SuggestedGroupNum, TimeAllowed, AllowableRaces," - // 9 10 11 12 - "RequiredFactionId1, RequiredFactionId2, RequiredFactionValue1, RequiredFactionValue2, " - // 13 14 15 16 17 18 19 20 - "RewardNextQuest, RewardXPDifficulty, RewardMoney, RewardBonusMoney, RewardDisplaySpell, RewardSpell, RewardHonor, RewardKillHonor, " - // 21 22 23 24 25 26 - "StartItem, Flags, RewardTitle, RequiredPlayerKills, RewardTalents, RewardArenaPoints, " - // 27 28 29 30 31 32 33 34 - "RewardItem1, RewardAmount1, RewardItem2, RewardAmount2, RewardItem3, RewardAmount3, RewardItem4, RewardAmount4, " - // 35 36 37 38 39 40 41 42 43 44 45 46 - "RewardChoiceItemID1, RewardChoiceItemQuantity1, RewardChoiceItemID2, RewardChoiceItemQuantity2, RewardChoiceItemID3, RewardChoiceItemQuantity3, RewardChoiceItemID4, RewardChoiceItemQuantity4, RewardChoiceItemID5, RewardChoiceItemQuantity5, RewardChoiceItemID6, RewardChoiceItemQuantity6, " - // 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 - "RewardFactionID1, RewardFactionValue1, RewardFactionOverride1, RewardFactionID2, RewardFactionValue2, RewardFactionOverride2, RewardFactionID3, RewardFactionValue3, RewardFactionOverride3, RewardFactionID4, RewardFactionValue4, RewardFactionOverride4, RewardFactionID5, RewardFactionValue5, RewardFactionOverride5," - // 62 63 64 65 - "POIContinent, POIx, POIy, POIPriority, " - // 66 67 68 69 70 - "LogTitle, LogDescription, QuestDescription, AreaDescription, QuestCompletionLog, " - // 71 72 73 74 75 76 77 78 - "RequiredNpcOrGo1, RequiredNpcOrGo2, RequiredNpcOrGo3, RequiredNpcOrGo4, RequiredNpcOrGoCount1, RequiredNpcOrGoCount2, RequiredNpcOrGoCount3, RequiredNpcOrGoCount4, " - // 79 80 81 82 83 84 85 86 - "ItemDrop1, ItemDrop2, ItemDrop3, ItemDrop4, ItemDropQuantity1, ItemDropQuantity2, ItemDropQuantity3, ItemDropQuantity4, " - // 87 88 89 90 91 92 93 94 95 96 97 98 - "RequiredItemId1, RequiredItemId2, RequiredItemId3, RequiredItemId4, RequiredItemId5, RequiredItemId6, RequiredItemCount1, RequiredItemCount2, RequiredItemCount3, RequiredItemCount4, RequiredItemCount5, RequiredItemCount6, " - // 99 100 101 102 103 - "Unknown0, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4" - " FROM quest_template"); + //0 1 2 3 4 5 6 7 8 + "ID, QuestType, QuestLevel, MinLevel, QuestSortID, QuestInfoID, SuggestedGroupNum, TimeAllowed, AllowableRaces," + // 9 10 11 12 + "RequiredFactionId1, RequiredFactionId2, RequiredFactionValue1, RequiredFactionValue2, " + // 13 14 15 16 17 18 19 20 + "RewardNextQuest, RewardXPDifficulty, RewardMoney, RewardBonusMoney, RewardDisplaySpell, RewardSpell, RewardHonor, RewardKillHonor, " + // 21 22 23 24 25 26 + "StartItem, Flags, RewardTitle, RequiredPlayerKills, RewardTalents, RewardArenaPoints, " + // 27 28 29 30 31 32 33 34 + "RewardItem1, RewardAmount1, RewardItem2, RewardAmount2, RewardItem3, RewardAmount3, RewardItem4, RewardAmount4, " + // 35 36 37 38 39 40 41 42 43 44 45 46 + "RewardChoiceItemID1, RewardChoiceItemQuantity1, RewardChoiceItemID2, RewardChoiceItemQuantity2, RewardChoiceItemID3, RewardChoiceItemQuantity3, RewardChoiceItemID4, RewardChoiceItemQuantity4, RewardChoiceItemID5, RewardChoiceItemQuantity5, RewardChoiceItemID6, RewardChoiceItemQuantity6, " + // 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 + "RewardFactionID1, RewardFactionValue1, RewardFactionOverride1, RewardFactionID2, RewardFactionValue2, RewardFactionOverride2, RewardFactionID3, RewardFactionValue3, RewardFactionOverride3, RewardFactionID4, RewardFactionValue4, RewardFactionOverride4, RewardFactionID5, RewardFactionValue5, RewardFactionOverride5," + // 62 63 64 65 + "POIContinent, POIx, POIy, POIPriority, " + // 66 67 68 69 70 + "LogTitle, LogDescription, QuestDescription, AreaDescription, QuestCompletionLog, " + // 71 72 73 74 75 76 77 78 + "RequiredNpcOrGo1, RequiredNpcOrGo2, RequiredNpcOrGo3, RequiredNpcOrGo4, RequiredNpcOrGoCount1, RequiredNpcOrGoCount2, RequiredNpcOrGoCount3, RequiredNpcOrGoCount4, " + // 79 80 81 82 83 84 85 86 + "ItemDrop1, ItemDrop2, ItemDrop3, ItemDrop4, ItemDropQuantity1, ItemDropQuantity2, ItemDropQuantity3, ItemDropQuantity4, " + // 87 88 89 90 91 92 93 94 95 96 97 98 + "RequiredItemId1, RequiredItemId2, RequiredItemId3, RequiredItemId4, RequiredItemId5, RequiredItemId6, RequiredItemCount1, RequiredItemCount2, RequiredItemCount3, RequiredItemCount4, RequiredItemCount5, RequiredItemCount6, " + // 99 100 101 102 103 + "Unknown0, ObjectiveText1, ObjectiveText2, ObjectiveText3, ObjectiveText4" + " FROM quest_template"); if (!result) { sLog->outErrorDb(">> Loaded 0 quests definitions. DB table `quest_template` is empty."); @@ -3903,7 +3953,7 @@ void ObjectMgr::LoadQuests() if (max) { _questTemplatesFast.clear(); - _questTemplatesFast.resize(max+1, nullptr); + _questTemplatesFast.resize(max + 1, nullptr); for (QuestMap::iterator itr = _questTemplates.begin(); itr != _questTemplates.end(); ++itr) _questTemplatesFast[itr->first] = itr->second; } @@ -3986,13 +4036,17 @@ void ObjectMgr::LoadQuests() // Load `quest_template_addon` // 0 1 2 3 4 5 6 7 8 result = WorldDatabase.Query("SELECT ID, MaxLevel, AllowableClasses, SourceSpellID, PrevQuestID, NextQuestID, ExclusiveGroup, RewardMailTemplateID, RewardMailDelay, " - //9 10 11 12 13 14 15 16 17 - "RequiredSkillID, RequiredSkillPoints, RequiredMinRepFaction, RequiredMaxRepFaction, RequiredMinRepValue, RequiredMaxRepValue, ProvidedItemCount, RewardMailSenderEntry, SpecialFlags FROM quest_template_addon LEFT JOIN quest_mail_sender ON Id=QuestId"); + //9 10 11 12 13 14 15 16 17 + "RequiredSkillID, RequiredSkillPoints, RequiredMinRepFaction, RequiredMaxRepFaction, RequiredMinRepValue, RequiredMaxRepValue, ProvidedItemCount, RewardMailSenderEntry, SpecialFlags FROM quest_template_addon LEFT JOIN quest_mail_sender ON Id=QuestId"); - if (!result) { - sLog->outError(">> Loaded 0 quest template addons. DB table `quest_template_addon` is empty."); - } else { - do { + if (!result) + { + sLog->outError(">> Loaded 0 quest template addons. DB table `quest_template_addon` is empty."); + } + else + { + do + { Field* fields = result->Fetch(); uint32 questId = fields[0].GetUInt32(); @@ -4000,7 +4054,7 @@ void ObjectMgr::LoadQuests() if (itr != _questTemplates.end()) itr->second->LoadQuestTemplateAddon(fields); else - sLog->outError("Table `quest_template_addon` has data for quest %u but such quest does not exist", questId); + sLog->outError("Table `quest_template_addon` has data for quest %u but such quest does not exist", questId); } while (result->NextRow()); } @@ -4011,7 +4065,7 @@ void ObjectMgr::LoadQuests() if (DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, iter->first, nullptr)) continue; - Quest * qinfo = iter->second; + Quest* qinfo = iter->second; // additional quest integrity checks (GO, creature_template and item_template must be loaded already) @@ -4021,7 +4075,7 @@ void ObjectMgr::LoadQuests() if (qinfo->SpecialFlags & ~QUEST_SPECIAL_FLAGS_DB_ALLOWED) { sLog->outErrorDb("Quest %u has `SpecialFlags` = %u > max allowed value. Correct `SpecialFlags` to value <= %u", - qinfo->GetQuestId(), qinfo->SpecialFlags, QUEST_SPECIAL_FLAGS_DB_ALLOWED); + qinfo->GetQuestId(), qinfo->SpecialFlags, QUEST_SPECIAL_FLAGS_DB_ALLOWED); qinfo->SpecialFlags &= QUEST_SPECIAL_FLAGS_DB_ALLOWED; } @@ -4066,7 +4120,7 @@ void ObjectMgr::LoadQuests() if (uint32 id = qinfo->RewardChoiceItemId[j]) { sLog->outErrorDb("Quest %u has `RewardChoiceItemId%d` = %u but item from `RewardChoiceItemId%d` can't be rewarded with quest flag QUEST_FLAGS_TRACKING.", - qinfo->GetQuestId(), j+1, id, j+1); + qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest ignore this data } } @@ -4078,7 +4132,7 @@ void ObjectMgr::LoadQuests() if (!sAreaTableStore.LookupEntry(qinfo->ZoneOrSort)) { sLog->outErrorDb("Quest %u has `ZoneOrSort` = %u (zone case) but zone with this id does not exist.", - qinfo->GetQuestId(), qinfo->ZoneOrSort); + qinfo->GetQuestId(), qinfo->ZoneOrSort); // no changes, quest not dependent from this value but can have problems at client } } @@ -4089,7 +4143,7 @@ void ObjectMgr::LoadQuests() if (!qSort) { sLog->outErrorDb("Quest %u has `ZoneOrSort` = %i (sort case) but quest sort with this id does not exist.", - qinfo->GetQuestId(), qinfo->ZoneOrSort); + qinfo->GetQuestId(), qinfo->ZoneOrSort); // no changes, quest not dependent from this value but can have problems at client (note some may be 0, we must allow this so no check) } //check for proper RequiredSkillId value (skill case) @@ -4098,7 +4152,7 @@ void ObjectMgr::LoadQuests() if (qinfo->RequiredSkillId != skill_id) { sLog->outErrorDb("Quest %u has `ZoneOrSort` = %i but `RequiredSkillId` does not have a corresponding value (%d).", - qinfo->GetQuestId(), qinfo->ZoneOrSort, skill_id); + qinfo->GetQuestId(), qinfo->ZoneOrSort, skill_id); //override, and force proper value here? } } @@ -4110,25 +4164,25 @@ void ObjectMgr::LoadQuests() if (!(qinfo->RequiredClasses & CLASSMASK_ALL_PLAYABLE)) { sLog->outErrorDb("Quest %u does not contain any playable classes in `RequiredClasses` (%u), value set to 0 (all classes).", qinfo->GetQuestId(), qinfo->RequiredClasses); - qinfo->RequiredClasses = 0; + qinfo->RequiredClasses = 0; } } // AllowableRaces, can be 0/RACEMASK_ALL_PLAYABLE to allow any race if (qinfo->AllowableRaces) - { + { if (!(qinfo->AllowableRaces & RACEMASK_ALL_PLAYABLE)) - { - sLog->outErrorDb("Quest %u does not contain any playable races in `AllowableRaces` (%u), value set to 0 (all races).", qinfo->GetQuestId(), qinfo->AllowableRaces); - qinfo->AllowableRaces = 0; - } + { + sLog->outErrorDb("Quest %u does not contain any playable races in `AllowableRaces` (%u), value set to 0 (all races).", qinfo->GetQuestId(), qinfo->AllowableRaces); + qinfo->AllowableRaces = 0; } + } // RequiredSkillId, can be 0 if (qinfo->RequiredSkillId) { if (!sSkillLineStore.LookupEntry(qinfo->RequiredSkillId)) { sLog->outErrorDb("Quest %u has `RequiredSkillId` = %u but this skill does not exist", - qinfo->GetQuestId(), qinfo->RequiredSkillId); + qinfo->GetQuestId(), qinfo->RequiredSkillId); } } @@ -4137,7 +4191,7 @@ void ObjectMgr::LoadQuests() if (qinfo->RequiredSkillPoints > sWorld->GetConfigMaxSkillValue()) { sLog->outErrorDb("Quest %u has `RequiredSkillPoints` = %u but max possible skill is %u, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredSkillPoints, sWorld->GetConfigMaxSkillValue()); + qinfo->GetQuestId(), qinfo->RequiredSkillPoints, sWorld->GetConfigMaxSkillValue()); // no changes, quest can't be done for this requirement } } @@ -4146,77 +4200,77 @@ void ObjectMgr::LoadQuests() if (qinfo->RequiredFactionId2 && !sFactionStore.LookupEntry(qinfo->RequiredFactionId2)) { sLog->outErrorDb("Quest %u has `RequiredFactionId2` = %u but faction template %u does not exist, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredFactionId2, qinfo->RequiredFactionId2); + qinfo->GetQuestId(), qinfo->RequiredFactionId2, qinfo->RequiredFactionId2); // no changes, quest can't be done for this requirement } if (qinfo->RequiredFactionId1 && !sFactionStore.LookupEntry(qinfo->RequiredFactionId1)) { sLog->outErrorDb("Quest %u has `RequiredFactionId1` = %u but faction template %u does not exist, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredFactionId1, qinfo->RequiredFactionId1); + qinfo->GetQuestId(), qinfo->RequiredFactionId1, qinfo->RequiredFactionId1); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction)) { sLog->outErrorDb("Quest %u has `RequiredMinRepFaction` = %u but faction template %u does not exist, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredMinRepFaction, qinfo->RequiredMinRepFaction); + qinfo->GetQuestId(), qinfo->RequiredMinRepFaction, qinfo->RequiredMinRepFaction); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction)) { sLog->outErrorDb("Quest %u has `RequiredMaxRepFaction` = %u but faction template %u does not exist, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredMaxRepFaction, qinfo->RequiredMaxRepFaction); + qinfo->GetQuestId(), qinfo->RequiredMaxRepFaction, qinfo->RequiredMaxRepFaction); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap) { sLog->outErrorDb("Quest %u has `RequiredMinRepValue` = %d but max reputation is %u, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredMinRepValue, ReputationMgr::Reputation_Cap); + qinfo->GetQuestId(), qinfo->RequiredMinRepValue, ReputationMgr::Reputation_Cap); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue) { sLog->outErrorDb("Quest %u has `RequiredMaxRepValue` = %d and `RequiredMinRepValue` = %d, quest can't be done.", - qinfo->GetQuestId(), qinfo->RequiredMaxRepValue, qinfo->RequiredMinRepValue); + qinfo->GetQuestId(), qinfo->RequiredMaxRepValue, qinfo->RequiredMinRepValue); // no changes, quest can't be done for this requirement } if (!qinfo->RequiredFactionId1 && qinfo->RequiredFactionValue1 != 0) { sLog->outErrorDb("Quest %u has `RequiredFactionValue1` = %d but `RequiredFactionId1` is 0, value has no effect", - qinfo->GetQuestId(), qinfo->RequiredFactionValue1); + qinfo->GetQuestId(), qinfo->RequiredFactionValue1); // warning } if (!qinfo->RequiredFactionId2 && qinfo->RequiredFactionValue2 != 0) { sLog->outErrorDb("Quest %u has `RequiredFactionValue2` = %d but `RequiredFactionId2` is 0, value has no effect", - qinfo->GetQuestId(), qinfo->RequiredFactionValue2); + qinfo->GetQuestId(), qinfo->RequiredFactionValue2); // warning } if (!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue != 0) { sLog->outErrorDb("Quest %u has `RequiredMinRepValue` = %d but `RequiredMinRepFaction` is 0, value has no effect", - qinfo->GetQuestId(), qinfo->RequiredMinRepValue); + qinfo->GetQuestId(), qinfo->RequiredMinRepValue); // warning } if (!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue != 0) { sLog->outErrorDb("Quest %u has `RequiredMaxRepValue` = %d but `RequiredMaxRepFaction` is 0, value has no effect", - qinfo->GetQuestId(), qinfo->RequiredMaxRepValue); + qinfo->GetQuestId(), qinfo->RequiredMaxRepValue); // warning } if (qinfo->RewardTitleId && !sCharTitlesStore.LookupEntry(qinfo->RewardTitleId)) { sLog->outErrorDb("Quest %u has `RewardTitleId` = %u but CharTitle Id %u does not exist, quest can't be rewarded with title.", - qinfo->GetQuestId(), qinfo->GetCharTitleId(), qinfo->GetCharTitleId()); + qinfo->GetQuestId(), qinfo->GetCharTitleId(), qinfo->GetCharTitleId()); qinfo->RewardTitleId = 0; // quest can't reward this title } @@ -4226,20 +4280,20 @@ void ObjectMgr::LoadQuests() if (!sObjectMgr->GetItemTemplate(qinfo->StartItem)) { sLog->outErrorDb("Quest %u has `StartItem` = %u but item with entry %u does not exist, quest can't be done.", - qinfo->GetQuestId(), qinfo->StartItem, qinfo->StartItem); + qinfo->GetQuestId(), qinfo->StartItem, qinfo->StartItem); qinfo->StartItem = 0; // quest can't be done for this requirement } else if (qinfo->StartItemCount == 0) { sLog->outErrorDb("Quest %u has `StartItem` = %u but `StartItemCount` = 0, set to 1 but need fix in DB.", - qinfo->GetQuestId(), qinfo->StartItem); + qinfo->GetQuestId(), qinfo->StartItem); qinfo->StartItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB } } else if (qinfo->StartItemCount > 0) { sLog->outErrorDb("Quest %u has `StartItem` = 0 but `StartItemCount` = %u, useless value.", - qinfo->GetQuestId(), qinfo->StartItemCount); + qinfo->GetQuestId(), qinfo->StartItemCount); qinfo->StartItemCount = 0; // no quest work changes in fact } @@ -4249,13 +4303,13 @@ void ObjectMgr::LoadQuests() if (!spellInfo) { sLog->outErrorDb("Quest %u has `SourceSpellid` = %u but spell %u doesn't exist, quest can't be done.", - qinfo->GetQuestId(), qinfo->SourceSpellid, qinfo->SourceSpellid); + qinfo->GetQuestId(), qinfo->SourceSpellid, qinfo->SourceSpellid); qinfo->SourceSpellid = 0; // quest can't be done for this requirement } else if (!SpellMgr::ComputeIsSpellValid(spellInfo)) { sLog->outErrorDb("Quest %u has `SourceSpellid` = %u but spell %u is broken, quest can't be done.", - qinfo->GetQuestId(), qinfo->SourceSpellid, qinfo->SourceSpellid); + qinfo->GetQuestId(), qinfo->SourceSpellid, qinfo->SourceSpellid); qinfo->SourceSpellid = 0; // quest can't be done for this requirement } } @@ -4268,7 +4322,7 @@ void ObjectMgr::LoadQuests() if (qinfo->RequiredItemCount[j] == 0) { sLog->outErrorDb("Quest %u has `RequiredItemId%d` = %u but `RequiredItemCount%d` = 0, quest can't be done.", - qinfo->GetQuestId(), j+1, id, j+1); + qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest can't be done for this requirement } @@ -4277,14 +4331,14 @@ void ObjectMgr::LoadQuests() if (!sObjectMgr->GetItemTemplate(id)) { sLog->outErrorDb("Quest %u has `RequiredItemId%d` = %u but item with entry %u does not exist, quest can't be done.", - qinfo->GetQuestId(), j+1, id, id); + qinfo->GetQuestId(), j + 1, id, id); qinfo->RequiredItemCount[j] = 0; // prevent incorrect work of quest } } - else if (qinfo->RequiredItemCount[j]>0) + else if (qinfo->RequiredItemCount[j] > 0) { sLog->outErrorDb("Quest %u has `RequiredItemId%d` = 0 but `RequiredItemCount%d` = %u, quest can't be done.", - qinfo->GetQuestId(), j+1, j+1, qinfo->RequiredItemCount[j]); + qinfo->GetQuestId(), j + 1, j + 1, qinfo->RequiredItemCount[j]); qinfo->RequiredItemCount[j] = 0; // prevent incorrect work of quest } } @@ -4297,16 +4351,16 @@ void ObjectMgr::LoadQuests() if (!sObjectMgr->GetItemTemplate(id)) { sLog->outErrorDb("Quest %u has `ItemDrop%d` = %u but item with entry %u does not exist, quest can't be done.", - qinfo->GetQuestId(), j+1, id, id); + qinfo->GetQuestId(), j + 1, id, id); // no changes, quest can't be done for this requirement } } else { - if (qinfo->ItemDropQuantity[j]>0) + if (qinfo->ItemDropQuantity[j] > 0) { sLog->outErrorDb("Quest %u has `ItemDrop%d` = 0 but `ItemDropQuantity%d` = %u.", - qinfo->GetQuestId(), j+1, j+1, qinfo->ItemDropQuantity[j]); + qinfo->GetQuestId(), j + 1, j + 1, qinfo->ItemDropQuantity[j]); // no changes, quest ignore this data } } @@ -4318,14 +4372,14 @@ void ObjectMgr::LoadQuests() if (id < 0 && !sObjectMgr->GetGameObjectTemplate(-id)) { sLog->outErrorDb("Quest %u has `RequiredNpcOrGo%d` = %i but gameobject %u does not exist, quest can't be done.", - qinfo->GetQuestId(), j+1, id, uint32(-id)); + qinfo->GetQuestId(), j + 1, id, uint32(-id)); qinfo->RequiredNpcOrGo[j] = 0; // quest can't be done for this requirement } if (id > 0 && !sObjectMgr->GetCreatureTemplate(id)) { sLog->outErrorDb("Quest %u has `RequiredNpcOrGo%d` = %i but creature with entry %u does not exist, quest can't be done.", - qinfo->GetQuestId(), j+1, id, uint32(id)); + qinfo->GetQuestId(), j + 1, id, uint32(id)); qinfo->RequiredNpcOrGo[j] = 0; // quest can't be done for this requirement } @@ -4338,14 +4392,14 @@ void ObjectMgr::LoadQuests() if (!qinfo->RequiredNpcOrGoCount[j]) { sLog->outErrorDb("Quest %u has `RequiredNpcOrGo%d` = %u but `RequiredNpcOrGoCount%d` = 0, quest can't be done.", - qinfo->GetQuestId(), j+1, id, j+1); + qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest can be incorrectly done, but we already report this } } - else if (qinfo->RequiredNpcOrGoCount[j]>0) + else if (qinfo->RequiredNpcOrGoCount[j] > 0) { sLog->outErrorDb("Quest %u has `RequiredNpcOrGo%d` = 0 but `RequiredNpcOrGoCount%d` = %u.", - qinfo->GetQuestId(), j+1, j+1, qinfo->RequiredNpcOrGoCount[j]); + qinfo->GetQuestId(), j + 1, j + 1, qinfo->RequiredNpcOrGoCount[j]); // no changes, quest ignore this data } } @@ -4358,21 +4412,21 @@ void ObjectMgr::LoadQuests() if (!sObjectMgr->GetItemTemplate(id)) { sLog->outErrorDb("Quest %u has `RewardChoiceItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.", - qinfo->GetQuestId(), j+1, id, id); + qinfo->GetQuestId(), j + 1, id, id); qinfo->RewardChoiceItemId[j] = 0; // no changes, quest will not reward this } if (!qinfo->RewardChoiceItemCount[j]) { sLog->outErrorDb("Quest %u has `RewardChoiceItemId%d` = %u but `RewardChoiceItemCount%d` = 0, quest can't be done.", - qinfo->GetQuestId(), j+1, id, j+1); + qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest can't be done } } - else if (qinfo->RewardChoiceItemCount[j]>0) + else if (qinfo->RewardChoiceItemCount[j] > 0) { sLog->outErrorDb("Quest %u has `RewardChoiceItemId%d` = 0 but `RewardChoiceItemCount%d` = %u.", - qinfo->GetQuestId(), j+1, j+1, qinfo->RewardChoiceItemCount[j]); + qinfo->GetQuestId(), j + 1, j + 1, qinfo->RewardChoiceItemCount[j]); // no changes, quest ignore this data } } @@ -4385,21 +4439,21 @@ void ObjectMgr::LoadQuests() if (!sObjectMgr->GetItemTemplate(id)) { sLog->outErrorDb("Quest %u has `RewardItemId%d` = %u but item with entry %u does not exist, quest will not reward this item.", - qinfo->GetQuestId(), j+1, id, id); + qinfo->GetQuestId(), j + 1, id, id); qinfo->RewardItemId[j] = 0; // no changes, quest will not reward this item } if (!qinfo->RewardItemIdCount[j]) { sLog->outErrorDb("Quest %u has `RewardItemId%d` = %u but `RewardItemIdCount%d` = 0, quest will not reward this item.", - qinfo->GetQuestId(), j+1, id, j+1); + qinfo->GetQuestId(), j + 1, id, j + 1); // no changes } } - else if (qinfo->RewardItemIdCount[j]>0) + else if (qinfo->RewardItemIdCount[j] > 0) { sLog->outErrorDb("Quest %u has `RewardItemId%d` = 0 but `RewardItemIdCount%d` = %u.", - qinfo->GetQuestId(), j+1, j+1, qinfo->RewardItemIdCount[j]); + qinfo->GetQuestId(), j + 1, j + 1, qinfo->RewardItemIdCount[j]); // no changes, quest ignore this data } } @@ -4410,11 +4464,11 @@ void ObjectMgr::LoadQuests() { if (abs(qinfo->RewardFactionValueId[j]) > 9) { - sLog->outErrorDb("Quest %u has RewardFactionValueId%d = %i. That is outside the range of valid values (-9 to 9).", qinfo->GetQuestId(), j+1, qinfo->RewardFactionValueId[j]); + sLog->outErrorDb("Quest %u has RewardFactionValueId%d = %i. That is outside the range of valid values (-9 to 9).", qinfo->GetQuestId(), j + 1, qinfo->RewardFactionValueId[j]); } if (!sFactionStore.LookupEntry(qinfo->RewardFactionId[j])) { - sLog->outErrorDb("Quest %u has `RewardFactionId%d` = %u but raw faction (faction.dbc) %u does not exist, quest will not reward reputation for this faction.", qinfo->GetQuestId(), j+1, qinfo->RewardFactionId[j], qinfo->RewardFactionId[j]); + sLog->outErrorDb("Quest %u has `RewardFactionId%d` = %u but raw faction (faction.dbc) %u does not exist, quest will not reward reputation for this faction.", qinfo->GetQuestId(), j + 1, qinfo->RewardFactionId[j], qinfo->RewardFactionId[j]); qinfo->RewardFactionId[j] = 0; // quest will not reward this } } @@ -4422,7 +4476,7 @@ void ObjectMgr::LoadQuests() else if (qinfo->RewardFactionValueIdOverride[j] != 0) { sLog->outErrorDb("Quest %u has `RewardFactionId%d` = 0 but `RewardFactionValueIdOverride%d` = %i.", - qinfo->GetQuestId(), j+1, j+1, qinfo->RewardFactionValueIdOverride[j]); + qinfo->GetQuestId(), j + 1, j + 1, qinfo->RewardFactionValueIdOverride[j]); // no changes, quest ignore this data } } @@ -4434,21 +4488,21 @@ void ObjectMgr::LoadQuests() if (!spellInfo) { sLog->outErrorDb("Quest %u has `RewardDisplaySpell` = %u but spell %u does not exist, spell removed as display reward.", - qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); + qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); qinfo->RewardDisplaySpell = 0; // no spell reward will display for this quest } else if (!SpellMgr::ComputeIsSpellValid(spellInfo)) { sLog->outErrorDb("Quest %u has `RewardDisplaySpell` = %u but spell %u is broken, quest will not have a spell reward.", - qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); + qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); qinfo->RewardDisplaySpell = 0; // no spell reward will display for this quest } else if (GetTalentSpellCost(qinfo->RewardDisplaySpell)) { sLog->outErrorDb("Quest %u has `RewardDisplaySpell` = %u but spell %u is talent, quest will not have a spell reward.", - qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); + qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); qinfo->RewardDisplaySpell = 0; // no spell reward will display for this quest } } @@ -4460,21 +4514,21 @@ void ObjectMgr::LoadQuests() if (!spellInfo) { sLog->outErrorDb("Quest %u has `RewardSpell` = %u but spell %u does not exist, quest will not have a spell reward.", - qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); + qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); qinfo->RewardSpell = 0; // no spell will be casted on player } else if (!SpellMgr::ComputeIsSpellValid(spellInfo)) { sLog->outErrorDb("Quest %u has `RewardSpell` = %u but spell %u is broken, quest will not have a spell reward.", - qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); + qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); qinfo->RewardSpell = 0; // no spell will be casted on player } else if (GetTalentSpellCost(qinfo->RewardSpell)) { sLog->outErrorDb("Quest %u has `RewardDisplaySpell` = %u but spell %u is talent, quest will not have a spell reward.", - qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); + qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); qinfo->RewardSpell = 0; // no spell will be casted on player } } @@ -4484,7 +4538,7 @@ void ObjectMgr::LoadQuests() if (!sMailTemplateStore.LookupEntry(qinfo->RewardMailTemplateId)) { sLog->outErrorDb("Quest %u has `RewardMailTemplateId` = %u but mail template %u does not exist, quest will not have a mail reward.", - qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId); + qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId); qinfo->RewardMailTemplateId = 0; // no mail will send to player qinfo->RewardMailDelay = 0; // no mail will send to player qinfo->RewardMailSenderEntry = 0; @@ -4493,7 +4547,7 @@ void ObjectMgr::LoadQuests() { std::map::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewardMailTemplateId); sLog->outErrorDb("Quest %u has `RewardMailTemplateId` = %u but mail template %u already used for quest %u, quest will not have a mail reward.", - qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId, used_mt_itr->second); + qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId, used_mt_itr->second); qinfo->RewardMailTemplateId = 0; // no mail will send to player qinfo->RewardMailDelay = 0; // no mail will send to player qinfo->RewardMailSenderEntry = 0; @@ -4508,7 +4562,7 @@ void ObjectMgr::LoadQuests() if (qNextItr == _questTemplates.end()) { sLog->outErrorDb("Quest %u has `RewardNextQuest` = %u but quest %u does not exist, quest chain will not work.", - qinfo->GetQuestId(), qinfo->RewardNextQuest, qinfo->RewardNextQuest); + qinfo->GetQuestId(), qinfo->RewardNextQuest, qinfo->RewardNextQuest); qinfo->RewardNextQuest = 0; } else @@ -4674,248 +4728,248 @@ void ObjectMgr::LoadScripts(ScriptsType type) switch (tmp.command) { case SCRIPT_COMMAND_TALK: - { - if (tmp.Talk.ChatType > CHAT_TYPE_WHISPER && tmp.Talk.ChatType != CHAT_MSG_RAID_BOSS_WHISPER) { - sLog->outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u", - tableName.c_str(), tmp.Talk.ChatType, tmp.id); - continue; + if (tmp.Talk.ChatType > CHAT_TYPE_WHISPER && tmp.Talk.ChatType != CHAT_MSG_RAID_BOSS_WHISPER) + { + sLog->outErrorDb("Table `%s` has invalid talk type (datalong = %u) in SCRIPT_COMMAND_TALK for script id %u", + tableName.c_str(), tmp.Talk.ChatType, tmp.id); + continue; + } + if (!tmp.Talk.TextID) + { + sLog->outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u", + tableName.c_str(), tmp.Talk.TextID, tmp.id); + continue; + } + break; } - if (!tmp.Talk.TextID) - { - sLog->outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u", - tableName.c_str(), tmp.Talk.TextID, tmp.id); - continue; - } - break; - } case SCRIPT_COMMAND_EMOTE: - { - if (!sEmotesStore.LookupEntry(tmp.Emote.EmoteID)) { - sLog->outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u", - tableName.c_str(), tmp.Emote.EmoteID, tmp.id); - continue; + if (!sEmotesStore.LookupEntry(tmp.Emote.EmoteID)) + { + sLog->outErrorDb("Table `%s` has invalid emote id (datalong = %u) in SCRIPT_COMMAND_EMOTE for script id %u", + tableName.c_str(), tmp.Emote.EmoteID, tmp.id); + continue; + } + break; } - break; - } case SCRIPT_COMMAND_TELEPORT_TO: - { - if (!sMapStore.LookupEntry(tmp.TeleportTo.MapID)) { - sLog->outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u", - tableName.c_str(), tmp.TeleportTo.MapID, tmp.id); - continue; - } + if (!sMapStore.LookupEntry(tmp.TeleportTo.MapID)) + { + sLog->outErrorDb("Table `%s` has invalid map (Id: %u) in SCRIPT_COMMAND_TELEPORT_TO for script id %u", + tableName.c_str(), tmp.TeleportTo.MapID, tmp.id); + continue; + } - if (!acore::IsValidMapCoord(tmp.TeleportTo.DestX, tmp.TeleportTo.DestY, tmp.TeleportTo.DestZ, tmp.TeleportTo.Orientation)) - { - sLog->outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f Z: %f O: %f) in SCRIPT_COMMAND_TELEPORT_TO for script id %u", - tableName.c_str(), tmp.TeleportTo.DestX, tmp.TeleportTo.DestY, tmp.TeleportTo.DestZ, tmp.TeleportTo.Orientation, tmp.id); - continue; + if (!acore::IsValidMapCoord(tmp.TeleportTo.DestX, tmp.TeleportTo.DestY, tmp.TeleportTo.DestZ, tmp.TeleportTo.Orientation)) + { + sLog->outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f Z: %f O: %f) in SCRIPT_COMMAND_TELEPORT_TO for script id %u", + tableName.c_str(), tmp.TeleportTo.DestX, tmp.TeleportTo.DestY, tmp.TeleportTo.DestZ, tmp.TeleportTo.Orientation, tmp.id); + continue; + } + break; } - break; - } case SCRIPT_COMMAND_QUEST_EXPLORED: - { - Quest const* quest = GetQuestTemplate(tmp.QuestExplored.QuestID); - if (!quest) { - sLog->outErrorDb("Table `%s` has invalid quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u", - tableName.c_str(), tmp.QuestExplored.QuestID, tmp.id); - continue; + Quest const* quest = GetQuestTemplate(tmp.QuestExplored.QuestID); + if (!quest) + { + sLog->outErrorDb("Table `%s` has invalid quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u", + tableName.c_str(), tmp.QuestExplored.QuestID, tmp.id); + continue; + } + + if (!quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) + { + sLog->outErrorDb("Table `%s` has quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT in quest flags. Script command or quest flags wrong. Quest modified to require objective.", + tableName.c_str(), tmp.QuestExplored.QuestID, tmp.id); + + // this will prevent quest completing without objective + const_cast(quest)->SetSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT); + + // continue; - quest objective requirement set and command can be allowed + } + + if (float(tmp.QuestExplored.Distance) > DEFAULT_VISIBILITY_DISTANCE) + { + sLog->outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u", + tableName.c_str(), tmp.QuestExplored.Distance, tmp.id); + continue; + } + + if (tmp.QuestExplored.Distance && float(tmp.QuestExplored.Distance) > DEFAULT_VISIBILITY_DISTANCE) + { + sLog->outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %f or 0 for disable distance check", + tableName.c_str(), tmp.QuestExplored.Distance, tmp.id, DEFAULT_VISIBILITY_DISTANCE); + continue; + } + + if (tmp.QuestExplored.Distance && float(tmp.QuestExplored.Distance) < INTERACTION_DISTANCE) + { + sLog->outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %f or 0 for disable distance check", + tableName.c_str(), tmp.QuestExplored.Distance, tmp.id, INTERACTION_DISTANCE); + continue; + } + + break; } - if (!quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) - { - sLog->outErrorDb("Table `%s` has quest (ID: %u) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT in quest flags. Script command or quest flags wrong. Quest modified to require objective.", - tableName.c_str(), tmp.QuestExplored.QuestID, tmp.id); - - // this will prevent quest completing without objective - const_cast(quest)->SetSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT); - - // continue; - quest objective requirement set and command can be allowed - } - - if (float(tmp.QuestExplored.Distance) > DEFAULT_VISIBILITY_DISTANCE) - { - sLog->outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u", - tableName.c_str(), tmp.QuestExplored.Distance, tmp.id); - continue; - } - - if (tmp.QuestExplored.Distance && float(tmp.QuestExplored.Distance) > DEFAULT_VISIBILITY_DISTANCE) - { - sLog->outErrorDb("Table `%s` has too large distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, max distance is %f or 0 for disable distance check", - tableName.c_str(), tmp.QuestExplored.Distance, tmp.id, DEFAULT_VISIBILITY_DISTANCE); - continue; - } - - if (tmp.QuestExplored.Distance && float(tmp.QuestExplored.Distance) < INTERACTION_DISTANCE) - { - sLog->outErrorDb("Table `%s` has too small distance (%u) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id %u, min distance is %f or 0 for disable distance check", - tableName.c_str(), tmp.QuestExplored.Distance, tmp.id, INTERACTION_DISTANCE); - continue; - } - - break; - } - case SCRIPT_COMMAND_KILL_CREDIT: - { - if (!GetCreatureTemplate(tmp.KillCredit.CreatureEntry)) { - sLog->outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u", - tableName.c_str(), tmp.KillCredit.CreatureEntry, tmp.id); - continue; + if (!GetCreatureTemplate(tmp.KillCredit.CreatureEntry)) + { + sLog->outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_KILL_CREDIT for script id %u", + tableName.c_str(), tmp.KillCredit.CreatureEntry, tmp.id); + continue; + } + break; } - break; - } case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT: - { - GameObjectData const* data = GetGOData(tmp.RespawnGameobject.GOGuid); - if (!data) { - sLog->outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u", - tableName.c_str(), tmp.RespawnGameobject.GOGuid, tmp.id); - continue; - } + GameObjectData const* data = GetGOData(tmp.RespawnGameobject.GOGuid); + if (!data) + { + sLog->outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u", + tableName.c_str(), tmp.RespawnGameobject.GOGuid, tmp.id); + continue; + } - GameObjectTemplate const* info = GetGameObjectTemplate(data->id); - if (!info) - { - sLog->outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u", - tableName.c_str(), tmp.RespawnGameobject.GOGuid, data->id, tmp.id); - continue; - } + GameObjectTemplate const* info = GetGameObjectTemplate(data->id); + if (!info) + { + sLog->outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u", + tableName.c_str(), tmp.RespawnGameobject.GOGuid, data->id, tmp.id); + continue; + } - if (info->type == GAMEOBJECT_TYPE_FISHINGNODE || - info->type == GAMEOBJECT_TYPE_FISHINGHOLE || - info->type == GAMEOBJECT_TYPE_DOOR || - info->type == GAMEOBJECT_TYPE_BUTTON || - info->type == GAMEOBJECT_TYPE_TRAP) - { - sLog->outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u", - tableName.c_str(), info->entry, tmp.id); - continue; + if (info->type == GAMEOBJECT_TYPE_FISHINGNODE || + info->type == GAMEOBJECT_TYPE_FISHINGHOLE || + info->type == GAMEOBJECT_TYPE_DOOR || + info->type == GAMEOBJECT_TYPE_BUTTON || + info->type == GAMEOBJECT_TYPE_TRAP) + { + sLog->outErrorDb("Table `%s` have gameobject type (%u) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id %u", + tableName.c_str(), info->entry, tmp.id); + continue; + } + break; } - break; - } case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE: - { - if (!acore::IsValidMapCoord(tmp.TempSummonCreature.PosX, tmp.TempSummonCreature.PosY, tmp.TempSummonCreature.PosZ, tmp.TempSummonCreature.Orientation)) { - sLog->outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f Z: %f O: %f) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u", - tableName.c_str(), tmp.TempSummonCreature.PosX, tmp.TempSummonCreature.PosY, tmp.TempSummonCreature.PosZ, tmp.TempSummonCreature.Orientation, tmp.id); - continue; - } + if (!acore::IsValidMapCoord(tmp.TempSummonCreature.PosX, tmp.TempSummonCreature.PosY, tmp.TempSummonCreature.PosZ, tmp.TempSummonCreature.Orientation)) + { + sLog->outErrorDb("Table `%s` has invalid coordinates (X: %f Y: %f Z: %f O: %f) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u", + tableName.c_str(), tmp.TempSummonCreature.PosX, tmp.TempSummonCreature.PosY, tmp.TempSummonCreature.PosZ, tmp.TempSummonCreature.Orientation, tmp.id); + continue; + } - uint32 entry = tmp.TempSummonCreature.CreatureEntry; - if (!GetCreatureTemplate(entry)) - { - sLog->outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u", - tableName.c_str(), tmp.TempSummonCreature.CreatureEntry, tmp.id); - continue; + uint32 entry = tmp.TempSummonCreature.CreatureEntry; + if (!GetCreatureTemplate(entry)) + { + sLog->outErrorDb("Table `%s` has invalid creature (Entry: %u) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id %u", + tableName.c_str(), tmp.TempSummonCreature.CreatureEntry, tmp.id); + continue; + } + break; } - break; - } case SCRIPT_COMMAND_OPEN_DOOR: case SCRIPT_COMMAND_CLOSE_DOOR: - { - GameObjectData const* data = GetGOData(tmp.ToggleDoor.GOGuid); - if (!data) { - sLog->outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in %s for script id %u", - tableName.c_str(), tmp.ToggleDoor.GOGuid, GetScriptCommandName(tmp.command).c_str(), tmp.id); - continue; - } + GameObjectData const* data = GetGOData(tmp.ToggleDoor.GOGuid); + if (!data) + { + sLog->outErrorDb("Table `%s` has invalid gameobject (GUID: %u) in %s for script id %u", + tableName.c_str(), tmp.ToggleDoor.GOGuid, GetScriptCommandName(tmp.command).c_str(), tmp.id); + continue; + } - GameObjectTemplate const* info = GetGameObjectTemplate(data->id); - if (!info) - { - sLog->outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in %s for script id %u", - tableName.c_str(), tmp.ToggleDoor.GOGuid, data->id, GetScriptCommandName(tmp.command).c_str(), tmp.id); - continue; - } + GameObjectTemplate const* info = GetGameObjectTemplate(data->id); + if (!info) + { + sLog->outErrorDb("Table `%s` has gameobject with invalid entry (GUID: %u Entry: %u) in %s for script id %u", + tableName.c_str(), tmp.ToggleDoor.GOGuid, data->id, GetScriptCommandName(tmp.command).c_str(), tmp.id); + continue; + } - if (info->type != GAMEOBJECT_TYPE_DOOR) - { - sLog->outErrorDb("Table `%s` has gameobject type (%u) non supported by command %s for script id %u", - tableName.c_str(), info->entry, GetScriptCommandName(tmp.command).c_str(), tmp.id); - continue; - } + if (info->type != GAMEOBJECT_TYPE_DOOR) + { + sLog->outErrorDb("Table `%s` has gameobject type (%u) non supported by command %s for script id %u", + tableName.c_str(), info->entry, GetScriptCommandName(tmp.command).c_str(), tmp.id); + continue; + } - break; - } + break; + } case SCRIPT_COMMAND_REMOVE_AURA: - { - if (!sSpellMgr->GetSpellInfo(tmp.RemoveAura.SpellID)) { - sLog->outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA for script id %u", - tableName.c_str(), tmp.RemoveAura.SpellID, tmp.id); - continue; + if (!sSpellMgr->GetSpellInfo(tmp.RemoveAura.SpellID)) + { + sLog->outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_REMOVE_AURA for script id %u", + tableName.c_str(), tmp.RemoveAura.SpellID, tmp.id); + continue; + } + if (tmp.RemoveAura.Flags & ~0x1) // 1 bits (0, 1) + { + sLog->outErrorDb("Table `%s` using unknown flags in datalong2 (%u) in SCRIPT_COMMAND_REMOVE_AURA for script id %u", + tableName.c_str(), tmp.RemoveAura.Flags, tmp.id); + continue; + } + break; } - if (tmp.RemoveAura.Flags & ~0x1) // 1 bits (0, 1) - { - sLog->outErrorDb("Table `%s` using unknown flags in datalong2 (%u) in SCRIPT_COMMAND_REMOVE_AURA for script id %u", - tableName.c_str(), tmp.RemoveAura.Flags, tmp.id); - continue; - } - break; - } case SCRIPT_COMMAND_CAST_SPELL: - { - if (!sSpellMgr->GetSpellInfo(tmp.CastSpell.SpellID)) { - sLog->outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", - tableName.c_str(), tmp.CastSpell.SpellID, tmp.id); - continue; + if (!sSpellMgr->GetSpellInfo(tmp.CastSpell.SpellID)) + { + sLog->outErrorDb("Table `%s` using non-existent spell (id: %u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", + tableName.c_str(), tmp.CastSpell.SpellID, tmp.id); + continue; + } + if (tmp.CastSpell.Flags > 4) // targeting type + { + sLog->outErrorDb("Table `%s` using unknown target in datalong2 (%u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", + tableName.c_str(), tmp.CastSpell.Flags, tmp.id); + continue; + } + if (tmp.CastSpell.Flags != 4 && tmp.CastSpell.CreatureEntry & ~0x1) // 1 bit (0, 1) + { + sLog->outErrorDb("Table `%s` using unknown flags in dataint (%u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", + tableName.c_str(), tmp.CastSpell.CreatureEntry, tmp.id); + continue; + } + else if (tmp.CastSpell.Flags == 4 && !GetCreatureTemplate(tmp.CastSpell.CreatureEntry)) + { + sLog->outErrorDb("Table `%s` using invalid creature entry in dataint (%u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", + tableName.c_str(), tmp.CastSpell.CreatureEntry, tmp.id); + continue; + } + break; } - if (tmp.CastSpell.Flags > 4) // targeting type - { - sLog->outErrorDb("Table `%s` using unknown target in datalong2 (%u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", - tableName.c_str(), tmp.CastSpell.Flags, tmp.id); - continue; - } - if (tmp.CastSpell.Flags != 4 && tmp.CastSpell.CreatureEntry & ~0x1) // 1 bit (0, 1) - { - sLog->outErrorDb("Table `%s` using unknown flags in dataint (%u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", - tableName.c_str(), tmp.CastSpell.CreatureEntry, tmp.id); - continue; - } - else if (tmp.CastSpell.Flags == 4 && !GetCreatureTemplate(tmp.CastSpell.CreatureEntry)) - { - sLog->outErrorDb("Table `%s` using invalid creature entry in dataint (%u) in SCRIPT_COMMAND_CAST_SPELL for script id %u", - tableName.c_str(), tmp.CastSpell.CreatureEntry, tmp.id); - continue; - } - break; - } case SCRIPT_COMMAND_CREATE_ITEM: - { - if (!GetItemTemplate(tmp.CreateItem.ItemEntry)) { - sLog->outErrorDb("Table `%s` has nonexistent item (entry: %u) in SCRIPT_COMMAND_CREATE_ITEM for script id %u", - tableName.c_str(), tmp.CreateItem.ItemEntry, tmp.id); - continue; + if (!GetItemTemplate(tmp.CreateItem.ItemEntry)) + { + sLog->outErrorDb("Table `%s` has nonexistent item (entry: %u) in SCRIPT_COMMAND_CREATE_ITEM for script id %u", + tableName.c_str(), tmp.CreateItem.ItemEntry, tmp.id); + continue; + } + if (!tmp.CreateItem.Amount) + { + sLog->outErrorDb("Table `%s` SCRIPT_COMMAND_CREATE_ITEM but amount is %u for script id %u", + tableName.c_str(), tmp.CreateItem.Amount, tmp.id); + continue; + } + break; } - if (!tmp.CreateItem.Amount) - { - sLog->outErrorDb("Table `%s` SCRIPT_COMMAND_CREATE_ITEM but amount is %u for script id %u", - tableName.c_str(), tmp.CreateItem.Amount, tmp.id); - continue; - } - break; - } default: break; } @@ -4928,8 +4982,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) (*scripts)[tmp.id].insert(std::pair(tmp.delay, tmp)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u script definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -4997,7 +5050,7 @@ void ObjectMgr::LoadEventScripts() std::set::const_iterator itr2 = evt_scripts.find(itr->first); if (itr2 == evt_scripts.end()) sLog->outErrorDb("Table `event_scripts` has script (Id: %u) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect %u", - itr->first, SPELL_EFFECT_SEND_EVENT); + itr->first, SPELL_EFFECT_SEND_EVENT); } } @@ -5022,8 +5075,7 @@ void ObjectMgr::LoadWaypointScripts() uint32 action = fields[0].GetUInt32(); actionSet.erase(action); - } - while (result->NextRow()); + } while (result->NextRow()); } for (std::set::iterator itr = actionSet.begin(); itr != actionSet.end(); ++itr) @@ -5053,7 +5105,7 @@ void ObjectMgr::LoadSpellScriptNames() Field* fields = result->Fetch(); int32 spellId = fields[0].GetInt32(); - const char *scriptName = fields[1].GetCString(); + const char* scriptName = fields[1].GetCString(); bool allRanks = false; if (spellId <= 0) @@ -5085,8 +5137,7 @@ void ObjectMgr::LoadSpellScriptNames() else _spellScriptsStore.insert(SpellScriptsContainer::value_type(spellInfo->Id, GetScriptId(scriptName))); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u spell script names in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -5108,11 +5159,11 @@ void ObjectMgr::ValidateSpellScripts() for (SpellScriptsContainer::iterator itr = _spellScriptsStore.begin(); itr != _spellScriptsStore.end();) { SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(itr->first); - std::vector > SpellScriptLoaders; + std::vector > SpellScriptLoaders; sScriptMgr->CreateSpellScriptLoaders(itr->first, SpellScriptLoaders); itr = _spellScriptsStore.upper_bound(itr->first); - for (std::vector >::iterator sitr = SpellScriptLoaders.begin(); sitr != SpellScriptLoaders.end(); ++sitr) + for (std::vector >::iterator sitr = SpellScriptLoaders.begin(); sitr != SpellScriptLoaders.end(); ++sitr) { SpellScript* spellScript = sitr->first->GetSpellScript(); AuraScript* auraScript = sitr->first->GetAuraScript(); @@ -5153,7 +5204,7 @@ void ObjectMgr::ValidateSpellScripts() void ObjectMgr::InitializeSpellInfoPrecomputedData() { uint32 limit = sSpellStore.GetNumRows(); - for(uint32 i=0; i<=limit; ++i) + for(uint32 i = 0; i <= limit; ++i) if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(i)) { const_cast(spellInfo)->SetStackableWithRanks(spellInfo->ComputeIsStackableWithRanks()); @@ -5187,8 +5238,7 @@ void ObjectMgr::LoadPageTexts() pageText.NextPage = fields[2].GetUInt32(); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); for (PageTextContainer::const_iterator itr = _pageTextStore.begin(); itr != _pageTextStore.end(); ++itr) { @@ -5280,8 +5330,7 @@ void ObjectMgr::LoadInstanceTemplate() _instanceTemplateStore[mapID] = instanceTemplate; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u instance templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -5346,27 +5395,27 @@ void ObjectMgr::LoadInstanceEncounters() switch (creditType) { case ENCOUNTER_CREDIT_KILL_CREATURE: - { - CreatureTemplate const* creatureInfo = GetCreatureTemplate(creditEntry); - if (!creatureInfo) { - sLog->outErrorDb("Table `instance_encounters` has an invalid creature (entry %u) linked to the encounter %u (%s), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); - continue; + CreatureTemplate const* creatureInfo = GetCreatureTemplate(creditEntry); + if (!creatureInfo) + { + sLog->outErrorDb("Table `instance_encounters` has an invalid creature (entry %u) linked to the encounter %u (%s), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); + continue; + } + const_cast(creatureInfo)->flags_extra |= CREATURE_FLAG_EXTRA_DUNGEON_BOSS; + break; } - const_cast(creatureInfo)->flags_extra |= CREATURE_FLAG_EXTRA_DUNGEON_BOSS; - break; - } case ENCOUNTER_CREDIT_CAST_SPELL: - { - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(creditEntry); - if (!spellInfo) { - sLog->outErrorDb("Table `instance_encounters` has an invalid spell (entry %u) linked to the encounter %u (%s), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); - continue; + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(creditEntry); + if (!spellInfo) + { + sLog->outErrorDb("Table `instance_encounters` has an invalid spell (entry %u) linked to the encounter %u (%s), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); + continue; + } + const_cast(spellInfo)->AttributesCu |= SPELL_ATTR0_CU_ENCOUNTER_REWARD; + break; } - const_cast(spellInfo)->AttributesCu |= SPELL_ATTR0_CU_ENCOUNTER_REWARD; - break; - } default: sLog->outErrorDb("Table `instance_encounters` has an invalid credit type (%u) for encounter %u (%s), skipped!", creditType, entry, dungeonEncounter->encounterName[0]); continue; @@ -5394,15 +5443,15 @@ void ObjectMgr::LoadGossipText() uint32 oldMSTime = getMSTime(); QueryResult result = WorldDatabase.Query("SELECT ID, " - "text0_0, text0_1, BroadcastTextID0, lang0, Probability0, em0_0, em0_1, em0_2, em0_3, em0_4, em0_5, " - "text1_0, text1_1, BroadcastTextID1, lang1, Probability1, em1_0, em1_1, em1_2, em1_3, em1_4, em1_5, " - "text2_0, text2_1, BroadcastTextID2, lang2, Probability2, em2_0, em2_1, em2_2, em2_3, em2_4, em2_5, " - "text3_0, text3_1, BroadcastTextID3, lang3, Probability3, em3_0, em3_1, em3_2, em3_3, em3_4, em3_5, " - "text4_0, text4_1, BroadcastTextID4, lang4, Probability4, em4_0, em4_1, em4_2, em4_3, em4_4, em4_5, " - "text5_0, text5_1, BroadcastTextID5, lang5, Probability5, em5_0, em5_1, em5_2, em5_3, em5_4, em5_5, " - "text6_0, text6_1, BroadcastTextID6, lang6, Probability6, em6_0, em6_1, em6_2, em6_3, em6_4, em6_5, " - "text7_0, text7_1, BroadcastTextID7, lang7, Probability7, em7_0, em7_1, em7_2, em7_3, em7_4, em7_5 " - "FROM npc_text"); + "text0_0, text0_1, BroadcastTextID0, lang0, Probability0, em0_0, em0_1, em0_2, em0_3, em0_4, em0_5, " + "text1_0, text1_1, BroadcastTextID1, lang1, Probability1, em1_0, em1_1, em1_2, em1_3, em1_4, em1_5, " + "text2_0, text2_1, BroadcastTextID2, lang2, Probability2, em2_0, em2_1, em2_2, em2_3, em2_4, em2_5, " + "text3_0, text3_1, BroadcastTextID3, lang3, Probability3, em3_0, em3_1, em3_2, em3_3, em3_4, em3_5, " + "text4_0, text4_1, BroadcastTextID4, lang4, Probability4, em4_0, em4_1, em4_2, em4_3, em4_4, em4_5, " + "text5_0, text5_1, BroadcastTextID5, lang5, Probability5, em5_0, em5_1, em5_2, em5_3, em5_4, em5_5, " + "text6_0, text6_1, BroadcastTextID6, lang6, Probability6, em6_0, em6_1, em6_2, em6_3, em6_4, em6_5, " + "text7_0, text7_1, BroadcastTextID7, lang7, Probability7, em7_0, em7_1, em7_2, em7_3, em7_4, em7_5 " + "FROM npc_text"); if (!result) { @@ -5474,9 +5523,9 @@ void ObjectMgr::LoadNpcTextLocales() _npcTextLocaleStore.clear(); // need for reload case QueryResult result = WorldDatabase.Query("SELECT ID, Locale, " - // 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 - "Text0_0, Text0_1, Text1_0, Text1_1, Text2_0, Text2_1, Text3_0, Text3_1, Text4_0, Text4_1, Text5_0, Text5_1, Text6_0, Text6_1, Text7_0, Text7_1 " - "FROM npc_text_locale"); + // 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 + "Text0_0, Text0_1, Text1_0, Text1_1, Text2_0, Text2_1, Text3_0, Text3_1, Text4_0, Text4_1, Text5_0, Text5_1, Text6_0, Text6_1, Text7_0, Text7_1 " + "FROM npc_text_locale"); if (!result) return; @@ -5622,8 +5671,7 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) CharacterDatabase.Execute(stmt); delete m; ++deletedCount; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Processed %u expired mails: %u deleted and %u returned in %u ms", deletedCount + returnedCount, deletedCount, returnedCount, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -5810,7 +5858,7 @@ void ObjectMgr::LoadAreaTriggerScripts() Field* fields = result->Fetch(); uint32 Trigger_ID = fields[0].GetUInt32(); - const char *scriptName = fields[1].GetCString(); + const char* scriptName = fields[1].GetCString(); AreaTrigger const* atEntry = GetAreaTrigger(Trigger_ID); if (!atEntry) @@ -5839,7 +5887,7 @@ uint32 ObjectMgr::GetNearestTaxiNode(float x, float y, float z, uint32 mapid, ui continue; uint8 field = (uint8)((i - 1) / 32); - uint32 submask = 1<<((i-1)%32); + uint32 submask = 1 << ((i - 1) % 32); // skip not taxi network nodes #ifndef ELUNA @@ -5849,7 +5897,7 @@ uint32 ObjectMgr::GetNearestTaxiNode(float x, float y, float z, uint32 mapid, ui #endif continue; - float dist2 = (node->x - x)*(node->x - x)+(node->y - y)*(node->y - y)+(node->z - z)*(node->z - z); + float dist2 = (node->x - x) * (node->x - x) + (node->y - y) * (node->y - y) + (node->z - z) * (node->z - z); if (found) { if (dist2 < dist) @@ -5869,7 +5917,7 @@ uint32 ObjectMgr::GetNearestTaxiNode(float x, float y, float z, uint32 mapid, ui return id; } -void ObjectMgr::GetTaxiPath(uint32 source, uint32 destination, uint32 &path, uint32 &cost) +void ObjectMgr::GetTaxiPath(uint32 source, uint32 destination, uint32& path, uint32& cost) { TaxiPathSetBySource::iterator src_i = sTaxiPathSetBySource.find(source); if (src_i == sTaxiPathSetBySource.end()) @@ -6186,7 +6234,7 @@ AreaTriggerTeleport const* ObjectMgr::GetMapEntranceTrigger(uint32 Map) const // xinef: no need to check, already done at loading //AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(itr->first); //if (atEntry) - return &itr->second; + return &itr->second; } } return nullptr; @@ -6196,12 +6244,12 @@ void ObjectMgr::SetHighestGuids() { QueryResult result = CharacterDatabase.Query("SELECT MAX(guid) FROM characters"); if (result) - _hiCharGuid = (*result)[0].GetUInt32()+1; + _hiCharGuid = (*result)[0].GetUInt32() + 1; result = WorldDatabase.Query("SELECT MAX(guid) FROM creature"); if (result) { - _hiCreatureGuid = (*result)[0].GetUInt32()+1; + _hiCreatureGuid = (*result)[0].GetUInt32() + 1; _hiCreatureRecycledGuid = _hiCreatureGuid; _hiCreatureRecycledGuidMax = _hiCreatureRecycledGuid + 10000; _hiCreatureGuid = _hiCreatureRecycledGuidMax + 1; @@ -6209,7 +6257,7 @@ void ObjectMgr::SetHighestGuids() result = CharacterDatabase.Query("SELECT MAX(guid) FROM item_instance"); if (result) - _hiItemGuid = (*result)[0].GetUInt32()+1; + _hiItemGuid = (*result)[0].GetUInt32() + 1; // Cleanup other tables from not existed guids ( >= _hiItemGuid) CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item >= '%u'", _hiItemGuid); // One-time query @@ -6220,7 +6268,7 @@ void ObjectMgr::SetHighestGuids() result = WorldDatabase.Query("SELECT MAX(guid) FROM gameobject"); if (result) { - _hiGoGuid = (*result)[0].GetUInt32()+1; + _hiGoGuid = (*result)[0].GetUInt32() + 1; _hiGoRecycledGuid = _hiGoGuid; _hiGoRecycledGuidMax = _hiGoRecycledGuid + 1; _hiGoGuid = _hiGoRecycledGuidMax + 1; @@ -6228,23 +6276,23 @@ void ObjectMgr::SetHighestGuids() result = WorldDatabase.Query("SELECT MAX(guid) FROM transports"); if (result) - _hiMoTransGuid = (*result)[0].GetUInt32()+1; + _hiMoTransGuid = (*result)[0].GetUInt32() + 1; result = CharacterDatabase.Query("SELECT MAX(id) FROM auctionhouse"); if (result) - _auctionId = (*result)[0].GetUInt32()+1; + _auctionId = (*result)[0].GetUInt32() + 1; result = CharacterDatabase.Query("SELECT MAX(id) FROM mail"); if (result) - _mailId = (*result)[0].GetUInt32()+1; + _mailId = (*result)[0].GetUInt32() + 1; result = CharacterDatabase.Query("SELECT MAX(corpseGuid) FROM corpse"); if (result) - _hiCorpseGuid = (*result)[0].GetUInt32()+1; + _hiCorpseGuid = (*result)[0].GetUInt32() + 1; result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team"); if (result) - sArenaTeamMgr->SetNextArenaTeamId((*result)[0].GetUInt32()+1); + sArenaTeamMgr->SetNextArenaTeamId((*result)[0].GetUInt32() + 1); result = CharacterDatabase.Query("SELECT MAX(fight_id) FROM log_arena_fights"); if (result) @@ -6252,11 +6300,11 @@ void ObjectMgr::SetHighestGuids() result = CharacterDatabase.Query("SELECT MAX(setguid) FROM character_equipmentsets"); if (result) - _equipmentSetGuid = (*result)[0].GetUInt64()+1; + _equipmentSetGuid = (*result)[0].GetUInt64() + 1; result = CharacterDatabase.Query("SELECT MAX(guildId) FROM guild"); if (result) - sGuildMgr->SetNextGuildId((*result)[0].GetUInt32()+1); + sGuildMgr->SetNextGuildId((*result)[0].GetUInt32() + 1); } uint32 ObjectMgr::GenerateAuctionID() @@ -6295,58 +6343,58 @@ uint32 ObjectMgr::GenerateLowGuid(HighGuid guidhigh) switch (guidhigh) { case HIGHGUID_ITEM: - { - ASSERT(_hiItemGuid < 0xFFFFFFFE && "Item guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiItemGuidMutex); - return _hiItemGuid++; - } + { + ASSERT(_hiItemGuid < 0xFFFFFFFE && "Item guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiItemGuidMutex); + return _hiItemGuid++; + } case HIGHGUID_UNIT: - { - ASSERT(_hiCreatureGuid < 0x00FFFFFE && "Creature guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiCreatureGuidMutex); - return _hiCreatureGuid++; - } + { + ASSERT(_hiCreatureGuid < 0x00FFFFFE && "Creature guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiCreatureGuidMutex); + return _hiCreatureGuid++; + } case HIGHGUID_PET: - { - ASSERT(_hiPetGuid < 0x00FFFFFE && "Pet guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiPetGuidMutex); - return _hiPetGuid++; - } + { + ASSERT(_hiPetGuid < 0x00FFFFFE && "Pet guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiPetGuidMutex); + return _hiPetGuid++; + } case HIGHGUID_VEHICLE: - { - ASSERT(_hiVehicleGuid < 0x00FFFFFF && "Vehicle guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiVehicleGuidMutex); - return _hiVehicleGuid++; - } + { + ASSERT(_hiVehicleGuid < 0x00FFFFFF && "Vehicle guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiVehicleGuidMutex); + return _hiVehicleGuid++; + } case HIGHGUID_PLAYER: - { - ASSERT(_hiCharGuid < 0xFFFFFFFE && "Player guid overflow!"); - return _hiCharGuid++; - } + { + ASSERT(_hiCharGuid < 0xFFFFFFFE && "Player guid overflow!"); + return _hiCharGuid++; + } case HIGHGUID_GAMEOBJECT: - { - ASSERT(_hiGoGuid < 0x00FFFFFE && "Gameobject guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiGoGuidMutex); - return _hiGoGuid++; - } + { + ASSERT(_hiGoGuid < 0x00FFFFFE && "Gameobject guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiGoGuidMutex); + return _hiGoGuid++; + } case HIGHGUID_CORPSE: - { - ASSERT(_hiCorpseGuid < 0xFFFFFFFE && "Corpse guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiCorpseGuidMutex); - return _hiCorpseGuid++; - } + { + ASSERT(_hiCorpseGuid < 0xFFFFFFFE && "Corpse guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiCorpseGuidMutex); + return _hiCorpseGuid++; + } case HIGHGUID_DYNAMICOBJECT: - { - ASSERT(_hiDoGuid < 0xFFFFFFFE && "DynamicObject guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiDoGuidMutex); - return _hiDoGuid++; - } + { + ASSERT(_hiDoGuid < 0xFFFFFFFE && "DynamicObject guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiDoGuidMutex); + return _hiDoGuid++; + } case HIGHGUID_MO_TRANSPORT: - { - ASSERT(_hiMoTransGuid < 0xFFFFFFFE && "MO Transport guid overflow!"); - ACORE_GUARD(ACE_Thread_Mutex, _hiMoTransGuidMutex); - return _hiMoTransGuid++; - } + { + ASSERT(_hiMoTransGuid < 0xFFFFFFFE && "MO Transport guid overflow!"); + ACORE_GUARD(ACE_Thread_Mutex, _hiMoTransGuidMutex); + return _hiMoTransGuid++; + } default: ASSERT(false && "ObjectMgr::GenerateLowGuid - Unknown HIGHGUID type"); return 0; @@ -6358,19 +6406,19 @@ uint32 ObjectMgr::GenerateRecycledLowGuid(HighGuid guidHigh) switch (guidHigh) { case HIGHGUID_UNIT: - { - ASSERT(_hiCreatureRecycledGuid < 0x00FFFFFE && "Creature recycled guid overflow!"); - if (_hiCreatureRecycledGuid < _hiCreatureRecycledGuidMax) - return _hiCreatureRecycledGuid++; - break; - } + { + ASSERT(_hiCreatureRecycledGuid < 0x00FFFFFE && "Creature recycled guid overflow!"); + if (_hiCreatureRecycledGuid < _hiCreatureRecycledGuidMax) + return _hiCreatureRecycledGuid++; + break; + } case HIGHGUID_GAMEOBJECT: - { - ASSERT(_hiGoRecycledGuid < 0x00FFFFFE && "Gameobject recycled guid overflow!"); - if (_hiGoRecycledGuid < _hiGoRecycledGuidMax) - return _hiGoRecycledGuid++; - break; - } + { + ASSERT(_hiGoRecycledGuid < 0x00FFFFFE && "Gameobject recycled guid overflow!"); + if (_hiGoRecycledGuid < _hiGoRecycledGuidMax) + return _hiGoRecycledGuid++; + break; + } default: // Default case is not handled by the recycler break; } @@ -6417,7 +6465,7 @@ inline void CheckGOLockId(GameObjectTemplate const* goInfo, uint32 dataN, uint32 return; sLog->outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but lock (Id: %u) not found.", - goInfo->entry, goInfo->type, N, goInfo->door.lockId, goInfo->door.lockId); + goInfo->entry, goInfo->type, N, goInfo->door.lockId, goInfo->door.lockId); } inline void CheckGOLinkedTrapId(GameObjectTemplate const* goInfo, uint32 dataN, uint32 N) @@ -6426,7 +6474,7 @@ inline void CheckGOLinkedTrapId(GameObjectTemplate const* goInfo, uint32 dataN, { if (trapInfo->type != GAMEOBJECT_TYPE_TRAP) sLog->outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but GO (Entry %u) have not GAMEOBJECT_TYPE_TRAP (%u) type.", - goInfo->entry, goInfo->type, N, dataN, dataN, GAMEOBJECT_TYPE_TRAP); + goInfo->entry, goInfo->type, N, dataN, dataN, GAMEOBJECT_TYPE_TRAP); } } @@ -6436,16 +6484,16 @@ inline void CheckGOSpellId(GameObjectTemplate const* goInfo, uint32 dataN, uint3 return; sLog->outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but Spell (Entry %u) not exist.", - goInfo->entry, goInfo->type, N, dataN, dataN); + goInfo->entry, goInfo->type, N, dataN, dataN); } inline void CheckAndFixGOChairHeightId(GameObjectTemplate const* goInfo, uint32 const& dataN, uint32 N) { - if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR)) + if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR - UNIT_STAND_STATE_SIT_LOW_CHAIR)) return; sLog->outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but correct chair height in range 0..%i.", - goInfo->entry, goInfo->type, N, dataN, UNIT_STAND_STATE_SIT_HIGH_CHAIR-UNIT_STAND_STATE_SIT_LOW_CHAIR); + goInfo->entry, goInfo->type, N, dataN, UNIT_STAND_STATE_SIT_HIGH_CHAIR - UNIT_STAND_STATE_SIT_LOW_CHAIR); // prevent client and server unexpected work const_cast(dataN) = 0; @@ -6467,7 +6515,7 @@ inline void CheckGOConsumable(GameObjectTemplate const* goInfo, uint32 dataN, ui return; sLog->outErrorDb("Gameobject (Entry: %u GoType: %u) have data%d=%u but expected boolean (0/1) consumable field value.", - goInfo->entry, goInfo->type, N, dataN); + goInfo->entry, goInfo->type, N, dataN); } void ObjectMgr::LoadGameObjectTemplate() @@ -6476,11 +6524,11 @@ void ObjectMgr::LoadGameObjectTemplate() // 0 1 2 3 4 5 6 7 QueryResult result = WorldDatabase.Query("SELECT entry, type, displayId, name, IconName, castBarCaption, unk1, size, " - // 8 9 10 11 12 13 14 15 16 17 18 19 20 - "Data0, Data1, Data2, Data3, Data4, Data5, Data6, Data7, Data8, Data9, Data10, Data11, Data12, " - // 21 22 23 24 25 26 27 28 29 30 31 32 33 - "Data13, Data14, Data15, Data16, Data17, Data18, Data19, Data20, Data21, Data22, Data23, AIName, ScriptName " - "FROM gameobject_template"); + // 8 9 10 11 12 13 14 15 16 17 18 19 20 + "Data0, Data1, Data2, Data3, Data4, Data5, Data6, Data7, Data8, Data9, Data10, Data11, Data12, " + // 21 22 23 24 25 26 27 28 29 30 31 32 33 + "Data13, Data14, Data15, Data16, Data17, Data18, Data19, Data20, Data21, Data22, Data23, AIName, ScriptName " + "FROM gameobject_template"); if (!result) { @@ -6520,137 +6568,136 @@ void ObjectMgr::LoadGameObjectTemplate() switch (got.type) { case GAMEOBJECT_TYPE_DOOR: //0 - { - if (got.door.lockId) - CheckGOLockId(&got, got.door.lockId, 1); - CheckGONoDamageImmuneId(&got, got.door.noDamageImmune, 3); - break; - } + { + if (got.door.lockId) + CheckGOLockId(&got, got.door.lockId, 1); + CheckGONoDamageImmuneId(&got, got.door.noDamageImmune, 3); + break; + } case GAMEOBJECT_TYPE_BUTTON: //1 - { - if (got.button.lockId) - CheckGOLockId(&got, got.button.lockId, 1); - CheckGONoDamageImmuneId(&got, got.button.noDamageImmune, 4); - break; - } + { + if (got.button.lockId) + CheckGOLockId(&got, got.button.lockId, 1); + CheckGONoDamageImmuneId(&got, got.button.noDamageImmune, 4); + break; + } case GAMEOBJECT_TYPE_QUESTGIVER: //2 - { - if (got.questgiver.lockId) - CheckGOLockId(&got, got.questgiver.lockId, 0); - CheckGONoDamageImmuneId(&got, got.questgiver.noDamageImmune, 5); - break; - } + { + if (got.questgiver.lockId) + CheckGOLockId(&got, got.questgiver.lockId, 0); + CheckGONoDamageImmuneId(&got, got.questgiver.noDamageImmune, 5); + break; + } case GAMEOBJECT_TYPE_CHEST: //3 - { - if (got.chest.lockId) - CheckGOLockId(&got, got.chest.lockId, 0); + { + if (got.chest.lockId) + CheckGOLockId(&got, got.chest.lockId, 0); - CheckGOConsumable(&got, got.chest.consumable, 3); + CheckGOConsumable(&got, got.chest.consumable, 3); - if (got.chest.linkedTrapId) // linked trap - CheckGOLinkedTrapId(&got, got.chest.linkedTrapId, 7); - break; - } + if (got.chest.linkedTrapId) // linked trap + CheckGOLinkedTrapId(&got, got.chest.linkedTrapId, 7); + break; + } case GAMEOBJECT_TYPE_TRAP: //6 - { - if (got.trap.lockId) - CheckGOLockId(&got, got.trap.lockId, 0); - break; - } + { + if (got.trap.lockId) + CheckGOLockId(&got, got.trap.lockId, 0); + break; + } case GAMEOBJECT_TYPE_CHAIR: //7 CheckAndFixGOChairHeightId(&got, got.chair.height, 1); break; case GAMEOBJECT_TYPE_SPELL_FOCUS: //8 - { - if (got.spellFocus.focusId) { - if (!sSpellFocusObjectStore.LookupEntry(got.spellFocus.focusId)) - sLog->outErrorDb("GameObject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.", - entry, got.type, got.spellFocus.focusId, got.spellFocus.focusId); - } + if (got.spellFocus.focusId) + { + if (!sSpellFocusObjectStore.LookupEntry(got.spellFocus.focusId)) + sLog->outErrorDb("GameObject (Entry: %u GoType: %u) have data0=%u but SpellFocus (Id: %u) not exist.", + entry, got.type, got.spellFocus.focusId, got.spellFocus.focusId); + } - if (got.spellFocus.linkedTrapId) // linked trap - CheckGOLinkedTrapId(&got, got.spellFocus.linkedTrapId, 2); - break; - } + if (got.spellFocus.linkedTrapId) // linked trap + CheckGOLinkedTrapId(&got, got.spellFocus.linkedTrapId, 2); + break; + } case GAMEOBJECT_TYPE_GOOBER: //10 - { - if (got.goober.lockId) - CheckGOLockId(&got, got.goober.lockId, 0); - - CheckGOConsumable(&got, got.goober.consumable, 3); - - if (got.goober.pageId) // pageId { - if (!GetPageText(got.goober.pageId)) - sLog->outErrorDb("GameObject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.", - entry, got.type, got.goober.pageId, got.goober.pageId); + if (got.goober.lockId) + CheckGOLockId(&got, got.goober.lockId, 0); + + CheckGOConsumable(&got, got.goober.consumable, 3); + + if (got.goober.pageId) // pageId + { + if (!GetPageText(got.goober.pageId)) + sLog->outErrorDb("GameObject (Entry: %u GoType: %u) have data7=%u but PageText (Entry %u) not exist.", + entry, got.type, got.goober.pageId, got.goober.pageId); + } + CheckGONoDamageImmuneId(&got, got.goober.noDamageImmune, 11); + if (got.goober.linkedTrapId) // linked trap + CheckGOLinkedTrapId(&got, got.goober.linkedTrapId, 12); + break; } - CheckGONoDamageImmuneId(&got, got.goober.noDamageImmune, 11); - if (got.goober.linkedTrapId) // linked trap - CheckGOLinkedTrapId(&got, got.goober.linkedTrapId, 12); - break; - } case GAMEOBJECT_TYPE_AREADAMAGE: //12 - { - if (got.areadamage.lockId) - CheckGOLockId(&got, got.areadamage.lockId, 0); - break; - } - case GAMEOBJECT_TYPE_CAMERA: //13 - { - if (got.camera.lockId) - CheckGOLockId(&got, got.camera.lockId, 0); - break; - } - case GAMEOBJECT_TYPE_MO_TRANSPORT: //15 - { - if (got.moTransport.taxiPathId) { - if (got.moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[got.moTransport.taxiPathId].empty()) - sLog->outErrorDb("GameObject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.", - entry, got.type, got.moTransport.taxiPathId, got.moTransport.taxiPathId); + if (got.areadamage.lockId) + CheckGOLockId(&got, got.areadamage.lockId, 0); + break; + } + case GAMEOBJECT_TYPE_CAMERA: //13 + { + if (got.camera.lockId) + CheckGOLockId(&got, got.camera.lockId, 0); + break; + } + case GAMEOBJECT_TYPE_MO_TRANSPORT: //15 + { + if (got.moTransport.taxiPathId) + { + if (got.moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[got.moTransport.taxiPathId].empty()) + sLog->outErrorDb("GameObject (Entry: %u GoType: %u) have data0=%u but TaxiPath (Id: %u) not exist.", + entry, got.type, got.moTransport.taxiPathId, got.moTransport.taxiPathId); + } + if (uint32 transportMap = got.moTransport.mapID) + _transportMaps.insert(transportMap); + break; } - if (uint32 transportMap = got.moTransport.mapID) - _transportMaps.insert(transportMap); - break; - } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18 break; case GAMEOBJECT_TYPE_SPELLCASTER: //22 - { - // always must have spell - CheckGOSpellId(&got, got.spellcaster.spellId, 0); - break; - } + { + // always must have spell + CheckGOSpellId(&got, got.spellcaster.spellId, 0); + break; + } case GAMEOBJECT_TYPE_FLAGSTAND: //24 - { - if (got.flagstand.lockId) - CheckGOLockId(&got, got.flagstand.lockId, 0); - CheckGONoDamageImmuneId(&got, got.flagstand.noDamageImmune, 5); - break; - } + { + if (got.flagstand.lockId) + CheckGOLockId(&got, got.flagstand.lockId, 0); + CheckGONoDamageImmuneId(&got, got.flagstand.noDamageImmune, 5); + break; + } case GAMEOBJECT_TYPE_FISHINGHOLE: //25 - { - if (got.fishinghole.lockId) - CheckGOLockId(&got, got.fishinghole.lockId, 4); - break; - } + { + if (got.fishinghole.lockId) + CheckGOLockId(&got, got.fishinghole.lockId, 4); + break; + } case GAMEOBJECT_TYPE_FLAGDROP: //26 - { - if (got.flagdrop.lockId) - CheckGOLockId(&got, got.flagdrop.lockId, 0); - CheckGONoDamageImmuneId(&got, got.flagdrop.noDamageImmune, 3); - break; - } + { + if (got.flagdrop.lockId) + CheckGOLockId(&got, got.flagdrop.lockId, 0); + CheckGONoDamageImmuneId(&got, got.flagdrop.noDamageImmune, 3); + break; + } case GAMEOBJECT_TYPE_BARBER_CHAIR: //32 CheckAndFixGOChairHeightId(&got, got.barberChair.chairheight, 0); break; } - ++count; - } - while (result->NextRow()); + ++count; + } while (result->NextRow()); sLog->outString(">> Loaded %u game object templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -6681,8 +6728,8 @@ void ObjectMgr::LoadGameObjectTemplateAddons() if (!got) { sLog->outErrorDb( - "GameObject template (Entry: %u) does not exist but has a record in `gameobject_template_addon`", - entry); + "GameObject template (Entry: %u) does not exist but has a record in `gameobject_template_addon`", + entry); continue; } @@ -6695,8 +6742,8 @@ void ObjectMgr::LoadGameObjectTemplateAddons() // checks if (gameObjectAddon.faction && !sFactionTemplateStore.LookupEntry(gameObjectAddon.faction)) sLog->outErrorDb( - "GameObject (Entry: %u) has invalid faction (%u) defined in `gameobject_template_addon`.", - entry, gameObjectAddon.faction); + "GameObject (Entry: %u) has invalid faction (%u) defined in `gameobject_template_addon`.", + entry, gameObjectAddon.faction); if (gameObjectAddon.maxgold > 0) { @@ -6707,15 +6754,14 @@ void ObjectMgr::LoadGameObjectTemplateAddons() break; default: sLog->outErrorDb( - "GameObject (Entry %u GoType: %u) cannot be looted but has maxgold set in `gameobject_template_addon`.", - entry, got->type); + "GameObject (Entry %u GoType: %u) cannot be looted but has maxgold set in `gameobject_template_addon`.", + entry, got->type); break; } } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u game object template addons in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -6743,8 +6789,7 @@ void ObjectMgr::LoadExplorationBaseXP() uint32 basexp = fields[1].GetInt32(); _baseXPTable[level] = basexp; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u BaseXP definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -6788,8 +6833,7 @@ void ObjectMgr::LoadPetNames() else _petHalfName0[entry].push_back(word); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u pet name parts in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -6803,17 +6847,17 @@ void ObjectMgr::LoadPetNumber() if (result) { Field* fields = result->Fetch(); - _hiPetNumber = fields[0].GetUInt32()+1; + _hiPetNumber = fields[0].GetUInt32() + 1; } - sLog->outString(">> Loaded the max pet number: %d in %u ms", _hiPetNumber-1, GetMSTimeDiffToNow(oldMSTime)); + sLog->outString(">> Loaded the max pet number: %d in %u ms", _hiPetNumber - 1, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } std::string ObjectMgr::GeneratePetName(uint32 entry) { - StringVector & list0 = _petHalfName0[entry]; - StringVector & list1 = _petHalfName1[entry]; + StringVector& list0 = _petHalfName0[entry]; + StringVector& list1 = _petHalfName1[entry]; if (list0.empty() || list1.empty()) { @@ -6825,7 +6869,7 @@ std::string ObjectMgr::GeneratePetName(uint32 entry) return std::string(petname); } - return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1)); + return *(list0.begin() + urand(0, list0.size() - 1)) + *(list1.begin() + urand(0, list1.size() - 1)); } uint32 ObjectMgr::GeneratePetNumber() @@ -6867,8 +6911,7 @@ void ObjectMgr::LoadCorpses() sObjectAccessor->AddCorpse(corpse); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u corpses in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -6956,8 +6999,7 @@ void ObjectMgr::LoadReputationRewardRate() _repRewardRateStore[factionId] = repRate; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u reputation_reward_rate in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -6973,9 +7015,9 @@ void ObjectMgr::LoadReputationOnKill() // 0 1 2 QueryResult result = WorldDatabase.Query("SELECT creature_id, RewOnKillRepFaction1, RewOnKillRepFaction2, " - // 3 4 5 6 7 8 9 - "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent " - "FROM creature_onkill_reputation"); + // 3 4 5 6 7 8 9 + "IsTeamAward1, MaxStanding1, RewOnKillRepValue1, IsTeamAward2, MaxStanding2, RewOnKillRepValue2, TeamDependent " + "FROM creature_onkill_reputation"); if (!result) { @@ -7141,8 +7183,7 @@ void ObjectMgr::LoadReputationSpilloverTemplate() _repSpilloverTemplateStore[factionId] = repTemplate; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u reputation_spillover_template in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -7321,8 +7362,7 @@ void ObjectMgr::LoadNPCSpellClickSpells() _spellClickInfoStore.insert(SpellClickInfoContainer::value_type(npc_entry, info)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // all spellclick data loaded, now we check if there are creatures with NPC_FLAG_SPELLCLICK but with no data // NOTE: It *CAN* be the other way around: no spellclick flag but with spellclick data, in case of creature-only vehicle accessories @@ -7496,7 +7536,7 @@ void ObjectMgr::LoadReservedPlayersNames() do { fields = result->Fetch(); - std::string name= fields[0].GetString(); + std::string name = fields[0].GetString(); std::wstring wstr; if (!Utf8toWStr (name, wstr)) @@ -7509,8 +7549,7 @@ void ObjectMgr::LoadReservedPlayersNames() _reservedNamesStore.insert(wstr); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u reserved player names in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -7519,7 +7558,7 @@ void ObjectMgr::LoadReservedPlayersNames() bool ObjectMgr::IsReservedName(const std::string& name) const { // pussywizard - if (name.size() >= 2 && (name[name.size()-2] == 'G' || name[name.size()-2] == 'g') && (name[name.size()-1] == 'M' || name[name.size()-1] == 'm')) + if (name.size() >= 2 && (name[name.size() - 2] == 'G' || name[name.size() - 2] == 'g') && (name[name.size() - 1] == 'M' || name[name.size() - 1] == 'm')) return true; std::wstring wstr; @@ -7623,7 +7662,7 @@ uint8 ObjectMgr::CheckPlayerName(const std::string& name, bool create) wstrToLower(wname); for (size_t i = 2; i < wname.size(); ++i) - if (wname[i] == wname[i-1] && wname[i] == wname[i-2]) + if (wname[i] == wname[i - 1] && wname[i] == wname[i - 2]) return CHAR_NAME_THREE_CONSECUTIVE; return CHAR_NAME_SUCCESS; @@ -7706,45 +7745,45 @@ void ObjectMgr::LoadGameObjectForQuests() ++count; break; case GAMEOBJECT_TYPE_CHEST: - { - // scan GO chest with loot including quest items - uint32 loot_id = (itr->second.GetLootId()); + { + // scan GO chest with loot including quest items + uint32 loot_id = (itr->second.GetLootId()); - // find quest loot for GO - if (itr->second.chest.questId || LootTemplates_Gameobject.HaveQuestLootFor(loot_id)) - { - itr->second.IsForQuests = true; - ++count; + // find quest loot for GO + if (itr->second.chest.questId || LootTemplates_Gameobject.HaveQuestLootFor(loot_id)) + { + itr->second.IsForQuests = true; + ++count; + } + break; } - break; - } case GAMEOBJECT_TYPE_GENERIC: - { - if (itr->second._generic.questID > 0) //quests objects { - itr->second.IsForQuests = true; - ++count; + if (itr->second._generic.questID > 0) //quests objects + { + itr->second.IsForQuests = true; + ++count; + } + break; } - break; - } case GAMEOBJECT_TYPE_SPELL_FOCUS: - { - if (itr->second.spellFocus.questID > 0) //quests objects { - itr->second.IsForQuests = true; - ++count; + if (itr->second.spellFocus.questID > 0) //quests objects + { + itr->second.IsForQuests = true; + ++count; + } + break; } - break; - } case GAMEOBJECT_TYPE_GOOBER: - { - if (itr->second.goober.questId > 0) //quests objects { - itr->second.IsForQuests = true; - ++count; + if (itr->second.goober.questId > 0) //quests objects + { + itr->second.IsForQuests = true; + ++count; + } + break; } - break; - } default: break; } @@ -7835,8 +7874,7 @@ void ObjectMgr::LoadFishingBaseSkillLevel() _fishingBaseForAreaStore[entry] = skill; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u areas for fishing base skill level in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -7872,7 +7910,7 @@ bool ObjectMgr::CheckDeclinedNames(std::wstring w_ownname, DeclinedName const& n if (!Utf8toWStr(names.name[i], wname)) return false; - if (mainpart != GetMainPartOfName(wname, i+1)) + if (mainpart != GetMainPartOfName(wname, i + 1)) x = false; if (w_ownname != wname) @@ -7884,7 +7922,7 @@ bool ObjectMgr::CheckDeclinedNames(std::wstring w_ownname, DeclinedName const& n uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id) { AreaTriggerScriptContainer::const_iterator i = _areaTriggerScriptStore.find(trigger_id); - if (i!= _areaTriggerScriptStore.end()) + if (i != _areaTriggerScriptStore.end()) return i->second; return 0; } @@ -7901,14 +7939,14 @@ int32 ObjectMgr::GetBaseReputationOf(FactionEntry const* factionEntry, uint8 rac return 0; uint32 raceMask = (1 << (race - 1)); - uint32 classMask = (1 << (playerClass-1)); + uint32 classMask = (1 << (playerClass - 1)); for (int i = 0; i < 4; i++) { if ((!factionEntry->BaseRepClassMask[i] || - factionEntry->BaseRepClassMask[i] & classMask) && - (!factionEntry->BaseRepRaceMask[i] || - factionEntry->BaseRepRaceMask[i] & raceMask)) + factionEntry->BaseRepClassMask[i] & classMask) && + (!factionEntry->BaseRepRaceMask[i] || + factionEntry->BaseRepRaceMask[i] & raceMask)) return factionEntry->BaseRepValue[i]; } @@ -7998,8 +8036,7 @@ void ObjectMgr::LoadGameTele() _gameTeleStore[id] = gt; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u GameTeleports in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -8143,8 +8180,7 @@ void ObjectMgr::LoadMailLevelRewards() _mailLevelRewardStore[level].push_back(MailLevelReward(raceMask, mailTemplateId, senderEntry)); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u level dependent mail rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -8209,7 +8245,7 @@ void ObjectMgr::AddSpellToTrainer(uint32 entry, uint32 spell, uint32 spellCost, trainerSpell.learnedSpell[0] = 0; // player must be able to cast spell on himself if (spellinfo->Effects[i].TargetA.GetTarget() != 0 && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_TARGET_ALLY - && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_TARGET_ANY && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_CASTER) + && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_TARGET_ANY && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_CASTER) { sLog->outErrorDb("Table `npc_trainer` has spell %u for trainer entry %u with learn effect which has incorrect target type, ignoring learn effect!", spell, entry); continue; @@ -8236,8 +8272,8 @@ void ObjectMgr::LoadTrainerSpell() _cacheTrainerSpellStore.clear(); QueryResult result = WorldDatabase.Query("SELECT b.ID, a.SpellID, a.MoneyCost, a.ReqSkillLine, a.ReqSkillRank, a.ReqLevel FROM npc_trainer AS a " - "INNER JOIN npc_trainer AS b ON a.ID = -(b.SpellID) " - "UNION SELECT * FROM npc_trainer WHERE SpellID > 0"); + "INNER JOIN npc_trainer AS b ON a.ID = -(b.SpellID) " + "UNION SELECT * FROM npc_trainer WHERE SpellID > 0"); if (!result) { @@ -8262,14 +8298,13 @@ void ObjectMgr::LoadTrainerSpell() AddSpellToTrainer(entry, spell, spellCost, reqSkill, reqSkillValue, reqLevel); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %d Trainers in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } -int ObjectMgr::LoadReferenceVendor(int32 vendor, int32 item, std::set *skip_vendors) +int ObjectMgr::LoadReferenceVendor(int32 vendor, int32 item, std::set* skip_vendors) { // find all items from the reference vendor PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_NPC_VENDOR_REF); @@ -8353,8 +8388,7 @@ void ObjectMgr::LoadVendors() vList.AddItem(item_id, maxcount, incrtime, ExtendedCost); ++count; } - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %d Vendors in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -8405,9 +8439,9 @@ void ObjectMgr::LoadGossipMenuItems() _gossipMenuItemsStore.clear(); QueryResult result = WorldDatabase.Query( - // 0 1 2 3 4 5 6 7 8 9 10 11 12 - "SELECT MenuID, OptionID, OptionIcon, OptionText, OptionBroadcastTextID, OptionType, OptionNpcFlag, ActionMenuID, ActionPoiID, BoxCoded, BoxMoney, BoxText, BoxBroadcastTextID " - "FROM gossip_menu_option ORDER BY MenuID, OptionID"); + // 0 1 2 3 4 5 6 7 8 9 10 11 12 + "SELECT MenuID, OptionID, OptionIcon, OptionText, OptionBroadcastTextID, OptionType, OptionNpcFlag, ActionMenuID, ActionPoiID, BoxCoded, BoxMoney, BoxText, BoxBroadcastTextID " + "FROM gossip_menu_option ORDER BY MenuID, OptionID"); if (!result) { @@ -8598,29 +8632,29 @@ void ObjectMgr::LoadScriptNames() _scriptNamesStore.push_back(""); QueryResult result = WorldDatabase.Query( - "SELECT DISTINCT(ScriptName) FROM achievement_criteria_data WHERE ScriptName <> '' AND type = 11 " - "UNION " - "SELECT DISTINCT(ScriptName) FROM battleground_template WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM spell_script_names WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM transports WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM game_weather WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM conditions WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(ScriptName) FROM outdoorpvp_template WHERE ScriptName <> '' " - "UNION " - "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''"); + "SELECT DISTINCT(ScriptName) FROM achievement_criteria_data WHERE ScriptName <> '' AND type = 11 " + "UNION " + "SELECT DISTINCT(ScriptName) FROM battleground_template WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM spell_script_names WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM transports WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM game_weather WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM conditions WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(ScriptName) FROM outdoorpvp_template WHERE ScriptName <> '' " + "UNION " + "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''"); if (!result) { @@ -8635,15 +8669,14 @@ void ObjectMgr::LoadScriptNames() { _scriptNamesStore.push_back((*result)[0].GetString()); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); std::sort(_scriptNamesStore.begin(), _scriptNamesStore.end()); sLog->outString(">> Loaded %d Script Names in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } -uint32 ObjectMgr::GetScriptId(const char *name) +uint32 ObjectMgr::GetScriptId(const char* name) { // use binary search to find the script name in the sorted vector // assume "" is the first element @@ -8737,8 +8770,7 @@ void ObjectMgr::LoadBroadcastTexts() } _broadcastTextStore[bct.Id] = bct; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded " SZFMTD " broadcast texts in %u ms", _broadcastTextStore.size(), GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -8780,8 +8812,7 @@ void ObjectMgr::LoadBroadcastTextLocales() AddLocaleString(MaleText, locale, bct->second.MaleText); AddLocaleString(FemaleText, locale, bct->second.FemaleText); - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u Broadcast Text Locales in %u ms", uint32(_broadcastTextStore.size()), GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -8880,8 +8911,7 @@ void ObjectMgr::LoadCreatureClassLevelStats() _creatureBaseStatsStore[MAKE_PAIR16(Level, Class)] = stats; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); CreatureTemplateContainer const* ctc = sObjectMgr->GetCreatureTemplates(); for (CreatureTemplateContainer::const_iterator itr = ctc->begin(); itr != ctc->end(); ++itr) @@ -8927,8 +8957,7 @@ void ObjectMgr::LoadFactionChangeAchievements() FactionChangeAchievements[alliance] = horde; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u faction change achievement pairs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -8964,8 +8993,7 @@ void ObjectMgr::LoadFactionChangeItems() FactionChangeItems[alliance] = horde; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u faction change item pairs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -9001,8 +9029,7 @@ void ObjectMgr::LoadFactionChangeQuests() FactionChangeQuests[alliance] = horde; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u faction change quest pairs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -9038,8 +9065,7 @@ void ObjectMgr::LoadFactionChangeReputations() FactionChangeReputation[alliance] = horde; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u faction change reputation pairs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -9075,8 +9101,7 @@ void ObjectMgr::LoadFactionChangeSpells() FactionChangeSpells[alliance] = horde; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u faction change spell pairs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -9111,8 +9136,7 @@ void ObjectMgr::LoadFactionChangeTitles() FactionChangeTitles[alliance] = horde; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u faction change title pairs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -9206,8 +9230,7 @@ void ObjectMgr::LoadGameObjectQuestItems() _gameObjectQuestItemStore[entry].push_back(item); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u gameobject quest items in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -9236,8 +9259,7 @@ void ObjectMgr::LoadCreatureQuestItems() _creatureQuestItemStore[entry].push_back(item); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creature quest items in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } diff --git a/src/server/game/Globals/ObjectMgr.h b/src/server/game/Globals/ObjectMgr.h index 0fdd03b12..85c68b27f 100644 --- a/src/server/game/Globals/ObjectMgr.h +++ b/src/server/game/Globals/ObjectMgr.h @@ -61,7 +61,7 @@ struct TempSummonGroupKey bool operator<(TempSummonGroupKey const& rhs) const { return std::tie(_summonerEntry, _summonerType, _summonGroup) < - std::tie(rhs._summonerEntry, rhs._summonerType, rhs._summonGroup); + std::tie(rhs._summonerEntry, rhs._summonerType, rhs._summonGroup); } private: @@ -222,7 +222,7 @@ struct ScriptInfo } MoveTo; struct // SCRIPT_COMMAND_FLAG_SET (4) - // SCRIPT_COMMAND_FLAG_REMOVE (5) + // SCRIPT_COMMAND_FLAG_REMOVE (5) { uint32 FieldID; // datalong uint32 FieldValue; // datalong2 @@ -271,13 +271,13 @@ struct ScriptInfo } TempSummonCreature; struct // SCRIPT_COMMAND_CLOSE_DOOR (12) - // SCRIPT_COMMAND_OPEN_DOOR (11) + // SCRIPT_COMMAND_OPEN_DOOR (11) { uint32 GOGuid; // datalong uint32 ResetDelay; // datalong2 } ToggleDoor; - // SCRIPT_COMMAND_ACTIVATE_OBJECT (13) + // SCRIPT_COMMAND_ACTIVATE_OBJECT (13) struct // SCRIPT_COMMAND_REMOVE_AURA (14) { @@ -353,7 +353,7 @@ struct ScriptInfo uint32 ModelID; // datalong } Model; - // SCRIPT_COMMAND_CLOSE_GOSSIP (33) + // SCRIPT_COMMAND_CLOSE_GOSSIP (33) struct // SCRIPT_COMMAND_PLAYMOVIE (34) { @@ -422,7 +422,7 @@ struct AreaTrigger struct BroadcastText { BroadcastText() : Id(0), Language(0), EmoteId0(0), EmoteId1(0), EmoteId2(0), - EmoteDelay0(0), EmoteDelay1(0), EmoteDelay2(0), SoundId(0), Unk1(0), Unk2(0) + EmoteDelay0(0), EmoteDelay1(0), EmoteDelay2(0), SoundId(0), Unk1(0), Unk2(0) { MaleText.resize(DEFAULT_LOCALE + 1); FemaleText.resize(DEFAULT_LOCALE + 1); @@ -511,7 +511,7 @@ typedef std::pair ItemMap; + typedef std::unordered_map ItemMap; - typedef std::unordered_map QuestMap; + typedef std::unordered_map QuestMap; - typedef std::unordered_map AreaTriggerContainer; + typedef std::unordered_map AreaTriggerContainer; - typedef std::unordered_map AreaTriggerTeleportContainer; + typedef std::unordered_map AreaTriggerTeleportContainer; - typedef std::unordered_map AreaTriggerScriptContainer; + typedef std::unordered_map AreaTriggerScriptContainer; - typedef std::unordered_map AccessRequirementContainer; + typedef std::unordered_map AccessRequirementContainer; - typedef std::unordered_map RepRewardRateContainer; - typedef std::unordered_map RepOnKillContainer; - typedef std::unordered_map RepSpilloverTemplateContainer; + typedef std::unordered_map RepRewardRateContainer; + typedef std::unordered_map RepOnKillContainer; + typedef std::unordered_map RepSpilloverTemplateContainer; - typedef std::unordered_map PointOfInterestContainer; + typedef std::unordered_map PointOfInterestContainer; - typedef std::vector ScriptNameContainer; + typedef std::vector ScriptNameContainer; - typedef std::map CharacterConversionMap; + typedef std::map CharacterConversionMap; - Player* GetPlayerByLowGUID(uint32 lowguid) const; + Player* GetPlayerByLowGUID(uint32 lowguid) const; - GameObjectTemplate const* GetGameObjectTemplate(uint32 entry); - bool IsGameObjectStaticTransport(uint32 entry); - GameObjectTemplateContainer const* GetGameObjectTemplates() const { return &_gameObjectTemplateStore; } - int LoadReferenceVendor(int32 vendor, int32 item_id, std::set *skip_vendors); + GameObjectTemplate const* GetGameObjectTemplate(uint32 entry); + bool IsGameObjectStaticTransport(uint32 entry); + GameObjectTemplateContainer const* GetGameObjectTemplates() const { return &_gameObjectTemplateStore; } + int LoadReferenceVendor(int32 vendor, int32 item_id, std::set* skip_vendors); - void LoadGameObjectTemplate(); - void LoadGameObjectTemplateAddons(); - void AddGameobjectInfo(GameObjectTemplate* goinfo); + void LoadGameObjectTemplate(); + void LoadGameObjectTemplateAddons(); + void AddGameobjectInfo(GameObjectTemplate* goinfo); - CreatureTemplate const* GetCreatureTemplate(uint32 entry); - CreatureTemplateContainer const* GetCreatureTemplates() const { return &_creatureTemplateStore; } - CreatureModelInfo const* GetCreatureModelInfo(uint32 modelId); - CreatureModelInfo const* GetCreatureModelRandomGender(uint32* displayID); - static uint32 ChooseDisplayId(CreatureTemplate const* cinfo, CreatureData const* data = nullptr); - static void ChooseCreatureFlags(CreatureTemplate const* cinfo, uint32& npcflag, uint32& unit_flags, uint32& dynamicflags, CreatureData const* data = nullptr); - EquipmentInfo const* GetEquipmentInfo(uint32 entry, int8& id); - CreatureAddon const* GetCreatureAddon(uint32 lowguid); - GameObjectAddon const* GetGameObjectAddon(uint32 lowguid); - GameObjectTemplateAddon const* GetGameObjectTemplateAddon(uint32 entry) const; - CreatureAddon const* GetCreatureTemplateAddon(uint32 entry); - ItemTemplate const* GetItemTemplate(uint32 entry); - ItemTemplateContainer const* GetItemTemplateStore() const { return &_itemTemplateStore; } - std::vector const* GetItemTemplateStoreFast() const { return &_itemTemplateStoreFast; } + CreatureTemplate const* GetCreatureTemplate(uint32 entry); + CreatureTemplateContainer const* GetCreatureTemplates() const { return &_creatureTemplateStore; } + CreatureModelInfo const* GetCreatureModelInfo(uint32 modelId); + CreatureModelInfo const* GetCreatureModelRandomGender(uint32* displayID); + static uint32 ChooseDisplayId(CreatureTemplate const* cinfo, CreatureData const* data = nullptr); + static void ChooseCreatureFlags(CreatureTemplate const* cinfo, uint32& npcflag, uint32& unit_flags, uint32& dynamicflags, CreatureData const* data = nullptr); + EquipmentInfo const* GetEquipmentInfo(uint32 entry, int8& id); + CreatureAddon const* GetCreatureAddon(uint32 lowguid); + GameObjectAddon const* GetGameObjectAddon(uint32 lowguid); + GameObjectTemplateAddon const* GetGameObjectTemplateAddon(uint32 entry) const; + CreatureAddon const* GetCreatureTemplateAddon(uint32 entry); + ItemTemplate const* GetItemTemplate(uint32 entry); + ItemTemplateContainer const* GetItemTemplateStore() const { return &_itemTemplateStore; } + std::vector const* GetItemTemplateStoreFast() const { return &_itemTemplateStoreFast; } - ItemSetNameEntry const* GetItemSetNameEntry(uint32 itemId) - { - ItemSetNameContainer::iterator itr = _itemSetNameStore.find(itemId); - if (itr != _itemSetNameStore.end()) - return &itr->second; - return nullptr; - } - - InstanceTemplate const* GetInstanceTemplate(uint32 mapId); - - PetLevelInfo const* GetPetLevelInfo(uint32 creature_id, uint8 level) const; - - PlayerClassInfo const* GetPlayerClassInfo(uint32 class_) const - { - if (class_ >= MAX_CLASSES) - return nullptr; - return _playerClassInfo[class_]; - } - void GetPlayerClassLevelInfo(uint32 class_, uint8 level, PlayerClassLevelInfo* info) const; - - PlayerInfo const* GetPlayerInfo(uint32 race, uint32 class_) const; - - void GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, PlayerLevelInfo* info) const; - - uint64 GetPlayerGUIDByName(std::string const& name) const; - bool GetPlayerNameByGUID(uint64 guid, std::string &name) const; - TeamId GetPlayerTeamIdByGUID(uint64 guid) const; - uint32 GetPlayerAccountIdByGUID(uint64 guid) const; - uint32 GetPlayerAccountIdByPlayerName(std::string const& name) const; - - uint32 GetNearestTaxiNode(float x, float y, float z, uint32 mapid, uint32 teamId); - void GetTaxiPath(uint32 source, uint32 destination, uint32 &path, uint32 &cost); - uint32 GetTaxiMountDisplayId(uint32 id, TeamId teamId, bool allowed_alt_team = false); - - GameObjectQuestItemList const* GetGameObjectQuestItemList(uint32 id) const - { - GameObjectQuestItemMap::const_iterator itr = _gameObjectQuestItemStore.find(id); - if (itr != _gameObjectQuestItemStore.end()) - return &itr->second; - return nullptr; - } - GameObjectQuestItemMap const* GetGameObjectQuestItemMap() const { return &_gameObjectQuestItemStore; } - - CreatureQuestItemList const* GetCreatureQuestItemList(uint32 id) const - { - CreatureQuestItemMap::const_iterator itr = _creatureQuestItemStore.find(id); - if (itr != _creatureQuestItemStore.end()) - return &itr->second; - return nullptr; - } - CreatureQuestItemMap const* GetCreatureQuestItemMap() const { return &_creatureQuestItemStore; } - - Quest const* GetQuestTemplate(uint32 quest_id) const - { - return quest_id < _questTemplatesFast.size() ? _questTemplatesFast[quest_id] : nullptr; - } - - QuestMap const& GetQuestTemplates() const { return _questTemplates; } - - uint32 GetQuestForAreaTrigger(uint32 Trigger_ID) const - { - QuestAreaTriggerContainer::const_iterator itr = _questAreaTriggerStore.find(Trigger_ID); - if (itr != _questAreaTriggerStore.end()) - return itr->second; - return 0; - } - - bool IsTavernAreaTrigger(uint32 Trigger_ID) const - { - return _tavernAreaTriggerStore.find(Trigger_ID) != _tavernAreaTriggerStore.end(); - } - - GossipText const* GetGossipText(uint32 Text_ID) const; - - AreaTrigger const* GetAreaTrigger(uint32 trigger) const - { - AreaTriggerContainer::const_iterator itr = _areaTriggerStore.find(trigger); - if (itr != _areaTriggerStore.end()) - return &itr->second; - return nullptr; - } - - AreaTriggerTeleport const* GetAreaTriggerTeleport(uint32 trigger) const - { - AreaTriggerTeleportContainer::const_iterator itr = _areaTriggerTeleportStore.find(trigger); - if (itr != _areaTriggerTeleportStore.end()) - return &itr->second; - return nullptr; - } - - AccessRequirement const* GetAccessRequirement(uint32 mapid, Difficulty difficulty) const - { - AccessRequirementContainer::const_iterator itr = _accessRequirementStore.find(MAKE_PAIR32(mapid, difficulty)); - if (itr != _accessRequirementStore.end()) - return itr->second; - return nullptr; - } - - AreaTriggerTeleport const* GetGoBackTrigger(uint32 Map) const; - AreaTriggerTeleport const* GetMapEntranceTrigger(uint32 Map) const; - - uint32 GetAreaTriggerScriptId(uint32 trigger_id); - SpellScriptsBounds GetSpellScriptsBounds(uint32 spell_id); - - RepRewardRate const* GetRepRewardRate(uint32 factionId) const - { - RepRewardRateContainer::const_iterator itr = _repRewardRateStore.find(factionId); - if (itr != _repRewardRateStore.end()) - return &itr->second; - - return nullptr; - } - - ReputationOnKillEntry const* GetReputationOnKilEntry(uint32 id) const - { - RepOnKillContainer::const_iterator itr = _repOnKillStore.find(id); - if (itr != _repOnKillStore.end()) - return &itr->second; - return nullptr; - } - - int32 GetBaseReputationOf(FactionEntry const* factionEntry, uint8 race, uint8 playerClass); - - RepSpilloverTemplate const* GetRepSpilloverTemplate(uint32 factionId) const - { - RepSpilloverTemplateContainer::const_iterator itr = _repSpilloverTemplateStore.find(factionId); - if (itr != _repSpilloverTemplateStore.end()) - return &itr->second; - - return nullptr; - } - - PointOfInterest const* GetPointOfInterest(uint32 id) const - { - PointOfInterestContainer::const_iterator itr = _pointsOfInterestStore.find(id); - if (itr != _pointsOfInterestStore.end()) - return &itr->second; - return nullptr; - } - - QuestPOIVector const* GetQuestPOIVector(uint32 questId) - { - QuestPOIContainer::const_iterator itr = _questPOIStore.find(questId); - if (itr != _questPOIStore.end()) - return &itr->second; - return nullptr; - } - - VehicleAccessoryList const* GetVehicleAccessoryList(Vehicle* veh) const; - - DungeonEncounterList const* GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) - { - std::unordered_map::const_iterator itr = _dungeonEncounterStore.find(MAKE_PAIR32(mapId, difficulty)); - if (itr != _dungeonEncounterStore.end()) - return &itr->second; - return nullptr; - } - - void LoadQuests(); - void LoadQuestStartersAndEnders() - { - sLog->outString("Loading GO Start Quest Data..."); - LoadGameobjectQuestStarters(); - sLog->outString("Loading GO End Quest Data..."); - LoadGameobjectQuestEnders(); - sLog->outString("Loading Creature Start Quest Data..."); - LoadCreatureQuestStarters(); - sLog->outString("Loading Creature End Quest Data..."); - LoadCreatureQuestEnders(); - } - void LoadGameobjectQuestStarters(); - void LoadGameobjectQuestEnders(); - void LoadCreatureQuestStarters(); - void LoadCreatureQuestEnders(); - - QuestRelations* GetGOQuestRelationMap() - { - return &_goQuestRelations; - } - - QuestRelations* GetGOQuestInvolvedRelationMap() - { - return &_goQuestInvolvedRelations; - } - - QuestRelationBounds GetGOQuestRelationBounds(uint32 go_entry) - { - return _goQuestRelations.equal_range(go_entry); - } - - QuestRelationBounds GetGOQuestInvolvedRelationBounds(uint32 go_entry) - { - return _goQuestInvolvedRelations.equal_range(go_entry); - } - - QuestRelations* GetCreatureQuestRelationMap() - { - return &_creatureQuestRelations; - } - - QuestRelations* GetCreatureQuestInvolvedRelationMap() - { - return &_creatureQuestInvolvedRelations; - } - - QuestRelationBounds GetCreatureQuestRelationBounds(uint32 creature_entry) - { - return _creatureQuestRelations.equal_range(creature_entry); - } - - QuestRelationBounds GetCreatureQuestInvolvedRelationBounds(uint32 creature_entry) - { - return _creatureQuestInvolvedRelations.equal_range(creature_entry); - } - - void LoadEventScripts(); - void LoadSpellScripts(); - void LoadWaypointScripts(); - - void LoadSpellScriptNames(); - void ValidateSpellScripts(); - void InitializeSpellInfoPrecomputedData(); - - bool LoadAcoreStrings(); - void LoadBroadcastTexts(); - void LoadBroadcastTextLocales(); - void LoadCreatureClassLevelStats(); - void LoadCreatureLocales(); - void LoadCreatureTemplates(); - void LoadCreatureTemplateAddons(); - void CheckCreatureTemplate(CreatureTemplate const* cInfo); - void LoadGameObjectQuestItems(); - void LoadCreatureQuestItems(); - void LoadTempSummons(); - void LoadCreatures(); - void LoadLinkedRespawn(); - bool SetCreatureLinkedRespawn(uint32 guid, uint32 linkedGuid); - void LoadCreatureAddons(); - void LoadGameObjectAddons(); - void LoadCreatureModelInfo(); - void LoadEquipmentTemplates(); - void LoadGameObjectLocales(); - void LoadGameobjects(); - void LoadItemTemplates(); - void LoadItemLocales(); - void LoadItemSetNames(); - void LoadItemSetNameLocales(); - void LoadQuestLocales(); - void LoadNpcTextLocales(); - void LoadQuestOfferRewardLocale(); - void LoadQuestRequestItemsLocale(); - void LoadPageTextLocales(); - void LoadGossipMenuItemsLocales(); - void LoadPointOfInterestLocales(); - void LoadInstanceTemplate(); - void LoadInstanceEncounters(); - void LoadMailLevelRewards(); - void LoadVehicleTemplateAccessories(); - void LoadVehicleAccessories(); - - void LoadGossipText(); - - void LoadAreaTriggers(); - void LoadAreaTriggerTeleports(); - void LoadAccessRequirements(); - void LoadQuestAreaTriggers(); - void LoadAreaTriggerScripts(); - void LoadTavernAreaTriggers(); - void LoadGameObjectForQuests(); - - void LoadPageTexts(); - PageText const* GetPageText(uint32 pageEntry); - - void LoadPlayerInfo(); - void LoadPetLevelInfo(); - void LoadExplorationBaseXP(); - void LoadPetNames(); - void LoadPetNumber(); - void LoadCorpses(); - void LoadFishingBaseSkillLevel(); - void ChangeFishingBaseSkillLevel(uint32 entry, int32 skill); - - void LoadReputationRewardRate(); - void LoadReputationOnKill(); - void LoadReputationSpilloverTemplate(); - - void LoadPointsOfInterest(); - void LoadQuestPOI(); - - void LoadNPCSpellClickSpells(); - - void LoadGameTele(); - - void LoadGossipMenu(); - void LoadGossipMenuItems(); - - void LoadVendors(); - void LoadTrainerSpell(); - void AddSpellToTrainer(uint32 entry, uint32 spell, uint32 spellCost, uint32 reqSkill, uint32 reqSkillValue, uint32 reqLevel); - - std::string GeneratePetName(uint32 entry); - uint32 GetBaseXP(uint8 level); - uint32 GetXPForLevel(uint8 level) const; - - int32 GetFishingBaseSkillLevel(uint32 entry) const - { - FishingBaseSkillContainer::const_iterator itr = _fishingBaseForAreaStore.find(entry); - return itr != _fishingBaseForAreaStore.end() ? itr->second : 0; - } - - void ReturnOrDeleteOldMails(bool serverUp); - - CreatureBaseStats const* GetCreatureBaseStats(uint8 level, uint8 unitClass); - - void SetHighestGuids(); - uint32 GenerateLowGuid(HighGuid guidhigh); - uint32 GenerateRecycledLowGuid(HighGuid guidHigh); - uint32 GenerateAuctionID(); - uint64 GenerateEquipmentSetGuid(); - uint32 GenerateMailID(); - uint32 GeneratePetNumber(); - - typedef std::multimap ExclusiveQuestGroups; - typedef std::pair ExclusiveQuestGroupsBounds; - - ExclusiveQuestGroups mExclusiveQuestGroups; - - MailLevelReward const* GetMailLevelReward(uint32 level, uint32 raceMask) - { - MailLevelRewardContainer::const_iterator map_itr = _mailLevelRewardStore.find(level); - if (map_itr == _mailLevelRewardStore.end()) - return nullptr; - - for (MailLevelRewardList::const_iterator set_itr = map_itr->second.begin(); set_itr != map_itr->second.end(); ++set_itr) - if (set_itr->raceMask & raceMask) - return &*set_itr; - - return nullptr; - } - - CellObjectGuids const& GetCellObjectGuids(uint16 mapid, uint8 spawnMode, uint32 cell_id) - { - MapObjectGuids::const_iterator itr1 = _mapObjectGuidsStore.find(MAKE_PAIR32(mapid, spawnMode)); - if (itr1 != _mapObjectGuidsStore.end()) - { - CellObjectGuidsMap::const_iterator itr2 = itr1->second.find(cell_id); - if (itr2 != itr1->second.end()) - return itr2->second; - } - return _emptyCellObjectGuids; - } - - CellObjectGuidsMap const& GetMapObjectGuids(uint16 mapid, uint8 spawnMode) - { - MapObjectGuids::const_iterator itr1 = _mapObjectGuidsStore.find(MAKE_PAIR32(mapid, spawnMode)); - if (itr1 != _mapObjectGuidsStore.end()) - return itr1->second; - return _emptyCellObjectGuidsMap; - } - - /** - * Gets temp summon data for all creatures of specified group. - * - * @param summonerId Summoner's entry. - * @param summonerType Summoner's type, see SummonerType for available types. - * @param group Id of required group. - * - * @return null if group was not found, otherwise reference to the creature group data - */ - std::vector const* GetSummonGroup(uint32 summonerId, SummonerType summonerType, uint8 group) const - { - TempSummonDataContainer::const_iterator itr = _tempSummonDataStore.find(TempSummonGroupKey(summonerId, summonerType, group)); - if (itr != _tempSummonDataStore.end()) - return &itr->second; - - return nullptr; - } - - BroadcastText const* GetBroadcastText(uint32 id) const - { - BroadcastTextContainer::const_iterator itr = _broadcastTextStore.find(id); - if (itr != _broadcastTextStore.end()) - return &itr->second; - return nullptr; - } - CreatureData const* GetCreatureData(uint32 guid) const - { - CreatureDataContainer::const_iterator itr = _creatureDataStore.find(guid); - if (itr == _creatureDataStore.end()) return nullptr; + ItemSetNameEntry const* GetItemSetNameEntry(uint32 itemId) + { + ItemSetNameContainer::iterator itr = _itemSetNameStore.find(itemId); + if (itr != _itemSetNameStore.end()) return &itr->second; - } - CreatureData& NewOrExistCreatureData(uint32 guid) { return _creatureDataStore[guid]; } - void DeleteCreatureData(uint32 guid); - uint64 GetLinkedRespawnGuid(uint64 guid) const - { - LinkedRespawnContainer::const_iterator itr = _linkedRespawnStore.find(guid); - if (itr == _linkedRespawnStore.end()) return 0; + return nullptr; + } + + InstanceTemplate const* GetInstanceTemplate(uint32 mapId); + + PetLevelInfo const* GetPetLevelInfo(uint32 creature_id, uint8 level) const; + + PlayerClassInfo const* GetPlayerClassInfo(uint32 class_) const + { + if (class_ >= MAX_CLASSES) + return nullptr; + return _playerClassInfo[class_]; + } + void GetPlayerClassLevelInfo(uint32 class_, uint8 level, PlayerClassLevelInfo* info) const; + + PlayerInfo const* GetPlayerInfo(uint32 race, uint32 class_) const; + + void GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, PlayerLevelInfo* info) const; + + uint64 GetPlayerGUIDByName(std::string const& name) const; + bool GetPlayerNameByGUID(uint64 guid, std::string& name) const; + TeamId GetPlayerTeamIdByGUID(uint64 guid) const; + uint32 GetPlayerAccountIdByGUID(uint64 guid) const; + uint32 GetPlayerAccountIdByPlayerName(std::string const& name) const; + + uint32 GetNearestTaxiNode(float x, float y, float z, uint32 mapid, uint32 teamId); + void GetTaxiPath(uint32 source, uint32 destination, uint32& path, uint32& cost); + uint32 GetTaxiMountDisplayId(uint32 id, TeamId teamId, bool allowed_alt_team = false); + + GameObjectQuestItemList const* GetGameObjectQuestItemList(uint32 id) const + { + GameObjectQuestItemMap::const_iterator itr = _gameObjectQuestItemStore.find(id); + if (itr != _gameObjectQuestItemStore.end()) + return &itr->second; + return nullptr; + } + GameObjectQuestItemMap const* GetGameObjectQuestItemMap() const { return &_gameObjectQuestItemStore; } + + CreatureQuestItemList const* GetCreatureQuestItemList(uint32 id) const + { + CreatureQuestItemMap::const_iterator itr = _creatureQuestItemStore.find(id); + if (itr != _creatureQuestItemStore.end()) + return &itr->second; + return nullptr; + } + CreatureQuestItemMap const* GetCreatureQuestItemMap() const { return &_creatureQuestItemStore; } + + Quest const* GetQuestTemplate(uint32 quest_id) const + { + return quest_id < _questTemplatesFast.size() ? _questTemplatesFast[quest_id] : nullptr; + } + + QuestMap const& GetQuestTemplates() const { return _questTemplates; } + + uint32 GetQuestForAreaTrigger(uint32 Trigger_ID) const + { + QuestAreaTriggerContainer::const_iterator itr = _questAreaTriggerStore.find(Trigger_ID); + if (itr != _questAreaTriggerStore.end()) return itr->second; - } + return 0; + } - GameObjectData const* GetGOData(uint32 guid) const - { - GameObjectDataContainer::const_iterator itr = _gameObjectDataStore.find(guid); - if (itr == _gameObjectDataStore.end()) return nullptr; + bool IsTavernAreaTrigger(uint32 Trigger_ID) const + { + return _tavernAreaTriggerStore.find(Trigger_ID) != _tavernAreaTriggerStore.end(); + } + + GossipText const* GetGossipText(uint32 Text_ID) const; + + AreaTrigger const* GetAreaTrigger(uint32 trigger) const + { + AreaTriggerContainer::const_iterator itr = _areaTriggerStore.find(trigger); + if (itr != _areaTriggerStore.end()) return &itr->second; - } - CreatureLocale const* GetCreatureLocale(uint32 entry) const - { - CreatureLocaleContainer::const_iterator itr = _creatureLocaleStore.find(entry); - if (itr == _creatureLocaleStore.end()) return nullptr; + return nullptr; + } + + AreaTriggerTeleport const* GetAreaTriggerTeleport(uint32 trigger) const + { + AreaTriggerTeleportContainer::const_iterator itr = _areaTriggerTeleportStore.find(trigger); + if (itr != _areaTriggerTeleportStore.end()) return &itr->second; - } - GameObjectLocale const* GetGameObjectLocale(uint32 entry) const - { - GameObjectLocaleContainer::const_iterator itr = _gameObjectLocaleStore.find(entry); - if (itr == _gameObjectLocaleStore.end()) return nullptr; + return nullptr; + } + + AccessRequirement const* GetAccessRequirement(uint32 mapid, Difficulty difficulty) const + { + AccessRequirementContainer::const_iterator itr = _accessRequirementStore.find(MAKE_PAIR32(mapid, difficulty)); + if (itr != _accessRequirementStore.end()) + return itr->second; + return nullptr; + } + + AreaTriggerTeleport const* GetGoBackTrigger(uint32 Map) const; + AreaTriggerTeleport const* GetMapEntranceTrigger(uint32 Map) const; + + uint32 GetAreaTriggerScriptId(uint32 trigger_id); + SpellScriptsBounds GetSpellScriptsBounds(uint32 spell_id); + + RepRewardRate const* GetRepRewardRate(uint32 factionId) const + { + RepRewardRateContainer::const_iterator itr = _repRewardRateStore.find(factionId); + if (itr != _repRewardRateStore.end()) return &itr->second; - } - ItemLocale const* GetItemLocale(uint32 entry) const - { - ItemLocaleContainer::const_iterator itr = _itemLocaleStore.find(entry); - if (itr == _itemLocaleStore.end()) return nullptr; + + return nullptr; + } + + ReputationOnKillEntry const* GetReputationOnKilEntry(uint32 id) const + { + RepOnKillContainer::const_iterator itr = _repOnKillStore.find(id); + if (itr != _repOnKillStore.end()) return &itr->second; - } - ItemSetNameLocale const* GetItemSetNameLocale(uint32 entry) const - { - ItemSetNameLocaleContainer::const_iterator itr = _itemSetNameLocaleStore.find(entry); - if (itr == _itemSetNameLocaleStore.end())return nullptr; + return nullptr; + } + + int32 GetBaseReputationOf(FactionEntry const* factionEntry, uint8 race, uint8 playerClass); + + RepSpilloverTemplate const* GetRepSpilloverTemplate(uint32 factionId) const + { + RepSpilloverTemplateContainer::const_iterator itr = _repSpilloverTemplateStore.find(factionId); + if (itr != _repSpilloverTemplateStore.end()) return &itr->second; - } - PageTextLocale const* GetPageTextLocale(uint32 entry) const - { - PageTextLocaleContainer::const_iterator itr = _pageTextLocaleStore.find(entry); - if (itr == _pageTextLocaleStore.end()) return nullptr; + + return nullptr; + } + + PointOfInterest const* GetPointOfInterest(uint32 id) const + { + PointOfInterestContainer::const_iterator itr = _pointsOfInterestStore.find(id); + if (itr != _pointsOfInterestStore.end()) return &itr->second; - } - QuestLocale const* GetQuestLocale(uint32 entry) const - { - QuestLocaleContainer::const_iterator itr = _questLocaleStore.find(entry); - if (itr == _questLocaleStore.end()) return nullptr; + return nullptr; + } + + QuestPOIVector const* GetQuestPOIVector(uint32 questId) + { + QuestPOIContainer::const_iterator itr = _questPOIStore.find(questId); + if (itr != _questPOIStore.end()) return &itr->second; - } - GossipMenuItemsLocale const* GetGossipMenuItemsLocale(uint32 entry) const - { - GossipMenuItemsLocaleContainer::const_iterator itr = _gossipMenuItemsLocaleStore.find(entry); - if (itr == _gossipMenuItemsLocaleStore.end()) return nullptr; + return nullptr; + } + + VehicleAccessoryList const* GetVehicleAccessoryList(Vehicle* veh) const; + + DungeonEncounterList const* GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) + { + std::unordered_map::const_iterator itr = _dungeonEncounterStore.find(MAKE_PAIR32(mapId, difficulty)); + if (itr != _dungeonEncounterStore.end()) return &itr->second; - } - PointOfInterestLocale const* GetPointOfInterestLocale(uint32 poi_id) const + return nullptr; + } + + void LoadQuests(); + void LoadQuestStartersAndEnders() + { + sLog->outString("Loading GO Start Quest Data..."); + LoadGameobjectQuestStarters(); + sLog->outString("Loading GO End Quest Data..."); + LoadGameobjectQuestEnders(); + sLog->outString("Loading Creature Start Quest Data..."); + LoadCreatureQuestStarters(); + sLog->outString("Loading Creature End Quest Data..."); + LoadCreatureQuestEnders(); + } + void LoadGameobjectQuestStarters(); + void LoadGameobjectQuestEnders(); + void LoadCreatureQuestStarters(); + void LoadCreatureQuestEnders(); + + QuestRelations* GetGOQuestRelationMap() + { + return &_goQuestRelations; + } + + QuestRelations* GetGOQuestInvolvedRelationMap() + { + return &_goQuestInvolvedRelations; + } + + QuestRelationBounds GetGOQuestRelationBounds(uint32 go_entry) + { + return _goQuestRelations.equal_range(go_entry); + } + + QuestRelationBounds GetGOQuestInvolvedRelationBounds(uint32 go_entry) + { + return _goQuestInvolvedRelations.equal_range(go_entry); + } + + QuestRelations* GetCreatureQuestRelationMap() + { + return &_creatureQuestRelations; + } + + QuestRelations* GetCreatureQuestInvolvedRelationMap() + { + return &_creatureQuestInvolvedRelations; + } + + QuestRelationBounds GetCreatureQuestRelationBounds(uint32 creature_entry) + { + return _creatureQuestRelations.equal_range(creature_entry); + } + + QuestRelationBounds GetCreatureQuestInvolvedRelationBounds(uint32 creature_entry) + { + return _creatureQuestInvolvedRelations.equal_range(creature_entry); + } + + void LoadEventScripts(); + void LoadSpellScripts(); + void LoadWaypointScripts(); + + void LoadSpellScriptNames(); + void ValidateSpellScripts(); + void InitializeSpellInfoPrecomputedData(); + + bool LoadAcoreStrings(); + void LoadBroadcastTexts(); + void LoadBroadcastTextLocales(); + void LoadCreatureClassLevelStats(); + void LoadCreatureLocales(); + void LoadCreatureTemplates(); + void LoadCreatureTemplateAddons(); + void CheckCreatureTemplate(CreatureTemplate const* cInfo); + void LoadGameObjectQuestItems(); + void LoadCreatureQuestItems(); + void LoadTempSummons(); + void LoadCreatures(); + void LoadLinkedRespawn(); + bool SetCreatureLinkedRespawn(uint32 guid, uint32 linkedGuid); + void LoadCreatureAddons(); + void LoadGameObjectAddons(); + void LoadCreatureModelInfo(); + void LoadEquipmentTemplates(); + void LoadGameObjectLocales(); + void LoadGameobjects(); + void LoadItemTemplates(); + void LoadItemLocales(); + void LoadItemSetNames(); + void LoadItemSetNameLocales(); + void LoadQuestLocales(); + void LoadNpcTextLocales(); + void LoadQuestOfferRewardLocale(); + void LoadQuestRequestItemsLocale(); + void LoadPageTextLocales(); + void LoadGossipMenuItemsLocales(); + void LoadPointOfInterestLocales(); + void LoadInstanceTemplate(); + void LoadInstanceEncounters(); + void LoadMailLevelRewards(); + void LoadVehicleTemplateAccessories(); + void LoadVehicleAccessories(); + + void LoadGossipText(); + + void LoadAreaTriggers(); + void LoadAreaTriggerTeleports(); + void LoadAccessRequirements(); + void LoadQuestAreaTriggers(); + void LoadAreaTriggerScripts(); + void LoadTavernAreaTriggers(); + void LoadGameObjectForQuests(); + + void LoadPageTexts(); + PageText const* GetPageText(uint32 pageEntry); + + void LoadPlayerInfo(); + void LoadPetLevelInfo(); + void LoadExplorationBaseXP(); + void LoadPetNames(); + void LoadPetNumber(); + void LoadCorpses(); + void LoadFishingBaseSkillLevel(); + void ChangeFishingBaseSkillLevel(uint32 entry, int32 skill); + + void LoadReputationRewardRate(); + void LoadReputationOnKill(); + void LoadReputationSpilloverTemplate(); + + void LoadPointsOfInterest(); + void LoadQuestPOI(); + + void LoadNPCSpellClickSpells(); + + void LoadGameTele(); + + void LoadGossipMenu(); + void LoadGossipMenuItems(); + + void LoadVendors(); + void LoadTrainerSpell(); + void AddSpellToTrainer(uint32 entry, uint32 spell, uint32 spellCost, uint32 reqSkill, uint32 reqSkillValue, uint32 reqLevel); + + std::string GeneratePetName(uint32 entry); + uint32 GetBaseXP(uint8 level); + uint32 GetXPForLevel(uint8 level) const; + + int32 GetFishingBaseSkillLevel(uint32 entry) const + { + FishingBaseSkillContainer::const_iterator itr = _fishingBaseForAreaStore.find(entry); + return itr != _fishingBaseForAreaStore.end() ? itr->second : 0; + } + + void ReturnOrDeleteOldMails(bool serverUp); + + CreatureBaseStats const* GetCreatureBaseStats(uint8 level, uint8 unitClass); + + void SetHighestGuids(); + uint32 GenerateLowGuid(HighGuid guidhigh); + uint32 GenerateRecycledLowGuid(HighGuid guidHigh); + uint32 GenerateAuctionID(); + uint64 GenerateEquipmentSetGuid(); + uint32 GenerateMailID(); + uint32 GeneratePetNumber(); + + typedef std::multimap ExclusiveQuestGroups; + typedef std::pair ExclusiveQuestGroupsBounds; + + ExclusiveQuestGroups mExclusiveQuestGroups; + + MailLevelReward const* GetMailLevelReward(uint32 level, uint32 raceMask) + { + MailLevelRewardContainer::const_iterator map_itr = _mailLevelRewardStore.find(level); + if (map_itr == _mailLevelRewardStore.end()) + return nullptr; + + for (MailLevelRewardList::const_iterator set_itr = map_itr->second.begin(); set_itr != map_itr->second.end(); ++set_itr) + if (set_itr->raceMask & raceMask) + return &*set_itr; + + return nullptr; + } + + CellObjectGuids const& GetCellObjectGuids(uint16 mapid, uint8 spawnMode, uint32 cell_id) + { + MapObjectGuids::const_iterator itr1 = _mapObjectGuidsStore.find(MAKE_PAIR32(mapid, spawnMode)); + if (itr1 != _mapObjectGuidsStore.end()) { - PointOfInterestLocaleContainer::const_iterator itr = _pointOfInterestLocaleStore.find(poi_id); - if (itr == _pointOfInterestLocaleStore.end()) return nullptr; + CellObjectGuidsMap::const_iterator itr2 = itr1->second.find(cell_id); + if (itr2 != itr1->second.end()) + return itr2->second; + } + return _emptyCellObjectGuids; + } + + CellObjectGuidsMap const& GetMapObjectGuids(uint16 mapid, uint8 spawnMode) + { + MapObjectGuids::const_iterator itr1 = _mapObjectGuidsStore.find(MAKE_PAIR32(mapid, spawnMode)); + if (itr1 != _mapObjectGuidsStore.end()) + return itr1->second; + return _emptyCellObjectGuidsMap; + } + + /** + * Gets temp summon data for all creatures of specified group. + * + * @param summonerId Summoner's entry. + * @param summonerType Summoner's type, see SummonerType for available types. + * @param group Id of required group. + * + * @return null if group was not found, otherwise reference to the creature group data + */ + std::vector const* GetSummonGroup(uint32 summonerId, SummonerType summonerType, uint8 group) const + { + TempSummonDataContainer::const_iterator itr = _tempSummonDataStore.find(TempSummonGroupKey(summonerId, summonerType, group)); + if (itr != _tempSummonDataStore.end()) return &itr->second; - } - QuestOfferRewardLocale const* GetQuestOfferRewardLocale(uint32 entry) const - { - auto itr = _questOfferRewardLocaleStore.find(entry); - if (itr == _questOfferRewardLocaleStore.end()) return nullptr; + + return nullptr; + } + + BroadcastText const* GetBroadcastText(uint32 id) const + { + BroadcastTextContainer::const_iterator itr = _broadcastTextStore.find(id); + if (itr != _broadcastTextStore.end()) return &itr->second; - } - QuestRequestItemsLocale const* GetQuestRequestItemsLocale(uint32 entry) const - { - auto itr = _questRequestItemsLocaleStore.find(entry); - if (itr == _questRequestItemsLocaleStore.end()) return nullptr; - return &itr->second; - } - NpcTextLocale const* GetNpcTextLocale(uint32 entry) const - { - NpcTextLocaleContainer::const_iterator itr = _npcTextLocaleStore.find(entry); - if (itr == _npcTextLocaleStore.end()) return nullptr; - return &itr->second; - } - GameObjectData& NewGOData(uint32 guid) { return _gameObjectDataStore[guid]; } - void DeleteGOData(uint32 guid); + return nullptr; + } + CreatureData const* GetCreatureData(uint32 guid) const + { + CreatureDataContainer::const_iterator itr = _creatureDataStore.find(guid); + if (itr == _creatureDataStore.end()) return nullptr; + return &itr->second; + } + CreatureData& NewOrExistCreatureData(uint32 guid) { return _creatureDataStore[guid]; } + void DeleteCreatureData(uint32 guid); + uint64 GetLinkedRespawnGuid(uint64 guid) const + { + LinkedRespawnContainer::const_iterator itr = _linkedRespawnStore.find(guid); + if (itr == _linkedRespawnStore.end()) return 0; + return itr->second; + } - AcoreString const* GetAcoreString(uint32 entry) const - { - AcoreStringContainer::const_iterator itr = _acoreStringStore.find(entry); - if (itr == _acoreStringStore.end()) - return nullptr; + GameObjectData const* GetGOData(uint32 guid) const + { + GameObjectDataContainer::const_iterator itr = _gameObjectDataStore.find(guid); + if (itr == _gameObjectDataStore.end()) return nullptr; + return &itr->second; + } + CreatureLocale const* GetCreatureLocale(uint32 entry) const + { + CreatureLocaleContainer::const_iterator itr = _creatureLocaleStore.find(entry); + if (itr == _creatureLocaleStore.end()) return nullptr; + return &itr->second; + } + GameObjectLocale const* GetGameObjectLocale(uint32 entry) const + { + GameObjectLocaleContainer::const_iterator itr = _gameObjectLocaleStore.find(entry); + if (itr == _gameObjectLocaleStore.end()) return nullptr; + return &itr->second; + } + ItemLocale const* GetItemLocale(uint32 entry) const + { + ItemLocaleContainer::const_iterator itr = _itemLocaleStore.find(entry); + if (itr == _itemLocaleStore.end()) return nullptr; + return &itr->second; + } + ItemSetNameLocale const* GetItemSetNameLocale(uint32 entry) const + { + ItemSetNameLocaleContainer::const_iterator itr = _itemSetNameLocaleStore.find(entry); + if (itr == _itemSetNameLocaleStore.end())return nullptr; + return &itr->second; + } + PageTextLocale const* GetPageTextLocale(uint32 entry) const + { + PageTextLocaleContainer::const_iterator itr = _pageTextLocaleStore.find(entry); + if (itr == _pageTextLocaleStore.end()) return nullptr; + return &itr->second; + } + QuestLocale const* GetQuestLocale(uint32 entry) const + { + QuestLocaleContainer::const_iterator itr = _questLocaleStore.find(entry); + if (itr == _questLocaleStore.end()) return nullptr; + return &itr->second; + } + GossipMenuItemsLocale const* GetGossipMenuItemsLocale(uint32 entry) const + { + GossipMenuItemsLocaleContainer::const_iterator itr = _gossipMenuItemsLocaleStore.find(entry); + if (itr == _gossipMenuItemsLocaleStore.end()) return nullptr; + return &itr->second; + } + PointOfInterestLocale const* GetPointOfInterestLocale(uint32 poi_id) const + { + PointOfInterestLocaleContainer::const_iterator itr = _pointOfInterestLocaleStore.find(poi_id); + if (itr == _pointOfInterestLocaleStore.end()) return nullptr; + return &itr->second; + } + QuestOfferRewardLocale const* GetQuestOfferRewardLocale(uint32 entry) const + { + auto itr = _questOfferRewardLocaleStore.find(entry); + if (itr == _questOfferRewardLocaleStore.end()) return nullptr; + return &itr->second; + } + QuestRequestItemsLocale const* GetQuestRequestItemsLocale(uint32 entry) const + { + auto itr = _questRequestItemsLocaleStore.find(entry); + if (itr == _questRequestItemsLocaleStore.end()) return nullptr; + return &itr->second; + } + NpcTextLocale const* GetNpcTextLocale(uint32 entry) const + { + NpcTextLocaleContainer::const_iterator itr = _npcTextLocaleStore.find(entry); + if (itr == _npcTextLocaleStore.end()) return nullptr; + return &itr->second; + } + GameObjectData& NewGOData(uint32 guid) { return _gameObjectDataStore[guid]; } + void DeleteGOData(uint32 guid); - return &itr->second; - } - char const* GetAcoreString(uint32 entry, LocaleConstant locale) const; - char const* GetAcoreStringForDBCLocale(uint32 entry) const { return GetAcoreString(entry, DBCLocaleIndex); } - LocaleConstant GetDBCLocaleIndex() const { return DBCLocaleIndex; } - void SetDBCLocaleIndex(LocaleConstant locale) { DBCLocaleIndex = locale; } + AcoreString const* GetAcoreString(uint32 entry) const + { + AcoreStringContainer::const_iterator itr = _acoreStringStore.find(entry); + if (itr == _acoreStringStore.end()) + return nullptr; - void AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance); - void DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid); + return &itr->second; + } + char const* GetAcoreString(uint32 entry, LocaleConstant locale) const; + char const* GetAcoreStringForDBCLocale(uint32 entry) const { return GetAcoreString(entry, DBCLocaleIndex); } + LocaleConstant GetDBCLocaleIndex() const { return DBCLocaleIndex; } + void SetDBCLocaleIndex(LocaleConstant locale) { DBCLocaleIndex = locale; } - // grid objects - void AddCreatureToGrid(uint32 guid, CreatureData const* data); - void RemoveCreatureFromGrid(uint32 guid, CreatureData const* data); - void AddGameobjectToGrid(uint32 guid, GameObjectData const* data); - void RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data); - uint32 AddGOData(uint32 entry, uint32 map, float x, float y, float z, float o, uint32 spawntimedelay = 0, float rotation0 = 0, float rotation1 = 0, float rotation2 = 0, float rotation3 = 0); - uint32 AddCreData(uint32 entry, uint32 map, float x, float y, float z, float o, uint32 spawntimedelay = 0); - bool MoveCreData(uint32 guid, uint32 map, Position pos); + void AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance); + void DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid); - // reserved names - void LoadReservedPlayersNames(); - bool IsReservedName(std::string const& name) const; + // grid objects + void AddCreatureToGrid(uint32 guid, CreatureData const* data); + void RemoveCreatureFromGrid(uint32 guid, CreatureData const* data); + void AddGameobjectToGrid(uint32 guid, GameObjectData const* data); + void RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data); + uint32 AddGOData(uint32 entry, uint32 map, float x, float y, float z, float o, uint32 spawntimedelay = 0, float rotation0 = 0, float rotation1 = 0, float rotation2 = 0, float rotation3 = 0); + uint32 AddCreData(uint32 entry, uint32 map, float x, float y, float z, float o, uint32 spawntimedelay = 0); + bool MoveCreData(uint32 guid, uint32 map, Position pos); - // name with valid structure and symbols - static uint8 CheckPlayerName(std::string const& name, bool create = false); - static PetNameInvalidReason CheckPetName(std::string const& name); - static bool IsValidCharterName(std::string const& name); - static bool IsValidChannelName(std::string const& name); + // reserved names + void LoadReservedPlayersNames(); + bool IsReservedName(std::string const& name) const; - static bool CheckDeclinedNames(std::wstring w_ownname, DeclinedName const& names); + // name with valid structure and symbols + static uint8 CheckPlayerName(std::string const& name, bool create = false); + static PetNameInvalidReason CheckPetName(std::string const& name); + static bool IsValidCharterName(std::string const& name); + static bool IsValidChannelName(std::string const& name); - GameTele const* GetGameTele(uint32 id) const - { - GameTeleContainer::const_iterator itr = _gameTeleStore.find(id); - if (itr == _gameTeleStore.end()) return nullptr; - return &itr->second; - } - GameTele const* GetGameTele(std::string const& name) const; - GameTeleContainer const& GetGameTeleMap() const { return _gameTeleStore; } - bool AddGameTele(GameTele& data); - bool DeleteGameTele(std::string const& name); + static bool CheckDeclinedNames(std::wstring w_ownname, DeclinedName const& names); - TrainerSpellData const* GetNpcTrainerSpells(uint32 entry) const - { - CacheTrainerSpellContainer::const_iterator iter = _cacheTrainerSpellStore.find(entry); - if (iter == _cacheTrainerSpellStore.end()) - return nullptr; + GameTele const* GetGameTele(uint32 id) const + { + GameTeleContainer::const_iterator itr = _gameTeleStore.find(id); + if (itr == _gameTeleStore.end()) return nullptr; + return &itr->second; + } + GameTele const* GetGameTele(std::string const& name) const; + GameTeleContainer const& GetGameTeleMap() const { return _gameTeleStore; } + bool AddGameTele(GameTele& data); + bool DeleteGameTele(std::string const& name); - return &iter->second; - } + TrainerSpellData const* GetNpcTrainerSpells(uint32 entry) const + { + CacheTrainerSpellContainer::const_iterator iter = _cacheTrainerSpellStore.find(entry); + if (iter == _cacheTrainerSpellStore.end()) + return nullptr; - VendorItemData const* GetNpcVendorItemList(uint32 entry) const - { - CacheVendorItemContainer::const_iterator iter = _cacheVendorItemStore.find(entry); - if (iter == _cacheVendorItemStore.end()) - return nullptr; + return &iter->second; + } - return &iter->second; - } + VendorItemData const* GetNpcVendorItemList(uint32 entry) const + { + CacheVendorItemContainer::const_iterator iter = _cacheVendorItemStore.find(entry); + if (iter == _cacheVendorItemStore.end()) + return nullptr; - void AddVendorItem(uint32 entry, uint32 item, int32 maxcount, uint32 incrtime, uint32 extendedCost, bool persist = true); // for event - bool RemoveVendorItem(uint32 entry, uint32 item, bool persist = true); // for event - bool IsVendorItemValid(uint32 vendor_entry, uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost, Player* player = NULL, std::set* skip_vendors = NULL, uint32 ORnpcflag = 0) const; + return &iter->second; + } - void LoadScriptNames(); - ScriptNameContainer &GetScriptNames() { return _scriptNamesStore; } - const char * GetScriptName(uint32 id) const { return id < _scriptNamesStore.size() ? _scriptNamesStore[id].c_str() : ""; } - uint32 GetScriptId(const char *name); + void AddVendorItem(uint32 entry, uint32 item, int32 maxcount, uint32 incrtime, uint32 extendedCost, bool persist = true); // for event + bool RemoveVendorItem(uint32 entry, uint32 item, bool persist = true); // for event + bool IsVendorItemValid(uint32 vendor_entry, uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost, Player* player = NULL, std::set* skip_vendors = NULL, uint32 ORnpcflag = 0) const; - SpellClickInfoMapBounds GetSpellClickInfoMapBounds(uint32 creature_id) const - { - return _spellClickInfoStore.equal_range(creature_id); - } + void LoadScriptNames(); + ScriptNameContainer& GetScriptNames() { return _scriptNamesStore; } + const char* GetScriptName(uint32 id) const { return id < _scriptNamesStore.size() ? _scriptNamesStore[id].c_str() : ""; } + uint32 GetScriptId(const char* name); - GossipMenusMapBounds GetGossipMenusMapBounds(uint32 uiMenuId) const - { - return _gossipMenusStore.equal_range(uiMenuId); - } + SpellClickInfoMapBounds GetSpellClickInfoMapBounds(uint32 creature_id) const + { + return _spellClickInfoStore.equal_range(creature_id); + } - GossipMenusMapBoundsNonConst GetGossipMenusMapBoundsNonConst(uint32 uiMenuId) - { - return _gossipMenusStore.equal_range(uiMenuId); - } + GossipMenusMapBounds GetGossipMenusMapBounds(uint32 uiMenuId) const + { + return _gossipMenusStore.equal_range(uiMenuId); + } - GossipMenuItemsMapBounds GetGossipMenuItemsMapBounds(uint32 uiMenuId) const - { - return _gossipMenuItemsStore.equal_range(uiMenuId); - } - GossipMenuItemsMapBoundsNonConst GetGossipMenuItemsMapBoundsNonConst(uint32 uiMenuId) - { - return _gossipMenuItemsStore.equal_range(uiMenuId); - } + GossipMenusMapBoundsNonConst GetGossipMenusMapBoundsNonConst(uint32 uiMenuId) + { + return _gossipMenusStore.equal_range(uiMenuId); + } - static void AddLocaleString(std::string const& s, LocaleConstant locale, StringVector& data); - static inline void GetLocaleString(const StringVector& data, int loc_idx, std::string& value) - { - if (data.size() > size_t(loc_idx) && !data[loc_idx].empty()) - value = data[loc_idx]; - } + GossipMenuItemsMapBounds GetGossipMenuItemsMapBounds(uint32 uiMenuId) const + { + return _gossipMenuItemsStore.equal_range(uiMenuId); + } + GossipMenuItemsMapBoundsNonConst GetGossipMenuItemsMapBoundsNonConst(uint32 uiMenuId) + { + return _gossipMenuItemsStore.equal_range(uiMenuId); + } - CharacterConversionMap FactionChangeAchievements; - CharacterConversionMap FactionChangeItems; - CharacterConversionMap FactionChangeQuests; - CharacterConversionMap FactionChangeReputation; - CharacterConversionMap FactionChangeSpells; - CharacterConversionMap FactionChangeTitles; + static void AddLocaleString(std::string const& s, LocaleConstant locale, StringVector& data); + static inline void GetLocaleString(const StringVector& data, int loc_idx, std::string& value) + { + if (data.size() > size_t(loc_idx) && !data[loc_idx].empty()) + value = data[loc_idx]; + } - void LoadFactionChangeAchievements(); - void LoadFactionChangeItems(); - void LoadFactionChangeQuests(); - void LoadFactionChangeReputations(); - void LoadFactionChangeSpells(); - void LoadFactionChangeTitles(); + CharacterConversionMap FactionChangeAchievements; + CharacterConversionMap FactionChangeItems; + CharacterConversionMap FactionChangeQuests; + CharacterConversionMap FactionChangeReputation; + CharacterConversionMap FactionChangeSpells; + CharacterConversionMap FactionChangeTitles; - private: - // first free id for selected id type - uint32 _auctionId; // pussywizard: accessed by a single thread - uint64 _equipmentSetGuid; // pussywizard: accessed by a single thread - uint32 _itemTextId; // pussywizard: unused? xD - uint32 _mailId; ACE_Thread_Mutex _mailIdMutex; - uint32 _hiPetNumber; ACE_Thread_Mutex _hiPetNumberMutex; + void LoadFactionChangeAchievements(); + void LoadFactionChangeItems(); + void LoadFactionChangeQuests(); + void LoadFactionChangeReputations(); + void LoadFactionChangeSpells(); + void LoadFactionChangeTitles(); - // first free low guid for selected guid type - uint32 _hiCharGuid; // pussywizard: accessed by a single thread - uint32 _hiCreatureGuid; ACE_Thread_Mutex _hiCreatureGuidMutex; - uint32 _hiPetGuid; ACE_Thread_Mutex _hiPetGuidMutex; - uint32 _hiVehicleGuid; ACE_Thread_Mutex _hiVehicleGuidMutex; - uint32 _hiItemGuid; ACE_Thread_Mutex _hiItemGuidMutex; - uint32 _hiGoGuid; ACE_Thread_Mutex _hiGoGuidMutex; - uint32 _hiDoGuid; ACE_Thread_Mutex _hiDoGuidMutex; - uint32 _hiCorpseGuid; ACE_Thread_Mutex _hiCorpseGuidMutex; - uint32 _hiMoTransGuid; ACE_Thread_Mutex _hiMoTransGuidMutex; +private: + // first free id for selected id type + uint32 _auctionId; // pussywizard: accessed by a single thread + uint64 _equipmentSetGuid; // pussywizard: accessed by a single thread + uint32 _itemTextId; // pussywizard: unused? xD + uint32 _mailId; + ACE_Thread_Mutex _mailIdMutex; + uint32 _hiPetNumber; + ACE_Thread_Mutex _hiPetNumberMutex; - uint32 _hiCreatureRecycledGuidMax; - uint32 _hiCreatureRecycledGuid; - uint32 _hiGoRecycledGuidMax; - uint32 _hiGoRecycledGuid; + // first free low guid for selected guid type + uint32 _hiCharGuid; // pussywizard: accessed by a single thread + uint32 _hiCreatureGuid; + ACE_Thread_Mutex _hiCreatureGuidMutex; + uint32 _hiPetGuid; + ACE_Thread_Mutex _hiPetGuidMutex; + uint32 _hiVehicleGuid; + ACE_Thread_Mutex _hiVehicleGuidMutex; + uint32 _hiItemGuid; + ACE_Thread_Mutex _hiItemGuidMutex; + uint32 _hiGoGuid; + ACE_Thread_Mutex _hiGoGuidMutex; + uint32 _hiDoGuid; + ACE_Thread_Mutex _hiDoGuidMutex; + uint32 _hiCorpseGuid; + ACE_Thread_Mutex _hiCorpseGuidMutex; + uint32 _hiMoTransGuid; + ACE_Thread_Mutex _hiMoTransGuidMutex; - QuestMap _questTemplates; - std::vector _questTemplatesFast; // pussywizard + uint32 _hiCreatureRecycledGuidMax; + uint32 _hiCreatureRecycledGuid; + uint32 _hiGoRecycledGuidMax; + uint32 _hiGoRecycledGuid; - typedef std::unordered_map GossipTextContainer; - typedef std::unordered_map QuestAreaTriggerContainer; - typedef std::set TavernAreaTriggerContainer; + QuestMap _questTemplates; + std::vector _questTemplatesFast; // pussywizard - QuestAreaTriggerContainer _questAreaTriggerStore; - TavernAreaTriggerContainer _tavernAreaTriggerStore; - GossipTextContainer _gossipTextStore; - AreaTriggerContainer _areaTriggerStore; - AreaTriggerTeleportContainer _areaTriggerTeleportStore; - AreaTriggerScriptContainer _areaTriggerScriptStore; - AccessRequirementContainer _accessRequirementStore; - DungeonEncounterContainer _dungeonEncounterStore; + typedef std::unordered_map GossipTextContainer; + typedef std::unordered_map QuestAreaTriggerContainer; + typedef std::set TavernAreaTriggerContainer; - RepRewardRateContainer _repRewardRateStore; - RepOnKillContainer _repOnKillStore; - RepSpilloverTemplateContainer _repSpilloverTemplateStore; + QuestAreaTriggerContainer _questAreaTriggerStore; + TavernAreaTriggerContainer _tavernAreaTriggerStore; + GossipTextContainer _gossipTextStore; + AreaTriggerContainer _areaTriggerStore; + AreaTriggerTeleportContainer _areaTriggerTeleportStore; + AreaTriggerScriptContainer _areaTriggerScriptStore; + AccessRequirementContainer _accessRequirementStore; + DungeonEncounterContainer _dungeonEncounterStore; - GossipMenusContainer _gossipMenusStore; - GossipMenuItemsContainer _gossipMenuItemsStore; - PointOfInterestContainer _pointsOfInterestStore; + RepRewardRateContainer _repRewardRateStore; + RepOnKillContainer _repOnKillStore; + RepSpilloverTemplateContainer _repSpilloverTemplateStore; - QuestPOIContainer _questPOIStore; + GossipMenusContainer _gossipMenusStore; + GossipMenuItemsContainer _gossipMenuItemsStore; + PointOfInterestContainer _pointsOfInterestStore; - QuestRelations _goQuestRelations; - QuestRelations _goQuestInvolvedRelations; - QuestRelations _creatureQuestRelations; - QuestRelations _creatureQuestInvolvedRelations; + QuestPOIContainer _questPOIStore; - //character reserved names - typedef std::set ReservedNamesContainer; - ReservedNamesContainer _reservedNamesStore; + QuestRelations _goQuestRelations; + QuestRelations _goQuestInvolvedRelations; + QuestRelations _creatureQuestRelations; + QuestRelations _creatureQuestInvolvedRelations; - GameTeleContainer _gameTeleStore; + //character reserved names + typedef std::set ReservedNamesContainer; + ReservedNamesContainer _reservedNamesStore; - ScriptNameContainer _scriptNamesStore; + GameTeleContainer _gameTeleStore; - SpellClickInfoContainer _spellClickInfoStore; + ScriptNameContainer _scriptNamesStore; - SpellScriptsContainer _spellScriptsStore; + SpellClickInfoContainer _spellClickInfoStore; - VehicleAccessoryContainer _vehicleTemplateAccessoryStore; - VehicleAccessoryContainer _vehicleAccessoryStore; + SpellScriptsContainer _spellScriptsStore; - LocaleConstant DBCLocaleIndex; + VehicleAccessoryContainer _vehicleTemplateAccessoryStore; + VehicleAccessoryContainer _vehicleAccessoryStore; - PageTextContainer _pageTextStore; - InstanceTemplateContainer _instanceTemplateStore; + LocaleConstant DBCLocaleIndex; - private: - void LoadScripts(ScriptsType type); - void LoadQuestRelationsHelper(QuestRelations& map, std::string const& table, bool starter, bool go); - void PlayerCreateInfoAddItemHelper(uint32 race_, uint32 class_, uint32 itemId, int32 count); + PageTextContainer _pageTextStore; + InstanceTemplateContainer _instanceTemplateStore; - MailLevelRewardContainer _mailLevelRewardStore; +private: + void LoadScripts(ScriptsType type); + void LoadQuestRelationsHelper(QuestRelations& map, std::string const& table, bool starter, bool go); + void PlayerCreateInfoAddItemHelper(uint32 race_, uint32 class_, uint32 itemId, int32 count); - CreatureBaseStatsContainer _creatureBaseStatsStore; + MailLevelRewardContainer _mailLevelRewardStore; - typedef std::map PetLevelInfoContainer; - // PetLevelInfoContainer[creature_id][level] - PetLevelInfoContainer _petInfoStore; // [creature_id][level] + CreatureBaseStatsContainer _creatureBaseStatsStore; - PlayerClassInfo* _playerClassInfo[MAX_CLASSES]; + typedef std::map PetLevelInfoContainer; + // PetLevelInfoContainer[creature_id][level] + PetLevelInfoContainer _petInfoStore; // [creature_id][level] - void BuildPlayerLevelInfo(uint8 race, uint8 class_, uint8 level, PlayerLevelInfo* plinfo) const; + PlayerClassInfo* _playerClassInfo[MAX_CLASSES]; - PlayerInfo* _playerInfo[MAX_RACES][MAX_CLASSES]; + void BuildPlayerLevelInfo(uint8 race, uint8 class_, uint8 level, PlayerLevelInfo* plinfo) const; - typedef std::vector PlayerXPperLevel; // [level] - PlayerXPperLevel _playerXPperLevel; + PlayerInfo* _playerInfo[MAX_RACES][MAX_CLASSES]; - typedef std::map BaseXPContainer; // [area level][base xp] - BaseXPContainer _baseXPTable; + typedef std::vector PlayerXPperLevel; // [level] + PlayerXPperLevel _playerXPperLevel; - typedef std::map FishingBaseSkillContainer; // [areaId][base skill level] - FishingBaseSkillContainer _fishingBaseForAreaStore; + typedef std::map BaseXPContainer; // [area level][base xp] + BaseXPContainer _baseXPTable; - typedef std::map HalfNameContainer; - HalfNameContainer _petHalfName0; - HalfNameContainer _petHalfName1; + typedef std::map FishingBaseSkillContainer; // [areaId][base skill level] + FishingBaseSkillContainer _fishingBaseForAreaStore; - typedef std::unordered_map ItemSetNameContainer; - ItemSetNameContainer _itemSetNameStore; + typedef std::map HalfNameContainer; + HalfNameContainer _petHalfName0; + HalfNameContainer _petHalfName1; - MapObjectGuids _mapObjectGuidsStore; - CellObjectGuidsMap _emptyCellObjectGuidsMap; - CellObjectGuids _emptyCellObjectGuids; - CreatureDataContainer _creatureDataStore; - CreatureTemplateContainer _creatureTemplateStore; - std::vector _creatureTemplateStoreFast; // pussywizard - CreatureModelContainer _creatureModelStore; - CreatureAddonContainer _creatureAddonStore; - CreatureAddonContainer _creatureTemplateAddonStore; - GameObjectAddonContainer _gameObjectAddonStore; - GameObjectQuestItemMap _gameObjectQuestItemStore; - CreatureQuestItemMap _creatureQuestItemStore; - EquipmentInfoContainer _equipmentInfoStore; - LinkedRespawnContainer _linkedRespawnStore; - CreatureLocaleContainer _creatureLocaleStore; - GameObjectDataContainer _gameObjectDataStore; - GameObjectLocaleContainer _gameObjectLocaleStore; - GameObjectTemplateContainer _gameObjectTemplateStore; - GameObjectTemplateAddonContainer _gameObjectTemplateAddonStore; - /// Stores temp summon data grouped by summoner's entry, summoner's type and group id - TempSummonDataContainer _tempSummonDataStore; + typedef std::unordered_map ItemSetNameContainer; + ItemSetNameContainer _itemSetNameStore; - BroadcastTextContainer _broadcastTextStore; - ItemTemplateContainer _itemTemplateStore; - std::vector _itemTemplateStoreFast; // pussywizard - ItemLocaleContainer _itemLocaleStore; - ItemSetNameLocaleContainer _itemSetNameLocaleStore; - QuestLocaleContainer _questLocaleStore; - QuestOfferRewardLocaleContainer _questOfferRewardLocaleStore; - QuestRequestItemsLocaleContainer _questRequestItemsLocaleStore; - NpcTextLocaleContainer _npcTextLocaleStore; - PageTextLocaleContainer _pageTextLocaleStore; - AcoreStringContainer _acoreStringStore; - GossipMenuItemsLocaleContainer _gossipMenuItemsLocaleStore; - PointOfInterestLocaleContainer _pointOfInterestLocaleStore; + MapObjectGuids _mapObjectGuidsStore; + CellObjectGuidsMap _emptyCellObjectGuidsMap; + CellObjectGuids _emptyCellObjectGuids; + CreatureDataContainer _creatureDataStore; + CreatureTemplateContainer _creatureTemplateStore; + std::vector _creatureTemplateStoreFast; // pussywizard + CreatureModelContainer _creatureModelStore; + CreatureAddonContainer _creatureAddonStore; + CreatureAddonContainer _creatureTemplateAddonStore; + GameObjectAddonContainer _gameObjectAddonStore; + GameObjectQuestItemMap _gameObjectQuestItemStore; + CreatureQuestItemMap _creatureQuestItemStore; + EquipmentInfoContainer _equipmentInfoStore; + LinkedRespawnContainer _linkedRespawnStore; + CreatureLocaleContainer _creatureLocaleStore; + GameObjectDataContainer _gameObjectDataStore; + GameObjectLocaleContainer _gameObjectLocaleStore; + GameObjectTemplateContainer _gameObjectTemplateStore; + GameObjectTemplateAddonContainer _gameObjectTemplateAddonStore; + /// Stores temp summon data grouped by summoner's entry, summoner's type and group id + TempSummonDataContainer _tempSummonDataStore; - CacheVendorItemContainer _cacheVendorItemStore; - CacheTrainerSpellContainer _cacheTrainerSpellStore; + BroadcastTextContainer _broadcastTextStore; + ItemTemplateContainer _itemTemplateStore; + std::vector _itemTemplateStoreFast; // pussywizard + ItemLocaleContainer _itemLocaleStore; + ItemSetNameLocaleContainer _itemSetNameLocaleStore; + QuestLocaleContainer _questLocaleStore; + QuestOfferRewardLocaleContainer _questOfferRewardLocaleStore; + QuestRequestItemsLocaleContainer _questRequestItemsLocaleStore; + NpcTextLocaleContainer _npcTextLocaleStore; + PageTextLocaleContainer _pageTextLocaleStore; + AcoreStringContainer _acoreStringStore; + GossipMenuItemsLocaleContainer _gossipMenuItemsLocaleStore; + PointOfInterestLocaleContainer _pointOfInterestLocaleStore; - std::set _difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures, used in CheckCreatureTemplate - std::set _hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values, used in CheckCreatureTemplate + CacheVendorItemContainer _cacheVendorItemStore; + CacheTrainerSpellContainer _cacheTrainerSpellStore; - enum CreatureLinkedRespawnType - { - CREATURE_TO_CREATURE, - CREATURE_TO_GO, // Creature is dependant on GO - GO_TO_GO, - GO_TO_CREATURE, // GO is dependant on creature - }; + std::set _difficultyEntries[MAX_DIFFICULTY - 1]; // already loaded difficulty 1 value in creatures, used in CheckCreatureTemplate + std::set _hasDifficultyEntries[MAX_DIFFICULTY - 1]; // already loaded creatures with difficulty 1 values, used in CheckCreatureTemplate - std::set _transportMaps; // Helper container storing map ids that are for transports only, loaded from gameobject_template + enum CreatureLinkedRespawnType + { + CREATURE_TO_CREATURE, + CREATURE_TO_GO, // Creature is dependant on GO + GO_TO_GO, + GO_TO_CREATURE, // GO is dependant on creature + }; + + std::set _transportMaps; // Helper container storing map ids that are for transports only, loaded from gameobject_template }; #define sObjectMgr ObjectMgr::instance() diff --git a/src/server/game/Grids/Cells/Cell.h b/src/server/game/Grids/Cells/Cell.h index 1fc8edd52..b2e74600b 100644 --- a/src/server/game/Grids/Cells/Cell.h +++ b/src/server/game/Grids/Cells/Cell.h @@ -39,22 +39,22 @@ struct Cell explicit Cell(CellCoord const& p); explicit Cell(float x, float y); - void Compute(uint32 &x, uint32 &y) const + void Compute(uint32& x, uint32& y) const { x = data.Part.grid_x * MAX_NUMBER_OF_CELLS + data.Part.cell_x; y = data.Part.grid_y * MAX_NUMBER_OF_CELLS + data.Part.cell_y; } - bool DiffCell(const Cell &cell) const + bool DiffCell(const Cell& cell) const { return(data.Part.cell_x != cell.data.Part.cell_x || - data.Part.cell_y != cell.data.Part.cell_y); + data.Part.cell_y != cell.data.Part.cell_y); } - bool DiffGrid(const Cell &cell) const + bool DiffGrid(const Cell& cell) const { return(data.Part.grid_x != cell.data.Part.grid_x || - data.Part.grid_y != cell.data.Part.grid_y); + data.Part.grid_y != cell.data.Part.grid_y); } uint32 CellX() const { return data.Part.cell_x; } @@ -67,8 +67,8 @@ struct Cell CellCoord GetCellCoord() const { return CellCoord( - data.Part.grid_x * MAX_NUMBER_OF_CELLS+data.Part.cell_x, - data.Part.grid_y * MAX_NUMBER_OF_CELLS+data.Part.cell_y); + data.Part.grid_x * MAX_NUMBER_OF_CELLS + data.Part.cell_x, + data.Part.grid_y * MAX_NUMBER_OF_CELLS + data.Part.cell_y); } Cell& operator=(Cell const& cell) @@ -93,13 +93,13 @@ struct Cell uint32 All; } data; - template void Visit(CellCoord const&, TypeContainerVisitor& visitor, Map &, WorldObject const&, float) const; - template void Visit(CellCoord const&, TypeContainerVisitor& visitor, Map &, float, float, float) const; + template void Visit(CellCoord const&, TypeContainerVisitor& visitor, Map&, WorldObject const&, float) const; + template void Visit(CellCoord const&, TypeContainerVisitor& visitor, Map&, float, float, float) const; static CellArea CalculateCellArea(float x, float y, float radius); private: - template void VisitCircle(TypeContainerVisitor &, Map &, CellCoord const&, CellCoord const&) const; + template void VisitCircle(TypeContainerVisitor&, Map&, CellCoord const&, CellCoord const&) const; }; #endif diff --git a/src/server/game/Grids/Grid.h b/src/server/game/Grids/Grid.h index da232c87f..b6563518b 100644 --- a/src/server/game/Grids/Grid.h +++ b/src/server/game/Grids/Grid.h @@ -27,97 +27,97 @@ template class GridLoader; template < -class ACTIVE_OBJECT, -class WORLD_OBJECT_TYPES, -class GRID_OBJECT_TYPES -> + class ACTIVE_OBJECT, + class WORLD_OBJECT_TYPES, + class GRID_OBJECT_TYPES + > class Grid { // allows the GridLoader to access its internals template friend class GridLoader; - public: +public: - /** destructor to clean up its resources. This includes unloading the - grid if it has not been unload. - */ - ~Grid() {} + /** destructor to clean up its resources. This includes unloading the + grid if it has not been unload. + */ + ~Grid() {} - /** an object of interested enters the grid - */ - template void AddWorldObject(SPECIFIC_OBJECT *obj) - { - i_objects.template insert(obj); - ASSERT(obj->IsInGrid()); - } + /** an object of interested enters the grid + */ + template void AddWorldObject(SPECIFIC_OBJECT* obj) + { + i_objects.template insert(obj); + ASSERT(obj->IsInGrid()); + } - /** an object of interested exits the grid - */ - //Actually an unlink is enough, no need to go through the container - //template void RemoveWorldObject(SPECIFIC_OBJECT *obj) - //{ - // ASSERT(obj->GetGridRef().isValid()); - // i_objects.template remove(obj); - // ASSERT(!obj->GetGridRef().isValid()); - //} + /** an object of interested exits the grid + */ + //Actually an unlink is enough, no need to go through the container + //template void RemoveWorldObject(SPECIFIC_OBJECT *obj) + //{ + // ASSERT(obj->GetGridRef().isValid()); + // i_objects.template remove(obj); + // ASSERT(!obj->GetGridRef().isValid()); + //} - /** Refreshes/update the grid. This required for remote grids. - */ - //void RefreshGrid(void) { /* TBI */} + /** Refreshes/update the grid. This required for remote grids. + */ + //void RefreshGrid(void) { /* TBI */} - /** Locks a grid. Any object enters must wait until the grid is unlock. - */ - //void LockGrid(void) { /* TBI */ } + /** Locks a grid. Any object enters must wait until the grid is unlock. + */ + //void LockGrid(void) { /* TBI */ } - /** Unlocks the grid. - */ - //void UnlockGrid(void) { /* TBI */ } + /** Unlocks the grid. + */ + //void UnlockGrid(void) { /* TBI */ } - // Visit grid objects - template - void Visit(TypeContainerVisitor > &visitor) - { - visitor.Visit(i_container); - } + // Visit grid objects + template + void Visit(TypeContainerVisitor >& visitor) + { + visitor.Visit(i_container); + } - // Visit world objects - template - void Visit(TypeContainerVisitor > &visitor) - { - visitor.Visit(i_objects); - } + // Visit world objects + template + void Visit(TypeContainerVisitor >& visitor) + { + visitor.Visit(i_objects); + } - /** Inserts a container type object into the grid. - */ - template void AddGridObject(SPECIFIC_OBJECT *obj) - { - i_container.template insert(obj); - ASSERT(obj->IsInGrid()); - } + /** Inserts a container type object into the grid. + */ + template void AddGridObject(SPECIFIC_OBJECT* obj) + { + i_container.template insert(obj); + ASSERT(obj->IsInGrid()); + } - /** Removes a containter type object from the grid - */ - //template void RemoveGridObject(SPECIFIC_OBJECT *obj) - //{ - // ASSERT(obj->GetGridRef().isValid()); - // i_container.template remove(obj); - // ASSERT(!obj->GetGridRef().isValid()); - //} + /** Removes a containter type object from the grid + */ + //template void RemoveGridObject(SPECIFIC_OBJECT *obj) + //{ + // ASSERT(obj->GetGridRef().isValid()); + // i_container.template remove(obj); + // ASSERT(!obj->GetGridRef().isValid()); + //} - /*bool NoWorldObjectInGrid() const - { - return i_objects.GetElements().isEmpty(); - } + /*bool NoWorldObjectInGrid() const + { + return i_objects.GetElements().isEmpty(); + } - bool NoGridObjectInGrid() const - { - return i_container.GetElements().isEmpty(); - }*/ - private: + bool NoGridObjectInGrid() const + { + return i_container.GetElements().isEmpty(); + }*/ +private: - TypeMapContainer i_container; - TypeMapContainer i_objects; - //typedef std::set ActiveGridObjects; - //ActiveGridObjects m_activeGridObjects; + TypeMapContainer i_container; + TypeMapContainer i_objects; + //typedef std::set ActiveGridObjects; + //ActiveGridObjects m_activeGridObjects; }; #endif diff --git a/src/server/game/Grids/GridDefines.h b/src/server/game/Grids/GridDefines.h index 0e428e2bd..aaa086cde 100644 --- a/src/server/game/Grids/GridDefines.h +++ b/src/server/game/Grids/GridDefines.h @@ -72,17 +72,17 @@ typedef TypeMapContainer WorldTypeMapContainer; template struct CoordPair { - CoordPair(uint32 x=0, uint32 y=0) + CoordPair(uint32 x = 0, uint32 y = 0) : x_coord(x) , y_coord(y) {} - CoordPair(const CoordPair &obj) + CoordPair(const CoordPair& obj) : x_coord(obj.x_coord) , y_coord(obj.y_coord) {} - CoordPair & operator=(const CoordPair &obj) + CoordPair& operator=(const CoordPair& obj) { x_coord = obj.x_coord; y_coord = obj.y_coord; @@ -143,13 +143,13 @@ struct CoordPair }; template -bool operator==(const CoordPair &p1, const CoordPair &p2) +bool operator==(const CoordPair& p1, const CoordPair& p2) { return (p1.x_coord == p2.x_coord && p1.y_coord == p2.y_coord); } template -bool operator!=(const CoordPair &p1, const CoordPair &p2) +bool operator!=(const CoordPair& p1, const CoordPair& p2) { return !(p1 == p2); } @@ -163,8 +163,8 @@ namespace acore inline RET_TYPE Compute(float x, float y, float center_offset, float size) { // calculate and store temporary values in double format for having same result as same mySQL calculations - double x_offset = (double(x) - center_offset)/size; - double y_offset = (double(y) - center_offset)/size; + double x_offset = (double(x) - center_offset) / size; + double y_offset = (double(y) - center_offset) / size; int x_val = int(x_offset + CENTER_VAL + 0.5f); int y_val = int(y_offset + CENTER_VAL + 0.5f); @@ -181,10 +181,10 @@ namespace acore return Compute(x, y, CENTER_GRID_CELL_OFFSET, SIZE_OF_GRID_CELL); } - inline CellCoord ComputeCellCoord(float x, float y, float &x_off, float &y_off) + inline CellCoord ComputeCellCoord(float x, float y, float& x_off, float& y_off) { - double x_offset = (double(x) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL; - double y_offset = (double(y) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL; + double x_offset = (double(x) - CENTER_GRID_CELL_OFFSET) / SIZE_OF_GRID_CELL; + double y_offset = (double(y) - CENTER_GRID_CELL_OFFSET) / SIZE_OF_GRID_CELL; int x_val = int(x_offset + CENTER_GRID_CELL_ID + 0.5f); int y_val = int(y_offset + CENTER_GRID_CELL_ID + 0.5f); @@ -193,7 +193,7 @@ namespace acore return CellCoord(x_val, y_val); } - inline void NormalizeMapCoord(float &c) + inline void NormalizeMapCoord(float& c) { if (c > MAP_HALFSIZE - 0.5f) c = MAP_HALFSIZE - 0.5f; diff --git a/src/server/game/Grids/GridRefManager.h b/src/server/game/Grids/GridRefManager.h index 70d5b3948..d799e8f43 100644 --- a/src/server/game/Grids/GridRefManager.h +++ b/src/server/game/Grids/GridRefManager.h @@ -15,16 +15,16 @@ class GridReference; template class GridRefManager : public RefManager, OBJECT> { - public: - typedef LinkedListHead::Iterator< GridReference > iterator; +public: + typedef LinkedListHead::Iterator< GridReference > iterator; - GridReference* getFirst() { return (GridReference*)RefManager, OBJECT>::getFirst(); } - GridReference* getLast() { return (GridReference*)RefManager, OBJECT>::getLast(); } + GridReference* getFirst() { return (GridReference*)RefManager, OBJECT>::getFirst(); } + GridReference* getLast() { return (GridReference*)RefManager, OBJECT>::getLast(); } - iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(nullptr); } - iterator rbegin() { return iterator(getLast()); } - iterator rend() { return iterator(nullptr); } + iterator begin() { return iterator(getFirst()); } + iterator end() { return iterator(nullptr); } + iterator rbegin() { return iterator(getLast()); } + iterator rend() { return iterator(nullptr); } }; #endif diff --git a/src/server/game/Grids/GridReference.h b/src/server/game/Grids/GridReference.h index e8ec95b9f..ba886927c 100644 --- a/src/server/game/Grids/GridReference.h +++ b/src/server/game/Grids/GridReference.h @@ -15,27 +15,27 @@ class GridRefManager; template class GridReference : public Reference, OBJECT> { - protected: - void targetObjectBuildLink() - { - // called from link() - this->getTarget()->insertFirst(this); - this->getTarget()->incSize(); - } - void targetObjectDestroyLink() - { - // called from unlink() - if (this->isValid()) this->getTarget()->decSize(); - } - void sourceObjectDestroyLink() - { - // called from invalidate() - this->getTarget()->decSize(); - } - public: - GridReference() : Reference, OBJECT>() {} - ~GridReference() { this->unlink(); } - GridReference* next() { return (GridReference*)Reference, OBJECT>::next(); } +protected: + void targetObjectBuildLink() + { + // called from link() + this->getTarget()->insertFirst(this); + this->getTarget()->incSize(); + } + void targetObjectDestroyLink() + { + // called from unlink() + if (this->isValid()) this->getTarget()->decSize(); + } + void sourceObjectDestroyLink() + { + // called from invalidate() + this->getTarget()->decSize(); + } +public: + GridReference() : Reference, OBJECT>() {} + ~GridReference() { this->unlink(); } + GridReference* next() { return (GridReference*)Reference, OBJECT>::next(); } }; #endif diff --git a/src/server/game/Grids/NGrid.h b/src/server/game/Grids/NGrid.h index fea4f4361..124a58660 100644 --- a/src/server/game/Grids/NGrid.h +++ b/src/server/game/Grids/NGrid.h @@ -17,88 +17,88 @@ template < -uint32 N, -class ACTIVE_OBJECT, -class WORLD_OBJECT_TYPES, -class GRID_OBJECT_TYPES -> + uint32 N, + class ACTIVE_OBJECT, + class WORLD_OBJECT_TYPES, + class GRID_OBJECT_TYPES + > class NGrid { - public: - typedef Grid GridType; - NGrid(uint32 id, int32 x, int32 y) - : i_gridId(id), i_x(x), i_y(y), i_GridObjectDataLoaded(false) - { - } +public: + typedef Grid GridType; + NGrid(uint32 id, int32 x, int32 y) + : i_gridId(id), i_x(x), i_y(y), i_GridObjectDataLoaded(false) + { + } - GridType& GetGridType(const uint32 x, const uint32 y) - { - ASSERT(x < N && y < N); - return i_cells[x][y]; - } + GridType& GetGridType(const uint32 x, const uint32 y) + { + ASSERT(x < N && y < N); + return i_cells[x][y]; + } - GridType const& GetGridType(const uint32 x, const uint32 y) const - { - ASSERT(x < N && y < N); - return i_cells[x][y]; - } + GridType const& GetGridType(const uint32 x, const uint32 y) const + { + ASSERT(x < N && y < N); + return i_cells[x][y]; + } - uint32 GetGridId(void) const { return i_gridId; } - int32 getX() const { return i_x; } - int32 getY() const { return i_y; } + uint32 GetGridId(void) const { return i_gridId; } + int32 getX() const { return i_x; } + int32 getY() const { return i_y; } - void link(GridRefManager >* pTo) - { - i_Reference.link(pTo, this); - } - bool isGridObjectDataLoaded() const { return i_GridObjectDataLoaded; } - void setGridObjectDataLoaded(bool pLoaded) { i_GridObjectDataLoaded = pLoaded; } + void link(GridRefManager >* pTo) + { + i_Reference.link(pTo, this); + } + bool isGridObjectDataLoaded() const { return i_GridObjectDataLoaded; } + void setGridObjectDataLoaded(bool pLoaded) { i_GridObjectDataLoaded = pLoaded; } - /* - template void AddWorldObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) - { - GetGridType(x, y).AddWorldObject(obj); - } + /* + template void AddWorldObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) + { + GetGridType(x, y).AddWorldObject(obj); + } - template void RemoveWorldObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) - { - GetGridType(x, y).RemoveWorldObject(obj); - } + template void RemoveWorldObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) + { + GetGridType(x, y).RemoveWorldObject(obj); + } - template void AddGridObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) - { - GetGridType(x, y).AddGridObject(obj); - } + template void AddGridObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) + { + GetGridType(x, y).AddGridObject(obj); + } - template void RemoveGridObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) - { - GetGridType(x, y).RemoveGridObject(obj); - } - */ + template void RemoveGridObject(const uint32 x, const uint32 y, SPECIFIC_OBJECT *obj) + { + GetGridType(x, y).RemoveGridObject(obj); + } + */ - // Visit all Grids (cells) in NGrid (grid) - template - void VisitAllGrids(TypeContainerVisitor > &visitor) - { - for (uint32 x = 0; x < N; ++x) - for (uint32 y = 0; y < N; ++y) - GetGridType(x, y).Visit(visitor); - } + // Visit all Grids (cells) in NGrid (grid) + template + void VisitAllGrids(TypeContainerVisitor >& visitor) + { + for (uint32 x = 0; x < N; ++x) + for (uint32 y = 0; y < N; ++y) + GetGridType(x, y).Visit(visitor); + } - // Visit a single Grid (cell) in NGrid (grid) - template - void VisitGrid(const uint32 x, const uint32 y, TypeContainerVisitor > &visitor) - { - GetGridType(x, y).Visit(visitor); - } + // Visit a single Grid (cell) in NGrid (grid) + template + void VisitGrid(const uint32 x, const uint32 y, TypeContainerVisitor >& visitor) + { + GetGridType(x, y).Visit(visitor); + } - private: - uint32 i_gridId; - GridReference > i_Reference; - int32 i_x; - int32 i_y; - GridType i_cells[N][N]; - bool i_GridObjectDataLoaded; +private: + uint32 i_gridId; + GridReference > i_Reference; + int32 i_x; + int32 i_y; + GridType i_cells[N][N]; + bool i_GridObjectDataLoaded; }; #endif diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.cpp b/src/server/game/Grids/Notifiers/GridNotifiers.cpp index 834f4d62c..20aa03b0a 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.cpp +++ b/src/server/game/Grids/Notifiers/GridNotifiers.cpp @@ -19,7 +19,7 @@ using namespace acore; -void VisibleNotifier::Visit(GameObjectMapType &m) +void VisibleNotifier::Visit(GameObjectMapType& m) { for (GameObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -35,7 +35,7 @@ void VisibleNotifier::SendToSelf() // at this moment i_clientGUIDs have guids that not iterate at grid level checks // but exist one case when this possible and object not out of range: transports if (Transport* transport = i_player.GetTransport()) - for (Transport::PassengerSet::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end();++itr) + for (Transport::PassengerSet::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end(); ++itr) { if (i_largeOnly != (*itr)->IsVisibilityOverridden()) continue; @@ -62,7 +62,7 @@ void VisibleNotifier::SendToSelf() } } - for (Player::ClientGUIDs::const_iterator it = vis_guids.begin();it != vis_guids.end(); ++it) + for (Player::ClientGUIDs::const_iterator it = vis_guids.begin(); it != vis_guids.end(); ++it) { if (WorldObject* obj = ObjectAccessor::GetWorldObject(i_player, *it)) if (i_largeOnly != obj->IsVisibilityOverridden()) @@ -100,7 +100,7 @@ void VisibleNotifier::SendToSelf() } } -void VisibleChangesNotifier::Visit(PlayerMapType &m) +void VisibleChangesNotifier::Visit(PlayerMapType& m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -116,7 +116,7 @@ void VisibleChangesNotifier::Visit(PlayerMapType &m) } } -void VisibleChangesNotifier::Visit(CreatureMapType &m) +void VisibleChangesNotifier::Visit(CreatureMapType& m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) if (iter->GetSource()->HasSharedVision()) @@ -125,7 +125,7 @@ void VisibleChangesNotifier::Visit(CreatureMapType &m) (*i)->UpdateVisibilityOf(&i_object); } -void VisibleChangesNotifier::Visit(DynamicObjectMapType &m) +void VisibleChangesNotifier::Visit(DynamicObjectMapType& m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) if (IS_PLAYER_GUID(iter->GetSource()->GetCasterGUID())) @@ -154,7 +154,7 @@ inline void CreatureUnitRelocationWorker(Creature* c, Unit* u) } } -void PlayerRelocationNotifier::Visit(PlayerMapType &m) +void PlayerRelocationNotifier::Visit(PlayerMapType& m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -165,7 +165,7 @@ void PlayerRelocationNotifier::Visit(PlayerMapType &m) } } -void CreatureRelocationNotifier::Visit(PlayerMapType &m) +void CreatureRelocationNotifier::Visit(PlayerMapType& m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -181,7 +181,7 @@ void CreatureRelocationNotifier::Visit(PlayerMapType &m) } } -void AIRelocationNotifier::Visit(CreatureMapType &m) +void AIRelocationNotifier::Visit(CreatureMapType& m) { bool self = isCreature && !((Creature*)(&i_unit))->IsMoveInLineOfSightStrictlyDisabled(); for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) @@ -197,7 +197,7 @@ void AIRelocationNotifier::Visit(CreatureMapType &m) } } -void MessageDistDeliverer::Visit(PlayerMapType &m) +void MessageDistDeliverer::Visit(PlayerMapType& m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -222,7 +222,7 @@ void MessageDistDeliverer::Visit(PlayerMapType &m) } } -void MessageDistDeliverer::Visit(CreatureMapType &m) +void MessageDistDeliverer::Visit(CreatureMapType& m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -241,7 +241,7 @@ void MessageDistDeliverer::Visit(CreatureMapType &m) } } -void MessageDistDeliverer::Visit(DynamicObjectMapType &m) +void MessageDistDeliverer::Visit(DynamicObjectMapType& m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -263,7 +263,7 @@ void MessageDistDeliverer::Visit(DynamicObjectMapType &m) } } -void MessageDistDelivererToHostile::Visit(PlayerMapType &m) +void MessageDistDelivererToHostile::Visit(PlayerMapType& m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -288,7 +288,7 @@ void MessageDistDelivererToHostile::Visit(PlayerMapType &m) } } -void MessageDistDelivererToHostile::Visit(CreatureMapType &m) +void MessageDistDelivererToHostile::Visit(CreatureMapType& m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -307,7 +307,7 @@ void MessageDistDelivererToHostile::Visit(CreatureMapType &m) } } -void MessageDistDelivererToHostile::Visit(DynamicObjectMapType &m) +void MessageDistDelivererToHostile::Visit(DynamicObjectMapType& m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { @@ -326,7 +326,7 @@ void MessageDistDelivererToHostile::Visit(DynamicObjectMapType &m) } template -void ObjectUpdater::Visit(GridRefManager &m) +void ObjectUpdater::Visit(GridRefManager& m) { T* obj; for (typename GridRefManager::iterator iter = m.begin(); iter != m.end(); ) diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.h b/src/server/game/Grids/Notifiers/GridNotifiers.h index 911d3f37e..04b909bd2 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.h +++ b/src/server/game/Grids/Notifiers/GridNotifiers.h @@ -28,57 +28,57 @@ namespace acore { struct VisibleNotifier { - Player &i_player; + Player& i_player; Player::ClientGUIDs vis_guids; - std::vector &i_visibleNow; + std::vector& i_visibleNow; bool i_gobjOnly; bool i_largeOnly; UpdateData i_data; - VisibleNotifier(Player &player, bool gobjOnly, bool largeOnly) : i_player(player), vis_guids(player.m_clientGUIDs), i_visibleNow(player.m_newVisible), i_gobjOnly(gobjOnly), i_largeOnly(largeOnly) + VisibleNotifier(Player& player, bool gobjOnly, bool largeOnly) : i_player(player), vis_guids(player.m_clientGUIDs), i_visibleNow(player.m_newVisible), i_gobjOnly(gobjOnly), i_largeOnly(largeOnly) { i_visibleNow.clear(); } - void Visit(GameObjectMapType &); - template void Visit(GridRefManager &m); + void Visit(GameObjectMapType&); + template void Visit(GridRefManager& m); void SendToSelf(void); }; struct VisibleChangesNotifier { - WorldObject &i_object; + WorldObject& i_object; - explicit VisibleChangesNotifier(WorldObject &object) : i_object(object) {} - template void Visit(GridRefManager &) {} - void Visit(PlayerMapType &); - void Visit(CreatureMapType &); - void Visit(DynamicObjectMapType &); + explicit VisibleChangesNotifier(WorldObject& object) : i_object(object) {} + template void Visit(GridRefManager&) {} + void Visit(PlayerMapType&); + void Visit(CreatureMapType&); + void Visit(DynamicObjectMapType&); }; struct PlayerRelocationNotifier : public VisibleNotifier { - PlayerRelocationNotifier(Player &player, bool largeOnly) : VisibleNotifier(player, false, largeOnly) {} + PlayerRelocationNotifier(Player& player, bool largeOnly) : VisibleNotifier(player, false, largeOnly) {} - template void Visit(GridRefManager &m) { VisibleNotifier::Visit(m); } - void Visit(PlayerMapType &); + template void Visit(GridRefManager& m) { VisibleNotifier::Visit(m); } + void Visit(PlayerMapType&); }; struct CreatureRelocationNotifier { - Creature &i_creature; - CreatureRelocationNotifier(Creature &c) : i_creature(c) {} - template void Visit(GridRefManager &) {} - void Visit(PlayerMapType &); + Creature& i_creature; + CreatureRelocationNotifier(Creature& c) : i_creature(c) {} + template void Visit(GridRefManager&) {} + void Visit(PlayerMapType&); }; struct AIRelocationNotifier { - Unit &i_unit; + Unit& i_unit; bool isCreature; - explicit AIRelocationNotifier(Unit &unit) : i_unit(unit), isCreature(unit.GetTypeId() == TYPEID_UNIT) {} - template void Visit(GridRefManager &) {} - void Visit(CreatureMapType &); + explicit AIRelocationNotifier(Unit& unit) : i_unit(unit), isCreature(unit.GetTypeId() == TYPEID_UNIT) {} + template void Visit(GridRefManager&) {} + void Visit(CreatureMapType&); }; struct MessageDistDeliverer @@ -95,10 +95,10 @@ namespace acore , skipped_receiver(skipped) { } - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); - void Visit(DynamicObjectMapType &m); - template void Visit(GridRefManager &) {} + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); + void Visit(DynamicObjectMapType& m); + template void Visit(GridRefManager&) {} void SendPacket(Player* player) { @@ -123,10 +123,10 @@ namespace acore : i_source(src), i_message(msg), i_phaseMask(src->GetPhaseMask()), i_distSq(dist * dist) { } - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); - void Visit(DynamicObjectMapType &m); - template void Visit(GridRefManager &) {} + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); + void Visit(DynamicObjectMapType& m); + template void Visit(GridRefManager&) {} void SendPacket(Player* player) { @@ -143,9 +143,9 @@ namespace acore uint32 i_timeDiff; bool i_largeOnly; explicit ObjectUpdater(const uint32 diff, bool largeOnly) : i_timeDiff(diff), i_largeOnly(largeOnly) {} - template void Visit(GridRefManager &m); - void Visit(PlayerMapType &) {} - void Visit(CorpseMapType &) {} + template void Visit(GridRefManager& m); + void Visit(PlayerMapType&) {} + void Visit(CorpseMapType&) {} }; // SEARCHERS & LIST SEARCHERS & WORKERS @@ -157,19 +157,19 @@ namespace acore { uint32 i_mapTypeMask; uint32 i_phaseMask; - WorldObject* &i_object; - Check &i_check; + WorldObject*& i_object; + Check& i_check; - WorldObjectSearcher(WorldObject const* searcher, WorldObject* & result, Check& check, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) + WorldObjectSearcher(WorldObject const* searcher, WorldObject*& result, Check& check, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) : i_mapTypeMask(mapTypeMask), i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(GameObjectMapType &m); - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); - void Visit(CorpseMapType &m); - void Visit(DynamicObjectMapType &m); + void Visit(GameObjectMapType& m); + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); + void Visit(CorpseMapType& m); + void Visit(DynamicObjectMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -177,19 +177,19 @@ namespace acore { uint32 i_mapTypeMask; uint32 i_phaseMask; - WorldObject* &i_object; - Check &i_check; + WorldObject*& i_object; + Check& i_check; - WorldObjectLastSearcher(WorldObject const* searcher, WorldObject* & result, Check& check, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) + WorldObjectLastSearcher(WorldObject const* searcher, WorldObject*& result, Check& check, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) : i_mapTypeMask(mapTypeMask), i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(GameObjectMapType &m); - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); - void Visit(CorpseMapType &m); - void Visit(DynamicObjectMapType &m); + void Visit(GameObjectMapType& m); + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); + void Visit(CorpseMapType& m); + void Visit(DynamicObjectMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -197,19 +197,19 @@ namespace acore { uint32 i_mapTypeMask; uint32 i_phaseMask; - std::list &i_objects; + std::list& i_objects; Check& i_check; - WorldObjectListSearcher(WorldObject const* searcher, std::list &objects, Check & check, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) + WorldObjectListSearcher(WorldObject const* searcher, std::list& objects, Check& check, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) : i_mapTypeMask(mapTypeMask), i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {} - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); - void Visit(CorpseMapType &m); - void Visit(GameObjectMapType &m); - void Visit(DynamicObjectMapType &m); + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); + void Visit(CorpseMapType& m); + void Visit(GameObjectMapType& m); + void Visit(DynamicObjectMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -222,51 +222,51 @@ namespace acore WorldObjectWorker(WorldObject const* searcher, Do const& _do, uint32 mapTypeMask = GRID_MAP_TYPE_MASK_ALL) : i_mapTypeMask(mapTypeMask), i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {} - void Visit(GameObjectMapType &m) + void Visit(GameObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_GAMEOBJECT)) return; - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - void Visit(PlayerMapType &m) + void Visit(PlayerMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_PLAYER)) return; - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - void Visit(CreatureMapType &m) + void Visit(CreatureMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CREATURE)) return; - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - void Visit(CorpseMapType &m) + void Visit(CorpseMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CORPSE)) return; - for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - void Visit(DynamicObjectMapType &m) + void Visit(DynamicObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_DYNAMICOBJECT)) return; - for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // Gameobject searchers @@ -275,15 +275,15 @@ namespace acore struct GameObjectSearcher { uint32 i_phaseMask; - GameObject* &i_object; - Check &i_check; + GameObject*& i_object; + Check& i_check; - GameObjectSearcher(WorldObject const* searcher, GameObject* & result, Check& check) + GameObjectSearcher(WorldObject const* searcher, GameObject*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(GameObjectMapType &m); + void Visit(GameObjectMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // Last accepted by Check GO if any (Check can change requirements at each call) @@ -291,30 +291,30 @@ namespace acore struct GameObjectLastSearcher { uint32 i_phaseMask; - GameObject* &i_object; + GameObject*& i_object; Check& i_check; - GameObjectLastSearcher(WorldObject const* searcher, GameObject* & result, Check& check) + GameObjectLastSearcher(WorldObject const* searcher, GameObject*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(GameObjectMapType &m); + void Visit(GameObjectMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template struct GameObjectListSearcher { uint32 i_phaseMask; - std::list &i_objects; + std::list& i_objects; Check& i_check; - GameObjectListSearcher(WorldObject const* searcher, std::list &objects, Check & check) + GameObjectListSearcher(WorldObject const* searcher, std::list& objects, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {} - void Visit(GameObjectMapType &m); + void Visit(GameObjectMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -330,7 +330,7 @@ namespace acore _func(itr->GetSource()); } - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} private: Functor& _func; @@ -344,16 +344,16 @@ namespace acore struct UnitSearcher { uint32 i_phaseMask; - Unit* &i_object; - Check & i_check; + Unit*& i_object; + Check& i_check; - UnitSearcher(WorldObject const* searcher, Unit* & result, Check & check) + UnitSearcher(WorldObject const* searcher, Unit*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(CreatureMapType &m); - void Visit(PlayerMapType &m); + void Visit(CreatureMapType& m); + void Visit(PlayerMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // Last accepted by Check Unit if any (Check can change requirements at each call) @@ -361,16 +361,16 @@ namespace acore struct UnitLastSearcher { uint32 i_phaseMask; - Unit* &i_object; - Check & i_check; + Unit*& i_object; + Check& i_check; - UnitLastSearcher(WorldObject const* searcher, Unit* & result, Check & check) + UnitLastSearcher(WorldObject const* searcher, Unit*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(CreatureMapType &m); - void Visit(PlayerMapType &m); + void Visit(CreatureMapType& m); + void Visit(PlayerMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // All accepted by Check units if any @@ -378,16 +378,16 @@ namespace acore struct UnitListSearcher { uint32 i_phaseMask; - std::list &i_objects; + std::list& i_objects; Check& i_check; - UnitListSearcher(WorldObject const* searcher, std::list &objects, Check & check) + UnitListSearcher(WorldObject const* searcher, std::list& objects, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {} - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // Creature searchers @@ -396,15 +396,15 @@ namespace acore struct CreatureSearcher { uint32 i_phaseMask; - Creature* &i_object; - Check & i_check; + Creature*& i_object; + Check& i_check; - CreatureSearcher(WorldObject const* searcher, Creature* & result, Check & check) + CreatureSearcher(WorldObject const* searcher, Creature*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(CreatureMapType &m); + void Visit(CreatureMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // Last accepted by Check Creature if any (Check can change requirements at each call) @@ -412,30 +412,30 @@ namespace acore struct CreatureLastSearcher { uint32 i_phaseMask; - Creature* &i_object; - Check & i_check; + Creature*& i_object; + Check& i_check; - CreatureLastSearcher(WorldObject const* searcher, Creature* & result, Check & check) + CreatureLastSearcher(WorldObject const* searcher, Creature*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(CreatureMapType &m); + void Visit(CreatureMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template struct CreatureListSearcher { uint32 i_phaseMask; - std::list &i_objects; + std::list& i_objects; Check& i_check; - CreatureListSearcher(WorldObject const* searcher, std::list &objects, Check & check) + CreatureListSearcher(WorldObject const* searcher, std::list& objects, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {} - void Visit(CreatureMapType &m); + void Visit(CreatureMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -447,14 +447,14 @@ namespace acore CreatureWorker(WorldObject const* searcher, Do& _do) : i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {} - void Visit(CreatureMapType &m) + void Visit(CreatureMapType& m) { - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // Player searchers @@ -463,53 +463,53 @@ namespace acore struct PlayerSearcher { uint32 i_phaseMask; - Player* &i_object; - Check & i_check; + Player*& i_object; + Check& i_check; - PlayerSearcher(WorldObject const* searcher, Player* & result, Check & check) + PlayerSearcher(WorldObject const* searcher, Player*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {} - void Visit(PlayerMapType &m); + void Visit(PlayerMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template struct PlayerListSearcher { uint32 i_phaseMask; - std::list &i_objects; + std::list& i_objects; Check& i_check; - PlayerListSearcher(WorldObject const* searcher, std::list &objects, Check & check) + PlayerListSearcher(WorldObject const* searcher, std::list& objects, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {} - void Visit(PlayerMapType &m); + void Visit(PlayerMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template struct PlayerListSearcherWithSharedVision { uint32 i_phaseMask; - std::list &i_objects; + std::list& i_objects; Check& i_check; - PlayerListSearcherWithSharedVision(WorldObject const* searcher, std::list &objects, Check & check) + PlayerListSearcherWithSharedVision(WorldObject const* searcher, std::list& objects, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {} - void Visit(PlayerMapType &m); - void Visit(CreatureMapType &m); + void Visit(PlayerMapType& m); + void Visit(CreatureMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template struct PlayerLastSearcher { uint32 i_phaseMask; - Player* &i_object; + Player*& i_object; Check& i_check; PlayerLastSearcher(WorldObject const* searcher, Player*& result, Check& check) : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) @@ -518,7 +518,7 @@ namespace acore void Visit(PlayerMapType& m); - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -530,14 +530,14 @@ namespace acore PlayerWorker(WorldObject const* searcher, Do& _do) : i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {} - void Visit(PlayerMapType &m) + void Visit(PlayerMapType& m) { - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) i_do(itr->GetSource()); } - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; template @@ -550,14 +550,14 @@ namespace acore PlayerDistWorker(WorldObject const* searcher, float _dist, Do& _do) : i_searcher(searcher), i_dist(_dist), i_do(_do) {} - void Visit(PlayerMapType &m) + void Visit(PlayerMapType& m) { - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_searcher) && itr->GetSource()->IsWithinDist(i_searcher, i_dist)) i_do(itr->GetSource()); } - template void Visit(GridRefManager &) {} + template void Visit(GridRefManager&) {} }; // CHECKS && DO classes @@ -566,134 +566,134 @@ namespace acore class AnyDeadUnitObjectInRangeCheck { - public: - AnyDeadUnitObjectInRangeCheck(Unit* searchObj, float range) : i_searchObj(searchObj), i_range(range) {} - bool operator()(Player* u); - bool operator()(Corpse* u); - bool operator()(Creature* u); - template bool operator()(NOT_INTERESTED*) { return false; } - protected: - Unit const* const i_searchObj; - float i_range; + public: + AnyDeadUnitObjectInRangeCheck(Unit* searchObj, float range) : i_searchObj(searchObj), i_range(range) {} + bool operator()(Player* u); + bool operator()(Corpse* u); + bool operator()(Creature* u); + template bool operator()(NOT_INTERESTED*) { return false; } + protected: + Unit const* const i_searchObj; + float i_range; }; class AnyDeadUnitSpellTargetInRangeCheck : public AnyDeadUnitObjectInRangeCheck { - public: - AnyDeadUnitSpellTargetInRangeCheck(Unit* searchObj, float range, SpellInfo const* spellInfo, SpellTargetCheckTypes check) - : AnyDeadUnitObjectInRangeCheck(searchObj, range), i_spellInfo(spellInfo), i_check(searchObj, searchObj, spellInfo, check, nullptr) - {} - bool operator()(Player* u); - bool operator()(Corpse* u); - bool operator()(Creature* u); - template bool operator()(NOT_INTERESTED*) { return false; } - protected: - SpellInfo const* i_spellInfo; - WorldObjectSpellTargetCheck i_check; + public: + AnyDeadUnitSpellTargetInRangeCheck(Unit* searchObj, float range, SpellInfo const* spellInfo, SpellTargetCheckTypes check) + : AnyDeadUnitObjectInRangeCheck(searchObj, range), i_spellInfo(spellInfo), i_check(searchObj, searchObj, spellInfo, check, nullptr) + {} + bool operator()(Player* u); + bool operator()(Corpse* u); + bool operator()(Creature* u); + template bool operator()(NOT_INTERESTED*) { return false; } + protected: + SpellInfo const* i_spellInfo; + WorldObjectSpellTargetCheck i_check; }; // WorldObject do classes class RespawnDo { - public: - RespawnDo() {} - void operator()(Creature* u) const { u->Respawn(); } - void operator()(GameObject* u) const { u->Respawn(); } - void operator()(WorldObject*) const {} - void operator()(Corpse*) const {} + public: + RespawnDo() {} + void operator()(Creature* u) const { u->Respawn(); } + void operator()(GameObject* u) const { u->Respawn(); } + void operator()(WorldObject*) const {} + void operator()(Corpse*) const {} }; // GameObject checks class GameObjectFocusCheck { - public: - GameObjectFocusCheck(Unit const* unit, uint32 focusId) : i_unit(unit), i_focusId(focusId) {} - bool operator()(GameObject* go) const - { - if (go->GetGOInfo()->type != GAMEOBJECT_TYPE_SPELL_FOCUS) - return false; + public: + GameObjectFocusCheck(Unit const* unit, uint32 focusId) : i_unit(unit), i_focusId(focusId) {} + bool operator()(GameObject* go) const + { + if (go->GetGOInfo()->type != GAMEOBJECT_TYPE_SPELL_FOCUS) + return false; - if (!go->isSpawned()) // xinef: dont allow to count deactivated objects - return false; + if (!go->isSpawned()) // xinef: dont allow to count deactivated objects + return false; - if (go->GetGOInfo()->spellFocus.focusId != i_focusId) - return false; + if (go->GetGOInfo()->spellFocus.focusId != i_focusId) + return false; - float dist = (float)((go->GetGOInfo()->spellFocus.dist)/2); + float dist = (float)((go->GetGOInfo()->spellFocus.dist) / 2); - return go->IsWithinDistInMap(i_unit, dist); - } - private: - Unit const* i_unit; - uint32 i_focusId; + return go->IsWithinDistInMap(i_unit, dist); + } + private: + Unit const* i_unit; + uint32 i_focusId; }; // Find the nearest Fishing hole and return true only if source object is in range of hole class NearestGameObjectFishingHole { - public: - NearestGameObjectFishingHole(WorldObject const& obj, float range) : i_obj(obj), i_range(range) {} - bool operator()(GameObject* go) + public: + NearestGameObjectFishingHole(WorldObject const& obj, float range) : i_obj(obj), i_range(range) {} + bool operator()(GameObject* go) + { + if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_FISHINGHOLE && go->isSpawned() && i_obj.IsWithinDistInMap(go, i_range) && i_obj.IsWithinDistInMap(go, (float)go->GetGOInfo()->fishinghole.radius)) { - if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_FISHINGHOLE && go->isSpawned() && i_obj.IsWithinDistInMap(go, i_range) && i_obj.IsWithinDistInMap(go, (float)go->GetGOInfo()->fishinghole.radius)) - { - i_range = i_obj.GetDistance(go); - return true; - } - return false; + i_range = i_obj.GetDistance(go); + return true; } - private: - WorldObject const& i_obj; - float i_range; + return false; + } + private: + WorldObject const& i_obj; + float i_range; - // prevent clone - NearestGameObjectFishingHole(NearestGameObjectFishingHole const&); + // prevent clone + NearestGameObjectFishingHole(NearestGameObjectFishingHole const&); }; class NearestGameObjectCheck { - public: - NearestGameObjectCheck(WorldObject const& obj) : i_obj(obj), i_range(999) {} - bool operator()(GameObject* go) + public: + NearestGameObjectCheck(WorldObject const& obj) : i_obj(obj), i_range(999) {} + bool operator()(GameObject* go) + { + if (i_obj.IsWithinDistInMap(go, i_range)) { - if (i_obj.IsWithinDistInMap(go, i_range)) - { - i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check - return true; - } - return false; + i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check + return true; } - private: - WorldObject const& i_obj; - float i_range; + return false; + } + private: + WorldObject const& i_obj; + float i_range; - // prevent clone this object - NearestGameObjectCheck(NearestGameObjectCheck const&); + // prevent clone this object + NearestGameObjectCheck(NearestGameObjectCheck const&); }; // Success at unit in range, range update for next check (this can be use with GameobjectLastSearcher to find nearest GO) class NearestGameObjectEntryInObjectRangeCheck { - public: - NearestGameObjectEntryInObjectRangeCheck(WorldObject const& obj, uint32 entry, float range) : i_obj(obj), i_entry(entry), i_range(range) {} - bool operator()(GameObject* go) + public: + NearestGameObjectEntryInObjectRangeCheck(WorldObject const& obj, uint32 entry, float range) : i_obj(obj), i_entry(entry), i_range(range) {} + bool operator()(GameObject* go) + { + if (go->GetEntry() == i_entry && i_obj.IsWithinDistInMap(go, i_range)) { - if (go->GetEntry() == i_entry && i_obj.IsWithinDistInMap(go, i_range)) - { - i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check - return true; - } - return false; + i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check + return true; } - private: - WorldObject const& i_obj; - uint32 i_entry; - float i_range; + return false; + } + private: + WorldObject const& i_obj; + uint32 i_entry; + float i_range; - // prevent clone this object - NearestGameObjectEntryInObjectRangeCheck(NearestGameObjectEntryInObjectRangeCheck const&); + // prevent clone this object + NearestGameObjectEntryInObjectRangeCheck(NearestGameObjectEntryInObjectRangeCheck const&); }; // Success at unit in range, range update for next check (this can be use with GameobjectLastSearcher to find nearest GO with a certain type) @@ -721,345 +721,345 @@ namespace acore class GameObjectWithDbGUIDCheck { - public: - GameObjectWithDbGUIDCheck(uint32 db_guid) : i_db_guid(db_guid) {} - bool operator()(GameObject const* go) const - { - return go->GetDBTableGUIDLow() == i_db_guid; - } - private: - uint32 i_db_guid; + public: + GameObjectWithDbGUIDCheck(uint32 db_guid) : i_db_guid(db_guid) {} + bool operator()(GameObject const* go) const + { + return go->GetDBTableGUIDLow() == i_db_guid; + } + private: + uint32 i_db_guid; }; // Unit checks class MostHPMissingInRange { - public: - MostHPMissingInRange(Unit const* obj, float range, uint32 hp) : i_obj(obj), i_range(range), i_hp(hp) {} - bool operator()(Unit* u) + public: + MostHPMissingInRange(Unit const* obj, float range, uint32 hp) : i_obj(obj), i_range(range), i_hp(hp) {} + bool operator()(Unit* u) + { + if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && u->GetMaxHealth() - u->GetHealth() > i_hp) { - if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && u->GetMaxHealth() - u->GetHealth() > i_hp) - { - i_hp = u->GetMaxHealth() - u->GetHealth(); - return true; - } - return false; + i_hp = u->GetMaxHealth() - u->GetHealth(); + return true; } - private: - Unit const* i_obj; - float i_range; - uint32 i_hp; + return false; + } + private: + Unit const* i_obj; + float i_range; + uint32 i_hp; }; class FriendlyCCedInRange { - public: - FriendlyCCedInRange(Unit const* obj, float range) : i_obj(obj), i_range(range) {} - bool operator()(Unit* u) - { - if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && + public: + FriendlyCCedInRange(Unit const* obj, float range) : i_obj(obj), i_range(range) {} + bool operator()(Unit* u) + { + if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && (u->isFeared() || u->IsCharmed() || u->isFrozen() || u->HasUnitState(UNIT_STATE_STUNNED) || u->HasUnitState(UNIT_STATE_CONFUSED))) - { - return true; - } - return false; + { + return true; } - private: - Unit const* i_obj; - float i_range; + return false; + } + private: + Unit const* i_obj; + float i_range; }; class FriendlyMissingBuffInRange { - public: - FriendlyMissingBuffInRange(Unit const* obj, float range, uint32 spellid) : i_obj(obj), i_range(range) - { - i_spell = spellid; - if( SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellid) ) - if( SpellInfo const* newSpell = sSpellMgr->GetSpellForDifficultyFromSpell(spell, const_cast(obj)) ) - i_spell = newSpell->Id; - } - bool operator()(Unit* u) - { - if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && + public: + FriendlyMissingBuffInRange(Unit const* obj, float range, uint32 spellid) : i_obj(obj), i_range(range) + { + i_spell = spellid; + if( SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellid) ) + if( SpellInfo const* newSpell = sSpellMgr->GetSpellForDifficultyFromSpell(spell, const_cast(obj)) ) + i_spell = newSpell->Id; + } + bool operator()(Unit* u) + { + if (u->IsAlive() && u->IsInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && !(u->HasAura(i_spell))) - { - return true; - } - return false; + { + return true; } - private: - Unit const* i_obj; - float i_range; - uint32 i_spell; + return false; + } + private: + Unit const* i_obj; + float i_range; + uint32 i_spell; }; class AnyUnfriendlyUnitInObjectRangeCheck { - public: - AnyUnfriendlyUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {} - bool operator()(Unit* u) - { - if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u) && + public: + AnyUnfriendlyUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {} + bool operator()(Unit* u) + { + if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u) && (i_funit->GetTypeId() != TYPEID_UNIT || !i_funit->ToCreature()->IsAvoidingAOE())) // pussywizard - return true; - else - return false; - } - private: - WorldObject const* i_obj; - Unit const* i_funit; - float i_range; + return true; + else + return false; + } + private: + WorldObject const* i_obj; + Unit const* i_funit; + float i_range; }; class AnyUnfriendlyNoTotemUnitInObjectRangeCheck { - public: - AnyUnfriendlyNoTotemUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {} - bool operator()(Unit* u) - { - if (!u->IsAlive()) - return false; + public: + AnyUnfriendlyNoTotemUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {} + bool operator()(Unit* u) + { + if (!u->IsAlive()) + return false; - if (u->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) - return false; + if (u->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) + return false; - if (u->GetTypeId() == TYPEID_UNIT && (u->ToCreature()->IsTotem() || u->ToCreature()->IsTrigger() || u->ToCreature()->IsAvoidingAOE())) // pussywizard: added IsAvoidingAOE() - return false; + if (u->GetTypeId() == TYPEID_UNIT && (u->ToCreature()->IsTotem() || u->ToCreature()->IsTrigger() || u->ToCreature()->IsAvoidingAOE())) // pussywizard: added IsAvoidingAOE() + return false; - if (!u->isTargetableForAttack(false, i_funit)) - return false; + if (!u->isTargetableForAttack(false, i_funit)) + return false; - return i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u); - } - private: - WorldObject const* i_obj; - Unit const* i_funit; - float i_range; + return i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u); + } + private: + WorldObject const* i_obj; + Unit const* i_funit; + float i_range; }; class AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck { - public: - AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck(Unit const* funit, float range) - : i_funit(funit), i_range(range) {} + public: + AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck(Unit const* funit, float range) + : i_funit(funit), i_range(range) {} - bool operator()(const Unit* u) - { - return u->IsAlive() - && i_funit->IsWithinDistInMap(u, i_range) - && !i_funit->IsFriendlyTo(u) - && i_funit->IsValidAttackTarget(u) - && !u->IsCritter() - && !u->IsTotem() //xinef: dont attack totems - /*&& i_funit->CanSeeOrDetect(u)*/; // pussywizard: already checked in IsValidAttackTarget(u) - } - private: - Unit const* i_funit; - float i_range; + bool operator()(const Unit* u) + { + return u->IsAlive() + && i_funit->IsWithinDistInMap(u, i_range) + && !i_funit->IsFriendlyTo(u) + && i_funit->IsValidAttackTarget(u) + && !u->IsCritter() + && !u->IsTotem() //xinef: dont attack totems + /*&& i_funit->CanSeeOrDetect(u)*/; // pussywizard: already checked in IsValidAttackTarget(u) + } + private: + Unit const* i_funit; + float i_range; }; class CreatureWithDbGUIDCheck { - public: - CreatureWithDbGUIDCheck(uint32 lowguid) : i_lowguid(lowguid) {} - bool operator()(Creature* u) - { - return u->GetDBTableGUIDLow() == i_lowguid; - } - private: - uint32 i_lowguid; + public: + CreatureWithDbGUIDCheck(uint32 lowguid) : i_lowguid(lowguid) {} + bool operator()(Creature* u) + { + return u->GetDBTableGUIDLow() == i_lowguid; + } + private: + uint32 i_lowguid; }; class AnyFriendlyUnitInObjectRangeCheck { - public: - AnyFriendlyUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool playerOnly = false) : i_obj(obj), i_funit(funit), i_range(range), i_playerOnly(playerOnly) {} - bool operator()(Unit* u) - { - if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && i_funit->IsFriendlyTo(u) && (!i_playerOnly || u->GetTypeId() == TYPEID_PLAYER)) - return true; - else - return false; - } - private: - WorldObject const* i_obj; - Unit const* i_funit; - float i_range; - bool i_playerOnly; + public: + AnyFriendlyUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool playerOnly = false) : i_obj(obj), i_funit(funit), i_range(range), i_playerOnly(playerOnly) {} + bool operator()(Unit* u) + { + if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && i_funit->IsFriendlyTo(u) && (!i_playerOnly || u->GetTypeId() == TYPEID_PLAYER)) + return true; + else + return false; + } + private: + WorldObject const* i_obj; + Unit const* i_funit; + float i_range; + bool i_playerOnly; }; class AnyFriendlyNotSelfUnitInObjectRangeCheck { - public: - AnyFriendlyNotSelfUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool playerOnly = false) : i_obj(obj), i_funit(funit), i_range(range), i_playerOnly(playerOnly) {} - bool operator()(Unit* u) - { - if (u != i_obj && u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && i_funit->IsFriendlyTo(u) && (!i_playerOnly || u->GetTypeId() == TYPEID_PLAYER)) - return true; - else - return false; - } - private: - WorldObject const* i_obj; - Unit const* i_funit; - float i_range; - bool i_playerOnly; + public: + AnyFriendlyNotSelfUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool playerOnly = false) : i_obj(obj), i_funit(funit), i_range(range), i_playerOnly(playerOnly) {} + bool operator()(Unit* u) + { + if (u != i_obj && u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range) && i_funit->IsFriendlyTo(u) && (!i_playerOnly || u->GetTypeId() == TYPEID_PLAYER)) + return true; + else + return false; + } + private: + WorldObject const* i_obj; + Unit const* i_funit; + float i_range; + bool i_playerOnly; }; class AnyGroupedUnitInObjectRangeCheck { - public: - AnyGroupedUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool raid) : _source(obj), _refUnit(funit), _range(range), _raid(raid) {} - bool operator()(Unit* u) + public: + AnyGroupedUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool raid) : _source(obj), _refUnit(funit), _range(range), _raid(raid) {} + bool operator()(Unit* u) + { + if (_raid) { - if (_raid) - { - if (!_refUnit->IsInRaidWith(u)) - return false; - } - else if (!_refUnit->IsInPartyWith(u)) + if (!_refUnit->IsInRaidWith(u)) return false; - - return !_refUnit->IsHostileTo(u) && u->IsAlive() && _source->IsWithinDistInMap(u, _range); } + else if (!_refUnit->IsInPartyWith(u)) + return false; - private: - WorldObject const* _source; - Unit const* _refUnit; - float _range; - bool _raid; + return !_refUnit->IsHostileTo(u) && u->IsAlive() && _source->IsWithinDistInMap(u, _range); + } + + private: + WorldObject const* _source; + Unit const* _refUnit; + float _range; + bool _raid; }; class AnyUnitInObjectRangeCheck { - public: - AnyUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {} - bool operator()(Unit* u) - { - if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range)) - return true; + public: + AnyUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {} + bool operator()(Unit* u) + { + if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range)) + return true; - return false; - } - private: - WorldObject const* i_obj; - float i_range; + return false; + } + private: + WorldObject const* i_obj; + float i_range; }; // Success at unit in range, range update for next check (this can be use with UnitLastSearcher to find nearest unit) class NearestAttackableUnitInObjectRangeCheck { - public: - NearestAttackableUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {} - bool operator()(Unit* u) - { - if (u->isTargetableForAttack(true, i_funit) && i_obj->IsWithinDistInMap(u, i_range) && + public: + NearestAttackableUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {} + bool operator()(Unit* u) + { + if (u->isTargetableForAttack(true, i_funit) && i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u) && i_funit->CanSeeOrDetect(u)) - { - i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check - return true; - } - - return false; + { + i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check + return true; } - private: - WorldObject const* i_obj; - Unit const* i_funit; - float i_range; - // prevent clone this object - NearestAttackableUnitInObjectRangeCheck(NearestAttackableUnitInObjectRangeCheck const&); + return false; + } + private: + WorldObject const* i_obj; + Unit const* i_funit; + float i_range; + + // prevent clone this object + NearestAttackableUnitInObjectRangeCheck(NearestAttackableUnitInObjectRangeCheck const&); }; class AnyAoETargetUnitInObjectRangeCheck { - public: - AnyAoETargetUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) - : i_obj(obj), i_funit(funit), _spellInfo(nullptr), i_range(range) - { - Unit const* check = i_funit; - Unit const* owner = i_funit->GetOwner(); - if (owner) - check = owner; - i_targetForPlayer = (check->GetTypeId() == TYPEID_PLAYER); - if (i_obj->GetTypeId() == TYPEID_DYNAMICOBJECT) - _spellInfo = sSpellMgr->GetSpellInfo(((DynamicObject*)i_obj)->GetSpellId()); - } - bool operator()(Unit* u) - { - // Check contains checks for: live, non-selectable, non-attackable flags, flight check and GM check, ignore totems - if (u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->IsTotem()) - return false; - - if (i_funit->_IsValidAttackTarget(u, _spellInfo,i_obj->GetTypeId() == TYPEID_DYNAMICOBJECT ? i_obj : nullptr) && i_obj->IsWithinDistInMap(u, i_range)) - return true; - + public: + AnyAoETargetUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) + : i_obj(obj), i_funit(funit), _spellInfo(nullptr), i_range(range) + { + Unit const* check = i_funit; + Unit const* owner = i_funit->GetOwner(); + if (owner) + check = owner; + i_targetForPlayer = (check->GetTypeId() == TYPEID_PLAYER); + if (i_obj->GetTypeId() == TYPEID_DYNAMICOBJECT) + _spellInfo = sSpellMgr->GetSpellInfo(((DynamicObject*)i_obj)->GetSpellId()); + } + bool operator()(Unit* u) + { + // Check contains checks for: live, non-selectable, non-attackable flags, flight check and GM check, ignore totems + if (u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->IsTotem()) return false; - } - private: - bool i_targetForPlayer; - WorldObject const* i_obj; - Unit const* i_funit; - SpellInfo const* _spellInfo; - float i_range; + + if (i_funit->_IsValidAttackTarget(u, _spellInfo, i_obj->GetTypeId() == TYPEID_DYNAMICOBJECT ? i_obj : nullptr) && i_obj->IsWithinDistInMap(u, i_range)) + return true; + + return false; + } + private: + bool i_targetForPlayer; + WorldObject const* i_obj; + Unit const* i_funit; + SpellInfo const* _spellInfo; + float i_range; }; class AnyAttackableUnitExceptForOriginalCasterInObjectRangeCheck { - public: - AnyAttackableUnitExceptForOriginalCasterInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) - : i_obj(obj), i_funit(funit), i_range(range) - {} - bool operator()(Unit* u) - { - if (!u->IsAlive() || u->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE) || (u->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC) && !u->IsInCombat())) - return false; - if (u->GetGUID() == i_funit->GetGUID()) - return false; - - if (i_obj->IsWithinDistInMap(u, i_range)) - return true; - + public: + AnyAttackableUnitExceptForOriginalCasterInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) + : i_obj(obj), i_funit(funit), i_range(range) + {} + bool operator()(Unit* u) + { + if (!u->IsAlive() || u->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE) || (u->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC) && !u->IsInCombat())) return false; - } - private: - WorldObject const* i_obj; - Unit const* i_funit; - float i_range; + if (u->GetGUID() == i_funit->GetGUID()) + return false; + + if (i_obj->IsWithinDistInMap(u, i_range)) + return true; + + return false; + } + private: + WorldObject const* i_obj; + Unit const* i_funit; + float i_range; }; // do attack at call of help to friendly crearture class CallOfHelpCreatureInRangeDo { - public: - CallOfHelpCreatureInRangeDo(Unit* funit, Unit* enemy, float range) - : i_funit(funit), i_enemy(enemy), i_range(range) - {} - void operator()(Creature* u) - { - if (u == i_funit) - return; + public: + CallOfHelpCreatureInRangeDo(Unit* funit, Unit* enemy, float range) + : i_funit(funit), i_enemy(enemy), i_range(range) + {} + void operator()(Creature* u) + { + if (u == i_funit) + return; - if (!u->CanAssistTo(i_funit, i_enemy, false)) - return; + if (!u->CanAssistTo(i_funit, i_enemy, false)) + return; - // too far - if (!u->IsWithinDistInMap(i_funit, i_range)) - return; + // too far + if (!u->IsWithinDistInMap(i_funit, i_range)) + return; - // only if see assisted creature's enemy - if (!u->IsWithinLOSInMap(i_enemy)) - return; + // only if see assisted creature's enemy + if (!u->IsWithinLOSInMap(i_enemy)) + return; - if (u->AI()) - u->AI()->AttackStart(i_enemy); - } - private: - Unit* const i_funit; - Unit* const i_enemy; - float i_range; + if (u->AI()) + u->AI()->AttackStart(i_enemy); + } + private: + Unit* const i_funit; + Unit* const i_enemy; + float i_range; }; struct AnyDeadUnitCheck @@ -1078,215 +1078,215 @@ namespace acore class NearestHostileUnitCheck { - public: - explicit NearestHostileUnitCheck(Creature const* creature, float dist = 0, bool playerOnly = false) : me(creature), i_playerOnly(playerOnly) - { - m_range = (dist == 0 ? 9999 : dist); - } - bool operator()(Unit* u) - { - if (!me->IsWithinDistInMap(u, m_range)) - return false; + public: + explicit NearestHostileUnitCheck(Creature const* creature, float dist = 0, bool playerOnly = false) : me(creature), i_playerOnly(playerOnly) + { + m_range = (dist == 0 ? 9999 : dist); + } + bool operator()(Unit* u) + { + if (!me->IsWithinDistInMap(u, m_range)) + return false; - if (!me->IsValidAttackTarget(u)) - return false; + if (!me->IsValidAttackTarget(u)) + return false; - if (i_playerOnly && u->GetTypeId() != TYPEID_PLAYER) - return false; + if (i_playerOnly && u->GetTypeId() != TYPEID_PLAYER) + return false; - m_range = me->GetDistance(u); // use found unit range as new range limit for next check - return true; - } + m_range = me->GetDistance(u); // use found unit range as new range limit for next check + return true; + } private: - Creature const* me; - float m_range; - bool i_playerOnly; - NearestHostileUnitCheck(NearestHostileUnitCheck const&); + Creature const* me; + float m_range; + bool i_playerOnly; + NearestHostileUnitCheck(NearestHostileUnitCheck const&); }; class NearestHostileUnitInAttackDistanceCheck { - public: - explicit NearestHostileUnitInAttackDistanceCheck(Creature const* creature, float dist) : me(creature), m_range(dist) {} - bool operator()(Unit* u) - { - if (!me->IsWithinDistInMap(u, m_range)) - return false; + public: + explicit NearestHostileUnitInAttackDistanceCheck(Creature const* creature, float dist) : me(creature), m_range(dist) {} + bool operator()(Unit* u) + { + if (!me->IsWithinDistInMap(u, m_range)) + return false; - if (!me->CanStartAttack(u)) - return false; + if (!me->CanStartAttack(u)) + return false; - m_range = me->GetDistance(u); // use found unit range as new range limit for next check - return true; - } - private: - Creature const* me; - float m_range; - NearestHostileUnitInAttackDistanceCheck(NearestHostileUnitInAttackDistanceCheck const&); + m_range = me->GetDistance(u); // use found unit range as new range limit for next check + return true; + } + private: + Creature const* me; + float m_range; + NearestHostileUnitInAttackDistanceCheck(NearestHostileUnitInAttackDistanceCheck const&); }; class AnyAssistCreatureInRangeCheck { - public: - AnyAssistCreatureInRangeCheck(Unit* funit, Unit* enemy, float range) - : i_funit(funit), i_enemy(enemy), i_range(range) - { - } - bool operator()(Creature* u) - { - if (u == i_funit) - return false; + public: + AnyAssistCreatureInRangeCheck(Unit* funit, Unit* enemy, float range) + : i_funit(funit), i_enemy(enemy), i_range(range) + { + } + bool operator()(Creature* u) + { + if (u == i_funit) + return false; - if (!u->CanAssistTo(i_funit, i_enemy)) - return false; + if (!u->CanAssistTo(i_funit, i_enemy)) + return false; - // too far - if (!i_funit->IsWithinDistInMap(u, i_range)) - return false; + // too far + if (!i_funit->IsWithinDistInMap(u, i_range)) + return false; - // only if see assisted creature - if (!i_funit->IsWithinLOSInMap(u)) - return false; + // only if see assisted creature + if (!i_funit->IsWithinLOSInMap(u)) + return false; - return true; - } - private: - Unit* const i_funit; - Unit* const i_enemy; - float i_range; + return true; + } + private: + Unit* const i_funit; + Unit* const i_enemy; + float i_range; }; class NearestAssistCreatureInCreatureRangeCheck { - public: - NearestAssistCreatureInCreatureRangeCheck(Creature* obj, Unit* enemy, float range) - : i_obj(obj), i_enemy(enemy), i_range(range) {} + public: + NearestAssistCreatureInCreatureRangeCheck(Creature* obj, Unit* enemy, float range) + : i_obj(obj), i_enemy(enemy), i_range(range) {} - bool operator()(Creature* u) - { - if (u == i_obj) - return false; - if (!u->CanAssistTo(i_obj, i_enemy)) - return false; + bool operator()(Creature* u) + { + if (u == i_obj) + return false; + if (!u->CanAssistTo(i_obj, i_enemy)) + return false; - if (!i_obj->IsWithinDistInMap(u, i_range)) - return false; + if (!i_obj->IsWithinDistInMap(u, i_range)) + return false; - if (!i_obj->IsWithinLOSInMap(u)) - return false; + if (!i_obj->IsWithinLOSInMap(u)) + return false; - i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check - return true; - } - private: - Creature* const i_obj; - Unit* const i_enemy; - float i_range; + i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check + return true; + } + private: + Creature* const i_obj; + Unit* const i_enemy; + float i_range; - // prevent clone this object - NearestAssistCreatureInCreatureRangeCheck(NearestAssistCreatureInCreatureRangeCheck const&); + // prevent clone this object + NearestAssistCreatureInCreatureRangeCheck(NearestAssistCreatureInCreatureRangeCheck const&); }; // Success at unit in range, range update for next check (this can be use with CreatureLastSearcher to find nearest creature) class NearestCreatureEntryWithLiveStateInObjectRangeCheck { - public: - NearestCreatureEntryWithLiveStateInObjectRangeCheck(WorldObject const& obj, uint32 entry, bool alive, float range) - : i_obj(obj), i_entry(entry), i_alive(alive), i_range(range) {} + public: + NearestCreatureEntryWithLiveStateInObjectRangeCheck(WorldObject const& obj, uint32 entry, bool alive, float range) + : i_obj(obj), i_entry(entry), i_alive(alive), i_range(range) {} - bool operator()(Creature* u) + bool operator()(Creature* u) + { + if (u->GetEntry() == i_entry && u->IsAlive() == i_alive && i_obj.IsWithinDistInMap(u, i_range)) { - if (u->GetEntry() == i_entry && u->IsAlive() == i_alive && i_obj.IsWithinDistInMap(u, i_range)) - { - i_range = i_obj.GetDistance(u); // use found unit range as new range limit for next check - return true; - } - return false; + i_range = i_obj.GetDistance(u); // use found unit range as new range limit for next check + return true; } - private: - WorldObject const& i_obj; - uint32 i_entry; - bool i_alive; - float i_range; + return false; + } + private: + WorldObject const& i_obj; + uint32 i_entry; + bool i_alive; + float i_range; - // prevent clone this object - NearestCreatureEntryWithLiveStateInObjectRangeCheck(NearestCreatureEntryWithLiveStateInObjectRangeCheck const&); + // prevent clone this object + NearestCreatureEntryWithLiveStateInObjectRangeCheck(NearestCreatureEntryWithLiveStateInObjectRangeCheck const&); }; class AnyPlayerInObjectRangeCheck { - public: - AnyPlayerInObjectRangeCheck(WorldObject const* obj, float range, bool reqAlive = true, bool disallowGM = false) : _obj(obj), _range(range), _reqAlive(reqAlive), _disallowGM(disallowGM) {} - bool operator()(Player* u) - { - if (_reqAlive && !u->IsAlive()) - return false; + public: + AnyPlayerInObjectRangeCheck(WorldObject const* obj, float range, bool reqAlive = true, bool disallowGM = false) : _obj(obj), _range(range), _reqAlive(reqAlive), _disallowGM(disallowGM) {} + bool operator()(Player* u) + { + if (_reqAlive && !u->IsAlive()) + return false; - if (_disallowGM && (u->IsGameMaster() || u->IsSpectator())) - return false; + if (_disallowGM && (u->IsGameMaster() || u->IsSpectator())) + return false; - if (!_obj->IsWithinDistInMap(u, _range)) - return false; + if (!_obj->IsWithinDistInMap(u, _range)) + return false; - return true; - } + return true; + } - // pussywizard: needed for DestroyForNearbyPlayers - bool operator()(Player* u, bool checkRange) - { - if (checkRange && !_obj->IsWithinDistInMap(u, _range)) - return false; + // pussywizard: needed for DestroyForNearbyPlayers + bool operator()(Player* u, bool checkRange) + { + if (checkRange && !_obj->IsWithinDistInMap(u, _range)) + return false; - return true; - } + return true; + } - private: - WorldObject const* _obj; - float _range; - bool _reqAlive; - bool _disallowGM; + private: + WorldObject const* _obj; + float _range; + bool _reqAlive; + bool _disallowGM; }; class AnyPlayerExactPositionInGameObjectRangeCheck { - public: - AnyPlayerExactPositionInGameObjectRangeCheck(GameObject const* go, float range) : _go(go), _range(range) {} - bool operator()(Player* u) - { - if (!_go->IsInRange(u->GetPositionX(), u->GetPositionY(), u->GetPositionZ(), _range)) - return false; + public: + AnyPlayerExactPositionInGameObjectRangeCheck(GameObject const* go, float range) : _go(go), _range(range) {} + bool operator()(Player* u) + { + if (!_go->IsInRange(u->GetPositionX(), u->GetPositionY(), u->GetPositionZ(), _range)) + return false; - return true; - } + return true; + } - private: - GameObject const* _go; - float _range; + private: + GameObject const* _go; + float _range; }; class NearestPlayerInObjectRangeCheck { - public: - NearestPlayerInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) + public: + NearestPlayerInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) + { + } + + bool operator()(Player* u) + { + if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range)) { + i_range = i_obj->GetDistance(u); + return true; } - bool operator()(Player* u) - { - if (u->IsAlive() && i_obj->IsWithinDistInMap(u, i_range)) - { - i_range = i_obj->GetDistance(u); - return true; - } + return false; + } + private: + WorldObject const* i_obj; + float i_range; - return false; - } - private: - WorldObject const* i_obj; - float i_range; - - NearestPlayerInObjectRangeCheck(NearestPlayerInObjectRangeCheck const&); + NearestPlayerInObjectRangeCheck(NearestPlayerInObjectRangeCheck const&); }; class AllFriendlyCreaturesInGrid @@ -1323,20 +1323,20 @@ namespace acore class AllCreaturesOfEntryInRange { - public: - AllCreaturesOfEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) {} - bool operator() (Unit* unit) - { - if (unit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(unit, m_fRange, false)) - return true; + public: + AllCreaturesOfEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) {} + bool operator() (Unit* unit) + { + if (unit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(unit, m_fRange, false)) + return true; - return false; - } + return false; + } - private: - const WorldObject* m_pObject; - uint32 m_uiEntry; - float m_fRange; + private: + const WorldObject* m_pObject; + uint32 m_uiEntry; + float m_fRange; }; class PlayerAtMinimumRangeAway @@ -1361,7 +1361,7 @@ namespace acore { public: GameObjectInRangeCheck(float _x, float _y, float _z, float _range, uint32 _entry = 0) : - x(_x), y(_y), z(_z), range(_range), entry(_entry) {} + x(_x), y(_y), z(_z), range(_range), entry(_entry) {} bool operator() (GameObject* go) { if (!entry || (go->GetGOInfo() && go->GetGOInfo()->entry == entry)) @@ -1388,106 +1388,106 @@ namespace acore class ObjectTypeIdCheck { - public: - ObjectTypeIdCheck(TypeID typeId, bool equals) : _typeId(typeId), _equals(equals) {} - bool operator()(WorldObject const* object) - { - return (object->GetTypeId() == _typeId) == _equals; - } + public: + ObjectTypeIdCheck(TypeID typeId, bool equals) : _typeId(typeId), _equals(equals) {} + bool operator()(WorldObject const* object) + { + return (object->GetTypeId() == _typeId) == _equals; + } - private: - TypeID _typeId; - bool _equals; + private: + TypeID _typeId; + bool _equals; }; class ObjectGUIDCheck { - public: - ObjectGUIDCheck(uint64 GUID, bool equals) : _GUID(GUID), _equals(equals) {} - bool operator()(WorldObject const* object) - { - return (object->GetGUID() == _GUID) == _equals; - } + public: + ObjectGUIDCheck(uint64 GUID, bool equals) : _GUID(GUID), _equals(equals) {} + bool operator()(WorldObject const* object) + { + return (object->GetGUID() == _GUID) == _equals; + } - private: - uint64 _GUID; - bool _equals; + private: + uint64 _GUID; + bool _equals; }; class UnitAuraCheck { - public: - UnitAuraCheck(bool present, uint32 spellId, uint64 casterGUID = 0) : _present(present), _spellId(spellId), _casterGUID(casterGUID) {} - bool operator()(Unit const* unit) const - { - return unit->HasAura(_spellId, _casterGUID) == _present; - } + public: + UnitAuraCheck(bool present, uint32 spellId, uint64 casterGUID = 0) : _present(present), _spellId(spellId), _casterGUID(casterGUID) {} + bool operator()(Unit const* unit) const + { + return unit->HasAura(_spellId, _casterGUID) == _present; + } - bool operator()(WorldObject const* object) const - { - return object->ToUnit() && object->ToUnit()->HasAura(_spellId, _casterGUID) == _present; - } + bool operator()(WorldObject const* object) const + { + return object->ToUnit() && object->ToUnit()->HasAura(_spellId, _casterGUID) == _present; + } - private: - bool _present; - uint32 _spellId; - uint64 _casterGUID; + private: + bool _present; + uint32 _spellId; + uint64 _casterGUID; }; class AllWorldObjectsInExactRange { - public: - AllWorldObjectsInExactRange(const WorldObject* object, float range, bool equals) : _object(object), _range(range), _equals(equals) { } - bool operator() (WorldObject const* object) - { - return (_object->GetExactDist2d(object) > _range) == _equals; - } + public: + AllWorldObjectsInExactRange(const WorldObject* object, float range, bool equals) : _object(object), _range(range), _equals(equals) { } + bool operator() (WorldObject const* object) + { + return (_object->GetExactDist2d(object) > _range) == _equals; + } - private: - const WorldObject* _object; - float _range; - bool _equals; + private: + const WorldObject* _object; + float _range; + bool _equals; }; class RandomCheck { - public: - explicit RandomCheck(uint8 chance) : _chance(chance) { } - bool operator()(WorldObject const* /*object*/) const - { - return roll_chance_i(_chance); - } + public: + explicit RandomCheck(uint8 chance) : _chance(chance) { } + bool operator()(WorldObject const* /*object*/) const + { + return roll_chance_i(_chance); + } - private: - uint8 const _chance; + private: + uint8 const _chance; }; - + class PowerCheck { - public: - explicit PowerCheck(Powers const power, bool equals) : _power(power), _equals(equals) { } - bool operator()(WorldObject const* object) const - { - return object->ToUnit() && (object->ToUnit()->getPowerType() == _power) == _equals; - } + public: + explicit PowerCheck(Powers const power, bool equals) : _power(power), _equals(equals) { } + bool operator()(WorldObject const* object) const + { + return object->ToUnit() && (object->ToUnit()->getPowerType() == _power) == _equals; + } - private: - Powers const _power; - bool const _equals; + private: + Powers const _power; + bool const _equals; }; class RaidCheck { - public: - explicit RaidCheck(Unit const* compare, bool equals) : _compare(compare), _equals(equals) { } - bool operator()(WorldObject const* object) const - { - return object->ToUnit() && object->ToUnit()->IsInRaidWith(_compare) == _equals; - } + public: + explicit RaidCheck(Unit const* compare, bool equals) : _compare(compare), _equals(equals) { } + bool operator()(WorldObject const* object) const + { + return object->ToUnit() && object->ToUnit()->IsInRaidWith(_compare) == _equals; + } - private: - Unit const* _compare; - bool const _equals; + private: + Unit const* _compare; + bool const _equals; }; // Player checks and do @@ -1496,41 +1496,41 @@ namespace acore template class LocalizedPacketDo { - public: - explicit LocalizedPacketDo(Builder& builder) : i_builder(builder) {} + public: + explicit LocalizedPacketDo(Builder& builder) : i_builder(builder) {} - ~LocalizedPacketDo() - { - for (size_t i = 0; i < i_data_cache.size(); ++i) - delete i_data_cache[i]; - } - void operator()(Player* p); + ~LocalizedPacketDo() + { + for (size_t i = 0; i < i_data_cache.size(); ++i) + delete i_data_cache[i]; + } + void operator()(Player* p); - private: - Builder& i_builder; - std::vector i_data_cache; // 0 = default, i => i-1 locale index + private: + Builder& i_builder; + std::vector i_data_cache; // 0 = default, i => i-1 locale index }; // Prepare using Builder localized packets with caching and send to player template class LocalizedPacketListDo { - public: - typedef std::vector WorldPacketList; - explicit LocalizedPacketListDo(Builder& builder) : i_builder(builder) {} + public: + typedef std::vector WorldPacketList; + explicit LocalizedPacketListDo(Builder& builder) : i_builder(builder) {} - ~LocalizedPacketListDo() - { - for (size_t i = 0; i < i_data_cache.size(); ++i) - for (size_t j = 0; j < i_data_cache[i].size(); ++j) - delete i_data_cache[i][j]; - } - void operator()(Player* p); + ~LocalizedPacketListDo() + { + for (size_t i = 0; i < i_data_cache.size(); ++i) + for (size_t j = 0; j < i_data_cache[i].size(); ++j) + delete i_data_cache[i][j]; + } + void operator()(Player* p); - private: - Builder& i_builder; - std::vector i_data_cache; - // 0 = default, i => i-1 locale index + private: + Builder& i_builder; + std::vector i_data_cache; + // 0 = default, i => i-1 locale index }; } #endif diff --git a/src/server/game/Grids/Notifiers/GridNotifiersImpl.h b/src/server/game/Grids/Notifiers/GridNotifiersImpl.h index b16b1ba1f..f8efb25e0 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiersImpl.h +++ b/src/server/game/Grids/Notifiers/GridNotifiersImpl.h @@ -17,7 +17,7 @@ #include "Opcodes.h" template -inline void acore::VisibleNotifier::Visit(GridRefManager &m) +inline void acore::VisibleNotifier::Visit(GridRefManager& m) { // Xinef: Update gameobjects only if (i_gobjOnly) @@ -37,7 +37,7 @@ inline void acore::VisibleNotifier::Visit(GridRefManager &m) // WorldObject searchers & workers template -void acore::WorldObjectSearcher::Visit(GameObjectMapType &m) +void acore::WorldObjectSearcher::Visit(GameObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_GAMEOBJECT)) return; @@ -46,7 +46,7 @@ void acore::WorldObjectSearcher::Visit(GameObjectMapType &m) if (i_object) return; - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -60,7 +60,7 @@ void acore::WorldObjectSearcher::Visit(GameObjectMapType &m) } template -void acore::WorldObjectSearcher::Visit(PlayerMapType &m) +void acore::WorldObjectSearcher::Visit(PlayerMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_PLAYER)) return; @@ -69,7 +69,7 @@ void acore::WorldObjectSearcher::Visit(PlayerMapType &m) if (i_object) return; - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -83,7 +83,7 @@ void acore::WorldObjectSearcher::Visit(PlayerMapType &m) } template -void acore::WorldObjectSearcher::Visit(CreatureMapType &m) +void acore::WorldObjectSearcher::Visit(CreatureMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CREATURE)) return; @@ -92,7 +92,7 @@ void acore::WorldObjectSearcher::Visit(CreatureMapType &m) if (i_object) return; - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -106,7 +106,7 @@ void acore::WorldObjectSearcher::Visit(CreatureMapType &m) } template -void acore::WorldObjectSearcher::Visit(CorpseMapType &m) +void acore::WorldObjectSearcher::Visit(CorpseMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CORPSE)) return; @@ -115,7 +115,7 @@ void acore::WorldObjectSearcher::Visit(CorpseMapType &m) if (i_object) return; - for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -129,7 +129,7 @@ void acore::WorldObjectSearcher::Visit(CorpseMapType &m) } template -void acore::WorldObjectSearcher::Visit(DynamicObjectMapType &m) +void acore::WorldObjectSearcher::Visit(DynamicObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_DYNAMICOBJECT)) return; @@ -138,7 +138,7 @@ void acore::WorldObjectSearcher::Visit(DynamicObjectMapType &m) if (i_object) return; - for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -153,12 +153,12 @@ void acore::WorldObjectSearcher::Visit(DynamicObjectMapType &m) template -void acore::WorldObjectLastSearcher::Visit(GameObjectMapType &m) +void acore::WorldObjectLastSearcher::Visit(GameObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_GAMEOBJECT)) return; - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -169,12 +169,12 @@ void acore::WorldObjectLastSearcher::Visit(GameObjectMapType &m) } template -void acore::WorldObjectLastSearcher::Visit(PlayerMapType &m) +void acore::WorldObjectLastSearcher::Visit(PlayerMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_PLAYER)) return; - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -185,12 +185,12 @@ void acore::WorldObjectLastSearcher::Visit(PlayerMapType &m) } template -void acore::WorldObjectLastSearcher::Visit(CreatureMapType &m) +void acore::WorldObjectLastSearcher::Visit(CreatureMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CREATURE)) return; - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -201,12 +201,12 @@ void acore::WorldObjectLastSearcher::Visit(CreatureMapType &m) } template -void acore::WorldObjectLastSearcher::Visit(CorpseMapType &m) +void acore::WorldObjectLastSearcher::Visit(CorpseMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CORPSE)) return; - for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -217,12 +217,12 @@ void acore::WorldObjectLastSearcher::Visit(CorpseMapType &m) } template -void acore::WorldObjectLastSearcher::Visit(DynamicObjectMapType &m) +void acore::WorldObjectLastSearcher::Visit(DynamicObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_DYNAMICOBJECT)) return; - for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -233,56 +233,56 @@ void acore::WorldObjectLastSearcher::Visit(DynamicObjectMapType &m) } template -void acore::WorldObjectListSearcher::Visit(PlayerMapType &m) +void acore::WorldObjectListSearcher::Visit(PlayerMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_PLAYER)) return; - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::WorldObjectListSearcher::Visit(CreatureMapType &m) +void acore::WorldObjectListSearcher::Visit(CreatureMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CREATURE)) return; - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::WorldObjectListSearcher::Visit(CorpseMapType &m) +void acore::WorldObjectListSearcher::Visit(CorpseMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_CORPSE)) return; - for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::WorldObjectListSearcher::Visit(GameObjectMapType &m) +void acore::WorldObjectListSearcher::Visit(GameObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_GAMEOBJECT)) return; - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::WorldObjectListSearcher::Visit(DynamicObjectMapType &m) +void acore::WorldObjectListSearcher::Visit(DynamicObjectMapType& m) { if (!(i_mapTypeMask & GRID_MAP_TYPE_MASK_DYNAMICOBJECT)) return; - for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } @@ -290,13 +290,13 @@ void acore::WorldObjectListSearcher::Visit(DynamicObjectMapType &m) // Gameobject searchers template -void acore::GameObjectSearcher::Visit(GameObjectMapType &m) +void acore::GameObjectSearcher::Visit(GameObjectMapType& m) { // already found if (i_object) return; - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -310,9 +310,9 @@ void acore::GameObjectSearcher::Visit(GameObjectMapType &m) } template -void acore::GameObjectLastSearcher::Visit(GameObjectMapType &m) +void acore::GameObjectLastSearcher::Visit(GameObjectMapType& m) { - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -323,9 +323,9 @@ void acore::GameObjectLastSearcher::Visit(GameObjectMapType &m) } template -void acore::GameObjectListSearcher::Visit(GameObjectMapType &m) +void acore::GameObjectListSearcher::Visit(GameObjectMapType& m) { - for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); @@ -334,13 +334,13 @@ void acore::GameObjectListSearcher::Visit(GameObjectMapType &m) // Unit searchers template -void acore::UnitSearcher::Visit(CreatureMapType &m) +void acore::UnitSearcher::Visit(CreatureMapType& m) { // already found if (i_object) return; - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -354,13 +354,13 @@ void acore::UnitSearcher::Visit(CreatureMapType &m) } template -void acore::UnitSearcher::Visit(PlayerMapType &m) +void acore::UnitSearcher::Visit(PlayerMapType& m) { // already found if (i_object) return; - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -374,9 +374,9 @@ void acore::UnitSearcher::Visit(PlayerMapType &m) } template -void acore::UnitLastSearcher::Visit(CreatureMapType &m) +void acore::UnitLastSearcher::Visit(CreatureMapType& m) { - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -387,9 +387,9 @@ void acore::UnitLastSearcher::Visit(CreatureMapType &m) } template -void acore::UnitLastSearcher::Visit(PlayerMapType &m) +void acore::UnitLastSearcher::Visit(PlayerMapType& m) { - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -400,18 +400,18 @@ void acore::UnitLastSearcher::Visit(PlayerMapType &m) } template -void acore::UnitListSearcher::Visit(PlayerMapType &m) +void acore::UnitListSearcher::Visit(PlayerMapType& m) { - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::UnitListSearcher::Visit(CreatureMapType &m) +void acore::UnitListSearcher::Visit(CreatureMapType& m) { - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); @@ -420,13 +420,13 @@ void acore::UnitListSearcher::Visit(CreatureMapType &m) // Creature searchers template -void acore::CreatureSearcher::Visit(CreatureMapType &m) +void acore::CreatureSearcher::Visit(CreatureMapType& m) { // already found if (i_object) return; - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -440,9 +440,9 @@ void acore::CreatureSearcher::Visit(CreatureMapType &m) } template -void acore::CreatureLastSearcher::Visit(CreatureMapType &m) +void acore::CreatureLastSearcher::Visit(CreatureMapType& m) { - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -453,36 +453,36 @@ void acore::CreatureLastSearcher::Visit(CreatureMapType &m) } template -void acore::CreatureListSearcher::Visit(CreatureMapType &m) +void acore::CreatureListSearcher::Visit(CreatureMapType& m) { - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::PlayerListSearcher::Visit(PlayerMapType &m) +void acore::PlayerListSearcher::Visit(PlayerMapType& m) { - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) if (i_check(itr->GetSource())) i_objects.push_back(itr->GetSource()); } template -void acore::PlayerListSearcherWithSharedVision::Visit(PlayerMapType &m) +void acore::PlayerListSearcherWithSharedVision::Visit(PlayerMapType& m) { - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask)) if (i_check(itr->GetSource(), true)) i_objects.push_back(itr->GetSource()); } template -void acore::PlayerListSearcherWithSharedVision::Visit(CreatureMapType &m) +void acore::PlayerListSearcherWithSharedVision::Visit(CreatureMapType& m) { - for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->GetSource()->InSamePhase(i_phaseMask) && itr->GetSource()->HasSharedVision()) for (SharedVisionList::const_iterator i = itr->GetSource()->GetSharedVisionList().begin(); i != itr->GetSource()->GetSharedVisionList().end(); ++i) if (i_check(*i, false)) @@ -490,13 +490,13 @@ void acore::PlayerListSearcherWithSharedVision::Visit(CreatureMapType &m) } template -void acore::PlayerSearcher::Visit(PlayerMapType &m) +void acore::PlayerSearcher::Visit(PlayerMapType& m) { // already found if (i_object) return; - for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr) + for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->GetSource()->InSamePhase(i_phaseMask)) continue; @@ -526,7 +526,7 @@ template void acore::LocalizedPacketDo::operator()(Player* p) { LocaleConstant loc_idx = p->GetSession()->GetSessionDbLocaleIndex(); - uint32 cache_idx = loc_idx+1; + uint32 cache_idx = loc_idx + 1; WorldPacket* data; // create if not cached yet @@ -553,14 +553,14 @@ template void acore::LocalizedPacketListDo::operator()(Player* p) { LocaleConstant loc_idx = p->GetSession()->GetSessionDbLocaleIndex(); - uint32 cache_idx = loc_idx+1; + uint32 cache_idx = loc_idx + 1; WorldPacketList* data_list; // create if not cached yet - if (i_data_cache.size() < cache_idx+1 || i_data_cache[cache_idx].empty()) + if (i_data_cache.size() < cache_idx + 1 || i_data_cache[cache_idx].empty()) { - if (i_data_cache.size() < cache_idx+1) - i_data_cache.resize(cache_idx+1); + if (i_data_cache.size() < cache_idx + 1) + i_data_cache.resize(cache_idx + 1); data_list = &i_data_cache[cache_idx]; diff --git a/src/server/game/Grids/ObjectGridLoader.cpp b/src/server/game/Grids/ObjectGridLoader.cpp index fc183b33f..744021ced 100644 --- a/src/server/game/Grids/ObjectGridLoader.cpp +++ b/src/server/game/Grids/ObjectGridLoader.cpp @@ -21,21 +21,21 @@ //TODO: to implement npc on transport, also need to load npcs at grid loading class ObjectWorldLoader { - public: - explicit ObjectWorldLoader(ObjectGridLoader& gloader) - : i_cell(gloader.i_cell), i_map(gloader.i_map), i_grid(gloader.i_grid), i_corpses (0) - {} +public: + explicit ObjectWorldLoader(ObjectGridLoader& gloader) + : i_cell(gloader.i_cell), i_map(gloader.i_map), i_grid(gloader.i_grid), i_corpses (0) + {} - void Visit(CorpseMapType &m); + void Visit(CorpseMapType& m); - template void Visit(GridRefManager&) { } + template void Visit(GridRefManager&) { } - private: - Cell i_cell; - Map* i_map; - public: - NGridType &i_grid; - uint32 i_corpses; +private: + Cell i_cell; + Map* i_map; +public: + NGridType& i_grid; + uint32 i_corpses; }; template void ObjectGridLoader::SetObjectCell(T* /*obj*/, CellCoord const& /*cellCoord*/) @@ -55,7 +55,7 @@ template<> void ObjectGridLoader::SetObjectCell(GameObject* obj, CellCoord const } template -void AddObjectHelper(CellCoord &cell, GridRefManager &m, uint32 &count, Map* /*map*/, T *obj) +void AddObjectHelper(CellCoord& cell, GridRefManager& m, uint32& count, Map* /*map*/, T* obj) { obj->AddToGrid(m); ObjectGridLoader::SetObjectCell(obj, cell); @@ -64,7 +64,7 @@ void AddObjectHelper(CellCoord &cell, GridRefManager &m, uint32 &count, Map* } template <> -void AddObjectHelper(CellCoord &cell, CreatureMapType &m, uint32 &count, Map* map, Creature *obj) +void AddObjectHelper(CellCoord& cell, CreatureMapType& m, uint32& count, Map* map, Creature* obj) { obj->AddToGrid(m); ObjectGridLoader::SetObjectCell(obj, cell); @@ -76,7 +76,7 @@ void AddObjectHelper(CellCoord &cell, CreatureMapType &m, uint32 &count, Map* ma } template <> -void AddObjectHelper(CellCoord &cell, GameObjectMapType &m, uint32 &count, Map* map, GameObject *obj) +void AddObjectHelper(CellCoord& cell, GameObjectMapType& m, uint32& count, Map* map, GameObject* obj) { obj->AddToGrid(m); ObjectGridLoader::SetObjectCell(obj, cell); @@ -88,7 +88,7 @@ void AddObjectHelper(CellCoord &cell, GameObjectMapType &m, uint32 &count, Map* } template -void LoadHelper(CellGuidSet const& guid_set, CellCoord &cell, GridRefManager &m, uint32 &count, Map* map) +void LoadHelper(CellGuidSet const& guid_set, CellCoord& cell, GridRefManager& m, uint32& count, Map* map) { for (CellGuidSet::const_iterator i_guid = guid_set.begin(); i_guid != guid_set.end(); ++i_guid) { @@ -106,7 +106,7 @@ void LoadHelper(CellGuidSet const& guid_set, CellCoord &cell, GridRefManager } template <> -void LoadHelper(CellGuidSet const& guid_set, CellCoord &cell, GridRefManager &m, uint32 &count, Map* map) +void LoadHelper(CellGuidSet const& guid_set, CellCoord& cell, GridRefManager& m, uint32& count, Map* map) { for (CellGuidSet::const_iterator i_guid = guid_set.begin(); i_guid != guid_set.end(); ++i_guid) { @@ -124,7 +124,7 @@ void LoadHelper(CellGuidSet const& guid_set, CellCoord &cell, GridRefManagerGetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cellCoord.GetId()); LoadHelper(cell_guids.gameobjects, cellCoord, m, i_gameObjects, i_map); } -void ObjectGridLoader::Visit(CreatureMapType &m) +void ObjectGridLoader::Visit(CreatureMapType& m) { CellCoord cellCoord = i_cell.GetCellCoord(); CellObjectGuids const& cell_guids = sObjectMgr->GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cellCoord.GetId()); LoadHelper(cell_guids.creatures, cellCoord, m, i_creatures, i_map); } -void ObjectWorldLoader::Visit(CorpseMapType &m) +void ObjectWorldLoader::Visit(CorpseMapType& m) { CellCoord cellCoord = i_cell.GetCellCoord(); // corpses are always added to spawn mode 0 and they are spawned by their instance id @@ -180,12 +180,14 @@ void ObjectWorldLoader::Visit(CorpseMapType &m) void ObjectGridLoader::LoadN(void) { - i_gameObjects = 0; i_creatures = 0; i_corpses = 0; + i_gameObjects = 0; + i_creatures = 0; + i_corpses = 0; i_cell.data.Part.cell_y = 0; - for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x) + for (unsigned int x = 0; x < MAX_NUMBER_OF_CELLS; ++x) { i_cell.data.Part.cell_x = x; - for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y) + for (unsigned int y = 0; y < MAX_NUMBER_OF_CELLS; ++y) { i_cell.data.Part.cell_y = y; @@ -210,11 +212,11 @@ void ObjectGridLoader::LoadN(void) } template -void ObjectGridUnloader::Visit(GridRefManager &m) +void ObjectGridUnloader::Visit(GridRefManager& m) { while (!m.isEmpty()) { - T *obj = m.getFirst()->GetSource(); + T* obj = m.getFirst()->GetSource(); // if option set then object already saved at this moment //if (!sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY)) // obj->SaveRespawnTime(); @@ -229,17 +231,17 @@ void ObjectGridUnloader::Visit(GridRefManager &m) } template -void ObjectGridCleaner::Visit(GridRefManager &m) +void ObjectGridCleaner::Visit(GridRefManager& m) { for (typename GridRefManager::iterator iter = m.begin(); iter != m.end(); ++iter) iter->GetSource()->CleanupsBeforeDelete(); } -template void ObjectGridUnloader::Visit(CreatureMapType &); -template void ObjectGridUnloader::Visit(GameObjectMapType &); -template void ObjectGridUnloader::Visit(DynamicObjectMapType &); -template void ObjectGridUnloader::Visit(CorpseMapType &); -template void ObjectGridCleaner::Visit(CreatureMapType &); -template void ObjectGridCleaner::Visit(GameObjectMapType &); -template void ObjectGridCleaner::Visit(DynamicObjectMapType &); -template void ObjectGridCleaner::Visit(CorpseMapType &); +template void ObjectGridUnloader::Visit(CreatureMapType&); +template void ObjectGridUnloader::Visit(GameObjectMapType&); +template void ObjectGridUnloader::Visit(DynamicObjectMapType&); +template void ObjectGridUnloader::Visit(CorpseMapType&); +template void ObjectGridCleaner::Visit(CreatureMapType&); +template void ObjectGridCleaner::Visit(GameObjectMapType&); +template void ObjectGridCleaner::Visit(DynamicObjectMapType&); +template void ObjectGridCleaner::Visit(CorpseMapType&); diff --git a/src/server/game/Grids/ObjectGridLoader.h b/src/server/game/Grids/ObjectGridLoader.h index c00e66ebd..b9f12c066 100644 --- a/src/server/game/Grids/ObjectGridLoader.h +++ b/src/server/game/Grids/ObjectGridLoader.h @@ -19,40 +19,40 @@ class ObjectGridLoader { friend class ObjectWorldLoader; - public: - ObjectGridLoader(NGridType &grid, Map* map, const Cell &cell) - : i_cell(cell), i_grid(grid), i_map(map), i_gameObjects(0), i_creatures(0), i_corpses (0) - {} +public: + ObjectGridLoader(NGridType& grid, Map* map, const Cell& cell) + : i_cell(cell), i_grid(grid), i_map(map), i_gameObjects(0), i_creatures(0), i_corpses (0) + {} - void Visit(GameObjectMapType &m); - void Visit(CreatureMapType &m); - void Visit(CorpseMapType &) const {} - void Visit(DynamicObjectMapType&) const {} + void Visit(GameObjectMapType& m); + void Visit(CreatureMapType& m); + void Visit(CorpseMapType&) const {} + void Visit(DynamicObjectMapType&) const {} - void LoadN(void); + void LoadN(void); - template static void SetObjectCell(T* obj, CellCoord const& cellCoord); + template static void SetObjectCell(T* obj, CellCoord const& cellCoord); - private: - Cell i_cell; - NGridType &i_grid; - Map* i_map; - uint32 i_gameObjects; - uint32 i_creatures; - uint32 i_corpses; +private: + Cell i_cell; + NGridType& i_grid; + Map* i_map; + uint32 i_gameObjects; + uint32 i_creatures; + uint32 i_corpses; }; //Clean up and remove from world class ObjectGridCleaner { - public: - template void Visit(GridRefManager &); +public: + template void Visit(GridRefManager&); }; //Delete objects before deleting NGrid class ObjectGridUnloader { - public: - template void Visit(GridRefManager &m); +public: + template void Visit(GridRefManager& m); }; #endif diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index cf160fb2e..75a7ef91b 100644 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -31,9 +31,9 @@ #include "UpdateFieldFlags.h" Roll::Roll(uint64 _guid, LootItem const& li) : itemGUID(_guid), itemid(li.itemid), -itemRandomPropId(li.randomPropertyId), itemRandomSuffix(li.randomSuffix), itemCount(li.count), -totalPlayersRolling(0), totalNeed(0), totalGreed(0), totalPass(0), itemSlot(0), -rollVoteMask(ROLL_ALL_TYPE_NO_DISENCHANT) + itemRandomPropId(li.randomPropertyId), itemRandomSuffix(li.randomSuffix), itemCount(li.count), + totalPlayersRolling(0), totalNeed(0), totalGreed(0), totalPass(0), itemSlot(0), + rollVoteMask(ROLL_ALL_TYPE_NO_DISENCHANT) { } @@ -52,10 +52,10 @@ Loot* Roll::getLoot() } Group::Group() : m_leaderGuid(0), m_leaderName(""), m_groupType(GROUPTYPE_NORMAL), -m_dungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL), m_raidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL), - m_bfGroup(nullptr), m_bgGroup(nullptr), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON), m_looterGuid(0), -m_masterLooterGuid(0), m_subGroupsCounts(nullptr), m_guid(0), m_counter(0), m_maxEnchantingLevel(0), _difficultyChangePreventionTime(0), -_difficultyChangePreventionType(DIFFICULTY_PREVENTION_CHANGE_NONE) + m_dungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL), m_raidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL), + m_bfGroup(nullptr), m_bgGroup(nullptr), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON), m_looterGuid(0), + m_masterLooterGuid(0), m_subGroupsCounts(nullptr), m_guid(0), m_counter(0), m_maxEnchantingLevel(0), _difficultyChangePreventionTime(0), + _difficultyChangePreventionType(DIFFICULTY_PREVENTION_CHANGE_NONE) { for (uint8 i = 0; i < TARGETICONCOUNT; ++i) m_targetIcons[i] = 0; @@ -76,7 +76,7 @@ Group::~Group() while (!RollId.empty()) { itr = RollId.begin(); - Roll *r = *itr; + Roll* r = *itr; RollId.erase(itr); delete(r); } @@ -178,7 +178,7 @@ bool Group::LoadGroupFromDB(Field* fields) m_lootThreshold = ItemQualities(fields[3].GetUInt8()); for (uint8 i = 0; i < TARGETICONCOUNT; ++i) - m_targetIcons[i] = fields[4+i].GetUInt32(); + m_targetIcons[i] = fields[4 + i].GetUInt32(); m_groupType = GroupType(fields[12].GetUInt8()); if (m_groupType & GROUPTYPE_RAID) @@ -192,9 +192,9 @@ bool Group::LoadGroupFromDB(Field* fields) uint32 r_diff = fields[14].GetUInt8(); if (r_diff >= MAX_RAID_DIFFICULTY) - m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL; + m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL; else - m_raidDifficulty = Difficulty(r_diff); + m_raidDifficulty = Difficulty(r_diff); m_masterLooterGuid = MAKE_NEW_GUID(fields[15].GetUInt32(), 0, HIGHGUID_PLAYER); @@ -320,7 +320,7 @@ void Group::RemoveInvite(Player* player) void Group::RemoveAllInvites() { - for (InvitesList::iterator itr=m_invitees.begin(); itr != m_invitees.end(); ++itr) + for (InvitesList::iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr) if (*itr) (*itr)->SetGroupInvite(nullptr); @@ -498,7 +498,7 @@ bool Group::AddMember(Player* player) return true; } -bool Group::RemoveMember(uint64 guid, const RemoveMethod &method /*= GROUP_REMOVEMETHOD_DEFAULT*/, uint64 kicker /*= 0*/, const char* reason /*= NULL*/) +bool Group::RemoveMember(uint64 guid, const RemoveMethod& method /*= GROUP_REMOVEMETHOD_DEFAULT*/, uint64 kicker /*= 0*/, const char* reason /*= NULL*/) { BroadcastGroupUpdate(); @@ -519,7 +519,7 @@ bool Group::RemoveMember(uint64 guid, const RemoveMethod &method /*= GROUP_REMOV if (isBGGroup() || isBFGroup()) player->RemoveFromBattlegroundOrBattlefieldRaid(); else - // Regular group + // Regular group { if (player->GetOriginalGroup() == this) player->SetOriginalGroup(nullptr); @@ -539,7 +539,7 @@ bool Group::RemoveMember(uint64 guid, const RemoveMethod &method /*= GROUP_REMOV } // Do we really need to send this opcode? - data.Initialize(SMSG_GROUP_LIST, 1+1+1+1+8+4+4+8); + data.Initialize(SMSG_GROUP_LIST, 1 + 1 + 1 + 1 + 8 + 4 + 4 + 8); data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0); data << uint64(m_guid) << uint32(m_counter) << uint32(0) << uint64(0); player->GetSession()->SendPacket(&data); @@ -693,7 +693,7 @@ void Group::ChangeLeader(uint64 newLeaderGuid) m_leaderName = newLeader->GetName(); ToggleGroupMemberFlag(slot, MEMBER_FLAG_ASSISTANT, false); - WorldPacket data(SMSG_GROUP_SET_LEADER, m_leaderName.size()+1); + WorldPacket data(SMSG_GROUP_SET_LEADER, m_leaderName.size() + 1); data << slot->name; BroadcastPacket(&data, true); @@ -750,7 +750,7 @@ void Group::Disband(bool hideDestroy /* = false */) } else { - data.Initialize(SMSG_GROUP_LIST, 1+1+1+1+8+4+4+8); + data.Initialize(SMSG_GROUP_LIST, 1 + 1 + 1 + 1 + 8 + 4 + 4 + 8); data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0); data << uint64(m_guid) << uint32(m_counter) << uint32(0) << uint64(0); player->GetSession()->SendPacket(&data); @@ -788,9 +788,9 @@ void Group::Disband(bool hideDestroy /* = false */) /*** LOOT SYSTEM ***/ /*********************************************************/ -void Group::SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll &r) +void Group::SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll& r) { - WorldPacket data(SMSG_LOOT_START_ROLL, (8+4+4+4+4+4+4+1)); + WorldPacket data(SMSG_LOOT_START_ROLL, (8 + 4 + 4 + 4 + 4 + 4 + 4 + 1)); data << uint64(r.itemGUID); // guid of rolled item data << uint32(mapid); // 3.3.3 mapid data << uint32(r.itemSlot); // itemslot @@ -801,7 +801,7 @@ void Group::SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll &r) data << uint32(CountDown); // the countdown time to choose "need" or "greed" data << uint8(r.rollVoteMask); // roll type mask - for (Roll::PlayerVote::const_iterator itr=r.playerVote.begin(); itr != r.playerVote.end(); ++itr) + for (Roll::PlayerVote::const_iterator itr = r.playerVote.begin(); itr != r.playerVote.end(); ++itr) { Player* p = ObjectAccessor::FindPlayerInOrOutOfWorld(itr->first); if (!p) @@ -836,7 +836,7 @@ void Group::SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, void Group::SendLootRoll(uint64 sourceGuid, uint64 targetGuid, uint8 rollNumber, uint8 rollType, Roll const& roll) { - WorldPacket data(SMSG_LOOT_ROLL, (8+4+8+4+4+4+1+1+1)); + WorldPacket data(SMSG_LOOT_ROLL, (8 + 4 + 8 + 4 + 4 + 4 + 1 + 1 + 1)); data << uint64(sourceGuid); // guid of the item rolled data << uint32(roll.itemSlot); // slot data << uint64(targetGuid); @@ -860,7 +860,7 @@ void Group::SendLootRoll(uint64 sourceGuid, uint64 targetGuid, uint8 rollNumber, void Group::SendLootRollWon(uint64 sourceGuid, uint64 targetGuid, uint8 rollNumber, uint8 rollType, Roll const& roll) { - WorldPacket data(SMSG_LOOT_ROLL_WON, (8+4+4+4+4+8+1+1)); + WorldPacket data(SMSG_LOOT_ROLL_WON, (8 + 4 + 4 + 4 + 4 + 8 + 1 + 1)); data << uint64(sourceGuid); // guid of the item rolled data << uint32(roll.itemSlot); // slot data << uint32(roll.itemid); // the itemEntryId for the item that shall be rolled for @@ -883,7 +883,7 @@ void Group::SendLootRollWon(uint64 sourceGuid, uint64 targetGuid, uint8 rollNumb void Group::SendLootAllPassed(Roll const& roll) { - WorldPacket data(SMSG_LOOT_ALL_PASSED, (8+4+4+4+4)); + WorldPacket data(SMSG_LOOT_ALL_PASSED, (8 + 4 + 4 + 4 + 4)); data << uint64(roll.itemGUID); // Guid of the item rolled data << uint32(roll.itemSlot); // Item loot slot data << uint32(roll.itemid); // The itemEntryId for the item that shall be rolled for @@ -906,7 +906,7 @@ void Group::SendLooter(Creature* creature, Player* groupLooter) { ASSERT(creature); - WorldPacket data(SMSG_LOOT_LIST, (8+8)); + WorldPacket data(SMSG_LOOT_LIST, (8 + 8)); data << uint64(creature->GetGUID()); if (GetLootMethod() == MASTER_LOOT && creature->loot.hasOverThresholdItem()) @@ -982,7 +982,7 @@ void Group::GroupLoot(Loot* loot, WorldObject* pLootedObject) // If there is any "auto pass", broadcast the pass now. if (r->totalPass) { - for (Roll::PlayerVote::const_iterator itr=r->playerVote.begin(); itr != r->playerVote.end(); ++itr) + for (Roll::PlayerVote::const_iterator itr = r->playerVote.begin(); itr != r->playerVote.end(); ++itr) { Player* p = ObjectAccessor::FindPlayer(itr->first); if (!p) @@ -1321,7 +1321,8 @@ void Group::EndRoll(Loot* pLoot, Map* allowedMap) { for (Rolls::iterator itr = RollId.begin(); itr != RollId.end();) { - if ((*itr)->getLoot() == pLoot) { + if ((*itr)->getLoot() == pLoot) + { CountTheRoll(itr, allowedMap); //i don't have to edit player votes, who didn't vote ... he will pass itr = RollId.begin(); } @@ -1349,7 +1350,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) uint64 maxguid = 0; // pussywizard: start with 0 >_> Player* player = nullptr; - for (Roll::PlayerVote::const_iterator itr=roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr) + for (Roll::PlayerVote::const_iterator itr = roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr) { if (itr->second != NEED) continue; @@ -1502,13 +1503,13 @@ void Group::SetTargetIcon(uint8 id, uint64 whoGuid, uint64 targetGuid) // clean other icons if (targetGuid != 0) - for (int i=0; igroup); data << uint8(slot->flags); @@ -1573,7 +1574,7 @@ void Group::SendUpdateToPlayer(uint64 playerGUID, MemberSlot* slot) data << uint64(m_guid); data << uint32(m_counter++); // 3.3, value increases every time this packet gets sent - data << uint32(GetMembersCount()-1); + data << uint32(GetMembersCount() - 1); for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr) { if (slot->guid == citr->guid) @@ -2074,7 +2075,7 @@ void Group::SetLfgRoles(uint64 guid, const uint8 roles) return; slot->roles = roles; - SendUpdate(); + SendUpdate(); } bool Group::IsFull() const @@ -2122,7 +2123,7 @@ uint32 Group::GetLowGUID() const return GUID_LOPART(m_guid); } -const char * Group::GetLeaderName() const +const char* Group::GetLeaderName() const { return m_leaderName.c_str(); } @@ -2177,7 +2178,7 @@ bool Group::SameSubGroup(uint64 guid1, uint64 guid2) const { member_citerator mslot2 = _getMemberCSlot(guid2); if (mslot2 == m_memberSlots.end()) - return false; + return false; return SameSubGroup(guid1, &*mslot2); } @@ -2198,7 +2199,7 @@ uint8 Group::GetMemberGroup(uint64 guid) const { member_citerator mslot = _getMemberCSlot(guid); if (mslot == m_memberSlots.end()) - return (MAX_RAID_SUBGROUPS+1); + return (MAX_RAID_SUBGROUPS + 1); return mslot->group; } @@ -2207,7 +2208,7 @@ void Group::SetBattlegroundGroup(Battleground* bg) m_bgGroup = bg; } -void Group::SetBattlefieldGroup(Battlefield *bg) +void Group::SetBattlefieldGroup(Battlefield* bg) { m_bfGroup = bg; } @@ -2216,7 +2217,7 @@ void Group::SetGroupMemberFlag(uint64 guid, bool apply, GroupMemberFlags flag) { // Assistants, main assistants and main tanks are only available in raid groups if (!isRaidGroup()) - return; + return; // Check if player is really in the raid member_witerator slot = _getMemberWSlot(guid); @@ -2224,7 +2225,8 @@ void Group::SetGroupMemberFlag(uint64 guid, bool apply, GroupMemberFlags flag) return; // Do flag specific actions, e.g ensure uniqueness - switch (flag) { + switch (flag) + { case MEMBER_FLAG_MAINASSIST: RemoveUniqueGroupMemberFlag(MEMBER_FLAG_MAINASSIST); // Remove main assist flag from current if any. break; @@ -2275,7 +2277,7 @@ bool Group::isRollLootActive() const Group::Rolls::iterator Group::GetRoll(uint64 Guid) { Rolls::iterator iter; - for (iter=RollId.begin(); iter != RollId.end(); ++iter) + for (iter = RollId.begin(); iter != RollId.end(); ++iter) if ((*iter)->itemGUID == Guid && (*iter)->isValid()) return iter; return RollId.end(); diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index ed7b491d7..90a5bdf91 100644 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -123,225 +123,225 @@ enum DifficultyPreventionChangeType }; #define GROUP_UPDATE_FLAGS_COUNT 20 - // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 +// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 static const uint8 GroupUpdateLength[GROUP_UPDATE_FLAGS_COUNT] = { 0, 2, 2, 2, 1, 2, 2, 2, 2, 4, 8, 8, 1, 2, 2, 2, 1, 2, 2, 8}; class Roll : public LootValidatorRef { - public: - Roll(uint64 _guid, LootItem const& li); - ~Roll(); - void setLoot(Loot* pLoot); - Loot* getLoot(); - void targetObjectBuildLink(); +public: + Roll(uint64 _guid, LootItem const& li); + ~Roll(); + void setLoot(Loot* pLoot); + Loot* getLoot(); + void targetObjectBuildLink(); - uint64 itemGUID; - uint32 itemid; - int32 itemRandomPropId; - uint32 itemRandomSuffix; - uint8 itemCount; - typedef std::map PlayerVote; - PlayerVote playerVote; //vote position correspond with player position (in group) - uint8 totalPlayersRolling; - uint8 totalNeed; - uint8 totalGreed; - uint8 totalPass; - uint8 itemSlot; - uint8 rollVoteMask; + uint64 itemGUID; + uint32 itemid; + int32 itemRandomPropId; + uint32 itemRandomSuffix; + uint8 itemCount; + typedef std::map PlayerVote; + PlayerVote playerVote; //vote position correspond with player position (in group) + uint8 totalPlayersRolling; + uint8 totalNeed; + uint8 totalGreed; + uint8 totalPass; + uint8 itemSlot; + uint8 rollVoteMask; }; /** request member stats checken **/ /** todo: uninvite people that not accepted invite **/ class Group { - public: - struct MemberSlot - { - uint64 guid; - std::string name; - uint8 group; - uint8 flags; - uint8 roles; - }; - typedef std::list MemberSlotList; - typedef MemberSlotList::const_iterator member_citerator; +public: + struct MemberSlot + { + uint64 guid; + std::string name; + uint8 group; + uint8 flags; + uint8 roles; + }; + typedef std::list MemberSlotList; + typedef MemberSlotList::const_iterator member_citerator; - protected: - typedef MemberSlotList::iterator member_witerator; - typedef std::set InvitesList; +protected: + typedef MemberSlotList::iterator member_witerator; + typedef std::set InvitesList; - typedef std::vector Rolls; + typedef std::vector Rolls; - public: - Group(); - ~Group(); +public: + Group(); + ~Group(); - // group manipulation methods - bool Create(Player* leader); - bool LoadGroupFromDB(Field* field); - void LoadMemberFromDB(uint32 guidLow, uint8 memberFlags, uint8 subgroup, uint8 roles); - bool AddInvite(Player* player); - void RemoveInvite(Player* player); - void RemoveAllInvites(); - bool AddLeaderInvite(Player* player); - bool AddMember(Player* player); - bool RemoveMember(uint64 guid, const RemoveMethod &method = GROUP_REMOVEMETHOD_DEFAULT, uint64 kicker = 0, const char* reason = nullptr); - void ChangeLeader(uint64 guid); - void SetLootMethod(LootMethod method); - void SetLooterGuid(uint64 guid); - void SetMasterLooterGuid(uint64 guid); - void UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed = false); - void SetLootThreshold(ItemQualities threshold); - void Disband(bool hideDestroy=false); - void SetLfgRoles(uint64 guid, const uint8 roles); + // group manipulation methods + bool Create(Player* leader); + bool LoadGroupFromDB(Field* field); + void LoadMemberFromDB(uint32 guidLow, uint8 memberFlags, uint8 subgroup, uint8 roles); + bool AddInvite(Player* player); + void RemoveInvite(Player* player); + void RemoveAllInvites(); + bool AddLeaderInvite(Player* player); + bool AddMember(Player* player); + bool RemoveMember(uint64 guid, const RemoveMethod& method = GROUP_REMOVEMETHOD_DEFAULT, uint64 kicker = 0, const char* reason = nullptr); + void ChangeLeader(uint64 guid); + void SetLootMethod(LootMethod method); + void SetLooterGuid(uint64 guid); + void SetMasterLooterGuid(uint64 guid); + void UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed = false); + void SetLootThreshold(ItemQualities threshold); + void Disband(bool hideDestroy = false); + void SetLfgRoles(uint64 guid, const uint8 roles); - // properties accessories - bool IsFull() const; - bool isLFGGroup() const; - bool isRaidGroup() const; - bool isBFGroup() const; - bool isBGGroup() const; - bool IsCreated() const; - uint64 GetLeaderGUID() const; - uint64 GetGUID() const; - uint32 GetLowGUID() const; - const char * GetLeaderName() const; - LootMethod GetLootMethod() const; - uint64 GetLooterGuid() const; - uint64 GetMasterLooterGuid() const; - ItemQualities GetLootThreshold() const; + // properties accessories + bool IsFull() const; + bool isLFGGroup() const; + bool isRaidGroup() const; + bool isBFGroup() const; + bool isBGGroup() const; + bool IsCreated() const; + uint64 GetLeaderGUID() const; + uint64 GetGUID() const; + uint32 GetLowGUID() const; + const char* GetLeaderName() const; + LootMethod GetLootMethod() const; + uint64 GetLooterGuid() const; + uint64 GetMasterLooterGuid() const; + ItemQualities GetLootThreshold() const; - // member manipulation methods - bool IsMember(uint64 guid) const; - bool IsLeader(uint64 guid) const; - uint64 GetMemberGUID(const std::string& name); - bool IsAssistant(uint64 guid) const; + // member manipulation methods + bool IsMember(uint64 guid) const; + bool IsLeader(uint64 guid) const; + uint64 GetMemberGUID(const std::string& name); + bool IsAssistant(uint64 guid) const; - Player* GetInvited(uint64 guid) const; - Player* GetInvited(const std::string& name) const; + Player* GetInvited(uint64 guid) const; + Player* GetInvited(const std::string& name) const; - bool SameSubGroup(uint64 guid1, uint64 guid2) const; - bool SameSubGroup(uint64 guid1, MemberSlot const* slot2) const; - bool SameSubGroup(Player const* member1, Player const* member2) const; - bool HasFreeSlotSubGroup(uint8 subgroup) const; + bool SameSubGroup(uint64 guid1, uint64 guid2) const; + bool SameSubGroup(uint64 guid1, MemberSlot const* slot2) const; + bool SameSubGroup(Player const* member1, Player const* member2) const; + bool HasFreeSlotSubGroup(uint8 subgroup) const; - MemberSlotList const& GetMemberSlots() const { return m_memberSlots; } - GroupReference* GetFirstMember() { return m_memberMgr.getFirst(); } - GroupReference const* GetFirstMember() const { return m_memberMgr.getFirst(); } - uint32 GetMembersCount() const { return m_memberSlots.size(); } + MemberSlotList const& GetMemberSlots() const { return m_memberSlots; } + GroupReference* GetFirstMember() { return m_memberMgr.getFirst(); } + GroupReference const* GetFirstMember() const { return m_memberMgr.getFirst(); } + uint32 GetMembersCount() const { return m_memberSlots.size(); } - uint8 GetMemberGroup(uint64 guid) const; + uint8 GetMemberGroup(uint64 guid) const; - void ConvertToLFG(); - void ConvertToRaid(); + void ConvertToLFG(); + void ConvertToRaid(); - void SetBattlegroundGroup(Battleground* bg); - void SetBattlefieldGroup(Battlefield* bf); - GroupJoinBattlegroundResult CanJoinBattlegroundQueue(Battleground const* bgTemplate, BattlegroundQueueTypeId bgQueueTypeId, uint32 MinPlayerCount, uint32 MaxPlayerCount, bool isRated, uint32 arenaSlot); + void SetBattlegroundGroup(Battleground* bg); + void SetBattlefieldGroup(Battlefield* bf); + GroupJoinBattlegroundResult CanJoinBattlegroundQueue(Battleground const* bgTemplate, BattlegroundQueueTypeId bgQueueTypeId, uint32 MinPlayerCount, uint32 MaxPlayerCount, bool isRated, uint32 arenaSlot); - void ChangeMembersGroup(uint64 guid, uint8 group); - void SetTargetIcon(uint8 id, uint64 whoGuid, uint64 targetGuid); - void SetGroupMemberFlag(uint64 guid, bool apply, GroupMemberFlags flag); - void RemoveUniqueGroupMemberFlag(GroupMemberFlags flag); + void ChangeMembersGroup(uint64 guid, uint8 group); + void SetTargetIcon(uint8 id, uint64 whoGuid, uint64 targetGuid); + void SetGroupMemberFlag(uint64 guid, bool apply, GroupMemberFlags flag); + void RemoveUniqueGroupMemberFlag(GroupMemberFlags flag); - Difficulty GetDifficulty(bool isRaid) const; - Difficulty GetDungeonDifficulty() const; - Difficulty GetRaidDifficulty() const; - void SetDungeonDifficulty(Difficulty difficulty); - void SetRaidDifficulty(Difficulty difficulty); - uint16 InInstance(); - void ResetInstances(uint8 method, bool isRaid, Player* leader); + Difficulty GetDifficulty(bool isRaid) const; + Difficulty GetDungeonDifficulty() const; + Difficulty GetRaidDifficulty() const; + void SetDungeonDifficulty(Difficulty difficulty); + void SetRaidDifficulty(Difficulty difficulty); + uint16 InInstance(); + void ResetInstances(uint8 method, bool isRaid, Player* leader); - // -no description- - //void SendInit(WorldSession* session); - void SendTargetIconList(WorldSession* session); - void SendUpdate(); - void SendUpdateToPlayer(uint64 playerGUID, MemberSlot* slot = nullptr); - void UpdatePlayerOutOfRange(Player* player); - // ignore: GUID of player that will be ignored - void BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group=-1, uint64 ignore=0); - void BroadcastReadyCheck(WorldPacket* packet); - void OfflineReadyCheck(); + // -no description- + //void SendInit(WorldSession* session); + void SendTargetIconList(WorldSession* session); + void SendUpdate(); + void SendUpdateToPlayer(uint64 playerGUID, MemberSlot* slot = nullptr); + void UpdatePlayerOutOfRange(Player* player); + // ignore: GUID of player that will be ignored + void BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group = -1, uint64 ignore = 0); + void BroadcastReadyCheck(WorldPacket* packet); + void OfflineReadyCheck(); - /*********************************************************/ - /*** LOOT SYSTEM ***/ - /*********************************************************/ + /*********************************************************/ + /*** LOOT SYSTEM ***/ + /*********************************************************/ - bool isRollLootActive() const; - void SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll &r); - void SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, bool canNeed, Roll const& r); - void SendLootRoll(uint64 SourceGuid, uint64 TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r); - void SendLootRollWon(uint64 SourceGuid, uint64 TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r); - void SendLootAllPassed(Roll const& roll); - void SendLooter(Creature* creature, Player* pLooter); - void GroupLoot(Loot* loot, WorldObject* pLootedObject); - void NeedBeforeGreed(Loot* loot, WorldObject* pLootedObject); - void MasterLoot(Loot* loot, WorldObject* pLootedObject); - Rolls::iterator GetRoll(uint64 Guid); - void CountTheRoll(Rolls::iterator roll, Map* allowedMap); - bool CountRollVote(uint64 playerGUID, uint64 Guid, uint8 Choise); - void EndRoll(Loot* loot, Map* allowedMap); + bool isRollLootActive() const; + void SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll& r); + void SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, bool canNeed, Roll const& r); + void SendLootRoll(uint64 SourceGuid, uint64 TargetGuid, uint8 RollNumber, uint8 RollType, const Roll& r); + void SendLootRollWon(uint64 SourceGuid, uint64 TargetGuid, uint8 RollNumber, uint8 RollType, const Roll& r); + void SendLootAllPassed(Roll const& roll); + void SendLooter(Creature* creature, Player* pLooter); + void GroupLoot(Loot* loot, WorldObject* pLootedObject); + void NeedBeforeGreed(Loot* loot, WorldObject* pLootedObject); + void MasterLoot(Loot* loot, WorldObject* pLootedObject); + Rolls::iterator GetRoll(uint64 Guid); + void CountTheRoll(Rolls::iterator roll, Map* allowedMap); + bool CountRollVote(uint64 playerGUID, uint64 Guid, uint8 Choise); + void EndRoll(Loot* loot, Map* allowedMap); - // related to disenchant rolls - void ResetMaxEnchantingLevel(); + // related to disenchant rolls + void ResetMaxEnchantingLevel(); - void LinkMember(GroupReference* pRef); + void LinkMember(GroupReference* pRef); - // FG: evil hacks - void BroadcastGroupUpdate(void); + // FG: evil hacks + void BroadcastGroupUpdate(void); - // LFG - void AddLfgBuffFlag() { m_lfgGroupFlags |= GROUP_LFG_FLAG_APPLY_RANDOM_BUFF; } - void AddLfgRandomInstanceFlag() { m_lfgGroupFlags |= GROUP_LFG_FLAG_IS_RANDOM_INSTANCE; } - void AddLfgHeroicFlag() { m_lfgGroupFlags |= GROUP_LFG_FLAG_IS_HEROIC; } - bool IsLfgWithBuff() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_APPLY_RANDOM_BUFF); } - bool IsLfgRandomInstance() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_IS_RANDOM_INSTANCE); } - bool IsLfgHeroic() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_IS_HEROIC); } + // LFG + void AddLfgBuffFlag() { m_lfgGroupFlags |= GROUP_LFG_FLAG_APPLY_RANDOM_BUFF; } + void AddLfgRandomInstanceFlag() { m_lfgGroupFlags |= GROUP_LFG_FLAG_IS_RANDOM_INSTANCE; } + void AddLfgHeroicFlag() { m_lfgGroupFlags |= GROUP_LFG_FLAG_IS_HEROIC; } + bool IsLfgWithBuff() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_APPLY_RANDOM_BUFF); } + bool IsLfgRandomInstance() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_IS_RANDOM_INSTANCE); } + bool IsLfgHeroic() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_IS_HEROIC); } - // Difficulty Change - uint32 GetDifficultyChangePreventionTime() const { return _difficultyChangePreventionTime > time(nullptr) ? _difficultyChangePreventionTime - time(nullptr) : 0; } - DifficultyPreventionChangeType GetDifficultyChangePreventionReason() const { return _difficultyChangePreventionType; } - void SetDifficultyChangePrevention(DifficultyPreventionChangeType type) - { - _difficultyChangePreventionTime = time(nullptr) + MINUTE; - _difficultyChangePreventionType = type; - } + // Difficulty Change + uint32 GetDifficultyChangePreventionTime() const { return _difficultyChangePreventionTime > time(nullptr) ? _difficultyChangePreventionTime - time(nullptr) : 0; } + DifficultyPreventionChangeType GetDifficultyChangePreventionReason() const { return _difficultyChangePreventionType; } + void SetDifficultyChangePrevention(DifficultyPreventionChangeType type) + { + _difficultyChangePreventionTime = time(nullptr) + MINUTE; + _difficultyChangePreventionType = type; + } - protected: - void _homebindIfInstance(Player* player); - void _cancelHomebindIfInstance(Player* player); +protected: + void _homebindIfInstance(Player* player); + void _cancelHomebindIfInstance(Player* player); - void _initRaidSubGroupsCounter(); - member_citerator _getMemberCSlot(uint64 Guid) const; - member_witerator _getMemberWSlot(uint64 Guid); - void SubGroupCounterIncrease(uint8 subgroup); - void SubGroupCounterDecrease(uint8 subgroup); - void ToggleGroupMemberFlag(member_witerator slot, uint8 flag, bool apply); + void _initRaidSubGroupsCounter(); + member_citerator _getMemberCSlot(uint64 Guid) const; + member_witerator _getMemberWSlot(uint64 Guid); + void SubGroupCounterIncrease(uint8 subgroup); + void SubGroupCounterDecrease(uint8 subgroup); + void ToggleGroupMemberFlag(member_witerator slot, uint8 flag, bool apply); - MemberSlotList m_memberSlots; - GroupRefManager m_memberMgr; - InvitesList m_invitees; - uint64 m_leaderGuid; - std::string m_leaderName; - GroupType m_groupType; - Difficulty m_dungeonDifficulty; - Difficulty m_raidDifficulty; - Battlefield* m_bfGroup; - Battleground* m_bgGroup; - uint64 m_targetIcons[TARGETICONCOUNT]; - LootMethod m_lootMethod; - ItemQualities m_lootThreshold; - uint64 m_looterGuid; - uint64 m_masterLooterGuid; - Rolls RollId; - uint8* m_subGroupsCounts; - uint64 m_guid; - uint32 m_counter; // used only in SMSG_GROUP_LIST - uint32 m_maxEnchantingLevel; - uint8 m_lfgGroupFlags; + MemberSlotList m_memberSlots; + GroupRefManager m_memberMgr; + InvitesList m_invitees; + uint64 m_leaderGuid; + std::string m_leaderName; + GroupType m_groupType; + Difficulty m_dungeonDifficulty; + Difficulty m_raidDifficulty; + Battlefield* m_bfGroup; + Battleground* m_bgGroup; + uint64 m_targetIcons[TARGETICONCOUNT]; + LootMethod m_lootMethod; + ItemQualities m_lootThreshold; + uint64 m_looterGuid; + uint64 m_masterLooterGuid; + Rolls RollId; + uint8* m_subGroupsCounts; + uint64 m_guid; + uint32 m_counter; // used only in SMSG_GROUP_LIST + uint32 m_maxEnchantingLevel; + uint8 m_lfgGroupFlags; - // Xinef: change difficulty prevention - uint32 _difficultyChangePreventionTime; - DifficultyPreventionChangeType _difficultyChangePreventionType; + // Xinef: change difficulty prevention + uint32 _difficultyChangePreventionTime; + DifficultyPreventionChangeType _difficultyChangePreventionType; }; #endif diff --git a/src/server/game/Groups/GroupMgr.cpp b/src/server/game/Groups/GroupMgr.cpp index 2b11f10bb..e3c354a53 100644 --- a/src/server/game/Groups/GroupMgr.cpp +++ b/src/server/game/Groups/GroupMgr.cpp @@ -35,7 +35,7 @@ void GroupMgr::InitGroupIds() if (result) { uint32 maxId = (*result)[0].GetUInt32(); - _groupIds.resize(maxId+1); + _groupIds.resize(maxId + 1); } } @@ -95,7 +95,7 @@ void GroupMgr::LoadGroups() // Delete all groups with less than 2 members CharacterDatabase.DirectExecute("DELETE FROM `groups` WHERE guid NOT IN (SELECT guid FROM group_member GROUP BY guid HAVING COUNT(guid) > 1)"); - + // Delete invalid lfg_data CharacterDatabase.DirectExecute("DELETE lfg_data FROM lfg_data LEFT JOIN `groups` ON lfg_data.guid = groups.guid WHERE groups.guid IS NULL OR groups.groupType <> 12"); // CharacterDatabase.DirectExecute("DELETE `groups` FROM `groups` LEFT JOIN lfg_data ON groups.guid = lfg_data.guid WHERE groups.groupType=12 AND lfg_data.guid IS NULL"); // group should be left so binds are cleared when disbanded @@ -104,8 +104,8 @@ void GroupMgr::LoadGroups() // 0 1 2 3 4 5 6 7 8 9 QueryResult result = CharacterDatabase.Query("SELECT g.leaderGuid, g.lootMethod, g.looterGuid, g.lootThreshold, g.icon1, g.icon2, g.icon3, g.icon4, g.icon5, g.icon6" - // 10 11 12 13 14 15 16 17 18 - ", g.icon7, g.icon8, g.groupType, g.difficulty, g.raidDifficulty, g.masterLooterGuid, g.guid, lfg.dungeon, lfg.state FROM `groups` g LEFT JOIN lfg_data lfg ON lfg.guid = g.guid ORDER BY g.guid ASC"); + // 10 11 12 13 14 15 16 17 18 + ", g.icon7, g.icon8, g.groupType, g.difficulty, g.raidDifficulty, g.masterLooterGuid, g.guid, lfg.dungeon, lfg.state FROM `groups` g LEFT JOIN lfg_data lfg ON lfg.guid = g.guid ORDER BY g.guid ASC"); if (!result) { @@ -129,8 +129,7 @@ void GroupMgr::LoadGroups() RegisterGroupId(group->GetLowGUID()); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u group definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -167,8 +166,7 @@ void GroupMgr::LoadGroups() // sLog->outError("GroupMgr::LoadGroups: Consistency failed, can't find group (storage id: %u)", fields[0].GetUInt32()); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u group members in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/Groups/GroupMgr.h b/src/server/game/Groups/GroupMgr.h index fbed611f4..a5ecc0b7d 100644 --- a/src/server/game/Groups/GroupMgr.h +++ b/src/server/game/Groups/GroupMgr.h @@ -17,7 +17,7 @@ private: public: static GroupMgr* instance(); - + typedef std::map GroupContainer; Group* GetGroupByGUID(uint32 guid) const; diff --git a/src/server/game/Groups/GroupRefManager.h b/src/server/game/Groups/GroupRefManager.h index 226ad3979..2332621a4 100644 --- a/src/server/game/Groups/GroupRefManager.h +++ b/src/server/game/Groups/GroupRefManager.h @@ -15,9 +15,9 @@ class GroupReference; class GroupRefManager : public RefManager { - public: - GroupReference* getFirst() { return ((GroupReference*)RefManager::getFirst()); } - GroupReference const* getFirst() const { return ((GroupReference const*)RefManager::getFirst()); } +public: + GroupReference* getFirst() { return ((GroupReference*)RefManager::getFirst()); } + GroupReference const* getFirst() const { return ((GroupReference const*)RefManager::getFirst()); } }; #endif diff --git a/src/server/game/Groups/GroupReference.h b/src/server/game/Groups/GroupReference.h index 8e7b459fb..ce2e979f2 100644 --- a/src/server/game/Groups/GroupReference.h +++ b/src/server/game/Groups/GroupReference.h @@ -14,18 +14,18 @@ class Player; class GroupReference : public Reference { - protected: - uint8 iSubGroup; - void targetObjectBuildLink(); - void targetObjectDestroyLink(); - void sourceObjectDestroyLink(); - public: - GroupReference() : Reference(), iSubGroup(0) {} - ~GroupReference() { unlink(); } - GroupReference* next() { return (GroupReference*)Reference::next(); } - GroupReference const* next() const { return (GroupReference const*)Reference::next(); } - uint8 getSubGroup() const { return iSubGroup; } - void setSubGroup(uint8 pSubGroup) { iSubGroup = pSubGroup; } +protected: + uint8 iSubGroup; + void targetObjectBuildLink(); + void targetObjectDestroyLink(); + void sourceObjectDestroyLink(); +public: + GroupReference() : Reference(), iSubGroup(0) {} + ~GroupReference() { unlink(); } + GroupReference* next() { return (GroupReference*)Reference::next(); } + GroupReference const* next() const { return (GroupReference const*)Reference::next(); } + uint8 getSubGroup() const { return iSubGroup; } + void setSubGroup(uint8 pSubGroup) { iSubGroup = pSubGroup; } }; #endif diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index c60a6057b..bb4612ab1 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -74,13 +74,20 @@ inline uint32 _GetGuildBankTabPrice(uint8 tabId) { switch (tabId) { - case 0: return 100; - case 1: return 250; - case 2: return 500; - case 3: return 1000; - case 4: return 2500; - case 5: return 5000; - default: return 0; + case 0: + return 100; + case 1: + return 250; + case 2: + return 500; + case 3: + return 1000; + case 4: + return 2500; + case 5: + return 5000; + default: + return 0; } } @@ -566,7 +573,7 @@ void Guild::BankTab::SendText(Guild const* guild, WorldSession* session) const { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "MSG_QUERY_GUILD_BANK_TEXT [%s]: Tabid: %u, Text: %s" - , session->GetPlayerInfo().c_str(), m_tabId, m_text.c_str()); + , session->GetPlayerInfo().c_str(), m_tabId, m_text.c_str()); #endif session->SendPacket(&data); } @@ -827,8 +834,8 @@ void Guild::MoveItemData::LogAction(MoveItemData* pFrom) const ASSERT(pFrom->GetItem()); sScriptMgr->OnGuildItemMove(m_pGuild, m_pPlayer, pFrom->GetItem(), - pFrom->IsBank(), pFrom->GetContainer(), pFrom->GetSlotId(), - IsBank(), GetContainer(), GetSlotId()); + pFrom->IsBank(), pFrom->GetContainer(), pFrom->GetSlotId(), + IsBank(), GetContainer(), GetSlotId()); } inline void Guild::MoveItemData::CopySlots(SlotIds& ids) const @@ -888,7 +895,7 @@ void Guild::PlayerMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData ASSERT(pFrom); // Bank -> Char m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_WITHDRAW_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUIDLow(), - pFrom->GetItem()->GetEntry(), count); + pFrom->GetItem()->GetEntry(), count); } inline InventoryResult Guild::PlayerMoveItemData::CanStore(Item* pItem, bool swap) @@ -962,7 +969,7 @@ Item* Guild::BankMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "GUILD STORAGE: StoreItem tab = %u, slot = %u, item = %u, count = %u", - m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); + m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); #endif pLastItem = _StoreItem(trans, pTab, pItem, pos, itr != m_vec.end()); } @@ -975,11 +982,11 @@ void Guild::BankMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* if (pFrom->IsBank()) // Bank -> Bank m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_MOVE_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUIDLow(), - pFrom->GetItem()->GetEntry(), count, m_container); + pFrom->GetItem()->GetEntry(), count, m_container); else // Char -> Bank m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_ITEM, m_container, m_pPlayer->GetGUIDLow(), - pFrom->GetItem()->GetEntry(), count); + pFrom->GetItem()->GetEntry(), count); } void Guild::BankMoveItemData::LogAction(MoveItemData* pFrom) const @@ -1067,7 +1074,7 @@ InventoryResult Guild::BankMoveItemData::CanStore(Item* pItem, bool swap) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "GUILD STORAGE: CanStore() tab = %u, slot = %u, item = %u, count = %u", - m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); + m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); #endif uint32 count = pItem->GetCount(); // Soulbound items cannot be moved @@ -1166,7 +1173,7 @@ bool Guild::Create(Player* pLeader, std::string const& name) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "GUILD: creating guild [%s] for leader %s (%u)", - name.c_str(), pLeader->GetName().c_str(), GUID_LOPART(m_leaderGuid)); + name.c_str(), pLeader->GetName().c_str(), GUID_LOPART(m_leaderGuid)); #endif SQLTransaction trans = CharacterDatabase.BeginTransaction(); @@ -1323,7 +1330,7 @@ void Guild::HandleQuery(WorldSession* session) session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_QUERY_RESPONSE [%s]", session->GetPlayerInfo().c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_QUERY_RESPONSE [%s]", session->GetPlayerInfo().c_str()); #endif } @@ -1446,7 +1453,7 @@ void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string c else if (RankInfo* rankInfo = GetRankInfo(rankId)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "Changed RankName to '%s', rights to 0x%08X", name.c_str(), rights); + sLog->outDebug(LOG_FILTER_GUILD, "Changed RankName to '%s', rights to 0x%08X", name.c_str(), rights); #endif rankInfo->SetName(name); @@ -1532,7 +1539,7 @@ void Guild::HandleInviteMember(WorldSession* session, std::string const& name) SendCommandResult(session, GUILD_COMMAND_INVITE, ERR_GUILD_COMMAND_SUCCESS, name); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "Player %s invited %s to join his Guild", player->GetName().c_str(), name.c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "Player %s invited %s to join his Guild", player->GetName().c_str(), name.c_str()); #endif pInvitee->SetGuildIdInvited(m_id); @@ -1543,15 +1550,15 @@ void Guild::HandleInviteMember(WorldSession* session, std::string const& name) data << m_name; pInvitee->GetSession()->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_INVITE [%s]", pInvitee->GetName().c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_INVITE [%s]", pInvitee->GetName().c_str()); #endif } void Guild::HandleAcceptMember(WorldSession* session) { Player* player = session->GetPlayer(); - if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && - player->GetTeamId() != sObjectMgr->GetPlayerTeamIdByGUID(GetLeaderGUID())) + if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && + player->GetTeamId() != sObjectMgr->GetPlayerTeamIdByGUID(GetLeaderGUID())) return; AddMember(player->GetGUID()); @@ -1730,8 +1737,8 @@ void Guild::HandleMemberDepositMoney(WorldSession* session, uint32 amount) std::string aux = ByteArrayToHexStr(reinterpret_cast(&m_bankMoney), 8, true); _BroadcastEvent(GE_BANK_MONEY_SET, 0, aux.c_str()); - if (amount > 10*GOLD) - CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" %s (guild id: %u, members: %u, new amount: %u, leader guid low: %u, char level: %u)\", NOW())", session->GetAccountId(), player->GetGUIDLow(), player->GetName().c_str(), session->GetRemoteAddress().c_str(), 0, "", amount, GetName().c_str(), GetId(), GetMemberCount(), GetTotalBankMoney(), (uint32)(GetLeaderGUID()&0xFFFFFFFF), player->getLevel()); + if (amount > 10 * GOLD) + CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" %s (guild id: %u, members: %u, new amount: %u, leader guid low: %u, char level: %u)\", NOW())", session->GetAccountId(), player->GetGUIDLow(), player->GetName().c_str(), session->GetRemoteAddress().c_str(), 0, "", amount, GetName().c_str(), GetId(), GetMemberCount(), GetTotalBankMoney(), (uint32)(GetLeaderGUID() & 0xFFFFFFFF), player->getLevel()); } bool Guild::HandleMemberWithdrawMoney(WorldSession* session, uint32 amount, bool repair) @@ -1748,8 +1755,8 @@ bool Guild::HandleMemberWithdrawMoney(WorldSession* session, uint32 amount, bool if (!member) return false; - if (uint32(_GetMemberRemainingMoney(member)) < amount) // Check if we have enough slot/money today - return false; + if (uint32(_GetMemberRemainingMoney(member)) < amount) // Check if we have enough slot/money today + return false; // Call script after validation and before money transfer. sScriptMgr->OnGuildMemberWitdrawMoney(this, player, amount, repair); @@ -1773,8 +1780,8 @@ bool Guild::HandleMemberWithdrawMoney(WorldSession* session, uint32 amount, bool _LogBankEvent(trans, repair ? GUILD_BANK_LOG_REPAIR_MONEY : GUILD_BANK_LOG_WITHDRAW_MONEY, uint8(0), player->GetGUIDLow(), amount); CharacterDatabase.CommitTransaction(trans); - if (amount > 10*GOLD) - CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" %s (guild id: %u, members: %u, new amount: %u, leader guid low: %u, char level: %u)\", NOW())", session->GetAccountId(), player->GetGUIDLow(), player->GetName().c_str(), session->GetRemoteAddress().c_str(), 0, "", amount, GetName().c_str(), GetId(), GetMemberCount(), GetTotalBankMoney(), (uint32)(GetLeaderGUID()&0xFFFFFFFF), player->getLevel()); + if (amount > 10 * GOLD) + CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" %s (guild id: %u, members: %u, new amount: %u, leader guid low: %u, char level: %u)\", NOW())", session->GetAccountId(), player->GetGUIDLow(), player->GetName().c_str(), session->GetRemoteAddress().c_str(), 0, "", amount, GetName().c_str(), GetId(), GetMemberCount(), GetTotalBankMoney(), (uint32)(GetLeaderGUID() & 0xFFFFFFFF), player->getLevel()); std::string aux = ByteArrayToHexStr(reinterpret_cast(&m_bankMoney), 8, true); _BroadcastEvent(GE_BANK_MONEY_SET, 0, aux.c_str()); @@ -1800,7 +1807,7 @@ void Guild::HandleDisband(WorldSession* session) { Disband(); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "Guild Successfully Disbanded"); + sLog->outDebug(LOG_FILTER_GUILD, "Guild Successfully Disbanded"); #endif delete this; } @@ -1817,7 +1824,7 @@ void Guild::SendInfo(WorldSession* session) const session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_INFO [%s]", session->GetPlayerInfo().c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_INFO [%s]", session->GetPlayerInfo().c_str()); #endif } @@ -1827,7 +1834,7 @@ void Guild::SendEventLog(WorldSession* session) const m_eventLog->WritePacket(data); session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_EVENT_LOG_QUERY [%s]", session->GetPlayerInfo().c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_EVENT_LOG_QUERY [%s]", session->GetPlayerInfo().c_str()); #endif } @@ -1842,7 +1849,7 @@ void Guild::SendBankLog(WorldSession* session, uint8 tabId) const pLog->WritePacket(data); session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_BANK_LOG_QUERY [%s]", session->GetPlayerInfo().c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_BANK_LOG_QUERY [%s]", session->GetPlayerInfo().c_str()); #endif } } @@ -1885,7 +1892,7 @@ void Guild::SendPermissions(WorldSession* session) const session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_PERMISSIONS [%s] Rank: %u", session->GetPlayerInfo().c_str(), rankId); + sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_PERMISSIONS [%s] Rank: %u", session->GetPlayerInfo().c_str(), rankId); #endif } @@ -1900,7 +1907,7 @@ void Guild::SendMoneyInfo(WorldSession* session) const data << int32(amount); session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_BANK_MONEY_WITHDRAWN [%s] Money: %u", session->GetPlayerInfo().c_str(), amount); + sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_BANK_MONEY_WITHDRAWN [%s] Money: %u", session->GetPlayerInfo().c_str(), amount); #endif } @@ -1913,7 +1920,7 @@ void Guild::SendLoginInfo(WorldSession* session) session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_EVENT [%s] MOTD", session->GetPlayerInfo().c_str()); + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_EVENT [%s] MOTD", session->GetPlayerInfo().c_str()); #endif SendBankTabsInfo(session); @@ -1966,7 +1973,7 @@ void Guild::LoadRankFromDB(Field* fields) bool Guild::LoadMemberFromDB(Field* fields) { uint32 lowguid = fields[1].GetUInt32(); - Member *member = new Member(m_id, MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER), fields[2].GetUInt8()); + Member* member = new Member(m_id, MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER), fields[2].GetUInt8()); if (!member->LoadFromDB(fields)) { _DeleteMemberFromDB(lowguid); @@ -1980,9 +1987,9 @@ bool Guild::LoadMemberFromDB(Field* fields) void Guild::LoadBankRightFromDB(Field* fields) { - // tabId rights slots + // tabId rights slots GuildBankRightsAndSlots rightsAndSlots(fields[1].GetUInt8(), fields[3].GetUInt8(), fields[4].GetUInt32()); - // rankId + // rankId _SetRankBankTabRightsAndSlots(fields[2].GetUInt8(), rightsAndSlots, false); } @@ -1991,13 +1998,13 @@ bool Guild::LoadEventLogFromDB(Field* fields) if (m_eventLog->CanInsert()) { m_eventLog->LoadEvent(new EventLogEntry( - m_id, // guild id - fields[1].GetUInt32(), // guid - time_t(fields[6].GetUInt32()), // timestamp - GuildEventLogTypes(fields[2].GetUInt8()), // event type - fields[3].GetUInt32(), // player guid 1 - fields[4].GetUInt32(), // player guid 2 - fields[5].GetUInt8())); // rank + m_id, // guild id + fields[1].GetUInt32(), // guid + time_t(fields[6].GetUInt32()), // timestamp + GuildEventLogTypes(fields[2].GetUInt8()), // event type + fields[3].GetUInt32(), // player guid 1 + fields[4].GetUInt32(), // player guid 2 + fields[5].GetUInt8())); // rank return true; } return false; @@ -2029,15 +2036,15 @@ bool Guild::LoadBankEventLogFromDB(Field* fields) return false; } pLog->LoadEvent(new BankEventLogEntry( - m_id, // guild id - guid, // guid - time_t(fields[8].GetUInt32()), // timestamp - dbTabId, // tab id - eventType, // event type - fields[4].GetUInt32(), // player guid - fields[5].GetUInt32(), // item or money - fields[6].GetUInt16(), // itam stack count - fields[7].GetUInt8())); // dest tab id + m_id, // guild id + guid, // guid + time_t(fields[8].GetUInt32()), // timestamp + dbTabId, // tab id + eventType, // event type + fields[4].GetUInt32(), // player guid + fields[5].GetUInt32(), // item or money + fields[6].GetUInt16(), // itam stack count + fields[7].GetUInt8())); // dest tab id } } return true; @@ -2058,7 +2065,7 @@ bool Guild::LoadBankItemFromDB(Field* fields) if (tabId >= _GetPurchasedTabsSize()) { sLog->outError("Invalid tab for item (GUID: %u, id: #%u) in guild bank, skipped.", - fields[14].GetUInt32(), fields[15].GetUInt32()); + fields[14].GetUInt32(), fields[15].GetUInt32()); return false; } return m_bankTabs[tabId]->LoadItemFromDB(fields); @@ -2356,7 +2363,7 @@ bool Guild::ChangeMemberRank(uint64 guid, uint8 newRank) void Guild::SwapItems(Player* player, uint8 tabId, uint8 slotId, uint8 destTabId, uint8 destSlotId, uint32 splitedAmount) { if (tabId >= _GetPurchasedTabsSize() || slotId >= GUILD_BANK_MAX_SLOTS || - destTabId >= _GetPurchasedTabsSize() || destSlotId >= GUILD_BANK_MAX_SLOTS) + destTabId >= _GetPurchasedTabsSize() || destSlotId >= GUILD_BANK_MAX_SLOTS) return; if (tabId == destTabId && slotId == destSlotId) @@ -2617,7 +2624,7 @@ inline void Guild::_UpdateMemberWithdrawSlots(SQLTransaction& trans, uint64 guid { uint8 rankId = member->GetRankId(); if (rankId != GR_GUILDMASTER - && member->GetBankWithdrawValue(tabId) < _GetRankBankTabSlotsPerDay(rankId, tabId)) + && member->GetBankWithdrawValue(tabId) < _GetRankBankTabSlotsPerDay(rankId, tabId)) member->UpdateBankWithdrawValue(trans, tabId, 1); } } @@ -2855,11 +2862,11 @@ void Guild::_BroadcastEvent(GuildEvents guildEvent, uint64 guid, const char* par BroadcastPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_EVENT [Broadcast] Event: %u", guildEvent); + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_EVENT [Broadcast] Event: %u", guildEvent); #endif } -void Guild::_SendBankList(WorldSession* session /* = NULL*/, uint8 tabId /*= 0*/, bool sendAllSlots /*= false*/, SlotIds *slots /*= NULL*/) const +void Guild::_SendBankList(WorldSession* session /* = NULL*/, uint8 tabId /*= 0*/, bool sendAllSlots /*= false*/, SlotIds* slots /*= NULL*/) const { WorldPacket data(SMSG_GUILD_BANK_LIST, 500); data << uint64(m_bankMoney); @@ -2897,7 +2904,7 @@ void Guild::_SendBankList(WorldSession* session /* = NULL*/, uint8 tabId /*= 0*/ data.put(rempos, numSlots); session->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %d", + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %d", session->GetPlayerInfo().c_str(), tabId, sendAllSlots, numSlots); #endif } @@ -2915,8 +2922,8 @@ void Guild::_SendBankList(WorldSession* session /* = NULL*/, uint8 tabId /*= 0*/ data.put(rempos, numSlots); player->GetSession()->SendPacket(&data); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %u" - , player->GetName().c_str(), tabId, sendAllSlots, numSlots); + sLog->outDebug(LOG_FILTER_GUILD, "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %u" + , player->GetName().c_str(), tabId, sendAllSlots, numSlots); #endif } } diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index f51dc6a89..b70eb9ae0 100644 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -43,8 +43,8 @@ enum GuildDefaultRanks GR_VETERAN = 2, GR_MEMBER = 3, GR_INITIATE = 4 - // When promoting member server does: rank-- - // When demoting member server does: rank++ + // When promoting member server does: rank-- + // When demoting member server does: rank++ }; enum GuildRankRights @@ -839,7 +839,7 @@ private: void _SendBankMoneyUpdate(WorldSession* session) const; void _SendBankContentUpdate(MoveItemData* pSrc, MoveItemData* pDest) const; void _SendBankContentUpdate(uint8 tabId, SlotIds slots) const; - void _SendBankList(WorldSession* session = NULL, uint8 tabId = 0, bool sendFullSlots = false, SlotIds *slots = nullptr) const; + void _SendBankList(WorldSession* session = NULL, uint8 tabId = 0, bool sendFullSlots = false, SlotIds* slots = nullptr) const; void _BroadcastEvent(GuildEvents guildEvent, uint64 guid, const char* param1 = NULL, const char* param2 = NULL, const char* param3 = nullptr) const; }; diff --git a/src/server/game/Guilds/GuildMgr.cpp b/src/server/game/Guilds/GuildMgr.cpp index b44a4a4d8..b5ed5b824 100644 --- a/src/server/game/Guilds/GuildMgr.cpp +++ b/src/server/game/Guilds/GuildMgr.cpp @@ -92,11 +92,11 @@ void GuildMgr::LoadGuilds() CharacterDatabase.DirectExecute("DELETE g FROM guild g LEFT JOIN guild_member gm ON g.guildid = gm.guildid WHERE gm.guildid IS NULL"); - // 0 1 2 3 4 5 6 + // 0 1 2 3 4 5 6 QueryResult result = CharacterDatabase.Query("SELECT g.guildid, g.name, g.leaderguid, g.EmblemStyle, g.EmblemColor, g.BorderStyle, g.BorderColor, " - // 7 8 9 10 11 12 - "g.BackgroundColor, g.info, g.motd, g.createdate, g.BankMoney, COUNT(gbt.guildid) " - "FROM guild g LEFT JOIN guild_bank_tab gbt ON g.guildid = gbt.guildid GROUP BY g.guildid ORDER BY g.guildid ASC"); + // 7 8 9 10 11 12 + "g.BackgroundColor, g.info, g.motd, g.createdate, g.BankMoney, COUNT(gbt.guildid) " + "FROM guild g LEFT JOIN guild_bank_tab gbt ON g.guildid = gbt.guildid GROUP BY g.guildid ORDER BY g.guildid ASC"); if (!result) { @@ -119,8 +119,7 @@ void GuildMgr::LoadGuilds() AddGuild(guild); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -153,8 +152,7 @@ void GuildMgr::LoadGuilds() guild->LoadRankFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild ranks in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -169,13 +167,13 @@ void GuildMgr::LoadGuilds() CharacterDatabase.DirectExecute("DELETE gm FROM guild_member gm LEFT JOIN guild g ON gm.guildId = g.guildId WHERE g.guildId IS NULL"); CharacterDatabase.DirectExecute("DELETE gm FROM guild_member_withdraw gm LEFT JOIN guild_member g ON gm.guid = g.guid WHERE g.guid IS NULL"); - // 0 1 2 3 4 5 6 7 8 9 10 + // 0 1 2 3 4 5 6 7 8 9 10 QueryResult result = CharacterDatabase.Query("SELECT guildid, gm.guid, `rank`, pnote, offnote, w.tab0, w.tab1, w.tab2, w.tab3, w.tab4, w.tab5, " - // 11 12 13 14 15 16 17 - "w.money, c.name, c.level, c.class, c.zone, c.account, c.logout_time " - "FROM guild_member gm " - "LEFT JOIN guild_member_withdraw w ON gm.guid = w.guid " - "LEFT JOIN characters c ON c.guid = gm.guid ORDER BY guildid ASC"); + // 11 12 13 14 15 16 17 + "w.money, c.name, c.level, c.class, c.zone, c.account, c.logout_time " + "FROM guild_member gm " + "LEFT JOIN guild_member_withdraw w ON gm.guid = w.guid " + "LEFT JOIN characters c ON c.guid = gm.guid ORDER BY guildid ASC"); if (!result) sLog->outString(">> Loaded 0 guild members. DB table `guild_member` is empty."); @@ -192,8 +190,7 @@ void GuildMgr::LoadGuilds() guild->LoadMemberFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild members int %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -207,7 +204,7 @@ void GuildMgr::LoadGuilds() // Delete orphaned guild bank right entries before loading the valid ones CharacterDatabase.DirectExecute("DELETE gbr FROM guild_bank_right gbr LEFT JOIN guild g ON gbr.guildId = g.guildId WHERE g.guildId IS NULL"); - // 0 1 2 3 4 + // 0 1 2 3 4 QueryResult result = CharacterDatabase.Query("SELECT guildid, TabId, rid, gbright, SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC"); if (!result) @@ -226,8 +223,7 @@ void GuildMgr::LoadGuilds() guild->LoadBankRightFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u bank tab rights in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -240,7 +236,7 @@ void GuildMgr::LoadGuilds() CharacterDatabase.DirectPExecute("DELETE FROM guild_eventlog WHERE LogGuid > %u", sWorld->getIntConfig(CONFIG_GUILD_EVENT_LOG_COUNT)); - // 0 1 2 3 4 5 6 + // 0 1 2 3 4 5 6 QueryResult result = CharacterDatabase.Query("SELECT guildid, LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp FROM guild_eventlog ORDER BY TimeStamp DESC, LogGuid DESC"); if (!result) @@ -259,8 +255,7 @@ void GuildMgr::LoadGuilds() guild->LoadEventLogFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild event logs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -274,7 +269,7 @@ void GuildMgr::LoadGuilds() // Remove log entries that exceed the number of allowed entries per guild CharacterDatabase.DirectPExecute("DELETE FROM guild_bank_eventlog WHERE LogGuid > %u", sWorld->getIntConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT)); - // 0 1 2 3 4 5 6 7 8 + // 0 1 2 3 4 5 6 7 8 QueryResult result = CharacterDatabase.Query("SELECT guildid, TabId, LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog ORDER BY TimeStamp DESC, LogGuid DESC"); if (!result) @@ -293,8 +288,7 @@ void GuildMgr::LoadGuilds() guild->LoadBankEventLogFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild bank event logs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -308,7 +302,7 @@ void GuildMgr::LoadGuilds() // Delete orphaned guild bank tab entries before loading the valid ones CharacterDatabase.DirectExecute("DELETE gbt FROM guild_bank_tab gbt LEFT JOIN guild g ON gbt.guildId = g.guildId WHERE g.guildId IS NULL"); - // 0 1 2 3 4 + // 0 1 2 3 4 QueryResult result = CharacterDatabase.Query("SELECT guildid, TabId, TabName, TabIcon, TabText FROM guild_bank_tab ORDER BY guildid ASC, TabId ASC"); if (!result) @@ -327,8 +321,7 @@ void GuildMgr::LoadGuilds() guild->LoadBankTabFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild bank tabs in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -342,10 +335,10 @@ void GuildMgr::LoadGuilds() // Delete orphan guild bank items CharacterDatabase.DirectExecute("DELETE gbi FROM guild_bank_item gbi LEFT JOIN guild g ON gbi.guildId = g.guildId WHERE g.guildId IS NULL"); - // 0 1 2 3 4 5 6 7 8 9 10 + // 0 1 2 3 4 5 6 7 8 9 10 QueryResult result = CharacterDatabase.Query("SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, " - // 11 12 13 14 15 - "guildid, TabId, SlotId, item_guid, itemEntry FROM guild_bank_item gbi INNER JOIN item_instance ii ON gbi.item_guid = ii.guid"); + // 11 12 13 14 15 + "guildid, TabId, SlotId, item_guid, itemEntry FROM guild_bank_item gbi INNER JOIN item_instance ii ON gbi.item_guid = ii.guid"); if (!result) { @@ -363,8 +356,7 @@ void GuildMgr::LoadGuilds() guild->LoadBankItemFromDB(fields); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u guild bank tab items in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } diff --git a/src/server/game/Handlers/AddonHandler.cpp b/src/server/game/Handlers/AddonHandler.cpp index f66945d3c..b3d67c531 100644 --- a/src/server/game/Handlers/AddonHandler.cpp +++ b/src/server/game/Handlers/AddonHandler.cpp @@ -47,7 +47,7 @@ bool AddonHandler::BuildAddonPacket(WorldPacket* Source, WorldPacket* Target) AddOnPacked.resize(AddonRealSize); // resize target for zlib action - if (uncompress(const_cast(AddOnPacked.contents()), &AddonRealSize, const_cast((*Source).contents() + CurrentPosition), (*Source).size() - CurrentPosition)== Z_OK) + if (uncompress(const_cast(AddOnPacked.contents()), &AddonRealSize, const_cast((*Source).contents() + CurrentPosition), (*Source).size() - CurrentPosition) == Z_OK) { Target->Initialize(SMSG_ADDON_INFO); @@ -61,13 +61,13 @@ bool AddonHandler::BuildAddonPacket(WorldPacket* Source, WorldPacket* Target) uint32 crc, unk2; // check next addon data format correctness - if (AddOnPacked.rpos()+1 > AddOnPacked.size()) + if (AddOnPacked.rpos() + 1 > AddOnPacked.size()) return false; AddOnPacked >> addonName; // recheck next addon data format correctness - if (AddOnPacked.rpos()+1+4+4 > AddOnPacked.size()) + if (AddOnPacked.rpos() + 1 + 4 + 4 > AddOnPacked.size()) return false; AddOnPacked >> enabled >> crc >> unk2; diff --git a/src/server/game/Handlers/AddonHandler.h b/src/server/game/Handlers/AddonHandler.h index 486be0803..9e527449b 100644 --- a/src/server/game/Handlers/AddonHandler.h +++ b/src/server/game/Handlers/AddonHandler.h @@ -18,7 +18,7 @@ public: ~AddonHandler(); static AddonHandler* instance(); - + //build addon packet bool BuildAddonPacket(WorldPacket* Source, WorldPacket* Target); }; diff --git a/src/server/game/Handlers/ArenaTeamHandler.cpp b/src/server/game/Handlers/ArenaTeamHandler.cpp index 757c515b0..6143ca8a9 100644 --- a/src/server/game/Handlers/ArenaTeamHandler.cpp +++ b/src/server/game/Handlers/ArenaTeamHandler.cpp @@ -17,7 +17,7 @@ #include "ArenaTeamMgr.h" #include "Opcodes.h" -void WorldSession::HandleInspectArenaTeamsOpcode(WorldPacket & recvData) +void WorldSession::HandleInspectArenaTeamsOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_INSPECT_ARENA_TEAMS"); @@ -42,7 +42,7 @@ void WorldSession::HandleInspectArenaTeamsOpcode(WorldPacket & recvData) } } -void WorldSession::HandleArenaTeamQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamQueryOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ARENA_TEAM_QUERY"); @@ -58,7 +58,7 @@ void WorldSession::HandleArenaTeamQueryOpcode(WorldPacket & recvData) } } -void WorldSession::HandleArenaTeamRosterOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamRosterOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ARENA_TEAM_ROSTER"); @@ -71,7 +71,7 @@ void WorldSession::HandleArenaTeamRosterOpcode(WorldPacket & recvData) arenaTeam->Roster(this); } -void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_INVITE"); @@ -151,7 +151,7 @@ void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket & recvData) player->SetArenaTeamIdInvited(arenaTeam->GetId()); - WorldPacket data(SMSG_ARENA_TEAM_INVITE, (8+10)); + WorldPacket data(SMSG_ARENA_TEAM_INVITE, (8 + 10)); data << GetPlayer()->GetName(); data << arenaTeam->GetName(); player->GetSession()->SendPacket(&data); @@ -161,7 +161,7 @@ void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket & recvData) #endif } -void WorldSession::HandleArenaTeamAcceptOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleArenaTeamAcceptOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_ACCEPT"); // empty opcode @@ -196,7 +196,7 @@ void WorldSession::HandleArenaTeamAcceptOpcode(WorldPacket & /*recvData*/) arenaTeam->BroadcastEvent(ERR_ARENA_TEAM_JOIN_SS, _player->GetGUID(), 2, _player->GetName().c_str(), arenaTeam->GetName(), ""); } -void WorldSession::HandleArenaTeamDeclineOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleArenaTeamDeclineOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_DECLINE"); // empty opcode @@ -206,7 +206,7 @@ void WorldSession::HandleArenaTeamDeclineOpcode(WorldPacket & /*recvData*/) _player->SetArenaTeamIdInvited(0); } -void WorldSession::HandleArenaTeamLeaveOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamLeaveOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_LEAVE"); @@ -250,7 +250,7 @@ void WorldSession::HandleArenaTeamLeaveOpcode(WorldPacket & recvData) SendArenaTeamCommandResult(ERR_ARENA_TEAM_QUIT_S, arenaTeam->GetName(), "", 0); } -void WorldSession::HandleArenaTeamDisbandOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamDisbandOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_DISBAND"); @@ -274,7 +274,7 @@ void WorldSession::HandleArenaTeamDisbandOpcode(WorldPacket & recvData) } } -void WorldSession::HandleArenaTeamRemoveOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamRemoveOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_REMOVE"); @@ -326,7 +326,7 @@ void WorldSession::HandleArenaTeamRemoveOpcode(WorldPacket & recvData) arenaTeam->BroadcastEvent(ERR_ARENA_TEAM_REMOVE_SSS, 0, 3, name, arenaTeam->GetName(), _player->GetName()); } -void WorldSession::HandleArenaTeamLeaderOpcode(WorldPacket & recvData) +void WorldSession::HandleArenaTeamLeaderOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_ARENA_TEAM_LEADER"); @@ -373,7 +373,7 @@ void WorldSession::HandleArenaTeamLeaderOpcode(WorldPacket & recvData) void WorldSession::SendArenaTeamCommandResult(uint32 teamAction, const std::string& team, const std::string& player, uint32 errorId) { - WorldPacket data(SMSG_ARENA_TEAM_COMMAND_RESULT, 4+team.length()+1+player.length()+1+4); + WorldPacket data(SMSG_ARENA_TEAM_COMMAND_RESULT, 4 + team.length() + 1 + player.length() + 1 + 4); data << uint32(teamAction); data << team; data << player; @@ -383,7 +383,7 @@ void WorldSession::SendArenaTeamCommandResult(uint32 teamAction, const std::stri void WorldSession::SendNotInArenaTeamPacket(uint8 type) { - WorldPacket data(SMSG_ARENA_ERROR, 4+1); // 886 - You are not in a %uv%u arena team + WorldPacket data(SMSG_ARENA_ERROR, 4 + 1); // 886 - You are not in a %uv%u arena team uint32 unk = 0; data << uint32(unk); // unk(0) if (!unk) diff --git a/src/server/game/Handlers/AuctionHouseHandler.cpp b/src/server/game/Handlers/AuctionHouseHandler.cpp index 091c98bc6..e06f10234 100644 --- a/src/server/game/Handlers/AuctionHouseHandler.cpp +++ b/src/server/game/Handlers/AuctionHouseHandler.cpp @@ -21,7 +21,7 @@ #include "AsyncAuctionListing.h" //void called when player click on auctioneer npc -void WorldSession::HandleAuctionHelloOpcode(WorldPacket & recvData) +void WorldSession::HandleAuctionHelloOpcode(WorldPacket& recvData) { uint64 guid; //NPC guid recvData >> guid; @@ -77,7 +77,7 @@ void WorldSession::SendAuctionCommandResult(uint32 auctionId, uint32 Action, uin //this function sends notification, if bidder is online void WorldSession::SendAuctionBidderNotification(uint32 location, uint32 auctionId, uint64 bidder, uint32 bidSum, uint32 diff, uint32 item_template) { - WorldPacket data(SMSG_AUCTION_BIDDER_NOTIFICATION, (8*4)); + WorldPacket data(SMSG_AUCTION_BIDDER_NOTIFICATION, (8 * 4)); data << uint32(location); data << uint32(auctionId); data << uint64(bidder); @@ -91,7 +91,7 @@ void WorldSession::SendAuctionBidderNotification(uint32 location, uint32 auction //this void causes on client to display: "Your auction sold" void WorldSession::SendAuctionOwnerNotification(AuctionEntry* auction) { - WorldPacket data(SMSG_AUCTION_OWNER_NOTIFICATION, (8*4)); + WorldPacket data(SMSG_AUCTION_OWNER_NOTIFICATION, (8 * 4)); data << uint32(auction->Id); data << uint32(auction->bid); data << uint32(0); //unk @@ -103,7 +103,7 @@ void WorldSession::SendAuctionOwnerNotification(AuctionEntry* auction) } //this void creates new auction and adds auction to some auctionhouse -void WorldSession::HandleAuctionSellItem(WorldPacket & recvData) +void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) { uint64 auctioneer; uint32 itemsCount, etime, bid, buyout; @@ -202,8 +202,8 @@ void WorldSession::HandleAuctionSellItem(WorldPacket & recvData) itemEntry = item->GetTemplate()->ItemId; if (sAuctionMgr->GetAItem(item->GetGUIDLow()) || !item->CanBeTraded() || item->IsNotEmptyBag() || - item->GetTemplate()->Flags & ITEM_FLAG_CONJURED || item->GetUInt32Value(ITEM_FIELD_DURATION) || - item->GetCount() < count[i] || itemEntry != item->GetTemplate()->ItemId) + item->GetTemplate()->Flags & ITEM_FLAG_CONJURED || item->GetUInt32Value(ITEM_FIELD_DURATION) || + item->GetCount() < count[i] || itemEntry != item->GetTemplate()->ItemId) { SendAuctionCommandResult(0, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); return; @@ -373,7 +373,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket & recvData) } //this function is called when client bids or buys out auction -void WorldSession::HandleAuctionPlaceBid(WorldPacket & recvData) +void WorldSession::HandleAuctionPlaceBid(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_AUCTION_PLACE_BID"); @@ -428,7 +428,7 @@ void WorldSession::HandleAuctionPlaceBid(WorldPacket & recvData) // price too low for next bid if not buyout if ((price < auction->buyout || auction->buyout == 0) && - price < auction->bid + auction->GetAuctionOutBid()) + price < auction->bid + auction->GetAuctionOutBid()) { //auction has already higher bid, client tests it! return; @@ -503,7 +503,7 @@ void WorldSession::HandleAuctionPlaceBid(WorldPacket & recvData) } //this void is called when auction_owner cancels his auction -void WorldSession::HandleAuctionRemoveItem(WorldPacket & recvData) +void WorldSession::HandleAuctionRemoveItem(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_AUCTION_REMOVE_ITEM"); @@ -551,8 +551,8 @@ void WorldSession::HandleAuctionRemoveItem(WorldPacket & recvData) // item will deleted or added to received mail list MailDraft(auction->BuildAuctionMailSubject(AUCTION_CANCELED), AuctionEntry::BuildAuctionMailBody(0, 0, auction->buyout, auction->deposit, 0)) - .AddItem(pItem) - .SendMailTo(trans, player, auction, MAIL_CHECK_MASK_COPIED); + .AddItem(pItem) + .SendMailTo(trans, player, auction, MAIL_CHECK_MASK_COPIED); } else { @@ -583,7 +583,7 @@ void WorldSession::HandleAuctionRemoveItem(WorldPacket & recvData) } //called when player lists his bids -void WorldSession::HandleAuctionListBidderItems(WorldPacket & recvData) +void WorldSession::HandleAuctionListBidderItems(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_AUCTION_LIST_BIDDER_ITEMS"); @@ -618,7 +618,7 @@ void WorldSession::HandleAuctionListBidderItems(WorldPacket & recvData) AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction()); - WorldPacket data(SMSG_AUCTION_BIDDER_LIST_RESULT, (4+4+4)+30000); // pussywizard: ensure there is enough memory + WorldPacket data(SMSG_AUCTION_BIDDER_LIST_RESULT, (4 + 4 + 4) + 30000); // pussywizard: ensure there is enough memory Player* player = GetPlayer(); data << (uint32) 0; //add 0 as count uint32 count = 0; @@ -644,7 +644,7 @@ void WorldSession::HandleAuctionListBidderItems(WorldPacket & recvData) } //this void sends player info about his auctions -void WorldSession::HandleAuctionListOwnerItems(WorldPacket & recvData) +void WorldSession::HandleAuctionListOwnerItems(WorldPacket& recvData) { // prevent crash caused by malformed packet uint64 guid; @@ -663,7 +663,7 @@ void WorldSession::HandleAuctionListOwnerItems(WorldPacket & recvData) diff = delay; _lastAuctionListOwnerItemsMSTime = now + delay; // set longest possible here, actual exectuing will change this to getMSTime of that moment - _player->m_Events.AddEvent(new AuctionListOwnerItemsDelayEvent(guid, _player->GetGUID(), true), _player->m_Events.CalculateTime(delay-diff)); + _player->m_Events.AddEvent(new AuctionListOwnerItemsDelayEvent(guid, _player->GetGUID(), true), _player->m_Events.CalculateTime(delay - diff)); } @@ -690,7 +690,7 @@ void WorldSession::HandleAuctionListOwnerItemsEvent(uint64 creatureGuid) AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(creature->getFaction()); - WorldPacket data(SMSG_AUCTION_OWNER_LIST_RESULT, (4+4+4)+60000); // pussywizard: ensure there is enough memory + WorldPacket data(SMSG_AUCTION_OWNER_LIST_RESULT, (4 + 4 + 4) + 60000); // pussywizard: ensure there is enough memory data << (uint32) 0; // amount place holder uint32 count = 0; @@ -704,7 +704,7 @@ void WorldSession::HandleAuctionListOwnerItemsEvent(uint64 creatureGuid) } //this void is called when player clicks on search button -void WorldSession::HandleAuctionListItems(WorldPacket & recvData) +void WorldSession::HandleAuctionListItems(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_AUCTION_LIST_ITEMS"); @@ -748,10 +748,10 @@ void WorldSession::HandleAuctionListItems(WorldPacket & recvData) diff = delay; _lastAuctionListItemsMSTime = now + delay - diff; ACORE_GUARD(ACE_Thread_Mutex, AsyncAuctionListingMgr::GetTempLock()); - AsyncAuctionListingMgr::GetTempList().push_back( AuctionListItemsDelayEvent(delay-diff, _player->GetGUID(), guid, searchedname, listfrom, levelmin, levelmax, usable, auctionSlotID, auctionMainCategory, auctionSubCategory, quality, getAll) ); + AsyncAuctionListingMgr::GetTempList().push_back( AuctionListItemsDelayEvent(delay - diff, _player->GetGUID(), guid, searchedname, listfrom, levelmin, levelmax, usable, auctionSlotID, auctionMainCategory, auctionSubCategory, quality, getAll) ); } -void WorldSession::HandleAuctionListPendingSales(WorldPacket & recvData) +void WorldSession::HandleAuctionListPendingSales(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_AUCTION_LIST_PENDING_SALES"); diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index 949f88c9e..370eb3b79 100644 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -23,7 +23,7 @@ #include "Group.h" #include "ScriptMgr.h" -void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket & recvData) +void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -60,7 +60,7 @@ void WorldSession::SendBattleGroundList(uint64 guid, BattlegroundTypeId bgTypeId SendPacket(&data); } -void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) +void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { uint64 guid; uint32 bgTypeId_; @@ -182,7 +182,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) SendPacket(&data); sScriptMgr->OnPlayerJoinBG(_player); - + } // check if group can queue: else @@ -194,11 +194,11 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) // pussywizard: for party members - remove queues for which leader is not queued to! std::set leaderQueueTypeIds; - for (uint32 i=0; iGetBattlegroundQueueTypeId(i)); for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) - for (uint32 i=0; iGetBattlegroundQueueTypeId(i)) if (leaderQueueTypeIds.count((uint32)mqtid) == 0) { @@ -319,7 +319,7 @@ void WorldSession::HandleBattlegroundPlayerPositionsOpcode(WorldPacket& /*recvDa SendPacket(&data); } -void WorldSession::HandlePVPLogDataOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandlePVPLogDataOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd MSG_PVP_LOG_DATA Message"); @@ -342,7 +342,7 @@ void WorldSession::HandlePVPLogDataOpcode(WorldPacket & /*recvData*/) #endif } -void WorldSession::HandleBattlefieldListOpcode(WorldPacket &recvData) +void WorldSession::HandleBattlefieldListOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_BATTLEFIELD_LIST Message"); @@ -366,7 +366,7 @@ void WorldSession::HandleBattlefieldListOpcode(WorldPacket &recvData) SendPacket(&data); } -void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) +void WorldSession::HandleBattleFieldPortOpcode(WorldPacket& recvData) { uint8 arenaType; // arenatype if arena uint8 unk2; // unk, can be 0x0 (may be if was invited?) and 0x1 @@ -384,7 +384,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) if (!_player->InBattlegroundQueue()) return; - // get BattlegroundQueue for received + // get BattlegroundQueue for received BattlegroundTypeId bgTypeId = BattlegroundTypeId(bgTypeId_); BattlegroundQueueTypeId bgQueueTypeId = BattlegroundMgr::BGQueueTypeId(bgTypeId, arenaType); BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId); @@ -473,7 +473,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) _player->RemoveBattlegroundQueueId(bgQueueTypeId); // track if player refuses to join the BG after being invited if (bg->isBattleground() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS) && - (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)) + (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->setUInt32(0, _player->GetGUIDLow()); @@ -507,7 +507,7 @@ void WorldSession::HandleBattlefieldLeaveOpcode(WorldPacket& recvData) _player->LeaveBattleground(); } -void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket& /*recvData*/) { // requested at login and on map change // send status for current queues and current bg @@ -568,7 +568,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) } } -void WorldSession::HandleBattlemasterJoinArena(WorldPacket & recvData) +void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) { uint64 guid; // arena Battlemaster guid uint8 arenaslot; // 2v2, 3v3 or 5v5 @@ -693,11 +693,11 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket & recvData) // pussywizard: for party members - remove queues for which leader is not queued to! std::set leaderQueueTypeIds; - for (uint32 i=0; iGetBattlegroundQueueTypeId(i)); for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) - for (uint32 i=0; iGetBattlegroundQueueTypeId(i)) if (leaderQueueTypeIds.count((uint32)mqtid) == 0) { @@ -786,7 +786,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket & recvData) } } -void WorldSession::HandleReportPvPAFK(WorldPacket & recvData) +void WorldSession::HandleReportPvPAFK(WorldPacket& recvData) { uint64 playerGuid; recvData >> playerGuid; diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index b497a3994..0e135114c 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -97,7 +97,7 @@ void WorldSession::HandleCalendarGetCalendar(WorldPacket& /*recvData*/) time_t resetTime = itr->second.extended ? save->GetExtendedResetTime() : save->GetResetTime(); dataBuffer << uint32(save->GetMapId()); dataBuffer << uint32(save->GetDifficulty()); - dataBuffer << uint32(resetTime >= currTime ? resetTime-currTime : 0); + dataBuffer << uint32(resetTime >= currTime ? resetTime - currTime : 0); dataBuffer << uint64(MAKE_NEW_GUID(save->GetInstanceId(), 0, HIGHGUID_INSTANCE)); // instance save id as unique instance copy id ++boundCounter; } @@ -172,7 +172,7 @@ void WorldSession::HandleCalendarGetEvent(WorldPacket& recvData) recvData >> eventId; sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_GET_EVENT. Player [" - UI64FMTD "] Event [" UI64FMTD "]", _player->GetGUID(), eventId); + UI64FMTD "] Event [" UI64FMTD "]", _player->GetGUID(), eventId); if (CalendarEvent* calendarEvent = sCalendarMgr->GetEvent(eventId)) sCalendarMgr->SendCalendarEvent(_player->GetGUID(), *calendarEvent, CALENDAR_SENDTYPE_GET); @@ -290,7 +290,7 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) SetCalendarEventCreationCooldown(time(nullptr) + CALENDAR_CREATE_EVENT_COOLDOWN); CalendarEvent* calendarEvent = new CalendarEvent(sCalendarMgr->GetFreeEventId(), guid, 0, CalendarEventType(type), dungeonId, - time_t(eventPackedTime), flags, time_t(unkPackedTime), title, description); + time_t(eventPackedTime), flags, time_t(unkPackedTime), title, description); if (calendarEvent->IsGuildEvent() || calendarEvent->IsGuildAnnouncement()) if (Player* creator = ObjectAccessor::FindPlayerInOrOutOfWorld(guid)) @@ -383,11 +383,11 @@ void WorldSession::HandleCalendarUpdateEvent(WorldPacket& recvData) } sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_UPDATE_EVENT [" UI64FMTD "] EventId [" UI64FMTD - "], InviteId [" UI64FMTD "] Title %s, Description %s, type %u " - "Repeatable %u, MaxInvites %u, Dungeon ID %d, Time %u " - "Time2 %u, Flags %u", guid, eventId, inviteId, title.c_str(), - description.c_str(), type, repetitionType, maxInvites, dungeonId, - eventPackedTime, timeZoneTime, flags); + "], InviteId [" UI64FMTD "] Title %s, Description %s, type %u " + "Repeatable %u, MaxInvites %u, Dungeon ID %d, Time %u " + "Time2 %u, Flags %u", guid, eventId, inviteId, title.c_str(), + description.c_str(), type, repetitionType, maxInvites, dungeonId, + eventPackedTime, timeZoneTime, flags); if (CalendarEvent* calendarEvent = sCalendarMgr->GetEvent(eventId)) { @@ -429,7 +429,7 @@ void WorldSession::HandleCalendarCopyEvent(WorldPacket& recvData) recvData >> eventId >> inviteId; recvData.ReadPackedTime(eventTime); sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_COPY_EVENT [" UI64FMTD "], EventId [" UI64FMTD - "] inviteId [" UI64FMTD "] Time: %u", guid, eventId, inviteId, eventTime); + "] inviteId [" UI64FMTD "] Time: %u", guid, eventId, inviteId, eventTime); // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack @@ -634,8 +634,8 @@ void WorldSession::HandleCalendarEventRsvp(WorldPacket& recvData) recvData >> eventId >> inviteId >> status; sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_EVENT_RSVP [" UI64FMTD"] EventId [" - UI64FMTD "], InviteId [" UI64FMTD "], status %u", guid, eventId, - inviteId, status); + UI64FMTD "], InviteId [" UI64FMTD "], status %u", guid, eventId, + inviteId, status); if (CalendarEvent* calendarEvent = sCalendarMgr->GetEvent(eventId)) { @@ -674,9 +674,9 @@ void WorldSession::HandleCalendarEventRemoveInvite(WorldPacket& recvData) recvData >> inviteId >> ownerInviteId >> eventId; sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_EVENT_REMOVE_INVITE [" - UI64FMTD "] EventId [" UI64FMTD "], ownerInviteId [" - UI64FMTD "], Invitee ([" UI64FMTD "] id: [" UI64FMTD "])", - guid, eventId, ownerInviteId, invitee, inviteId); + UI64FMTD "] EventId [" UI64FMTD "], ownerInviteId [" + UI64FMTD "], Invitee ([" UI64FMTD "] id: [" UI64FMTD "])", + guid, eventId, ownerInviteId, invitee, inviteId); if (CalendarEvent* calendarEvent = sCalendarMgr->GetEvent(eventId)) { @@ -704,8 +704,8 @@ void WorldSession::HandleCalendarEventStatus(WorldPacket& recvData) recvData.readPackGUID(invitee); recvData >> eventId >> inviteId >> ownerInviteId >> status; sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_EVENT_STATUS [" UI64FMTD"] EventId [" - UI64FMTD "] ownerInviteId [" UI64FMTD "], Invitee ([" UI64FMTD "] id: [" - UI64FMTD "], status %u", guid, eventId, ownerInviteId, invitee, inviteId, status); + UI64FMTD "] ownerInviteId [" UI64FMTD "], Invitee ([" UI64FMTD "] id: [" + UI64FMTD "], status %u", guid, eventId, ownerInviteId, invitee, inviteId, status); if (CalendarEvent* calendarEvent = sCalendarMgr->GetEvent(eventId)) { @@ -738,8 +738,8 @@ void WorldSession::HandleCalendarEventModeratorStatus(WorldPacket& recvData) recvData.readPackGUID(invitee); recvData >> eventId >> inviteId >> ownerInviteId >> rank; sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_EVENT_MODERATOR_STATUS [" UI64FMTD "] EventId [" - UI64FMTD "] ownerInviteId [" UI64FMTD "], Invitee ([" UI64FMTD "] id: [" - UI64FMTD "], rank %u", guid, eventId, ownerInviteId, invitee, inviteId, rank); + UI64FMTD "] ownerInviteId [" UI64FMTD "], Invitee ([" UI64FMTD "] id: [" + UI64FMTD "], rank %u", guid, eventId, ownerInviteId, invitee, inviteId, rank); if (CalendarEvent* calendarEvent = sCalendarMgr->GetEvent(eventId)) { @@ -764,7 +764,7 @@ void WorldSession::HandleCalendarComplain(WorldPacket& recvData) recvData >> eventId >> complainGUID; sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_COMPLAIN [" UI64FMTD "] EventId [" - UI64FMTD "] guid [" UI64FMTD "]", guid, eventId, complainGUID); + UI64FMTD "] guid [" UI64FMTD "]", guid, eventId, complainGUID); // what to do with complains? } @@ -775,7 +775,7 @@ void WorldSession::HandleCalendarGetNumPending(WorldPacket& /*recvData*/) uint32 pending = sCalendarMgr->GetPlayerNumPending(guid); sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_CALENDAR_GET_NUM_PENDING: [" UI64FMTD - "] Pending: %u", guid, pending); + "] Pending: %u", guid, pending); WorldPacket data(SMSG_CALENDAR_SEND_NUM_PENDING, 4); data << uint32(pending); @@ -786,7 +786,7 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPacket& recvData) { uint32 mapId, difficulty; uint8 toggleExtendOn; - recvData >> mapId >> difficulty>> toggleExtendOn; + recvData >> mapId >> difficulty >> toggleExtendOn; const MapEntry* entry = sMapStore.LookupEntry(mapId); if (!entry || !entry->IsRaid()) @@ -824,7 +824,7 @@ void WorldSession::SendCalendarRaidLockout(InstanceSave const* save, bool add) data << uint32(save->GetMapId()); data << uint32(save->GetDifficulty()); - data << uint32(save->GetResetTime() >= currTime ? save->GetResetTime()-currTime : 0); + data << uint32(save->GetResetTime() >= currTime ? save->GetResetTime() - currTime : 0); data << uint64(MAKE_NEW_GUID(save->GetInstanceId(), 0, HIGHGUID_INSTANCE)); SendPacket(&data); } @@ -838,7 +838,7 @@ void WorldSession::SendCalendarRaidLockoutUpdated(InstanceSave const* save, bool data.AppendPackedTime(currTime); data << uint32(save->GetMapId()); data << uint32(save->GetDifficulty()); - data << uint32(resetTimeOp >= currTime ? resetTimeOp-currTime : resetTimeOp); // pussywizard: old time in secs to reset - data << uint32(resetTime >= currTime ? resetTime-currTime : 0); // pussywizard: new time in secs to reset + data << uint32(resetTimeOp >= currTime ? resetTimeOp - currTime : resetTimeOp); // pussywizard: old time in secs to reset + data << uint32(resetTime >= currTime ? resetTime - currTime : 0); // pussywizard: new time in secs to reset SendPacket(&data); } diff --git a/src/server/game/Handlers/ChannelHandler.cpp b/src/server/game/Handlers/ChannelHandler.cpp index 81ebac075..19484cbc5 100644 --- a/src/server/game/Handlers/ChannelHandler.cpp +++ b/src/server/game/Handlers/ChannelHandler.cpp @@ -59,7 +59,7 @@ void WorldSession::HandleLeaveChannel(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_LEAVE_CHANNEL %s Channel: %s, unk1: %u", - GetPlayerInfo().c_str(), channelName.c_str(), unk); + GetPlayerInfo().c_str(), channelName.c_str(), unk); #endif if (channelName.empty()) return; @@ -78,8 +78,8 @@ void WorldSession::HandleChannelList(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "%s %s Channel: %s", - recvPacket.GetOpcode() == CMSG_CHANNEL_DISPLAY_LIST ? "CMSG_CHANNEL_DISPLAY_LIST" : "CMSG_CHANNEL_LIST", - GetPlayerInfo().c_str(), channelName.c_str()); + recvPacket.GetOpcode() == CMSG_CHANNEL_DISPLAY_LIST ? "CMSG_CHANNEL_DISPLAY_LIST" : "CMSG_CHANNEL_LIST", + GetPlayerInfo().c_str(), channelName.c_str()); #endif if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeamId())) if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer())) @@ -93,7 +93,7 @@ void WorldSession::HandleChannelPassword(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_PASSWORD %s Channel: %s, Password: %s", - GetPlayerInfo().c_str(), channelName.c_str(), password.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), password.c_str()); #endif if (password.length() > MAX_CHANNEL_PASS_STR) return; @@ -110,7 +110,7 @@ void WorldSession::HandleChannelSetOwner(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_SET_OWNER %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -127,7 +127,7 @@ void WorldSession::HandleChannelOwner(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_OWNER %s Channel: %s", - GetPlayerInfo().c_str(), channelName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str()); #endif if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeamId())) if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer())) @@ -141,7 +141,7 @@ void WorldSession::HandleChannelModerator(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_MODERATOR %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -158,7 +158,7 @@ void WorldSession::HandleChannelUnmoderator(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_UNMODERATOR %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -175,7 +175,7 @@ void WorldSession::HandleChannelMute(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_MUTE %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -192,7 +192,7 @@ void WorldSession::HandleChannelUnmute(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_UNMUTE %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -209,7 +209,7 @@ void WorldSession::HandleChannelInvite(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_INVITE %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -226,7 +226,7 @@ void WorldSession::HandleChannelKick(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_KICK %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -243,7 +243,7 @@ void WorldSession::HandleChannelBan(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_BAN %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -260,7 +260,7 @@ void WorldSession::HandleChannelUnban(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_UNBAN %s Channel: %s, Target: %s", - GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str(), targetName.c_str()); #endif if (!normalizePlayerName(targetName)) return; @@ -277,34 +277,34 @@ void WorldSession::HandleChannelAnnouncements(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_CHANNEL_ANNOUNCEMENTS %s Channel: %s", - GetPlayerInfo().c_str(), channelName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str()); #endif if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeamId())) if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer())) channel->Announce(GetPlayer()); } -void WorldSession::HandleChannelDisplayListQuery(WorldPacket &recvPacket) +void WorldSession::HandleChannelDisplayListQuery(WorldPacket& recvPacket) { // this should be OK because the 2 function _were_ the same HandleChannelList(recvPacket); } -void WorldSession::HandleGetChannelMemberCount(WorldPacket &recvPacket) +void WorldSession::HandleGetChannelMemberCount(WorldPacket& recvPacket) { std::string channelName; recvPacket >> channelName; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_CHATSYS, "CMSG_GET_CHANNEL_MEMBER_COUNT %s Channel: %s", - GetPlayerInfo().c_str(), channelName.c_str()); + GetPlayerInfo().c_str(), channelName.c_str()); #endif if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetPlayer()->GetTeamId())) { if (Channel* channel = cMgr->GetChannel(channelName, GetPlayer())) { sLog->outDebug(LOG_FILTER_CHATSYS, "SMSG_CHANNEL_MEMBER_COUNT %s Channel: %s Count: %u", - GetPlayerInfo().c_str(), channelName.c_str(), channel->GetNumPlayers()); + GetPlayerInfo().c_str(), channelName.c_str(), channel->GetNumPlayers()); WorldPacket data(SMSG_CHANNEL_MEMBER_COUNT, channel->GetName().size() + 1 + 4); data << channel->GetName(); @@ -315,7 +315,7 @@ void WorldSession::HandleGetChannelMemberCount(WorldPacket &recvPacket) } } -void WorldSession::HandleSetChannelWatch(WorldPacket &recvPacket) +void WorldSession::HandleSetChannelWatch(WorldPacket& recvPacket) { std::string channelName; recvPacket >> channelName; @@ -330,7 +330,7 @@ void WorldSession::HandleSetChannelWatch(WorldPacket &recvPacket) channel->AddWatching(GetPlayer()); } -void WorldSession::HandleClearChannelWatch(WorldPacket &recvPacket) +void WorldSession::HandleClearChannelWatch(WorldPacket& recvPacket) { std::string channelName; recvPacket >> channelName; diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index 9d7125d39..038f02650 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -45,15 +45,15 @@ class LoginQueryHolder : public SQLQueryHolder { - private: - uint32 m_accountId; - uint64 m_guid; - public: - LoginQueryHolder(uint32 accountId, uint64 guid) - : m_accountId(accountId), m_guid(guid) { } - uint64 GetGuid() const { return m_guid; } - uint32 GetAccountId() const { return m_accountId; } - bool Initialize(); +private: + uint32 m_accountId; + uint64 m_guid; +public: + LoginQueryHolder(uint32 accountId, uint64 guid) + : m_accountId(accountId), m_guid(guid) { } + uint64 GetGuid() const { return m_guid; } + uint32 GetAccountId() const { return m_accountId; } + bool Initialize(); }; bool LoginQueryHolder::Initialize() @@ -216,8 +216,7 @@ void WorldSession::HandleCharEnum(PreparedQueryResult result) _legitCharacters.insert(guidlow); ++num; } - } - while (result->NextRow()); + } while (result->NextRow()); } data.put(0, num); @@ -225,7 +224,7 @@ void WorldSession::HandleCharEnum(PreparedQueryResult result) SendPacket(&data); } -void WorldSession::HandleCharEnumOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleCharEnumOpcode(WorldPacket& /*recvData*/) { // remove expired bans // pussywizard: moved to world update to do it once >_> @@ -390,152 +389,71 @@ void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, Characte switch (_charCreateCallback.GetStage()) { case 0: - { - if (result) { - WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_NAME_IN_USE); - SendPacket(&data); - delete createInfo; - _charCreateCallback.Reset(); - return; - } - - ASSERT(_charCreateCallback.GetParam() == createInfo); - - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SUM_REALM_CHARACTERS); - stmt->setUInt32(0, GetAccountId()); - - _charCreateCallback.FreeResult(); - _charCreateCallback.SetFutureResult(LoginDatabase.AsyncQuery(stmt)); - _charCreateCallback.NextStage(); - } - break; - case 1: - { - uint16 acctCharCount = 0; - if (result) - { - Field* fields = result->Fetch(); - // SELECT SUM(x) is MYSQL_TYPE_NEWDECIMAL - needs to be read as string - const char* ch = fields[0].GetCString(); - if (ch) - acctCharCount = atoi(ch); - } - - if (acctCharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_ACCOUNT)) - { - WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_ACCOUNT_LIMIT); - SendPacket(&data); - delete createInfo; - _charCreateCallback.Reset(); - return; - } - - - ASSERT(_charCreateCallback.GetParam() == createInfo); - - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS); - stmt->setUInt32(0, GetAccountId()); - - _charCreateCallback.FreeResult(); - _charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt)); - _charCreateCallback.NextStage(); - } - break; - case 2: - { - if (result) - { - Field* fields = result->Fetch(); - createInfo->CharCount = uint8(fields[0].GetUInt64()); // SQL's COUNT() returns uint64 but it will always be less than uint8.Max - - if (createInfo->CharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_REALM)) + if (result) { WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_SERVER_LIMIT); + data << uint8(CHAR_CREATE_NAME_IN_USE); SendPacket(&data); delete createInfo; _charCreateCallback.Reset(); return; } - } - bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || !AccountMgr::IsPlayerAccount(GetSecurity()); - uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS); + ASSERT(_charCreateCallback.GetParam() == createInfo); - _charCreateCallback.FreeResult(); - - if (!allowTwoSideAccounts || skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) - { - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CREATE_INFO); + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SUM_REALM_CHARACTERS); stmt->setUInt32(0, GetAccountId()); - stmt->setUInt32(1, (skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) ? 10 : 1); - _charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt)); + + _charCreateCallback.FreeResult(); + _charCreateCallback.SetFutureResult(LoginDatabase.AsyncQuery(stmt)); _charCreateCallback.NextStage(); - return; } - - _charCreateCallback.NextStage(); - HandleCharCreateCallback(PreparedQueryResult(nullptr), createInfo); // Will jump to case 3 - } - break; - case 3: - { - bool haveSameRace = false; - uint32 heroicReqLevel = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_MIN_LEVEL_FOR_HEROIC_CHARACTER); - bool hasHeroicReqLevel = (heroicReqLevel == 0); - bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || !AccountMgr::IsPlayerAccount(GetSecurity()); - uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS); - - if (result) + break; + case 1: { - TeamId teamId = Player::TeamIdForRace(createInfo->Race); - uint32 freeHeroicSlots = sWorld->getIntConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM); - - Field* field = result->Fetch(); - uint8 accRace = field[1].GetUInt8(); - - if (AccountMgr::IsPlayerAccount(GetSecurity()) && createInfo->Class == CLASS_DEATH_KNIGHT) + uint16 acctCharCount = 0; + if (result) { - uint8 accClass = field[2].GetUInt8(); - if (accClass == CLASS_DEATH_KNIGHT) - { - if (freeHeroicSlots > 0) - --freeHeroicSlots; - - if (freeHeroicSlots == 0) - { - WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_UNIQUE_CLASS_LIMIT); - SendPacket(&data); - delete createInfo; - _charCreateCallback.Reset(); - return; - } - } - - if (!hasHeroicReqLevel) - { - uint8 accLevel = field[0].GetUInt8(); - if (accLevel >= heroicReqLevel) - hasHeroicReqLevel = true; - } + Field* fields = result->Fetch(); + // SELECT SUM(x) is MYSQL_TYPE_NEWDECIMAL - needs to be read as string + const char* ch = fields[0].GetCString(); + if (ch) + acctCharCount = atoi(ch); } - // need to check team only for first character - // TODO: what to if account already has characters of both races? - if (!allowTwoSideAccounts) + if (acctCharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_ACCOUNT)) { - uint32 accTeamId = TEAM_NEUTRAL; - if (accRace > 0) - accTeamId = Player::TeamIdForRace(accRace); + WorldPacket data(SMSG_CHAR_CREATE, 1); + data << uint8(CHAR_CREATE_ACCOUNT_LIMIT); + SendPacket(&data); + delete createInfo; + _charCreateCallback.Reset(); + return; + } - if (accTeamId != teamId) + + ASSERT(_charCreateCallback.GetParam() == createInfo); + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS); + stmt->setUInt32(0, GetAccountId()); + + _charCreateCallback.FreeResult(); + _charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt)); + _charCreateCallback.NextStage(); + } + break; + case 2: + { + if (result) + { + Field* fields = result->Fetch(); + createInfo->CharCount = uint8(fields[0].GetUInt64()); // SQL's COUNT() returns uint64 but it will always be less than uint8.Max + + if (createInfo->CharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_REALM)) { WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_PVP_TEAMS_VIOLATION); + data << uint8(CHAR_CREATE_SERVER_LIMIT); SendPacket(&data); delete createInfo; _charCreateCallback.Reset(); @@ -543,23 +461,45 @@ void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, Characte } } - // search same race for cinematic or same class if need - // TODO: check if cinematic already shown? (already logged in?; cinematic field) - while ((skipCinematics == 1 && !haveSameRace) || createInfo->Class == CLASS_DEATH_KNIGHT) + bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || !AccountMgr::IsPlayerAccount(GetSecurity()); + uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS); + + _charCreateCallback.FreeResult(); + + if (!allowTwoSideAccounts || skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) { - if (!result->NextRow()) - break; + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CREATE_INFO); + stmt->setUInt32(0, GetAccountId()); + stmt->setUInt32(1, (skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) ? 10 : 1); + _charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt)); + _charCreateCallback.NextStage(); + return; + } - field = result->Fetch(); - accRace = field[1].GetUInt8(); + _charCreateCallback.NextStage(); + HandleCharCreateCallback(PreparedQueryResult(nullptr), createInfo); // Will jump to case 3 + } + break; + case 3: + { + bool haveSameRace = false; + uint32 heroicReqLevel = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_MIN_LEVEL_FOR_HEROIC_CHARACTER); + bool hasHeroicReqLevel = (heroicReqLevel == 0); + bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_ACCOUNTS) || !AccountMgr::IsPlayerAccount(GetSecurity()); + uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS); - if (!haveSameRace) - haveSameRace = createInfo->Race == accRace; + if (result) + { + TeamId teamId = Player::TeamIdForRace(createInfo->Race); + uint32 freeHeroicSlots = sWorld->getIntConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM); + + Field* field = result->Fetch(); + uint8 accRace = field[1].GetUInt8(); if (AccountMgr::IsPlayerAccount(GetSecurity()) && createInfo->Class == CLASS_DEATH_KNIGHT) { - uint8 acc_class = field[2].GetUInt8(); - if (acc_class == CLASS_DEATH_KNIGHT) + uint8 accClass = field[2].GetUInt8(); + if (accClass == CLASS_DEATH_KNIGHT) { if (freeHeroicSlots > 0) --freeHeroicSlots; @@ -577,100 +517,159 @@ void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, Characte if (!hasHeroicReqLevel) { - uint8 acc_level = field[0].GetUInt8(); - if (acc_level >= heroicReqLevel) + uint8 accLevel = field[0].GetUInt8(); + if (accLevel >= heroicReqLevel) hasHeroicReqLevel = true; } } + + // need to check team only for first character + // TODO: what to if account already has characters of both races? + if (!allowTwoSideAccounts) + { + uint32 accTeamId = TEAM_NEUTRAL; + if (accRace > 0) + accTeamId = Player::TeamIdForRace(accRace); + + if (accTeamId != teamId) + { + WorldPacket data(SMSG_CHAR_CREATE, 1); + data << uint8(CHAR_CREATE_PVP_TEAMS_VIOLATION); + SendPacket(&data); + delete createInfo; + _charCreateCallback.Reset(); + return; + } + } + + // search same race for cinematic or same class if need + // TODO: check if cinematic already shown? (already logged in?; cinematic field) + while ((skipCinematics == 1 && !haveSameRace) || createInfo->Class == CLASS_DEATH_KNIGHT) + { + if (!result->NextRow()) + break; + + field = result->Fetch(); + accRace = field[1].GetUInt8(); + + if (!haveSameRace) + haveSameRace = createInfo->Race == accRace; + + if (AccountMgr::IsPlayerAccount(GetSecurity()) && createInfo->Class == CLASS_DEATH_KNIGHT) + { + uint8 acc_class = field[2].GetUInt8(); + if (acc_class == CLASS_DEATH_KNIGHT) + { + if (freeHeroicSlots > 0) + --freeHeroicSlots; + + if (freeHeroicSlots == 0) + { + WorldPacket data(SMSG_CHAR_CREATE, 1); + data << uint8(CHAR_CREATE_UNIQUE_CLASS_LIMIT); + SendPacket(&data); + delete createInfo; + _charCreateCallback.Reset(); + return; + } + } + + if (!hasHeroicReqLevel) + { + uint8 acc_level = field[0].GetUInt8(); + if (acc_level >= heroicReqLevel) + hasHeroicReqLevel = true; + } + } + } } - } - if (AccountMgr::IsPlayerAccount(GetSecurity()) && createInfo->Class == CLASS_DEATH_KNIGHT && !hasHeroicReqLevel) - { - WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_LEVEL_REQUIREMENT); - SendPacket(&data); - delete createInfo; - _charCreateCallback.Reset(); - return; - } + if (AccountMgr::IsPlayerAccount(GetSecurity()) && createInfo->Class == CLASS_DEATH_KNIGHT && !hasHeroicReqLevel) + { + WorldPacket data(SMSG_CHAR_CREATE, 1); + data << uint8(CHAR_CREATE_LEVEL_REQUIREMENT); + SendPacket(&data); + delete createInfo; + _charCreateCallback.Reset(); + return; + } - if (createInfo->Data.rpos() < createInfo->Data.wpos()) - { - uint8 unk; - createInfo->Data >> unk; + if (createInfo->Data.rpos() < createInfo->Data.wpos()) + { + uint8 unk; + createInfo->Data >> unk; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_NETWORKIO, "Character creation %s (account %u) has unhandled tail data: [%u]", createInfo->Name.c_str(), GetAccountId(), unk); + sLog->outDebug(LOG_FILTER_NETWORKIO, "Character creation %s (account %u) has unhandled tail data: [%u]", createInfo->Name.c_str(), GetAccountId(), unk); #endif - } + } + + // pussywizard: + if (sWorld->GetGlobalPlayerGUID(createInfo->Name)) + { + WorldPacket data(SMSG_CHAR_CREATE, 1); + data << uint8(CHAR_CREATE_NAME_IN_USE); + SendPacket(&data); + delete createInfo; + _charCreateCallback.Reset(); + return; + } + + Player newChar(this); + newChar.GetMotionMaster()->Initialize(); + if (!newChar.Create(sObjectMgr->GenerateLowGuid(HIGHGUID_PLAYER), createInfo)) + { + // Player not create (race/class/etc problem?) + newChar.CleanupsBeforeDelete(); + + WorldPacket data(SMSG_CHAR_CREATE, 1); + data << uint8(CHAR_CREATE_ERROR); + SendPacket(&data); + delete createInfo; + _charCreateCallback.Reset(); + return; + } + + if ((haveSameRace && skipCinematics == 1) || skipCinematics == 2) + newChar.setCinematic(1); // not show intro + + newChar.SetAtLoginFlag(AT_LOGIN_FIRST); // First login + + // Player created, save it now + newChar.SaveToDB(true, false); + createInfo->CharCount += 1; + + SQLTransaction trans = LoginDatabase.BeginTransaction(); + + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM); + stmt->setUInt32(0, GetAccountId()); + stmt->setUInt32(1, realmID); + trans->Append(stmt); + + stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS); + stmt->setUInt32(0, createInfo->CharCount); + stmt->setUInt32(1, GetAccountId()); + stmt->setUInt32(2, realmID); + trans->Append(stmt); + + LoginDatabase.CommitTransaction(trans); - // pussywizard: - if (sWorld->GetGlobalPlayerGUID(createInfo->Name)) - { WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_NAME_IN_USE); + data << uint8(CHAR_CREATE_SUCCESS); SendPacket(&data); - delete createInfo; - _charCreateCallback.Reset(); - return; - } - Player newChar(this); - newChar.GetMotionMaster()->Initialize(); - if (!newChar.Create(sObjectMgr->GenerateLowGuid(HIGHGUID_PLAYER), createInfo)) - { - // Player not create (race/class/etc problem?) + std::string IP_str = GetRemoteAddress(); +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDetail("Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), IP_str.c_str(), createInfo->Name.c_str(), newChar.GetGUIDLow()); +#endif + sLog->outChar("Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), IP_str.c_str(), createInfo->Name.c_str(), newChar.GetGUIDLow()); + sScriptMgr->OnPlayerCreate(&newChar); + sWorld->AddGlobalPlayerData(newChar.GetGUIDLow(), GetAccountId(), newChar.GetName(), newChar.getGender(), newChar.getRace(), newChar.getClass(), newChar.getLevel(), 0, 0); + newChar.CleanupsBeforeDelete(); - - WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_ERROR); - SendPacket(&data); delete createInfo; _charCreateCallback.Reset(); - return; } - - if ((haveSameRace && skipCinematics == 1) || skipCinematics == 2) - newChar.setCinematic(1); // not show intro - - newChar.SetAtLoginFlag(AT_LOGIN_FIRST); // First login - - // Player created, save it now - newChar.SaveToDB(true, false); - createInfo->CharCount += 1; - - SQLTransaction trans = LoginDatabase.BeginTransaction(); - - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM); - stmt->setUInt32(0, GetAccountId()); - stmt->setUInt32(1, realmID); - trans->Append(stmt); - - stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS); - stmt->setUInt32(0, createInfo->CharCount); - stmt->setUInt32(1, GetAccountId()); - stmt->setUInt32(2, realmID); - trans->Append(stmt); - - LoginDatabase.CommitTransaction(trans); - - WorldPacket data(SMSG_CHAR_CREATE, 1); - data << uint8(CHAR_CREATE_SUCCESS); - SendPacket(&data); - - std::string IP_str = GetRemoteAddress(); -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDetail("Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), IP_str.c_str(), createInfo->Name.c_str(), newChar.GetGUIDLow()); -#endif - sLog->outChar("Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), IP_str.c_str(), createInfo->Name.c_str(), newChar.GetGUIDLow()); - sScriptMgr->OnPlayerCreate(&newChar); - sWorld->AddGlobalPlayerData(newChar.GetGUIDLow(), GetAccountId(), newChar.GetName(), newChar.getGender(), newChar.getRace(), newChar.getClass(), newChar.getLevel(), 0, 0); - - newChar.CleanupsBeforeDelete(); - delete createInfo; - _charCreateCallback.Reset(); - } - break; + break; } } @@ -753,7 +752,7 @@ void WorldSession::HandleCharDeleteOpcode(WorldPacket& recvData) SendPacket(&data); } -void WorldSession::HandlePlayerLoginOpcode(WorldPacket & recvData) +void WorldSession::HandlePlayerLoginOpcode(WorldPacket& recvData) { if (PlayerLoading() || GetPlayer() != nullptr) { @@ -771,7 +770,7 @@ void WorldSession::HandlePlayerLoginOpcode(WorldPacket & recvData) KickPlayer("Account can't login with this character"); return; } - + // pussywizard: if (WorldSession* sess = sWorld->FindOfflineSessionForCharacterGUID(GUID_LOPART(playerGuid))) if (sess->GetAccountId() != GetAccountId()) @@ -860,7 +859,7 @@ void WorldSession::HandlePlayerLoginOpcode(WorldPacket & recvData) m_playerLoading = true; - LoginQueryHolder *holder = new LoginQueryHolder(GetAccountId(), playerGuid); + LoginQueryHolder* holder = new LoginQueryHolder(GetAccountId(), playerGuid); if (!holder->Initialize()) { delete holder; // delete all unprocessed queries @@ -876,7 +875,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder* holder) uint64 playerGuid = holder->GetGuid(); Player* pCurrChar = new Player(this); - // for send server info and strings (config) + // for send server info and strings (config) ChatHandler chH = ChatHandler(this); // "GetAccountId() == db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools) @@ -947,7 +946,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder* holder) } - data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4+4); + data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4 + 4); data << uint32(0); data << uint32(0); SendPacket(&data); @@ -1076,7 +1075,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder* holder) pCurrChar->CheckAllAchievementCriteria(); } - // Reputations if "StartAllReputation" is enabled, -- TODO: Fix this in a better way + // Reputations if "StartAllReputation" is enabled, -- TODO: Fix this in a better way if (sWorld->getBoolConfig(CONFIG_START_ALL_REP)) { ReputationMgr& repMgr = pCurrChar->GetReputationMgr(); @@ -1132,7 +1131,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder* holder) std::string IP_str = GetRemoteAddress(); sLog->outChar("Account: %d (IP: %s) Login Character:[%s] (GUID: %u) Level: %d", - GetAccountId(), IP_str.c_str(), pCurrChar->GetName().c_str(), pCurrChar->GetGUIDLow(), pCurrChar->getLevel()); + GetAccountId(), IP_str.c_str(), pCurrChar->GetName().c_str(), pCurrChar->GetGUIDLow(), pCurrChar->getLevel()); if (!pCurrChar->IsStandState() && !pCurrChar->HasUnitState(UNIT_STATE_STUNNED)) pCurrChar->SetStandState(UNIT_STAND_STATE_STAND); @@ -1185,7 +1184,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder* holder) continue; if ((isReferrer && pCurrChar->GetSession()->GetAccountId() == itr->second->GetRecruiterId()) || (!isReferrer && pCurrChar->GetSession()->GetRecruiterId() == itr->second->GetAccountId())) { - Player * rf = itr->second->GetPlayer(); + Player* rf = itr->second->GetPlayer(); if (rf != nullptr) { pCurrChar->SendUpdateToPlayer(rf); @@ -1197,7 +1196,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder* holder) sScriptMgr->OnPlayerLogin(pCurrChar); - if (pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST)) + if (pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST)) { pCurrChar->RemoveAtLoginFlag(AT_LOGIN_FIRST); sScriptMgr->OnFirstLogin(pCurrChar); @@ -1241,7 +1240,7 @@ void WorldSession::HandlePlayerLoginToCharInWorld(Player* pCurrChar) #endif } - data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4+4); + data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4 + 4); data << uint32(0); data << uint32(0); SendPacket(&data); @@ -1280,10 +1279,10 @@ void WorldSession::HandlePlayerLoginToCharInWorld(Player* pCurrChar) for (int32 eff = 0; eff < 96; ++eff) { - if (eff != 0 && eff%32 == 0) + if (eff != 0 && eff % 32 == 0) _mask[i++] = 0; - _mask[i] = uint32(1) << (eff-(32*i)); + _mask[i] = uint32(1) << (eff - (32 * i)); int32 val = 0; for (SpellModList::const_iterator itr = spellMods.begin(); itr != spellMods.end(); ++itr) if ((*itr)->type == modType && (*itr)->mask & _mask) @@ -1292,7 +1291,7 @@ void WorldSession::HandlePlayerLoginToCharInWorld(Player* pCurrChar) if (val == 0) continue; - WorldPacket data(Opcode, (1+1+4)); + WorldPacket data(Opcode, (1 + 1 + 4)); data << uint8(eff); data << uint8(opType); data << int32(val); @@ -1300,7 +1299,7 @@ void WorldSession::HandlePlayerLoginToCharInWorld(Player* pCurrChar) } } } - + if (Group* group = pCurrChar->GetGroup()) group->SendUpdate(); @@ -1351,7 +1350,7 @@ void WorldSession::HandleSetFactionAtWar(WorldPacket& recvData) } //I think this function is never used :/ I dunno, but i guess this opcode not exists -void WorldSession::HandleSetFactionCheat(WorldPacket & /*recvData*/) +void WorldSession::HandleSetFactionCheat(WorldPacket& /*recvData*/) { sLog->outError("WORLD SESSION: HandleSetFactionCheat, not expected call, please report."); GetPlayer()->GetReputationMgr().SendStates(); @@ -1373,13 +1372,13 @@ void WorldSession::HandleTutorialFlag(WorldPacket& recvData) SetTutorialInt(index, flag); } -void WorldSession::HandleTutorialClear(WorldPacket & /*recvData*/) +void WorldSession::HandleTutorialClear(WorldPacket& /*recvData*/) { for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i) SetTutorialInt(i, 0xFFFFFFFF); } -void WorldSession::HandleTutorialReset(WorldPacket & /*recvData*/) +void WorldSession::HandleTutorialReset(WorldPacket& /*recvData*/) { for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i) SetTutorialInt(i, 0x00000000); @@ -1395,7 +1394,7 @@ void WorldSession::HandleSetWatchedFactionOpcode(WorldPacket& recvData) GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact); } -void WorldSession::HandleSetFactionInactiveOpcode(WorldPacket & recvData) +void WorldSession::HandleSetFactionInactiveOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("WORLD: Received CMSG_SET_FACTION_INACTIVE"); @@ -1445,7 +1444,7 @@ void WorldSession::HandleCharRenameOpcode(WorldPacket& recvData) uint8 res = ObjectMgr::CheckPlayerName(newName, true); if (res != CHAR_NAME_SUCCESS) { - WorldPacket data(SMSG_CHAR_RENAME, 1+8+(newName.size()+1)); + WorldPacket data(SMSG_CHAR_RENAME, 1 + 8 + (newName.size() + 1)); data << uint8(res); data << uint64(guid); data << newName; @@ -1524,7 +1523,7 @@ void WorldSession::HandleChangePlayerNameOpcodeCallBack(PreparedQueryResult resu sLog->outChar("Account: %d (IP: %s), Character [%s] (guid: %u) Changed name to: %s", GetAccountId(), GetRemoteAddress().c_str(), oldName.c_str(), guidLow, newName.c_str()); - WorldPacket data(SMSG_CHAR_RENAME, 1+8+(newName.size()+1)); + WorldPacket data(SMSG_CHAR_RENAME, 1 + 8 + (newName.size() + 1)); data << uint8(RESPONSE_SUCCESS); data << uint64(guid); data << newName; @@ -1549,7 +1548,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) std::string name; if (!sObjectMgr->GetPlayerNameByGUID(guid, name)) { - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(1); data << uint64(guid); SendPacket(&data); @@ -1559,7 +1558,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) std::wstring wname; if (!Utf8toWStr(name, wname)) { - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(1); data << uint64(guid); SendPacket(&data); @@ -1568,7 +1567,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) if (!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using { - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(1); data << uint64(guid); SendPacket(&data); @@ -1582,7 +1581,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) if (name2 != name) // character have different name { - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(1); data << uint64(guid); SendPacket(&data); @@ -1594,7 +1593,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) recvData >> declinedname.name[i]; if (!normalizePlayerName(declinedname.name[i])) { - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(1); data << uint64(guid); SendPacket(&data); @@ -1604,7 +1603,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) if (!ObjectMgr::CheckDeclinedNames(wname, declinedname)) { - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(1); data << uint64(guid); SendPacket(&data); @@ -1624,13 +1623,13 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) stmt->setUInt32(0, GUID_LOPART(guid)); for (uint8 i = 0; i < 5; i++) - stmt->setString(i+1, declinedname.name[i]); + stmt->setString(i + 1, declinedname.name[i]); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); - WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8); + WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8); data << uint32(0); // OK data << uint64(guid); SendPacket(&data); @@ -1743,7 +1742,7 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) if (!IsLegitCharacterForAccount(GUID_LOPART(guid))) { sLog->outError("Account %u, IP: %s tried to customise character %u, but it does not belong to their account!", - GetAccountId(), GetRemoteAddress().c_str(), GUID_LOPART(guid)); + GetAccountId(), GetRemoteAddress().c_str(), GUID_LOPART(guid)); recvData.rfinish(); KickPlayer("HandleCharCustomize"); return; @@ -1862,9 +1861,9 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) // xinef: update global data sWorld->UpdateGlobalNameData(GUID_LOPART(guid), playerData->name, newName); - sWorld->UpdateGlobalPlayerData(GUID_LOPART(guid), PLAYER_UPDATE_DATA_NAME|PLAYER_UPDATE_DATA_GENDER, newName, 0, gender); + sWorld->UpdateGlobalPlayerData(GUID_LOPART(guid), PLAYER_UPDATE_DATA_NAME | PLAYER_UPDATE_DATA_GENDER, newName, 0, gender); - WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1+8+(newName.size()+1)+6); + WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1 + 8 + (newName.size() + 1) + 6); data << uint8(RESPONSE_SUCCESS); data << uint64(guid); data << newName; @@ -1877,7 +1876,7 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) SendPacket(&data); } -void WorldSession::HandleEquipmentSetSave(WorldPacket &recvData) +void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_EQUIPMENT_SET_SAVE"); @@ -1938,7 +1937,7 @@ void WorldSession::HandleEquipmentSetSave(WorldPacket &recvData) _player->SetEquipmentSet(index, eqSet); } -void WorldSession::HandleEquipmentSetDelete(WorldPacket &recvData) +void WorldSession::HandleEquipmentSetDelete(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_EQUIPMENT_SET_DELETE"); @@ -1950,7 +1949,7 @@ void WorldSession::HandleEquipmentSetDelete(WorldPacket &recvData) _player->DeleteEquipmentSet(setGuid); } -void WorldSession::HandleEquipmentSetUse(WorldPacket &recvData) +void WorldSession::HandleEquipmentSetUse(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_EQUIPMENT_SET_USE"); @@ -1981,14 +1980,17 @@ void WorldSession::HandleEquipmentSetUse(WorldPacket &recvData) item = _player->GetItemByGuid(itemGuid); uint16 dstpos = i | (INVENTORY_SLOT_BAG_0 << 8); - + InventoryResult msg; Item* uItem = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i); - if (uItem) { - if (uItem->IsEquipped()) { + if (uItem) + { + if (uItem->IsEquipped()) + { msg = _player->CanUnequipItem(dstpos, true); - if (msg != EQUIP_ERR_OK) { + if (msg != EQUIP_ERR_OK) + { _player->SendEquipError(msg, uItem, nullptr); continue; } @@ -2010,14 +2012,17 @@ void WorldSession::HandleEquipmentSetUse(WorldPacket &recvData) } } - if (item) { + if (item) + { if (item->GetPos() == dstpos) continue; - if (!item->IsEquipped()) { + if (!item->IsEquipped()) + { uint16 _candidatePos; msg = _player->CanEquipItem(NULL_SLOT, _candidatePos, item, true); - if (msg != EQUIP_ERR_OK) { + if (msg != EQUIP_ERR_OK) + { _player->SendEquipError(msg, item, nullptr); continue; } @@ -2042,7 +2047,7 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) if (!IsLegitCharacterForAccount(GUID_LOPART(guid))) { sLog->outError("Account %u, IP: %s tried to factionchange character %u, but it does not belong to their account!", - GetAccountId(), GetRemoteAddress().c_str(), GUID_LOPART(guid)); + GetAccountId(), GetRemoteAddress().c_str(), GUID_LOPART(guid)); recvData.rfinish(); KickPlayer("HandleCharFactionOrRaceChange"); return; @@ -2105,9 +2110,9 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) // check auctions, current packet is processed single-threaded way, so not a problem bool has_auctions = false; - for (uint8 i=0; i<2; ++i) // check both neutral and faction-specific AH + for (uint8 i = 0; i < 2; ++i) // check both neutral and faction-specific AH { - AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(i == 0 ? 0 : (((1<<(playerData->race-1))&RACEMASK_ALLIANCE) ? 12 : 29)); + AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(i == 0 ? 0 : (((1 << (playerData->race - 1))&RACEMASK_ALLIANCE) ? 12 : 29)); AuctionHouseObject::AuctionEntryMap::const_iterator itr = auctionHouse->GetAuctionsBegin(); AuctionHouseObject::AuctionEntryMap::const_iterator _end = auctionHouse->GetAuctionsEnd(); for (; itr != _end; ++itr) @@ -2157,7 +2162,7 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) // xinef: check money bool valid = Player::TeamIdForRace(oldRace) == Player::TeamIdForRace(race); if ((level < 10 && money <= 0) || (level > 10 && level <= 30 && money <= 3000000 ) || (level > 30 && level <= 50 && money <= 10000000) || - (level > 50 && level <= 70 && money <= 50000000) || (level > 70 && money <= 200000000)) + (level > 50 && level <= 70 && money <= 50000000) || (level > 70 && money <= 200000000)) valid = true; if (!valid) { @@ -2267,8 +2272,8 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) // xinef: update global data sWorld->UpdateGlobalNameData(GUID_LOPART(guid), playerData->name, newname); - sWorld->UpdateGlobalPlayerData(GUID_LOPART(guid), - PLAYER_UPDATE_DATA_NAME|PLAYER_UPDATE_DATA_RACE|PLAYER_UPDATE_DATA_GENDER, newname, 0, gender, race); + sWorld->UpdateGlobalPlayerData(GUID_LOPART(guid), + PLAYER_UPDATE_DATA_NAME | PLAYER_UPDATE_DATA_RACE | PLAYER_UPDATE_DATA_GENDER, newname, 0, gender, race); if (oldRace != race) { diff --git a/src/server/game/Handlers/ChatHandler.cpp b/src/server/game/Handlers/ChatHandler.cpp index 2daeeb9ee..07a37c37a 100644 --- a/src/server/game/Handlers/ChatHandler.cpp +++ b/src/server/game/Handlers/ChatHandler.cpp @@ -32,7 +32,7 @@ #include "LuaEngine.h" #endif -void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) +void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) { uint32 type; uint32 lang; @@ -144,17 +144,17 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) case CHAT_MSG_RAID: case CHAT_MSG_GUILD: case CHAT_MSG_BATTLEGROUND: - // check if addon messages are disabled - if (!sWorld->getBoolConfig(CONFIG_ADDON_CHANNEL)) - { - recvData.rfinish(); - return; - } + // check if addon messages are disabled + if (!sWorld->getBoolConfig(CONFIG_ADDON_CHANNEL)) + { + recvData.rfinish(); + return; + } - if (sWorld->getBoolConfig(CONFIG_CHATLOG_ADDON)) - { - std::string msg; - recvData >> msg; + if (sWorld->getBoolConfig(CONFIG_CHATLOG_ADDON)) + { + std::string msg; + recvData >> msg; if (msg.empty()) return; @@ -166,27 +166,27 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) #endif } - break; + break; case CHAT_MSG_WHISPER: - // check if addon messages are disabled - if (!sWorld->getBoolConfig(CONFIG_ADDON_CHANNEL)) - { - recvData.rfinish(); - return; - } + // check if addon messages are disabled + if (!sWorld->getBoolConfig(CONFIG_ADDON_CHANNEL)) + { + recvData.rfinish(); + return; + } - if (sWorld->getBoolConfig(CONFIG_CHATLOG_ADDON)) - { - std::string to, msg; - recvData >> to >> msg; - if (msg.empty()) - return; - } + if (sWorld->getBoolConfig(CONFIG_CHATLOG_ADDON)) + { + std::string to, msg; + recvData >> to >> msg; + if (msg.empty()) + return; + } - break; + break; default: sLog->outError("Player %s (GUID: %u) sent a chatmessage with an invalid language/message type combination", - GetPlayer()->GetName().c_str(), GetPlayer()->GetGUIDLow()); + GetPlayer()->GetName().c_str(), GetPlayer()->GetGUIDLow()); recvData.rfinish(); return; @@ -208,29 +208,29 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) { switch (type) { - case CHAT_MSG_PARTY: - case CHAT_MSG_PARTY_LEADER: - case CHAT_MSG_RAID: - case CHAT_MSG_RAID_LEADER: - case CHAT_MSG_RAID_WARNING: - // allow two side chat at group channel if two side group allowed - if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP)) - lang = LANG_UNIVERSAL; + case CHAT_MSG_PARTY: + case CHAT_MSG_PARTY_LEADER: + case CHAT_MSG_RAID: + case CHAT_MSG_RAID_LEADER: + case CHAT_MSG_RAID_WARNING: + // allow two side chat at group channel if two side group allowed + if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP)) + lang = LANG_UNIVERSAL; - specialMessageLimit = 35; - break; - case CHAT_MSG_GUILD: - case CHAT_MSG_OFFICER: - // allow two side chat at guild channel if two side guild allowed - if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD)) - lang = LANG_UNIVERSAL; + specialMessageLimit = 35; + break; + case CHAT_MSG_GUILD: + case CHAT_MSG_OFFICER: + // allow two side chat at guild channel if two side guild allowed + if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD)) + lang = LANG_UNIVERSAL; - specialMessageLimit = 15; - break; - case CHAT_MSG_WHISPER: - if (sender->getLevel() >= 80) specialMessageLimit = 15; - break; + break; + case CHAT_MSG_WHISPER: + if (sender->getLevel() >= 80) + specialMessageLimit = 15; + break; } } // but overwrite it by SPELL_AURA_MOD_LANGUAGE auras (only single case used) @@ -318,8 +318,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) size_t found1 = msg.find("|Hquest"); if (found1 != std::string::npos) { - size_t found2 = msg.find(":", found1+8); - size_t found3 = msg.find("|", found1+8); + size_t found2 = msg.find(":", found1 + 8); + size_t found3 = msg.find("|", found1 + 8); if (found3 != std::string::npos) { if (found2 == std::string::npos) @@ -330,7 +330,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) } // prevent crash player - if (msg.find("| |Hquest") != std::string::npos) { + if (msg.find("| |Hquest") != std::string::npos) + { return; } @@ -341,255 +342,293 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) case CHAT_MSG_SAY: case CHAT_MSG_EMOTE: case CHAT_MSG_YELL: - { - // Prevent cheating - if (!sender->IsAlive()) - return; - - if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_SAY_LEVEL_REQ)) { - SendNotification(GetAcoreString(LANG_SAY_REQ), sWorld->getIntConfig(CONFIG_CHAT_SAY_LEVEL_REQ)); - return; - } + // Prevent cheating + if (!sender->IsAlive()) + return; - if (type == CHAT_MSG_SAY) - sender->Say(msg, lang); - else if (type == CHAT_MSG_EMOTE) - sender->TextEmote(msg); - else if (type == CHAT_MSG_YELL) - sender->Yell(msg, lang); - } break; - case CHAT_MSG_WHISPER: - { - if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_WHISPER_LEVEL_REQ)) - { - SendNotification(GetAcoreString(LANG_WHISPER_REQ), sWorld->getIntConfig(CONFIG_CHAT_WHISPER_LEVEL_REQ)); - return; - } - - if (!normalizePlayerName(to)) - { - SendPlayerNotFoundNotice(to); - break; - } - - Player* receiver = ObjectAccessor::FindPlayerByName(to, false); - bool senderIsPlayer = AccountMgr::IsPlayerAccount(GetSecurity()); - bool receiverIsPlayer = AccountMgr::IsPlayerAccount(receiver ? receiver->GetSession()->GetSecurity() : SEC_PLAYER); - if (!receiver || (senderIsPlayer && !receiverIsPlayer && !receiver->isAcceptWhispers() && !receiver->IsInWhisperWhiteList(sender->GetGUID()))) - { - SendPlayerNotFoundNotice(to); - return; - } - - if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) && senderIsPlayer && receiverIsPlayer) - if (GetPlayer()->GetTeamId() != receiver->GetTeamId()) + if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_SAY_LEVEL_REQ)) { - SendWrongFactionNotice(); + SendNotification(GetAcoreString(LANG_SAY_REQ), sWorld->getIntConfig(CONFIG_CHAT_SAY_LEVEL_REQ)); return; } - // pussywizard: optimization - if (GetPlayer()->HasAura(1852) && !receiver->IsGameMaster()) - { - SendNotification(GetAcoreString(LANG_GM_SILENCE), GetPlayer()->GetName().c_str()); - return; + if (type == CHAT_MSG_SAY) + sender->Say(msg, lang); + else if (type == CHAT_MSG_EMOTE) + sender->TextEmote(msg); + else if (type == CHAT_MSG_YELL) + sender->Yell(msg, lang); } + break; + case CHAT_MSG_WHISPER: + { + if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_WHISPER_LEVEL_REQ)) + { + SendNotification(GetAcoreString(LANG_WHISPER_REQ), sWorld->getIntConfig(CONFIG_CHAT_WHISPER_LEVEL_REQ)); + return; + } - // If player is a Gamemaster and doesn't accept whisper, we auto-whitelist every player that the Gamemaster is talking to - if (!senderIsPlayer && !sender->isAcceptWhispers() && !sender->IsInWhisperWhiteList(receiver->GetGUID())) - sender->AddWhisperWhiteList(receiver->GetGUID()); + if (!normalizePlayerName(to)) + { + SendPlayerNotFoundNotice(to); + break; + } - GetPlayer()->Whisper(msg, lang, receiver->GetGUID()); - } break; + Player* receiver = ObjectAccessor::FindPlayerByName(to, false); + bool senderIsPlayer = AccountMgr::IsPlayerAccount(GetSecurity()); + bool receiverIsPlayer = AccountMgr::IsPlayerAccount(receiver ? receiver->GetSession()->GetSecurity() : SEC_PLAYER); + if (!receiver || (senderIsPlayer && !receiverIsPlayer && !receiver->isAcceptWhispers() && !receiver->IsInWhisperWhiteList(sender->GetGUID()))) + { + SendPlayerNotFoundNotice(to); + return; + } + + if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) && senderIsPlayer && receiverIsPlayer) + if (GetPlayer()->GetTeamId() != receiver->GetTeamId()) + { + SendWrongFactionNotice(); + return; + } + + // pussywizard: optimization + if (GetPlayer()->HasAura(1852) && !receiver->IsGameMaster()) + { + SendNotification(GetAcoreString(LANG_GM_SILENCE), GetPlayer()->GetName().c_str()); + return; + } + + // If player is a Gamemaster and doesn't accept whisper, we auto-whitelist every player that the Gamemaster is talking to + if (!senderIsPlayer && !sender->isAcceptWhispers() && !sender->IsInWhisperWhiteList(receiver->GetGUID())) + sender->AddWhisperWhiteList(receiver->GetGUID()); + + GetPlayer()->Whisper(msg, lang, receiver->GetGUID()); + } + break; case CHAT_MSG_PARTY: case CHAT_MSG_PARTY_LEADER: - { - // if player is in battleground, he cannot say to battleground members by /p - Group* group = GetPlayer()->GetOriginalGroup(); - if (!group) { - group = sender->GetGroup(); - if (!group || group->isBGGroup()) + // if player is in battleground, he cannot say to battleground members by /p + Group* group = GetPlayer()->GetOriginalGroup(); + if (!group) + { + group = sender->GetGroup(); + if (!group || group->isBGGroup()) + return; + } + + if (type == CHAT_MSG_PARTY_LEADER && !group->IsLeader(sender->GetGUID())) return; - } - if (type == CHAT_MSG_PARTY_LEADER && !group->IsLeader(sender->GetGUID())) - return; - - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); #ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) - return; + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) + return; #endif - WorldPacket data; - ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); - group->BroadcastPacket(&data, false, group->GetMemberGroup(GetPlayer()->GetGUID())); - } break; + WorldPacket data; + ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); + group->BroadcastPacket(&data, false, group->GetMemberGroup(GetPlayer()->GetGUID())); + } + break; case CHAT_MSG_GUILD: - { - if (GetPlayer()->GetGuildId()) { - if (Guild* guild = sGuildMgr->GetGuildById(GetPlayer()->GetGuildId())) + if (GetPlayer()->GetGuildId()) { - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, guild); + if (Guild* guild = sGuildMgr->GetGuildById(GetPlayer()->GetGuildId())) + { + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, guild); #ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, guild)) - return; + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, guild)) + return; #endif - guild->BroadcastToGuild(this, false, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); + guild->BroadcastToGuild(this, false, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); + } } } - } break; + break; case CHAT_MSG_OFFICER: - { - if (GetPlayer()->GetGuildId()) { - if (Guild* guild = sGuildMgr->GetGuildById(GetPlayer()->GetGuildId())) + if (GetPlayer()->GetGuildId()) { - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, guild); + if (Guild* guild = sGuildMgr->GetGuildById(GetPlayer()->GetGuildId())) + { + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, guild); #ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, guild)) - return; + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, guild)) + return; #endif - guild->BroadcastToGuild(this, true, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); + guild->BroadcastToGuild(this, true, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); + } } } - } break; + break; case CHAT_MSG_RAID: - { - // if player is in battleground, he cannot say to battleground members by /ra - Group* group = GetPlayer()->GetOriginalGroup(); - if (!group) { - group = GetPlayer()->GetGroup(); - if (!group || group->isBGGroup() || !group->isRaidGroup()) - return; - } - - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); -#ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) - return; -#endif - WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID, Language(lang), sender, NULL, msg); - group->BroadcastPacket(&data, false); - } break; - case CHAT_MSG_RAID_LEADER: - { - // if player is in battleground, he cannot say to battleground members by /ra - Group* group = GetPlayer()->GetOriginalGroup(); - if (!group) - { - group = GetPlayer()->GetGroup(); - if (!group || group->isBGGroup() || !group->isRaidGroup() || !group->IsLeader(sender->GetGUID())) - return; - } - - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); -#ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) - return; -#endif - WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_LEADER, Language(lang), sender, NULL, msg); - group->BroadcastPacket(&data, false); - } break; - case CHAT_MSG_RAID_WARNING: - { - Group* group = GetPlayer()->GetGroup(); - if (!group || !group->isRaidGroup() || !(group->IsLeader(GetPlayer()->GetGUID()) || group->IsAssistant(GetPlayer()->GetGUID())) || group->isBGGroup()) - return; - - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); -#ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) - return; -#endif - WorldPacket data; - //in battleground, raid warning is sent only to players in battleground - code is ok - ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_WARNING, Language(lang), sender, NULL, msg); - group->BroadcastPacket(&data, false); - } break; - case CHAT_MSG_BATTLEGROUND: - { - //battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() - Group* group = GetPlayer()->GetGroup(); - if (!group || !group->isBGGroup()) - return; - - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); -#ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) - return; -#endif - WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND, Language(lang), sender, NULL, msg); - group->BroadcastPacket(&data, false); - } break; - case CHAT_MSG_BATTLEGROUND_LEADER: - { - // battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() - Group* group = GetPlayer()->GetGroup(); - if (!group || !group->isBGGroup() || !group->IsLeader(GetPlayer()->GetGUID())) - return; - - sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); -#ifdef ELUNA - if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) - return; -#endif - WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND_LEADER, Language(lang), sender, NULL, msg); - group->BroadcastPacket(&data, false); - } break; - case CHAT_MSG_CHANNEL: - { - if (AccountMgr::IsPlayerAccount(GetSecurity())) - { - if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_CHANNEL_LEVEL_REQ)) + // if player is in battleground, he cannot say to battleground members by /ra + Group* group = GetPlayer()->GetOriginalGroup(); + if (!group) { - SendNotification(GetAcoreString(LANG_CHANNEL_REQ), sWorld->getIntConfig(CONFIG_CHAT_CHANNEL_LEVEL_REQ)); + group = GetPlayer()->GetGroup(); + if (!group || group->isBGGroup() || !group->isRaidGroup()) + return; + } + + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); +#ifdef ELUNA + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) return; +#endif + WorldPacket data; + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID, Language(lang), sender, NULL, msg); + group->BroadcastPacket(&data, false); + } + break; + case CHAT_MSG_RAID_LEADER: + { + // if player is in battleground, he cannot say to battleground members by /ra + Group* group = GetPlayer()->GetOriginalGroup(); + if (!group) + { + group = GetPlayer()->GetGroup(); + if (!group || group->isBGGroup() || !group->isRaidGroup() || !group->IsLeader(sender->GetGUID())) + return; + } + + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); +#ifdef ELUNA + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) + return; +#endif + WorldPacket data; + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_LEADER, Language(lang), sender, NULL, msg); + group->BroadcastPacket(&data, false); + } + break; + case CHAT_MSG_RAID_WARNING: + { + Group* group = GetPlayer()->GetGroup(); + if (!group || !group->isRaidGroup() || !(group->IsLeader(GetPlayer()->GetGUID()) || group->IsAssistant(GetPlayer()->GetGUID())) || group->isBGGroup()) + return; + + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); +#ifdef ELUNA + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) + return; +#endif + WorldPacket data; + //in battleground, raid warning is sent only to players in battleground - code is ok + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_WARNING, Language(lang), sender, NULL, msg); + group->BroadcastPacket(&data, false); + } + break; + case CHAT_MSG_BATTLEGROUND: + { + //battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() + Group* group = GetPlayer()->GetGroup(); + if (!group || !group->isBGGroup()) + return; + + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); +#ifdef ELUNA + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) + return; +#endif + WorldPacket data; + ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND, Language(lang), sender, NULL, msg); + group->BroadcastPacket(&data, false); + } + break; + case CHAT_MSG_BATTLEGROUND_LEADER: + { + // battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() + Group* group = GetPlayer()->GetGroup(); + if (!group || !group->isBGGroup() || !group->IsLeader(GetPlayer()->GetGUID())) + return; + + sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); +#ifdef ELUNA + if (!sEluna->OnChat(GetPlayer(), type, lang, msg, group)) + return; +#endif + WorldPacket data; + ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND_LEADER, Language(lang), sender, NULL, msg); + group->BroadcastPacket(&data, false); + } + break; + case CHAT_MSG_CHANNEL: + { + if (AccountMgr::IsPlayerAccount(GetSecurity())) + { + if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_CHANNEL_LEVEL_REQ)) + { + SendNotification(GetAcoreString(LANG_CHANNEL_REQ), sWorld->getIntConfig(CONFIG_CHAT_CHANNEL_LEVEL_REQ)); + return; + } + } + + if (ChannelMgr* cMgr = ChannelMgr::forTeam(sender->GetTeamId())) + { + if (Channel* chn = cMgr->GetChannel(channel, sender)) + { + sScriptMgr->OnPlayerChat(sender, type, lang, msg, chn); + +#ifdef ELUNA + if (!sEluna->OnChat(sender, type, lang, msg, chn)) + return; +#endif + chn->Say(sender->GetGUID(), msg.c_str(), lang); + } } } - - if (ChannelMgr* cMgr = ChannelMgr::forTeam(sender->GetTeamId())) + break; + case CHAT_MSG_AFK: { - if (Channel* chn = cMgr->GetChannel(channel, sender)) + if (!sender->IsInCombat()) { - sScriptMgr->OnPlayerChat(sender, type, lang, msg, chn); + if (sender->isAFK()) // Already AFK + { + if (msg.empty()) + sender->ToggleAFK(); // Remove AFK + else + sender->autoReplyMsg = msg; // Update message + } + else // New AFK mode + { + sender->autoReplyMsg = msg.empty() ? GetAcoreString(LANG_PLAYER_AFK_DEFAULT) : msg; + if (sender->isDND()) + sender->ToggleDND(); + + sender->ToggleAFK(); + } + + sScriptMgr->OnPlayerChat(sender, type, lang, msg); #ifdef ELUNA - if (!sEluna->OnChat(sender, type, lang, msg, chn)) + if (!sEluna->OnChat(sender, type, lang, msg)) return; #endif - chn->Say(sender->GetGUID(), msg.c_str(), lang); } + break; } - } break; - case CHAT_MSG_AFK: - { - if (!sender->IsInCombat()) + case CHAT_MSG_DND: { - if (sender->isAFK()) // Already AFK + if (sender->isDND()) // Already DND { if (msg.empty()) - sender->ToggleAFK(); // Remove AFK + sender->ToggleDND(); // Remove DND else - sender->autoReplyMsg = msg; // Update message + sender->autoReplyMsg = msg; // Update message } - else // New AFK mode + else // New DND mode { - sender->autoReplyMsg = msg.empty() ? GetAcoreString(LANG_PLAYER_AFK_DEFAULT) : msg; + sender->autoReplyMsg = msg.empty() ? GetAcoreString(LANG_PLAYER_DND_DEFAULT) : msg; - if (sender->isDND()) - sender->ToggleDND(); + if (sender->isAFK()) + sender->ToggleAFK(); - sender->ToggleAFK(); + sender->ToggleDND(); } sScriptMgr->OnPlayerChat(sender, type, lang, msg); @@ -597,42 +636,15 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recvData) if (!sEluna->OnChat(sender, type, lang, msg)) return; #endif + break; } - break; - } - case CHAT_MSG_DND: - { - if (sender->isDND()) // Already DND - { - if (msg.empty()) - sender->ToggleDND(); // Remove DND - else - sender->autoReplyMsg = msg; // Update message - } - else // New DND mode - { - sender->autoReplyMsg = msg.empty() ? GetAcoreString(LANG_PLAYER_DND_DEFAULT) : msg; - - if (sender->isAFK()) - sender->ToggleAFK(); - - sender->ToggleDND(); - } - - sScriptMgr->OnPlayerChat(sender, type, lang, msg); -#ifdef ELUNA - if (!sEluna->OnChat(sender, type, lang, msg)) - return; -#endif - break; - } default: sLog->outError("CHAT: unknown message type %u, lang: %u", type, lang); break; } } -void WorldSession::HandleEmoteOpcode(WorldPacket & recvData) +void WorldSession::HandleEmoteOpcode(WorldPacket& recvData) { if (!GetPlayer()->IsAlive() || GetPlayer()->HasUnitState(UNIT_STATE_DIED)) return; @@ -655,35 +667,35 @@ namespace acore { class EmoteChatBuilder { - public: - EmoteChatBuilder(Player const& player, uint32 text_emote, uint32 emote_num, Unit const* target) - : i_player(player), i_text_emote(text_emote), i_emote_num(emote_num), i_target(target) {} + public: + EmoteChatBuilder(Player const& player, uint32 text_emote, uint32 emote_num, Unit const* target) + : i_player(player), i_text_emote(text_emote), i_emote_num(emote_num), i_target(target) {} - void operator()(WorldPacket& data, LocaleConstant loc_idx) - { - std::string const name(i_target ? i_target->GetNameForLocaleIdx(loc_idx) : ""); - uint32 namlen = name.size(); + void operator()(WorldPacket& data, LocaleConstant loc_idx) + { + std::string const name(i_target ? i_target->GetNameForLocaleIdx(loc_idx) : ""); + uint32 namlen = name.size(); - data.Initialize(SMSG_TEXT_EMOTE, 20 + namlen); - data << i_player.GetGUID(); - data << uint32(i_text_emote); - data << uint32(i_emote_num); - data << uint32(namlen); - if (namlen > 1) - data << name; - else - data << uint8(0x00); - } + data.Initialize(SMSG_TEXT_EMOTE, 20 + namlen); + data << i_player.GetGUID(); + data << uint32(i_text_emote); + data << uint32(i_emote_num); + data << uint32(namlen); + if (namlen > 1) + data << name; + else + data << uint8(0x00); + } - private: - Player const& i_player; - uint32 i_text_emote; - uint32 i_emote_num; - Unit const* i_target; + private: + Player const& i_player; + uint32 i_text_emote; + uint32 i_emote_num; + Unit const* i_target; }; } // namespace acore -void WorldSession::HandleTextEmoteOpcode(WorldPacket & recvData) +void WorldSession::HandleTextEmoteOpcode(WorldPacket& recvData) { if (!GetPlayer()->IsAlive()) return; @@ -726,8 +738,8 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket & recvData) // Only allow text-emotes for "dead" entities (feign death included) if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) break; - GetPlayer()->HandleEmoteCommand(emote_anim); - break; + GetPlayer()->HandleEmoteCommand(emote_anim); + break; } Unit* unit = ObjectAccessor::GetUnit(*_player, guid); @@ -768,7 +780,7 @@ void WorldSession::HandleChatIgnoredOpcode(WorldPacket& recvData) player->GetSession()->SendPacket(&data); } -void WorldSession::HandleChannelDeclineInvite(WorldPacket &recvPacket) +void WorldSession::HandleChannelDeclineInvite(WorldPacket& recvPacket) { // used only with EXTRA_LOGS UNUSED(recvPacket); @@ -780,14 +792,14 @@ void WorldSession::HandleChannelDeclineInvite(WorldPacket &recvPacket) void WorldSession::SendPlayerNotFoundNotice(std::string const& name) { - WorldPacket data(SMSG_CHAT_PLAYER_NOT_FOUND, name.size()+1); + WorldPacket data(SMSG_CHAT_PLAYER_NOT_FOUND, name.size() + 1); data << name; SendPacket(&data); } void WorldSession::SendPlayerAmbiguousNotice(std::string const& name) { - WorldPacket data(SMSG_CHAT_PLAYER_AMBIGUOUS, name.size()+1); + WorldPacket data(SMSG_CHAT_PLAYER_AMBIGUOUS, name.size() + 1); data << name; SendPacket(&data); } diff --git a/src/server/game/Handlers/CombatHandler.cpp b/src/server/game/Handlers/CombatHandler.cpp index 288fa5bc4..618081145 100644 --- a/src/server/game/Handlers/CombatHandler.cpp +++ b/src/server/game/Handlers/CombatHandler.cpp @@ -58,7 +58,7 @@ void WorldSession::HandleAttackSwingOpcode(WorldPacket& recvData) _player->Attack(pEnemy, true); } -void WorldSession::HandleAttackStopOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleAttackStopOpcode(WorldPacket& /*recvData*/) { GetPlayer()->AttackStop(); } @@ -81,7 +81,7 @@ void WorldSession::HandleSetSheathedOpcode(WorldPacket& recvData) void WorldSession::SendAttackStop(Unit const* enemy) { - WorldPacket data(SMSG_ATTACKSTOP, (8+8+4)); // we guess size + WorldPacket data(SMSG_ATTACKSTOP, (8 + 8 + 4)); // we guess size data.append(GetPlayer()->GetPackGUID()); data.append(enemy ? enemy->GetPackGUID() : 0); // must be packed guid data << uint32(0); // unk, can be 1 also diff --git a/src/server/game/Handlers/GroupHandler.cpp b/src/server/game/Handlers/GroupHandler.cpp index 14fbc421b..45dfd30bd 100644 --- a/src/server/game/Handlers/GroupHandler.cpp +++ b/src/server/game/Handlers/GroupHandler.cpp @@ -263,7 +263,7 @@ void WorldSession::HandleGroupAcceptOpcode(WorldPacket& recvData) group->BroadcastGroupUpdate(); } -void WorldSession::HandleGroupDeclineOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleGroupDeclineOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GROUP_DECLINE"); @@ -417,7 +417,7 @@ void WorldSession::HandleGroupSetLeaderOpcode(WorldPacket& recvData) group->SendUpdate(); } -void WorldSession::HandleGroupDisbandOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleGroupDisbandOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GROUP_DISBAND"); @@ -524,7 +524,7 @@ void WorldSession::HandleMinimapPingOpcode(WorldPacket& recvData) /********************/ // everything's fine, do it - WorldPacket data(MSG_MINIMAP_PING, (8+4+4)); + WorldPacket data(MSG_MINIMAP_PING, (8 + 4 + 4)); data << uint64(GetPlayer()->GetGUID()); data << float(x); data << float(y); @@ -551,7 +551,7 @@ void WorldSession::HandleRandomRollOpcode(WorldPacket& recvData) //sLog->outDebug("ROLL: MIN: %u, MAX: %u, ROLL: %u", minimum, maximum, roll); - WorldPacket data(MSG_RANDOM_ROLL, 4+4+4+8); + WorldPacket data(MSG_RANDOM_ROLL, 4 + 4 + 4 + 8); data << uint32(minimum); data << uint32(maximum); data << uint32(roll); @@ -603,7 +603,7 @@ void WorldSession::HandleRaidTargetUpdateOpcode(WorldPacket& recvData) } } -void WorldSession::HandleGroupRaidConvertOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleGroupRaidConvertOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GROUP_RAID_CONVERT"); @@ -748,10 +748,10 @@ void WorldSession::HandleRaidReadyCheckOpcode(WorldPacket& recvData) { // Check if player is in BG if (_player->InBattleground()) - { - _player->GetSession()->SendNotification(LANG_BG_READY_CHECK_ERROR); - return; - } + { + _player->GetSession()->SendNotification(LANG_BG_READY_CHECK_ERROR); + return; + } } // everything's fine, do it @@ -774,7 +774,7 @@ void WorldSession::HandleRaidReadyCheckOpcode(WorldPacket& recvData) } } -void WorldSession::HandleRaidReadyCheckFinishedOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleRaidReadyCheckFinishedOpcode(WorldPacket& /*recvData*/) { //Group* group = GetPlayer()->GetGroup(); //if (!group) @@ -965,14 +965,14 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke if (mask & GROUP_UPDATE_FLAG_VEHICLE_SEAT) { if (Vehicle* veh = player->GetVehicle()) - *data << uint32(veh->GetVehicleInfo()->m_seatID[player->m_movementInfo.transport.seat]); + * data << uint32(veh->GetVehicleInfo()->m_seatID[player->m_movementInfo.transport.seat]); else *data << uint32(0); } } /*this procedure handles clients CMSG_REQUEST_PARTY_MEMBER_STATS request*/ -void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket &recvData) +void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_REQUEST_PARTY_MEMBER_STATS"); uint64 Guid; @@ -981,7 +981,7 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket &recvData) Player* player = HashMapHolder::Find(Guid); if (!player) { - WorldPacket data(SMSG_PARTY_MEMBER_STATS_FULL, 3+4+2); + WorldPacket data(SMSG_PARTY_MEMBER_STATS_FULL, 3 + 4 + 2); data << uint8(0); // only for SMSG_PARTY_MEMBER_STATS_FULL, probably arena/bg related data.appendPackGUID(Guid); data << uint32(GROUP_UPDATE_FLAG_STATUS); @@ -993,21 +993,21 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket &recvData) Pet* pet = player->GetPet(); Powers powerType = player->getPowerType(); - WorldPacket data(SMSG_PARTY_MEMBER_STATS_FULL, 4+2+2+2+1+2*6+8+1+8); + WorldPacket data(SMSG_PARTY_MEMBER_STATS_FULL, 4 + 2 + 2 + 2 + 1 + 2 * 6 + 8 + 1 + 8); data << uint8(0); // only for SMSG_PARTY_MEMBER_STATS_FULL, probably arena/bg related data.append(player->GetPackGUID()); uint32 updateFlags = GROUP_UPDATE_FLAG_STATUS | GROUP_UPDATE_FLAG_CUR_HP | GROUP_UPDATE_FLAG_MAX_HP - | GROUP_UPDATE_FLAG_CUR_POWER | GROUP_UPDATE_FLAG_MAX_POWER | GROUP_UPDATE_FLAG_LEVEL - | GROUP_UPDATE_FLAG_ZONE | GROUP_UPDATE_FLAG_POSITION | GROUP_UPDATE_FLAG_AURAS - | GROUP_UPDATE_FLAG_PET_NAME | GROUP_UPDATE_FLAG_PET_MODEL_ID | GROUP_UPDATE_FLAG_PET_AURAS; + | GROUP_UPDATE_FLAG_CUR_POWER | GROUP_UPDATE_FLAG_MAX_POWER | GROUP_UPDATE_FLAG_LEVEL + | GROUP_UPDATE_FLAG_ZONE | GROUP_UPDATE_FLAG_POSITION | GROUP_UPDATE_FLAG_AURAS + | GROUP_UPDATE_FLAG_PET_NAME | GROUP_UPDATE_FLAG_PET_MODEL_ID | GROUP_UPDATE_FLAG_PET_AURAS; if (powerType != POWER_MANA) updateFlags |= GROUP_UPDATE_FLAG_POWER_TYPE; if (pet) updateFlags |= GROUP_UPDATE_FLAG_PET_GUID | GROUP_UPDATE_FLAG_PET_CUR_HP | GROUP_UPDATE_FLAG_PET_MAX_HP - | GROUP_UPDATE_FLAG_PET_POWER_TYPE | GROUP_UPDATE_FLAG_PET_CUR_POWER | GROUP_UPDATE_FLAG_PET_MAX_POWER; + | GROUP_UPDATE_FLAG_PET_POWER_TYPE | GROUP_UPDATE_FLAG_PET_CUR_POWER | GROUP_UPDATE_FLAG_PET_MAX_POWER; if (player->GetVehicle()) updateFlags |= GROUP_UPDATE_FLAG_VEHICLE_SEAT; @@ -1107,7 +1107,7 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket &recvData) SendPacket(&data); } -/*!*/void WorldSession::HandleRequestRaidInfoOpcode(WorldPacket & /*recvData*/) +/*!*/void WorldSession::HandleRequestRaidInfoOpcode(WorldPacket& /*recvData*/) { // every time the player checks the character screen _player->SendRaidInfo(); @@ -1120,7 +1120,7 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket &recvData) #endif }*/ -void WorldSession::HandleOptOutOfLootOpcode(WorldPacket & recvData) +void WorldSession::HandleOptOutOfLootOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_OPT_OUT_OF_LOOT"); diff --git a/src/server/game/Handlers/GuildHandler.cpp b/src/server/game/Handlers/GuildHandler.cpp index 6fb61eaa9..4198b5cd7 100644 --- a/src/server/game/Handlers/GuildHandler.cpp +++ b/src/server/game/Handlers/GuildHandler.cpp @@ -17,7 +17,8 @@ #include "SocialMgr.h" // Cleanup bad characters -void cleanStr(std::string &str) { +void cleanStr(std::string& str) +{ str.erase(remove(str.begin(), str.end(), '|'), str.end()); } @@ -27,7 +28,7 @@ void WorldSession::HandleGuildQueryOpcode(WorldPacket& recvPacket) recvPacket >> guildId; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_QUERY [%s]: Guild: %u", GetPlayerInfo().c_str(), guildId); + sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_QUERY [%s]: Guild: %u", GetPlayerInfo().c_str(), guildId); #endif if (!guildId) return; @@ -226,7 +227,7 @@ void WorldSession::HandleGuildSetOfficerNoteOpcode(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_SET_OFFICER_NOTE [%s]: Target: %s, Note: %s", - GetPlayerInfo().c_str(), playerName.c_str(), note.c_str()); + GetPlayerInfo().c_str(), playerName.c_str(), note.c_str()); #endif // Check for overflow @@ -349,10 +350,10 @@ void WorldSession::HandleSaveGuildEmblemOpcode(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "MSG_SAVE_GUILD_EMBLEM [%s]: Guid: [" UI64FMTD - "] Style: %d, Color: %d, BorderStyle: %d, BorderColor: %d, BackgroundColor: %d" - , GetPlayerInfo().c_str(), vendorGuid, emblemInfo.GetStyle() - , emblemInfo.GetColor(), emblemInfo.GetBorderStyle() - , emblemInfo.GetBorderColor(), emblemInfo.GetBackgroundColor()); + "] Style: %d, Color: %d, BorderStyle: %d, BorderColor: %d, BackgroundColor: %d" + , GetPlayerInfo().c_str(), vendorGuid, emblemInfo.GetStyle() + , emblemInfo.GetColor(), emblemInfo.GetBorderStyle() + , emblemInfo.GetBorderColor(), emblemInfo.GetBackgroundColor()); #endif if (GetPlayer()->GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_TABARDDESIGNER)) { @@ -379,7 +380,7 @@ void WorldSession::HandleGuildEventLogQueryOpcode(WorldPacket& /* recvPacket */) guild->SendEventLog(this); } -void WorldSession::HandleGuildBankMoneyWithdrawn(WorldPacket & /* recvData */) +void WorldSession::HandleGuildBankMoneyWithdrawn(WorldPacket& /* recvData */) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "MSG_GUILD_BANK_MONEY_WITHDRAWN [%s]", GetPlayerInfo().c_str()); @@ -408,9 +409,9 @@ void WorldSession::HandleGuildBankerActivate(WorldPacket& recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_BANKER_ACTIVATE [%s]: Go: [" UI64FMTD "] AllSlots: %u" - , GetPlayerInfo().c_str(), guid, sendAllSlots); + , GetPlayerInfo().c_str(), guid, sendAllSlots); #endif - Guild * const guild = GetPlayer()->GetGuild(); + Guild* const guild = GetPlayer()->GetGuild(); if (!guild) { Guild::SendCommandResult(this, GUILD_COMMAND_VIEW_TAB, ERR_GUILD_PLAYER_NOT_IN_GUILD); @@ -431,7 +432,7 @@ void WorldSession::HandleGuildBankQueryTab(WorldPacket& recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_BANK_QUERY_TAB [%s]: Go: [" UI64FMTD "], TabId: %u, ShowTabs: %u" - , GetPlayerInfo().c_str(), guid, tabId, full); + , GetPlayerInfo().c_str(), guid, tabId, full); #endif if (GetPlayer()->GetGameObjectIfCanInteractWith(guid, GAMEOBJECT_TYPE_GUILD_BANK)) if (Guild* guild = GetPlayer()->GetGuild()) @@ -446,7 +447,7 @@ void WorldSession::HandleGuildBankDepositMoney(WorldPacket& recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_BANK_DEPOSIT_MONEY [%s]: Go: [" UI64FMTD "], money: %u", - GetPlayerInfo().c_str(), guid, money); + GetPlayerInfo().c_str(), guid, money); #endif if (GetPlayer()->GetGameObjectIfCanInteractWith(guid, GAMEOBJECT_TYPE_GUILD_BANK)) if (money && GetPlayer()->HasEnoughMoney(money)) @@ -462,7 +463,7 @@ void WorldSession::HandleGuildBankWithdrawMoney(WorldPacket& recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_BANK_WITHDRAW_MONEY [%s]: Go: [" UI64FMTD "], money: %u", - GetPlayerInfo().c_str(), guid, money); + GetPlayerInfo().c_str(), guid, money); #endif if (money && GetPlayer()->GetGameObjectIfCanInteractWith(guid, GAMEOBJECT_TYPE_GUILD_BANK)) if (Guild* guild = GetPlayer()->GetGuild()) @@ -579,7 +580,7 @@ void WorldSession::HandleGuildBankUpdateTab(WorldPacket& recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_GUILD, "CMSG_GUILD_BANK_UPDATE_TAB [%s]: Go: [" UI64FMTD "], TabId: %u, Name: %s, Icon: %s" - , GetPlayerInfo().c_str(), guid, tabId, name.c_str(), icon.c_str()); + , GetPlayerInfo().c_str(), guid, tabId, name.c_str(), icon.c_str()); #endif // Check for overflow @@ -608,7 +609,7 @@ void WorldSession::HandleGuildBankLogQuery(WorldPacket& recvData) guild->SendBankLog(this, tabId); } -void WorldSession::HandleQueryGuildBankTabText(WorldPacket &recvData) +void WorldSession::HandleQueryGuildBankTabText(WorldPacket& recvData) { uint8 tabId; recvData >> tabId; @@ -621,7 +622,7 @@ void WorldSession::HandleQueryGuildBankTabText(WorldPacket &recvData) guild->SendBankTabText(this, tabId); } -void WorldSession::HandleSetGuildBankTabText(WorldPacket &recvData) +void WorldSession::HandleSetGuildBankTabText(WorldPacket& recvData) { uint8 tabId; std::string text; diff --git a/src/server/game/Handlers/ItemHandler.cpp b/src/server/game/Handlers/ItemHandler.cpp index bde1340f5..30874d70d 100644 --- a/src/server/game/Handlers/ItemHandler.cpp +++ b/src/server/game/Handlers/ItemHandler.cpp @@ -16,7 +16,7 @@ #include "ObjectAccessor.h" #include "SpellInfo.h" -void WorldSession::HandleSplitItemOpcode(WorldPacket & recvData) +void WorldSession::HandleSplitItemOpcode(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_SPLIT_ITEM"); uint8 srcbag, srcslot, dstbag, dstslot; @@ -49,7 +49,7 @@ void WorldSession::HandleSplitItemOpcode(WorldPacket & recvData) _player->SplitItem(src, dst, count); } -void WorldSession::HandleSwapInvItemOpcode(WorldPacket & recvData) +void WorldSession::HandleSwapInvItemOpcode(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_SWAP_INV_ITEM"); uint8 srcslot, dstslot; @@ -91,7 +91,7 @@ void WorldSession::HandleSwapInvItemOpcode(WorldPacket & recvData) _player->SwapItem(src, dst); } -void WorldSession::HandleAutoEquipItemSlotOpcode(WorldPacket & recvData) +void WorldSession::HandleAutoEquipItemSlotOpcode(WorldPacket& recvData) { uint64 itemguid; uint8 dstslot; @@ -110,7 +110,7 @@ void WorldSession::HandleAutoEquipItemSlotOpcode(WorldPacket & recvData) _player->SwapItem(item->GetPos(), dstpos); } -void WorldSession::HandleSwapItem(WorldPacket & recvData) +void WorldSession::HandleSwapItem(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_SWAP_ITEM"); uint8 dstbag, dstslot, srcbag, srcslot; @@ -152,7 +152,7 @@ void WorldSession::HandleSwapItem(WorldPacket & recvData) _player->SwapItem(src, dst); } -void WorldSession::HandleAutoEquipItemOpcode(WorldPacket & recvData) +void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_AUTOEQUIP_ITEM"); uint8 srcbag, srcslot; @@ -249,7 +249,7 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket & recvData) } } -void WorldSession::HandleDestroyItemOpcode(WorldPacket & recvData) +void WorldSession::HandleDestroyItemOpcode(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_DESTROYITEM"); uint8 bag, slot, count, data1, data2, data3; @@ -424,7 +424,7 @@ void ItemTemplate::InitializeQueryData() } // Only _static_ data send in this packet !!! -void WorldSession::HandleItemQuerySingleOpcode(WorldPacket & recvData) +void WorldSession::HandleItemQuerySingleOpcode(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_ITEM_QUERY_SINGLE"); uint32 item; @@ -437,144 +437,144 @@ void WorldSession::HandleItemQuerySingleOpcode(WorldPacket & recvData) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item); if (pProto) { - std::string Name = pProto->Name1; - std::string Description = pProto->Description; + std::string Name = pProto->Name1; + std::string Description = pProto->Description; - int loc_idx = GetSessionDbLocaleIndex(); - if (loc_idx >= 0) - { - if (ItemLocale const* il = sObjectMgr->GetItemLocale(pProto->ItemId)) - { - ObjectMgr::GetLocaleString(il->Name, loc_idx, Name); - ObjectMgr::GetLocaleString(il->Description, loc_idx, Description); - } - } - // guess size - WorldPacket queryData(SMSG_ITEM_QUERY_SINGLE_RESPONSE, 600); - queryData << pProto->ItemId; - queryData << pProto->Class; - queryData << pProto->SubClass; - queryData << pProto->SoundOverrideSubclass; - queryData << Name; - queryData << uint8(0x00); //pProto->Name2; // blizz not send name there, just uint8(0x00); <-- \0 = empty string = empty name... - queryData << uint8(0x00); //pProto->Name3; // blizz not send name there, just uint8(0x00); - queryData << uint8(0x00); //pProto->Name4; // blizz not send name there, just uint8(0x00); - queryData << pProto->DisplayInfoID; - queryData << pProto->Quality; - queryData << pProto->Flags; - queryData << pProto->Flags2; - queryData << pProto->BuyPrice; - queryData << pProto->SellPrice; - queryData << pProto->InventoryType; - queryData << pProto->AllowableClass; - queryData << pProto->AllowableRace; - queryData << pProto->ItemLevel; - queryData << pProto->RequiredLevel; - queryData << pProto->RequiredSkill; - queryData << pProto->RequiredSkillRank; - queryData << pProto->RequiredSpell; - queryData << pProto->RequiredHonorRank; - queryData << pProto->RequiredCityRank; - queryData << pProto->RequiredReputationFaction; - queryData << pProto->RequiredReputationRank; - queryData << int32(pProto->MaxCount); - queryData << int32(pProto->Stackable); - queryData << pProto->ContainerSlots; - queryData << pProto->StatsCount; // item stats count - for (uint32 i = 0; i < pProto->StatsCount; ++i) - { - queryData << pProto->ItemStat[i].ItemStatType; - queryData << pProto->ItemStat[i].ItemStatValue; - } - queryData << pProto->ScalingStatDistribution; // scaling stats distribution - queryData << pProto->ScalingStatValue; // some kind of flags used to determine stat values column - for (int i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) - { - queryData << pProto->Damage[i].DamageMin; - queryData << pProto->Damage[i].DamageMax; - queryData << pProto->Damage[i].DamageType; - } + int loc_idx = GetSessionDbLocaleIndex(); + if (loc_idx >= 0) + { + if (ItemLocale const* il = sObjectMgr->GetItemLocale(pProto->ItemId)) + { + ObjectMgr::GetLocaleString(il->Name, loc_idx, Name); + ObjectMgr::GetLocaleString(il->Description, loc_idx, Description); + } + } + // guess size + WorldPacket queryData(SMSG_ITEM_QUERY_SINGLE_RESPONSE, 600); + queryData << pProto->ItemId; + queryData << pProto->Class; + queryData << pProto->SubClass; + queryData << pProto->SoundOverrideSubclass; + queryData << Name; + queryData << uint8(0x00); //pProto->Name2; // blizz not send name there, just uint8(0x00); <-- \0 = empty string = empty name... + queryData << uint8(0x00); //pProto->Name3; // blizz not send name there, just uint8(0x00); + queryData << uint8(0x00); //pProto->Name4; // blizz not send name there, just uint8(0x00); + queryData << pProto->DisplayInfoID; + queryData << pProto->Quality; + queryData << pProto->Flags; + queryData << pProto->Flags2; + queryData << pProto->BuyPrice; + queryData << pProto->SellPrice; + queryData << pProto->InventoryType; + queryData << pProto->AllowableClass; + queryData << pProto->AllowableRace; + queryData << pProto->ItemLevel; + queryData << pProto->RequiredLevel; + queryData << pProto->RequiredSkill; + queryData << pProto->RequiredSkillRank; + queryData << pProto->RequiredSpell; + queryData << pProto->RequiredHonorRank; + queryData << pProto->RequiredCityRank; + queryData << pProto->RequiredReputationFaction; + queryData << pProto->RequiredReputationRank; + queryData << int32(pProto->MaxCount); + queryData << int32(pProto->Stackable); + queryData << pProto->ContainerSlots; + queryData << pProto->StatsCount; // item stats count + for (uint32 i = 0; i < pProto->StatsCount; ++i) + { + queryData << pProto->ItemStat[i].ItemStatType; + queryData << pProto->ItemStat[i].ItemStatValue; + } + queryData << pProto->ScalingStatDistribution; // scaling stats distribution + queryData << pProto->ScalingStatValue; // some kind of flags used to determine stat values column + for (int i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) + { + queryData << pProto->Damage[i].DamageMin; + queryData << pProto->Damage[i].DamageMax; + queryData << pProto->Damage[i].DamageType; + } - // resistances (7) - queryData << pProto->Armor; - queryData << pProto->HolyRes; - queryData << pProto->FireRes; - queryData << pProto->NatureRes; - queryData << pProto->FrostRes; - queryData << pProto->ShadowRes; - queryData << pProto->ArcaneRes; + // resistances (7) + queryData << pProto->Armor; + queryData << pProto->HolyRes; + queryData << pProto->FireRes; + queryData << pProto->NatureRes; + queryData << pProto->FrostRes; + queryData << pProto->ShadowRes; + queryData << pProto->ArcaneRes; - queryData << pProto->Delay; - queryData << pProto->AmmoType; - queryData << pProto->RangedModRange; + queryData << pProto->Delay; + queryData << pProto->AmmoType; + queryData << pProto->RangedModRange; - for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s) - { - // send DBC data for cooldowns in same way as it used in Spell::SendSpellCooldown - // use `item_template` or if not set then only use spell cooldowns - SpellInfo const* spell = sSpellMgr->GetSpellInfo(pProto->Spells[s].SpellId); - if (spell) - { - bool db_data = pProto->Spells[s].SpellCooldown >= 0 || pProto->Spells[s].SpellCategoryCooldown >= 0; + for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s) + { + // send DBC data for cooldowns in same way as it used in Spell::SendSpellCooldown + // use `item_template` or if not set then only use spell cooldowns + SpellInfo const* spell = sSpellMgr->GetSpellInfo(pProto->Spells[s].SpellId); + if (spell) + { + bool db_data = pProto->Spells[s].SpellCooldown >= 0 || pProto->Spells[s].SpellCategoryCooldown >= 0; - queryData << pProto->Spells[s].SpellId; - queryData << pProto->Spells[s].SpellTrigger; - queryData << uint32(-abs(pProto->Spells[s].SpellCharges)); + queryData << pProto->Spells[s].SpellId; + queryData << pProto->Spells[s].SpellTrigger; + queryData << uint32(-abs(pProto->Spells[s].SpellCharges)); - if (db_data) - { - queryData << uint32(pProto->Spells[s].SpellCooldown); - queryData << uint32(pProto->Spells[s].SpellCategory); - queryData << uint32(pProto->Spells[s].SpellCategoryCooldown); - } - else - { - queryData << uint32(spell->RecoveryTime); - queryData << uint32(spell->GetCategory()); - queryData << uint32(spell->CategoryRecoveryTime); - } - } - else - { - queryData << uint32(0); - queryData << uint32(0); - queryData << uint32(0); - queryData << uint32(-1); - queryData << uint32(0); - queryData << uint32(-1); - } - } - queryData << pProto->Bonding; - queryData << Description; - queryData << pProto->PageText; - queryData << pProto->LanguageID; - queryData << pProto->PageMaterial; - queryData << pProto->StartQuest; - queryData << pProto->LockID; - queryData << int32(pProto->Material); - queryData << pProto->Sheath; - queryData << pProto->RandomProperty; - queryData << pProto->RandomSuffix; - queryData << pProto->Block; - queryData << pProto->ItemSet; - queryData << pProto->MaxDurability; - queryData << pProto->Area; - queryData << pProto->Map; // Added in 1.12.x & 2.0.1 client branch - queryData << pProto->BagFamily; - queryData << pProto->TotemCategory; - for (int s = 0; s < MAX_ITEM_PROTO_SOCKETS; ++s) - { - queryData << pProto->Socket[s].Color; - queryData << pProto->Socket[s].Content; - } - queryData << pProto->socketBonus; - queryData << pProto->GemProperties; - queryData << pProto->RequiredDisenchantSkill; - queryData << pProto->ArmorDamageModifier; - queryData << pProto->Duration; // added in 2.4.2.8209, duration (seconds) - queryData << pProto->ItemLimitCategory; // WotLK, ItemLimitCategory - queryData << pProto->HolidayId; // Holiday.dbc? - SendPacket(&queryData); + if (db_data) + { + queryData << uint32(pProto->Spells[s].SpellCooldown); + queryData << uint32(pProto->Spells[s].SpellCategory); + queryData << uint32(pProto->Spells[s].SpellCategoryCooldown); + } + else + { + queryData << uint32(spell->RecoveryTime); + queryData << uint32(spell->GetCategory()); + queryData << uint32(spell->CategoryRecoveryTime); + } + } + else + { + queryData << uint32(0); + queryData << uint32(0); + queryData << uint32(0); + queryData << uint32(-1); + queryData << uint32(0); + queryData << uint32(-1); + } + } + queryData << pProto->Bonding; + queryData << Description; + queryData << pProto->PageText; + queryData << pProto->LanguageID; + queryData << pProto->PageMaterial; + queryData << pProto->StartQuest; + queryData << pProto->LockID; + queryData << int32(pProto->Material); + queryData << pProto->Sheath; + queryData << pProto->RandomProperty; + queryData << pProto->RandomSuffix; + queryData << pProto->Block; + queryData << pProto->ItemSet; + queryData << pProto->MaxDurability; + queryData << pProto->Area; + queryData << pProto->Map; // Added in 1.12.x & 2.0.1 client branch + queryData << pProto->BagFamily; + queryData << pProto->TotemCategory; + for (int s = 0; s < MAX_ITEM_PROTO_SOCKETS; ++s) + { + queryData << pProto->Socket[s].Color; + queryData << pProto->Socket[s].Content; + } + queryData << pProto->socketBonus; + queryData << pProto->GemProperties; + queryData << pProto->RequiredDisenchantSkill; + queryData << pProto->ArmorDamageModifier; + queryData << pProto->Duration; // added in 2.4.2.8209, duration (seconds) + queryData << pProto->ItemLimitCategory; // WotLK, ItemLimitCategory + queryData << pProto->HolidayId; // Holiday.dbc? + SendPacket(&queryData); } else { @@ -587,7 +587,7 @@ void WorldSession::HandleItemQuerySingleOpcode(WorldPacket & recvData) } } -void WorldSession::HandleReadItem(WorldPacket & recvData) +void WorldSession::HandleReadItem(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_READ_ITEM"); @@ -624,7 +624,7 @@ void WorldSession::HandleReadItem(WorldPacket & recvData) _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, nullptr); } -void WorldSession::HandleSellItemOpcode(WorldPacket & recvData) +void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_SELL_ITEM"); @@ -746,7 +746,7 @@ void WorldSession::HandleSellItemOpcode(WorldPacket & recvData) return; } -void WorldSession::HandleBuybackItem(WorldPacket & recvData) +void WorldSession::HandleBuybackItem(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_BUYBACK_ITEM"); @@ -807,7 +807,7 @@ void WorldSession::HandleBuybackItem(WorldPacket & recvData) _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, 0, 0); } -void WorldSession::HandleBuyItemInSlotOpcode(WorldPacket & recvData) +void WorldSession::HandleBuyItemInSlotOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_BUY_ITEM_IN_SLOT"); @@ -851,7 +851,7 @@ void WorldSession::HandleBuyItemInSlotOpcode(WorldPacket & recvData) GetPlayer()->BuyItemFromVendorSlot(vendorguid, slot, item, count, bag, bagslot); } -void WorldSession::HandleBuyItemOpcode(WorldPacket & recvData) +void WorldSession::HandleBuyItemOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_BUY_ITEM"); @@ -871,7 +871,7 @@ void WorldSession::HandleBuyItemOpcode(WorldPacket & recvData) GetPlayer()->BuyItemFromVendorSlot(vendorguid, slot, item, count, NULL_BAG, NULL_SLOT); } -void WorldSession::HandleListInventoryOpcode(WorldPacket & recvData) +void WorldSession::HandleListInventoryOpcode(WorldPacket& recvData) { uint64 guid; @@ -991,7 +991,7 @@ void WorldSession::SendListInventory(uint64 vendorGuid, uint32 vendorEntry) SendPacket(&data); } -void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket & recvData) +void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) { //sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_AUTOSTORE_BAG_ITEM"); uint8 srcbag, srcslot, dstbag; @@ -1090,8 +1090,8 @@ void WorldSession::HandleBuyBankSlotOpcode(WorldPacket& recvPacket) _player->SetBankBagSlotCount(slot); _player->ModifyMoney(-int32(price)); - data << uint32(ERR_BANKSLOT_OK); - SendPacket(&data); + data << uint32(ERR_BANKSLOT_OK); + SendPacket(&data); _player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT); } @@ -1190,7 +1190,7 @@ void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket) } } -void WorldSession::HandleSetAmmoOpcode(WorldPacket & recvData) +void WorldSession::HandleSetAmmoOpcode(WorldPacket& recvData) { if (!_player->IsAlive()) { @@ -1221,7 +1221,7 @@ void WorldSession::HandleSetAmmoOpcode(WorldPacket & recvData) void WorldSession::SendEnchantmentLog(uint64 target, uint64 caster, uint32 itemId, uint32 enchantId) { - WorldPacket data(SMSG_ENCHANTMENTLOG, (8+8+4+4)); // last check 2.0.10 + WorldPacket data(SMSG_ENCHANTMENTLOG, (8 + 8 + 4 + 4)); // last check 2.0.10 data.appendPackGUID(target); data.appendPackGUID(caster); data << uint32(itemId); @@ -1231,8 +1231,8 @@ void WorldSession::SendEnchantmentLog(uint64 target, uint64 caster, uint32 itemI void WorldSession::SendItemEnchantTimeUpdate(uint64 Playerguid, uint64 Itemguid, uint32 slot, uint32 Duration) { - // last check 2.0.10 - WorldPacket data(SMSG_ITEM_ENCHANT_TIME_UPDATE, (8+4+4+8)); + // last check 2.0.10 + WorldPacket data(SMSG_ITEM_ENCHANT_TIME_UPDATE, (8 + 4 + 4 + 8)); data << uint64(Itemguid); data << uint32(slot); data << uint32(Duration); @@ -1240,7 +1240,7 @@ void WorldSession::SendItemEnchantTimeUpdate(uint64 Playerguid, uint64 Itemguid, SendPacket(&data); } -void WorldSession::HandleItemNameQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleItemNameQueryOpcode(WorldPacket& recvData) { uint32 itemid; recvData >> itemid; @@ -1258,7 +1258,7 @@ void WorldSession::HandleItemNameQueryOpcode(WorldPacket & recvData) if (ItemSetNameLocale const* isnl = sObjectMgr->GetItemSetNameLocale(itemid)) ObjectMgr::GetLocaleString(isnl->Name, loc_idx, Name); - WorldPacket data(SMSG_ITEM_NAME_QUERY_RESPONSE, (4+Name.size()+1+4)); + WorldPacket data(SMSG_ITEM_NAME_QUERY_RESPONSE, (4 + Name.size() + 1 + 4)); data << uint32(itemid); data << Name; data << uint32(pName->InventoryType); @@ -1346,7 +1346,7 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) } // maybe not correct check (it is better than nothing) - if (item->GetTemplate()->MaxCount>0) + if (item->GetTemplate()->MaxCount > 0) { _player->SendEquipError(EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED, item, nullptr); return; @@ -1365,12 +1365,24 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) switch (item->GetEntry()) { - case 5042: item->SetEntry(5043); break; - case 5048: item->SetEntry(5044); break; - case 17303: item->SetEntry(17302); break; - case 17304: item->SetEntry(17305); break; - case 17307: item->SetEntry(17308); break; - case 21830: item->SetEntry(21831); break; + case 5042: + item->SetEntry(5043); + break; + case 5048: + item->SetEntry(5044); + break; + case 17303: + item->SetEntry(17302); + break; + case 17304: + item->SetEntry(17305); + break; + case 17307: + item->SetEntry(17308); + break; + case 21830: + item->SetEntry(21831); + break; } item->SetUInt64Value(ITEM_FIELD_GIFTCREATOR, _player->GetGUID()); item->SetUInt32Value(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED); @@ -1403,7 +1415,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) //cheat -> tried to socket same gem multiple times if ((gem_guids[0] && (gem_guids[0] == gem_guids[1] || gem_guids[0] == gem_guids[2])) || - (gem_guids[1] && (gem_guids[1] == gem_guids[2]))) + (gem_guids[1] && (gem_guids[1] == gem_guids[2]))) return; Item* itemTarget = _player->GetItemByGuid(item_guid); @@ -1460,7 +1472,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) for (int i = 0; i < MAX_GEM_SOCKETS; ++i) //get new and old enchantments { GemEnchants[i] = (GemProps[i]) ? GemProps[i]->spellitemenchantement : 0; - OldEnchants[i] = itemTarget->GetEnchantmentId(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT+i)); + OldEnchants[i] = itemTarget->GetEnchantmentId(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i)); } // check unique-equipped conditions @@ -1559,13 +1571,13 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (GemEnchants[i]) { - itemTarget->SetEnchantment(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT+i), GemEnchants[i], 0, 0, _player->GetGUID()); + itemTarget->SetEnchantment(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i), GemEnchants[i], 0, 0, _player->GetGUID()); if (Item* guidItem = _player->GetItemByGuid(gem_guids[i])) _player->DestroyItem(guidItem->GetBagSlot(), guidItem->GetSlot(), true); } } - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) _player->ApplyEnchantment(itemTarget, EnchantmentSlot(enchant_slot), true); bool SocketBonusToBeActivated = itemTarget->GemsFitSockets();//current socketbonus state @@ -1632,7 +1644,7 @@ void WorldSession::HandleItemRefundInfoRequest(WorldPacket& recvData) GetPlayer()->SendRefundInfo(item); } -void WorldSession::HandleItemRefund(WorldPacket &recvData) +void WorldSession::HandleItemRefund(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_ITEM_REFUND"); @@ -1661,7 +1673,7 @@ void WorldSession::HandleItemRefund(WorldPacket &recvData) * * This function is called when player clicks on item which has some flag set */ -void WorldSession::HandleItemTextQuery(WorldPacket & recvData ) +void WorldSession::HandleItemTextQuery(WorldPacket& recvData ) { uint64 itemGuid; recvData >> itemGuid; @@ -1707,8 +1719,8 @@ bool WorldSession::CanUseBank(uint64 bankerGUID) const bool WorldSession::recoveryItem(Item* pItem) { if (sWorld->getBoolConfig(CONFIG_ITEMDELETE_METHOD) - && pItem->GetTemplate()->Quality >= sWorld->getIntConfig(CONFIG_ITEMDELETE_QUALITY) - && pItem->GetTemplate()->ItemLevel >= sWorld->getIntConfig(CONFIG_ITEMDELETE_ITEM_LEVEL)) + && pItem->GetTemplate()->Quality >= sWorld->getIntConfig(CONFIG_ITEMDELETE_QUALITY) + && pItem->GetTemplate()->ItemLevel >= sWorld->getIntConfig(CONFIG_ITEMDELETE_ITEM_LEVEL)) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_RECOVERY_ITEM); diff --git a/src/server/game/Handlers/LFGHandler.cpp b/src/server/game/Handlers/LFGHandler.cpp index c1745405c..1e3a8d103 100644 --- a/src/server/game/Handlers/LFGHandler.cpp +++ b/src/server/game/Handlers/LFGHandler.cpp @@ -344,7 +344,7 @@ void WorldSession::SendLfgUpdatePlayer(lfg::LfgUpdateData const& updateData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_UPDATE_PLAYER %s updatetype: %u", - GetPlayerInfo().c_str(), updateData.updateType); + GetPlayerInfo().c_str(), updateData.updateType); #endif WorldPacket data(SMSG_LFG_UPDATE_PLAYER, 1 + 1 + (size > 0 ? 1 : 0) * (1 + 1 + 1 + 1 + size * 4 + updateData.comment.length())); data << uint8(updateData.updateType); // Lfg Update type @@ -387,7 +387,7 @@ void WorldSession::SendLfgUpdateParty(lfg::LfgUpdateData const& updateData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_UPDATE_PARTY %s updatetype: %u", - GetPlayerInfo().c_str(), updateData.updateType); + GetPlayerInfo().c_str(), updateData.updateType); #endif WorldPacket data(SMSG_LFG_UPDATE_PARTY, 1 + 1 + (size > 0 ? 1 : 0) * (1 + 1 + 1 + 1 + 1 + size * 4 + updateData.comment.length())); data << uint8(updateData.updateType); // Lfg Update type @@ -492,9 +492,9 @@ void WorldSession::SendLfgQueueStatus(lfg::LfgQueueStatusData const& queueData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "SMSG_LFG_QUEUE_STATUS [" UI64FMTD "] dungeon: %u - waitTime: %d - avgWaitTime: %d - waitTimeTanks: %d - waitTimeHealer: %d - waitTimeDps: %d - queuedTime: %u - tanks: %u - healers: %u - dps: %u", - GetPlayer()->GetGUID(), queueData.dungeonId, queueData.waitTime, queueData.waitTimeAvg, queueData.waitTimeTank, queueData.waitTimeHealer, queueData.waitTimeDps, queueData.queuedTime, queueData.tanks, queueData.healers, queueData.dps); + GetPlayer()->GetGUID(), queueData.dungeonId, queueData.waitTime, queueData.waitTimeAvg, queueData.waitTimeTank, queueData.waitTimeHealer, queueData.waitTimeDps, queueData.queuedTime, queueData.tanks, queueData.healers, queueData.dps); #endif - WorldPacket data(SMSG_LFG_QUEUE_STATUS, 4 + 4 + 4 + 4 + 4 +4 + 1 + 1 + 1 + 4); + WorldPacket data(SMSG_LFG_QUEUE_STATUS, 4 + 4 + 4 + 4 + 4 + 4 + 1 + 1 + 1 + 4); data << uint32(queueData.dungeonId); // Dungeon data << int32(queueData.waitTimeAvg); // Average Wait time data << int32(queueData.waitTime); // Wait Time @@ -514,7 +514,7 @@ void WorldSession::SendLfgPlayerReward(lfg::LfgPlayerRewardData const& rewardDat return; sLog->outDebug(LOG_FILTER_LFG, "SMSG_LFG_PLAYER_REWARD %s rdungeonEntry: %u, sdungeonEntry: %u, done: %u", - GetPlayerInfo().c_str(), rewardData.rdungeonEntry, rewardData.sdungeonEntry, rewardData.done); + GetPlayerInfo().c_str(), rewardData.rdungeonEntry, rewardData.sdungeonEntry, rewardData.done); uint8 itemNum = rewardData.quest->GetRewItemsCount(); @@ -560,7 +560,7 @@ void WorldSession::SendLfgBootProposalUpdate(lfg::LfgPlayerBoot const& boot) } #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "SMSG_LFG_BOOT_PROPOSAL_UPDATE [" UI64FMTD "] inProgress: %u - didVote: %u - agree: %u - victim: [" UI64FMTD "] votes: %u - agrees: %u - left: %u - needed: %u - reason %s", - guid, uint8(boot.inProgress), uint8(playerVote != lfg::LFG_ANSWER_PENDING), uint8(playerVote == lfg::LFG_ANSWER_AGREE), boot.victim, votesNum, agreeNum, secsleft, lfg::LFG_GROUP_KICK_VOTES_NEEDED, boot.reason.c_str()); + guid, uint8(boot.inProgress), uint8(playerVote != lfg::LFG_ANSWER_PENDING), uint8(playerVote == lfg::LFG_ANSWER_AGREE), boot.victim, votesNum, agreeNum, secsleft, lfg::LFG_GROUP_KICK_VOTES_NEEDED, boot.reason.c_str()); #endif WorldPacket data(SMSG_LFG_BOOT_PROPOSAL_UPDATE, 1 + 1 + 1 + 8 + 4 + 4 + 4 + 4 + boot.reason.length()); data << uint8(boot.inProgress); // Vote in progress @@ -596,7 +596,7 @@ void WorldSession::SendLfgUpdateProposal(lfg::LfgProposal const& proposal) dungeonEntry = sLFGMgr->GetLFGDungeonEntry(dungeonEntry); - WorldPacket data(SMSG_LFG_PROPOSAL_UPDATE, 4 + 1 + 4 + 4 + 1 + 1 + proposal.players.size() * (4 + 1 + 1 + 1 + 1 +1)); + WorldPacket data(SMSG_LFG_PROPOSAL_UPDATE, 4 + 1 + 4 + 4 + 1 + 1 + proposal.players.size() * (4 + 1 + 1 + 1 + 1 + 1)); data << uint32(dungeonEntry); // Dungeon data << uint8(proposal.state); // Proposal state data << uint32(proposal.id); // Proposal ID diff --git a/src/server/game/Handlers/LootHandler.cpp b/src/server/game/Handlers/LootHandler.cpp index 32066cba5..d95ff121d 100644 --- a/src/server/game/Handlers/LootHandler.cpp +++ b/src/server/game/Handlers/LootHandler.cpp @@ -97,7 +97,7 @@ void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recvData) DoLootRelease(lguid); } -void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_LOOT_MONEY"); @@ -114,51 +114,51 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recvData*/) switch (GUID_HIPART(guid)) { case HIGHGUID_GAMEOBJECT: - { - GameObject* go = GetPlayer()->GetMap()->GetGameObject(guid); + { + GameObject* go = GetPlayer()->GetMap()->GetGameObject(guid); - // do not check distance for GO if player is the owner of it (ex. fishing bobber) - if (go && ((go->GetOwnerGUID() == player->GetGUID() || go->IsWithinDistInMap(player, INTERACTION_DISTANCE)))) - loot = &go->loot; + // do not check distance for GO if player is the owner of it (ex. fishing bobber) + if (go && ((go->GetOwnerGUID() == player->GetGUID() || go->IsWithinDistInMap(player, INTERACTION_DISTANCE)))) + loot = &go->loot; - break; - } + break; + } case HIGHGUID_CORPSE: // remove insignia ONLY in BG - { - Corpse* bones = ObjectAccessor::GetCorpse(*player, guid); - - if (bones && bones->IsWithinDistInMap(player, INTERACTION_DISTANCE)) { - loot = &bones->loot; - shareMoney = false; - } + Corpse* bones = ObjectAccessor::GetCorpse(*player, guid); - break; - } + if (bones && bones->IsWithinDistInMap(player, INTERACTION_DISTANCE)) + { + loot = &bones->loot; + shareMoney = false; + } + + break; + } case HIGHGUID_ITEM: - { - if (Item* item = player->GetItemByGuid(guid)) { - loot = &item->loot; - shareMoney = false; + if (Item* item = player->GetItemByGuid(guid)) + { + loot = &item->loot; + shareMoney = false; + } + break; } - break; - } case HIGHGUID_UNIT: case HIGHGUID_VEHICLE: - { - Creature* creature = player->GetMap()->GetCreature(guid); - bool lootAllowed = creature && creature->IsAlive() == (player->getClass() == CLASS_ROGUE && creature->loot.loot_type == LOOT_PICKPOCKETING); - if (lootAllowed && creature->IsWithinDistInMap(player, INTERACTION_DISTANCE)) { - loot = &creature->loot; - if (creature->IsAlive()) - shareMoney = false; + Creature* creature = player->GetMap()->GetCreature(guid); + bool lootAllowed = creature && creature->IsAlive() == (player->getClass() == CLASS_ROGUE && creature->loot.loot_type == LOOT_PICKPOCKETING); + if (lootAllowed && creature->IsWithinDistInMap(player, INTERACTION_DISTANCE)) + { + loot = &creature->loot; + if (creature->IsAlive()) + shareMoney = false; + } + else + player->SendLootError(guid, lootAllowed ? LOOT_ERROR_TOO_FAR : LOOT_ERROR_DIDNT_KILL); + break; } - else - player->SendLootError(guid, lootAllowed ? LOOT_ERROR_TOO_FAR : LOOT_ERROR_DIDNT_KILL); - break; - } default: return; // unlootable type } @@ -257,8 +257,8 @@ void WorldSession::HandleLootReleaseOpcode(WorldPacket& recvData) void WorldSession::DoLootRelease(uint64 lguid) { - Player *player = GetPlayer(); - Loot *loot; + Player* player = GetPlayer(); + Loot* loot; player->SetLootGUID(0); player->SendLootRelease(lguid); @@ -286,7 +286,8 @@ void WorldSession::DoLootRelease(uint64 lguid) else if (loot->isLooted() || go->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE) { if (go->GetGoType() == GAMEOBJECT_TYPE_FISHINGHOLE) - { // The fishing hole used once more + { + // The fishing hole used once more go->AddUse(); // if the max usage is reached, will be despawned in next tick if (go->GetUseCount() >= go->GetGOValue()->FishingHole.MaxOpens) go->SetLootState(GO_JUST_DEACTIVATED); @@ -295,8 +296,8 @@ void WorldSession::DoLootRelease(uint64 lguid) } else { - go->SetLootState(GO_JUST_DEACTIVATED); - + go->SetLootState(GO_JUST_DEACTIVATED); + // Xinef: moved event execution to loot release (after everything is looted) // Xinef: 99% sure that this worked like this on blizz // Xinef: prevents exploits with just opening GO and spawning bilions of npcs, which can crash core if you know what you're doin ;) @@ -504,8 +505,8 @@ void WorldSession::HandleLootMasterGiveOpcode(WorldPacket& recvData) #endif // mark as looted - item.count=0; - item.is_looted=true; + item.count = 0; + item.is_looted = true; loot->NotifyItemRemoved(slotid); --loot->unlootedCount; diff --git a/src/server/game/Handlers/MailHandler.cpp b/src/server/game/Handlers/MailHandler.cpp index 06b6868a6..c6603b1df 100644 --- a/src/server/game/Handlers/MailHandler.cpp +++ b/src/server/game/Handlers/MailHandler.cpp @@ -46,7 +46,7 @@ bool WorldSession::CanOpenMailBox(uint64 guid) return true; } -void WorldSession::HandleSendMail(WorldPacket & recvData) +void WorldSession::HandleSendMail(WorldPacket& recvData) { uint64 mailbox, unk3; std::string receiver, subject, body; @@ -59,7 +59,8 @@ void WorldSession::HandleSendMail(WorldPacket & recvData) recvData >> subject; // prevent client crash - if (subject.find("| |") != std::string::npos || body.find("| |") != std::string::npos) { + if (subject.find("| |") != std::string::npos || body.find("| |") != std::string::npos) + { return; } @@ -196,8 +197,8 @@ void WorldSession::HandleSendMail(WorldPacket & recvData) }*/ uint32 rc_account = receive - ? receive->GetSession()->GetAccountId() - : sObjectMgr->GetPlayerAccountIdByGUID(rc); + ? receive->GetSession()->GetAccountId() + : sObjectMgr->GetPlayerAccountIdByGUID(rc); if (/*!accountBound*/ GetAccountId() != rc_account && !sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL) && player->GetTeamId() != rc_teamId && AccountMgr::IsPlayerAccount(GetSecurity())) { @@ -292,7 +293,7 @@ void WorldSession::HandleSendMail(WorldPacket & recvData) needItemDelay = GetAccountId() != rc_account; } - if( money >= 10*GOLD ) + if( money >= 10 * GOLD ) { CleanStringForMysqlQuery(subject); CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \" %s\", NOW())", GetAccountId(), player->GetGUIDLow(), player->GetName().c_str(), player->GetSession()->GetRemoteAddress().c_str(), rc_account, receiver.c_str(), money, subject.c_str()); @@ -308,16 +309,16 @@ void WorldSession::HandleSendMail(WorldPacket & recvData) // will delete item or place to receiver mail list draft - .AddMoney(money) - .AddCOD(COD) - .SendMailTo(trans, MailReceiver(receive, GUID_LOPART(rc)), MailSender(player), body.empty() ? MAIL_CHECK_MASK_COPIED : MAIL_CHECK_MASK_HAS_BODY, deliver_delay); + .AddMoney(money) + .AddCOD(COD) + .SendMailTo(trans, MailReceiver(receive, GUID_LOPART(rc)), MailSender(player), body.empty() ? MAIL_CHECK_MASK_COPIED : MAIL_CHECK_MASK_HAS_BODY, deliver_delay); player->SaveInventoryAndGoldToDB(trans); CharacterDatabase.CommitTransaction(trans); } //called when mail is read -void WorldSession::HandleMailMarkAsRead(WorldPacket & recvData) +void WorldSession::HandleMailMarkAsRead(WorldPacket& recvData) { uint64 mailbox; uint32 mailId; @@ -340,7 +341,7 @@ void WorldSession::HandleMailMarkAsRead(WorldPacket & recvData) } //called when client deletes mail -void WorldSession::HandleMailDelete(WorldPacket & recvData) +void WorldSession::HandleMailDelete(WorldPacket& recvData) { uint64 mailbox; uint32 mailId; @@ -370,7 +371,7 @@ void WorldSession::HandleMailDelete(WorldPacket & recvData) player->SendMailResult(mailId, MAIL_DELETED, MAIL_OK); } -void WorldSession::HandleMailReturnToSender(WorldPacket & recvData) +void WorldSession::HandleMailReturnToSender(WorldPacket& recvData) { uint64 mailbox; uint32 mailId; @@ -433,7 +434,7 @@ void WorldSession::HandleMailReturnToSender(WorldPacket & recvData) } //called when player takes item attached in mail -void WorldSession::HandleMailTakeItem(WorldPacket & recvData) +void WorldSession::HandleMailTakeItem(WorldPacket& recvData) { uint64 mailbox; uint32 mailId; @@ -499,10 +500,10 @@ void WorldSession::HandleMailTakeItem(WorldPacket & recvData) if (sender || sender_accId) { MailDraft(m->subject, "") - .AddMoney(m->COD) - .SendMailTo(trans, MailReceiver(sender, m->sender), MailSender(MAIL_NORMAL, m->receiver), MAIL_CHECK_MASK_COD_PAYMENT); + .AddMoney(m->COD) + .SendMailTo(trans, MailReceiver(sender, m->sender), MailSender(MAIL_NORMAL, m->receiver), MAIL_CHECK_MASK_COD_PAYMENT); - if( m->COD >= 10*GOLD ) + if( m->COD >= 10 * GOLD ) { std::string senderName; if (!sObjectMgr->GetPlayerNameByGUID(sender_guid, senderName)) @@ -574,7 +575,7 @@ void WorldSession::HandleMailTakeMoney(WorldPacket& recvData) } //called when player lists his received mails -void WorldSession::HandleGetMailList(WorldPacket & recvData) +void WorldSession::HandleGetMailList(WorldPacket& recvData) { uint64 mailbox; recvData >> mailbox; @@ -611,7 +612,7 @@ void WorldSession::HandleGetMailList(WorldPacket & recvData) uint8 item_count = uint8((*itr)->items.size()); // max count is MAX_MAIL_ITEMS (12) - size_t next_mail_size = 2+4+1+((*itr)->messageType == MAIL_NORMAL ? 8 : 4)+4*8+((*itr)->subject.size()+1)+((*itr)->body.size()+1)+1+item_count*(1+4+4+MAX_INSPECTED_ENCHANTMENT_SLOT*3*4+4+4+4+4+4+4+1); + size_t next_mail_size = 2 + 4 + 1 + ((*itr)->messageType == MAIL_NORMAL ? 8 : 4) + 4 * 8 + ((*itr)->subject.size() + 1) + ((*itr)->body.size() + 1) + 1 + item_count * (1 + 4 + 4 + MAX_INSPECTED_ENCHANTMENT_SLOT * 3 * 4 + 4 + 4 + 4 + 4 + 4 + 4 + 1); if (data.wpos() + next_mail_size > MAX_NETCLIENT_PACKET_SIZE) { @@ -640,10 +641,12 @@ void WorldSession::HandleGetMailList(WorldPacket & recvData) std::string subject = (*itr)->subject; std::string body = (*itr)->body; - if (subject.find("| |") != std::string::npos) { + if (subject.find("| |") != std::string::npos) + { subject = ""; } - if (body.find("| |") != std::string::npos) { + if (body.find("| |") != std::string::npos) + { body = ""; } @@ -652,7 +655,7 @@ void WorldSession::HandleGetMailList(WorldPacket & recvData) data << uint32((*itr)->stationery); // stationery (Stationery.dbc) data << uint32((*itr)->money); // Gold data << uint32((*itr)->checked); // flags - data << float(float((*itr)->expire_time-time(nullptr))/DAY); // Time + data << float(float((*itr)->expire_time - time(nullptr)) / DAY); // Time data << uint32((*itr)->mailTemplateId); // mail template (MailTemplate.dbc) data << subject; // Subject string - once 00, when mail type = 3, max 256 data << body; // message? max 8000 @@ -702,7 +705,7 @@ void WorldSession::HandleGetMailList(WorldPacket & recvData) } //used when player copies mail body to his inventory -void WorldSession::HandleMailCreateTextItem(WorldPacket & recvData) +void WorldSession::HandleMailCreateTextItem(WorldPacket& recvData) { uint64 mailbox; uint32 mailId; @@ -771,7 +774,7 @@ void WorldSession::HandleMailCreateTextItem(WorldPacket & recvData) } //TODO Fix me! ... this void has probably bad condition, but good data are sent -void WorldSession::HandleQueryNextMailTime(WorldPacket & /*recvData*/) +void WorldSession::HandleQueryNextMailTime(WorldPacket& /*recvData*/) { WorldPacket data(MSG_QUERY_NEXT_MAIL_TIME, 8); diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index f4acd35d4..c90c6e866 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -48,7 +48,7 @@ #include "LuaEngine.h" #endif -void WorldSession::HandleRepopRequestOpcode(WorldPacket & recv_data) +void WorldSession::HandleRepopRequestOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_REPOP_REQUEST Message"); @@ -85,7 +85,7 @@ void WorldSession::HandleRepopRequestOpcode(WorldPacket & recv_data) GetPlayer()->RepopAtGraveyard(); } -void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket & recv_data) +void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_GOSSIP_SELECT_OPTION"); @@ -376,8 +376,8 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recvData) if (!str[i].empty()) { if (wgname.find(str[i]) != std::wstring::npos || - wpname.find(str[i]) != std::wstring::npos || - Utf8FitTo(aname, str[i])) + wpname.find(str[i]) != std::wstring::npos || + Utf8FitTo(aname, str[i])) { s_show = true; break; @@ -412,7 +412,7 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recvData) } -void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleLogoutRequestOpcode(WorldPacket& /*recv_data*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_LOGOUT_REQUEST Message, security - %u", GetSecurity()); @@ -422,13 +422,13 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) DoLootRelease(lguid); bool instantLogout = ((GetSecurity() >= 0 && uint32(GetSecurity()) >= sWorld->getIntConfig(CONFIG_INSTANT_LOGOUT)) - || (GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && !GetPlayer()->IsInCombat())) || GetPlayer()->IsInFlight(); + || (GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && !GetPlayer()->IsInCombat())) || GetPlayer()->IsInFlight(); bool preventAfkSanctuaryLogout = sWorld->getIntConfig(CONFIG_AFK_PREVENT_LOGOUT) == 1 - && GetPlayer()->isAFK() && sAreaTableStore.LookupEntry(GetPlayer()->GetAreaId())->IsSanctuary(); + && GetPlayer()->isAFK() && sAreaTableStore.LookupEntry(GetPlayer()->GetAreaId())->IsSanctuary(); bool preventAfkLogout = sWorld->getIntConfig(CONFIG_AFK_PREVENT_LOGOUT) == 2 - && GetPlayer()->isAFK(); + && GetPlayer()->isAFK(); /// TODO: Possibly add RBAC permission to log out in combat bool canLogoutInCombat = GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); @@ -441,7 +441,7 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) else if (preventAfkSanctuaryLogout || preventAfkLogout || GetPlayer()->duel || GetPlayer()->HasAura(9454)) // is dueling or frozen by GM via freeze command reason = 2; // FIXME - Need the correct value - WorldPacket data(SMSG_LOGOUT_RESPONSE, 1+4); + WorldPacket data(SMSG_LOGOUT_RESPONSE, 1 + 4); data << uint32(reason); data << uint8(instantLogout); SendPacket(&data); @@ -465,7 +465,7 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) if (GetPlayer()->getStandState() == UNIT_STAND_STATE_STAND) GetPlayer()->SetStandState(UNIT_STAND_STATE_SIT); - WorldPacket data(SMSG_FORCE_MOVE_ROOT, (8+4)); // guess size + WorldPacket data(SMSG_FORCE_MOVE_ROOT, (8 + 4)); // guess size data.append(GetPlayer()->GetPackGUID()); data << (uint32)2; SendPacket(&data); @@ -475,14 +475,14 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) LogoutRequest(time(nullptr)); } -void WorldSession::HandlePlayerLogoutOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandlePlayerLogoutOpcode(WorldPacket& /*recv_data*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_PLAYER_LOGOUT Message"); #endif } -void WorldSession::HandleLogoutCancelOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleLogoutCancelOpcode(WorldPacket& /*recv_data*/) { LogoutRequest(0); @@ -492,7 +492,7 @@ void WorldSession::HandleLogoutCancelOpcode(WorldPacket & /*recv_data*/) // not remove flags if can't free move - its not set in Logout request code. if (GetPlayer()->CanFreeMove()) { - data.Initialize(SMSG_FORCE_MOVE_UNROOT, 9+4); + data.Initialize(SMSG_FORCE_MOVE_UNROOT, 9 + 4); data.append(GetPlayer()->GetPackGUID()); data << uint32(0); SendPacket(&data); @@ -502,7 +502,7 @@ void WorldSession::HandleLogoutCancelOpcode(WorldPacket & /*recv_data*/) } } -void WorldSession::HandleTogglePvP(WorldPacket & recv_data) +void WorldSession::HandleTogglePvP(WorldPacket& recv_data) { // this opcode can be used in two ways: Either set explicit new status or toggle old status if (recv_data.size() == 1) @@ -523,7 +523,7 @@ void WorldSession::HandleTogglePvP(WorldPacket & recv_data) // pvp->HandlePlayerActivityChanged(_player); } -void WorldSession::HandleZoneUpdateOpcode(WorldPacket & recv_data) +void WorldSession::HandleZoneUpdateOpcode(WorldPacket& recv_data) { uint32 newZone; recv_data >> newZone; @@ -539,7 +539,7 @@ void WorldSession::HandleZoneUpdateOpcode(WorldPacket & recv_data) //GetPlayer()->SendInitWorldStates(true, newZone); } -void WorldSession::HandleSetSelectionOpcode(WorldPacket & recv_data) +void WorldSession::HandleSetSelectionOpcode(WorldPacket& recv_data) { uint64 guid; recv_data >> guid; @@ -547,7 +547,7 @@ void WorldSession::HandleSetSelectionOpcode(WorldPacket & recv_data) _player->SetSelection(guid); } -void WorldSession::HandleStandStateChangeOpcode(WorldPacket & recv_data) +void WorldSession::HandleStandStateChangeOpcode(WorldPacket& recv_data) { uint32 animstate; recv_data >> animstate; @@ -566,7 +566,7 @@ void WorldSession::HandleStandStateChangeOpcode(WorldPacket & recv_data) _player->SetStandState(animstate); } -void WorldSession::HandleContactListOpcode(WorldPacket & recv_data) +void WorldSession::HandleContactListOpcode(WorldPacket& recv_data) { uint32 unk; recv_data >> unk; @@ -576,7 +576,7 @@ void WorldSession::HandleContactListOpcode(WorldPacket & recv_data) _player->GetSocial()->SendSocialList(_player); } -void WorldSession::HandleAddFriendOpcode(WorldPacket & recv_data) +void WorldSession::HandleAddFriendOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ADD_FRIEND"); @@ -646,7 +646,7 @@ void WorldSession::HandleAddFriendOpcode(WorldPacket & recv_data) #endif } -void WorldSession::HandleDelFriendOpcode(WorldPacket & recv_data) +void WorldSession::HandleDelFriendOpcode(WorldPacket& recv_data) { uint64 FriendGUID; @@ -665,7 +665,7 @@ void WorldSession::HandleDelFriendOpcode(WorldPacket & recv_data) #endif } -void WorldSession::HandleAddIgnoreOpcode(WorldPacket & recv_data) +void WorldSession::HandleAddIgnoreOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ADD_IGNORE"); @@ -742,11 +742,10 @@ void WorldSession::HandleCharacterAuraFrozen(PreparedQueryResult result) Field* fields = result->Fetch(); std::string player = fields[0].GetString(); handler.PSendSysMessage(LANG_COMMAND_FROZEN_PLAYERS, player.c_str()); - } - while (result->NextRow()); + } while (result->NextRow()); } -void WorldSession::HandleDelIgnoreOpcode(WorldPacket & recv_data) +void WorldSession::HandleDelIgnoreOpcode(WorldPacket& recv_data) { uint64 IgnoreGUID; @@ -765,7 +764,7 @@ void WorldSession::HandleDelIgnoreOpcode(WorldPacket & recv_data) #endif } -void WorldSession::HandleSetContactNotesOpcode(WorldPacket & recv_data) +void WorldSession::HandleSetContactNotesOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_SET_CONTACT_NOTES"); @@ -776,7 +775,7 @@ void WorldSession::HandleSetContactNotesOpcode(WorldPacket & recv_data) _player->GetSocial()->SetFriendNote(GUID_LOPART(guid), note); } -void WorldSession::HandleBugOpcode(WorldPacket & recv_data) +void WorldSession::HandleBugOpcode(WorldPacket& recv_data) { uint32 suggestion, contentlen, typelen; std::string content, type; @@ -804,7 +803,7 @@ void WorldSession::HandleBugOpcode(WorldPacket & recv_data) CharacterDatabase.Execute(stmt); } -void WorldSession::HandleReclaimCorpseOpcode(WorldPacket &recv_data) +void WorldSession::HandleReclaimCorpseOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_RECLAIM_CORPSE"); @@ -843,7 +842,7 @@ void WorldSession::HandleReclaimCorpseOpcode(WorldPacket &recv_data) _player->SpawnCorpseBones(); } -void WorldSession::HandleResurrectResponseOpcode(WorldPacket & recv_data) +void WorldSession::HandleResurrectResponseOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_RESURRECT_RESPONSE"); @@ -880,8 +879,8 @@ void WorldSession::SendAreaTriggerMessage(const char* Text, ...) vsnprintf(szStr, 1024, Text, ap); va_end(ap); - uint32 length = strlen(szStr)+1; - WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length); + uint32 length = strlen(szStr) + 1; + WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4 + length); data << length; data << szStr; SendPacket(&data); @@ -901,7 +900,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) in flight, ignore Area Trigger ID:%u", - player->GetName().c_str(), player->GetGUIDLow(), triggerId); + player->GetName().c_str(), player->GetGUIDLow(), triggerId); #endif return; } @@ -911,7 +910,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) send unknown (by DBC) Area Trigger ID:%u", - player->GetName().c_str(), player->GetGUIDLow(), triggerId); + player->GetName().c_str(), player->GetGUIDLow(), triggerId); #endif return; } @@ -920,7 +919,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) too far (trigger map: %u player map: %u), ignore Area Trigger ID: %u", - player->GetName().c_str(), atEntry->map, player->GetMapId(), player->GetGUIDLow(), triggerId); + player->GetName().c_str(), atEntry->map, player->GetMapId(), player->GetGUIDLow(), triggerId); #endif return; } @@ -977,7 +976,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recv_data) player->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, at->target_Orientation, TELE_TO_NOT_LEAVE_TRANSPORT); } -void WorldSession::HandleUpdateAccountData(WorldPacket &recv_data) +void WorldSession::HandleUpdateAccountData(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_UPDATE_ACCOUNT_DATA"); @@ -997,7 +996,7 @@ void WorldSession::HandleUpdateAccountData(WorldPacket &recv_data) { SetAccountData(AccountDataType(type), 0, ""); - WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA_COMPLETE, 4+4); + WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA_COMPLETE, 4 + 4); data << uint32(type); data << uint32(0); SendPacket(&data); @@ -1030,7 +1029,7 @@ void WorldSession::HandleUpdateAccountData(WorldPacket &recv_data) SetAccountData(AccountDataType(type), timestamp, adata); - WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA_COMPLETE, 4+4); + WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA_COMPLETE, 4 + 4); data << uint32(type); data << uint32(0); SendPacket(&data); @@ -1071,7 +1070,7 @@ void WorldSession::HandleRequestAccountData(WorldPacket& recv_data) dest.resize(destSize); - WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA, 8+4+4+4+destSize); + WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA, 8 + 4 + 4 + 4 + destSize); data << uint64(_player ? _player->GetGUID() : 0); // player guid data << uint32(type); // type (0-7) data << uint32(adata->Time); // unix time @@ -1135,21 +1134,21 @@ void WorldSession::HandleSetActionButtonOpcode(WorldPacket& recv_data) } } -void WorldSession::HandleCompleteCinematic(WorldPacket & /*recv_data*/) +void WorldSession::HandleCompleteCinematic(WorldPacket& /*recv_data*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_COMPLETE_CINEMATIC"); #endif } -void WorldSession::HandleNextCinematicCamera(WorldPacket & /*recv_data*/) +void WorldSession::HandleNextCinematicCamera(WorldPacket& /*recv_data*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_NEXT_CINEMATIC_CAMERA"); #endif } -void WorldSession::HandleFeatherFallAck(WorldPacket &recv_data) +void WorldSession::HandleFeatherFallAck(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_MOVE_FEATHER_FALL_ACK"); @@ -1163,54 +1162,54 @@ void WorldSession::HandleMoveUnRootAck(WorldPacket& recv_data) { // no used recv_data.rfinish(); // prevent warnings spam -/* - uint64 guid; - recv_data >> guid; + /* + uint64 guid; + recv_data >> guid; - // now can skip not our packet - if (_player->GetGUID() != guid) - { - recv_data.rfinish(); // prevent warnings spam - return; - } + // now can skip not our packet + if (_player->GetGUID() != guid) + { + recv_data.rfinish(); // prevent warnings spam + return; + } -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_FORCE_MOVE_UNROOT_ACK"); -#endif + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_FORCE_MOVE_UNROOT_ACK"); + #endif - recv_data.read_skip(); // unk + recv_data.read_skip(); // unk - MovementInfo movementInfo; - movementInfo.guid = guid; - ReadMovementInfo(recv_data, &movementInfo); - recv_data.read_skip(); // unk2 -*/ + MovementInfo movementInfo; + movementInfo.guid = guid; + ReadMovementInfo(recv_data, &movementInfo); + recv_data.read_skip(); // unk2 + */ } void WorldSession::HandleMoveRootAck(WorldPacket& recv_data) { // no used recv_data.rfinish(); // prevent warnings spam -/* - uint64 guid; - recv_data >> guid; + /* + uint64 guid; + recv_data >> guid; - // now can skip not our packet - if (_player->GetGUID() != guid) - { - recv_data.rfinish(); // prevent warnings spam - return; - } + // now can skip not our packet + if (_player->GetGUID() != guid) + { + recv_data.rfinish(); // prevent warnings spam + return; + } -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_FORCE_MOVE_ROOT_ACK"); -#endif + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_FORCE_MOVE_ROOT_ACK"); + #endif - recv_data.read_skip(); // unk + recv_data.read_skip(); // unk - MovementInfo movementInfo; - ReadMovementInfo(recv_data, &movementInfo); -*/ + MovementInfo movementInfo; + ReadMovementInfo(recv_data, &movementInfo); + */ } void WorldSession::HandleSetActionBarToggles(WorldPacket& recv_data) @@ -1261,7 +1260,7 @@ void WorldSession::HandleInspectOpcode(WorldPacket& recv_data) uint32 talent_points = 0x47; uint32 guid_size = player->GetPackGUID().wpos(); - WorldPacket data(SMSG_INSPECT_TALENT, guid_size+4+talent_points); + WorldPacket data(SMSG_INSPECT_TALENT, guid_size + 4 + talent_points); data.append(player->GetPackGUID()); if (sWorld->getBoolConfig(CONFIG_TALENTS_INSPECTING) || _player->IsGameMaster()) @@ -1293,7 +1292,7 @@ void WorldSession::HandleInspectHonorStatsOpcode(WorldPacket& recv_data) return; } - WorldPacket data(MSG_INSPECT_HONOR_STATS, 8+1+4*4); + WorldPacket data(MSG_INSPECT_HONOR_STATS, 8 + 1 + 4 * 4); data << uint64(player->GetGUID()); data << uint8(player->GetHonorPoints()); data << uint32(player->GetUInt32Value(PLAYER_FIELD_KILLS)); @@ -1396,7 +1395,7 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) std::string msg = charname + "'s " + "account is " + acc + ", e-mail: " + email + ", last ip: " + lastip; - WorldPacket data(SMSG_WHOIS, msg.size()+1); + WorldPacket data(SMSG_WHOIS, msg.size() + 1); data << msg; SendPacket(&data); @@ -1405,7 +1404,7 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) #endif } -void WorldSession::HandleComplainOpcode(WorldPacket & recv_data) +void WorldSession::HandleComplainOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_COMPLAIN"); @@ -1449,7 +1448,7 @@ void WorldSession::HandleComplainOpcode(WorldPacket & recv_data) #endif } -void WorldSession::HandleRealmSplitOpcode(WorldPacket & recv_data) +void WorldSession::HandleRealmSplitOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_REALM_SPLIT"); @@ -1459,7 +1458,7 @@ void WorldSession::HandleRealmSplitOpcode(WorldPacket & recv_data) std::string split_date = "01/01/01"; recv_data >> unk; - WorldPacket data(SMSG_REALM_SPLIT, 4+4+split_date.size()+1); + WorldPacket data(SMSG_REALM_SPLIT, 4 + 4 + split_date.size() + 1); data << unk; data << uint32(0x00000000); // realm split state // split states: @@ -1487,7 +1486,8 @@ void WorldSession::HandleFarSightOpcode(WorldPacket& recvData) #endif if (WorldObject* target = _player->GetViewpoint()) _player->SetSeer(target); - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outError("Player %s requests non-existing seer " UI64FMTD, _player->GetName().c_str(), _player->GetUInt64Value(PLAYER_FARSIGHT)); #endif @@ -1504,7 +1504,7 @@ void WorldSession::HandleFarSightOpcode(WorldPacket& recvData) GetPlayer()->UpdateVisibilityForPlayer(); } -void WorldSession::HandleSetTitleOpcode(WorldPacket & recv_data) +void WorldSession::HandleSetTitleOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_SET_TITLE"); @@ -1516,7 +1516,7 @@ void WorldSession::HandleSetTitleOpcode(WorldPacket & recv_data) // -1 at none if (title > 0 && title < MAX_TITLE_INDEX) { - if (!GetPlayer()->HasTitle(title)) + if (!GetPlayer()->HasTitle(title)) return; } else @@ -1525,7 +1525,7 @@ void WorldSession::HandleSetTitleOpcode(WorldPacket & recv_data) GetPlayer()->SetUInt32Value(PLAYER_CHOSEN_TITLE, title); } -void WorldSession::HandleTimeSyncResp(WorldPacket & recv_data) +void WorldSession::HandleTimeSyncResp(WorldPacket& recv_data) { uint32 counter, clientTicks; recv_data >> counter >> clientTicks; @@ -1533,7 +1533,7 @@ void WorldSession::HandleTimeSyncResp(WorldPacket & recv_data) _player->m_timeSyncClient = clientTicks; } -void WorldSession::HandleResetInstancesOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleResetInstancesOpcode(WorldPacket& /*recv_data*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_RESET_INSTANCES"); @@ -1548,7 +1548,7 @@ void WorldSession::HandleResetInstancesOpcode(WorldPacket & /*recv_data*/) Player::ResetInstances(_player->GetGUIDLow(), INSTANCE_RESET_ALL, false); } -void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket & recv_data) +void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_SET_DUNGEON_DIFFICULTY"); @@ -1603,7 +1603,7 @@ void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket & recv_data) } } -void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recv_data) +void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_SET_RAID_DIFFICULTY"); @@ -1656,7 +1656,7 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recv_data) return; } - if (IsSharedDifficultyMap(groupGuy->GetMap()->GetId()) && (_player->GetRaidDifficulty() >= 0 && uint32(mode%2) == uint32(_player->GetRaidDifficulty()%2)) && group->isRaidGroup()) + if (IsSharedDifficultyMap(groupGuy->GetMap()->GetId()) && (_player->GetRaidDifficulty() >= 0 && uint32(mode % 2) == uint32(_player->GetRaidDifficulty() % 2)) && group->isRaidGroup()) { if (!currMap) currMap = groupGuy->GetMap(); @@ -1669,8 +1669,8 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recv_data) } if (!groupGuy->IsAlive() || groupGuy->IsInCombat() || groupGuy->GetVictim() || groupGuy->m_mover != groupGuy || groupGuy->IsNonMeleeSpellCast(true) || (!groupGuy->GetMotionMaster()->empty() && groupGuy->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE) - || !groupGuy->movespline->Finalized() || !groupGuy->GetMap()->ToInstanceMap() || !groupGuy->GetMap()->ToInstanceMap()->GetInstanceScript() || groupGuy->GetMap()->ToInstanceMap()->GetInstanceScript()->IsEncounterInProgress() - || !groupGuy->Satisfy(sObjectMgr->GetAccessRequirement(groupGuy->GetMap()->GetId(), Difficulty(mode)), groupGuy->GetMap()->GetId(), false)) + || !groupGuy->movespline->Finalized() || !groupGuy->GetMap()->ToInstanceMap() || !groupGuy->GetMap()->ToInstanceMap()->GetInstanceScript() || groupGuy->GetMap()->ToInstanceMap()->GetInstanceScript()->IsEncounterInProgress() + || !groupGuy->Satisfy(sObjectMgr->GetAccessRequirement(groupGuy->GetMap()->GetId(), Difficulty(mode)), groupGuy->GetMap()->GetId(), false)) { _player->SendRaidDifficulty(group != nullptr); return; @@ -1695,7 +1695,7 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recv_data) if (p->GetGroup() != group) { if (!p->IsInWorld() || !p->IsAlive() || p->IsInCombat() || p->GetVictim() || p->m_mover != p || p->IsNonMeleeSpellCast(true) || (!p->GetMotionMaster()->empty() && p->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE) - || !p->movespline->Finalized() || !p->GetMap()->ToInstanceMap() || !p->GetMap()->ToInstanceMap()->GetInstanceScript() || p->GetMap()->ToInstanceMap()->GetInstanceScript()->IsEncounterInProgress()) + || !p->movespline->Finalized() || !p->GetMap()->ToInstanceMap() || !p->GetMap()->ToInstanceMap()->GetInstanceScript() || p->GetMap()->ToInstanceMap()->GetInstanceScript()->IsEncounterInProgress()) { _player->SendRaidDifficulty(group != nullptr); return; @@ -1727,15 +1727,15 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recv_data) { anyoneInside = true; - float x,y,z,o; - groupGuy->GetPosition(x,y,z,o); + float x, y, z, o; + groupGuy->GetPosition(x, y, z, o); Map* oldMap = groupGuy->GetMap(); oldMap->RemovePlayerFromMap(groupGuy, false); groupGuy->ResetMap(); oldMap->AfterPlayerUnlinkFromMap(); groupGuy->SetMap(homeMap571); groupGuy->Relocate(5790.20f, 2071.36f, 636.07f, 3.60f); - Position dest = {x, y, z+0.1f, o}; + Position dest = {x, y, z + 0.1f, o}; playerTeleport[groupGuy] = dest; } } @@ -1765,7 +1765,7 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recv_data) } } -void WorldSession::HandleCancelMountAuraOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleCancelMountAuraOpcode(WorldPacket& /*recv_data*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_CANCEL_MOUNT_AURA"); @@ -1788,7 +1788,7 @@ void WorldSession::HandleCancelMountAuraOpcode(WorldPacket & /*recv_data*/) _player->RemoveAurasByType(SPELL_AURA_MOUNTED); } -void WorldSession::HandleMoveSetCanFlyAckOpcode(WorldPacket & recv_data) +void WorldSession::HandleMoveSetCanFlyAckOpcode(WorldPacket& recv_data) { // fly mode on/off #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) @@ -1816,12 +1816,12 @@ void WorldSession::HandleMoveSetCanFlyAckOpcode(WorldPacket & recv_data) _player->m_mover->m_movementInfo.flags = movementInfo.GetMovementFlags(); } -void WorldSession::HandleRequestPetInfoOpcode(WorldPacket & /*recv_data */) +void WorldSession::HandleRequestPetInfoOpcode(WorldPacket& /*recv_data */) { /* -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: CMSG_REQUEST_PET_INFO"); -#endif + #endif recv_data.hexlike(); */ @@ -1831,7 +1831,7 @@ void WorldSession::HandleRequestPetInfoOpcode(WorldPacket & /*recv_data */) _player->CharmSpellInitialize(); } -void WorldSession::HandleSetTaxiBenchmarkOpcode(WorldPacket & recv_data) +void WorldSession::HandleSetTaxiBenchmarkOpcode(WorldPacket& recv_data) { uint8 mode; recv_data >> mode; @@ -1843,7 +1843,7 @@ void WorldSession::HandleSetTaxiBenchmarkOpcode(WorldPacket & recv_data) #endif } -void WorldSession::HandleQueryInspectAchievements(WorldPacket & recv_data) +void WorldSession::HandleQueryInspectAchievements(WorldPacket& recv_data) { uint64 guid; recv_data.readPackGUID(guid); @@ -1885,7 +1885,7 @@ void WorldSession::SendSetPhaseShift(uint32 PhaseShift) } //Battlefield and Battleground -void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket & recv_data) +void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_AREA_SPIRIT_HEALER_QUERY"); @@ -1907,10 +1907,10 @@ void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket & recv_data) sBattlegroundMgr->SendAreaSpiritHealerQueryOpcode(_player, bg, guid); if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(_player->GetZoneId())) - bf->SendAreaSpiritHealerQueryOpcode(_player,guid); + bf->SendAreaSpiritHealerQueryOpcode(_player, guid); } -void WorldSession::HandleAreaSpiritHealerQueueOpcode(WorldPacket & recv_data) +void WorldSession::HandleAreaSpiritHealerQueueOpcode(WorldPacket& recv_data) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_AREA_SPIRIT_HEALER_QUEUE"); diff --git a/src/server/game/Handlers/MovementHandler.cpp b/src/server/game/Handlers/MovementHandler.cpp index 78557ce51..45172030f 100644 --- a/src/server/game/Handlers/MovementHandler.cpp +++ b/src/server/game/Handlers/MovementHandler.cpp @@ -28,7 +28,7 @@ #define MOVEMENT_PACKET_TIME_DELAY 0 -void WorldSession::HandleMoveWorldportAckOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleMoveWorldportAckOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: got MSG_MOVE_WORLDPORT_ACK."); @@ -238,7 +238,7 @@ void WorldSession::HandleMoveTeleportAck(WorldPacket& recvData) sLog->outStaticDebug("Guid " UI64FMTD, guid); #endif #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug("Flags %u, time %u", flags, time/IN_MILLISECONDS); + sLog->outStaticDebug("Flags %u, time %u", flags, time / IN_MILLISECONDS); #endif Player* plMover = _player->m_mover->ToPlayer(); @@ -261,7 +261,7 @@ void WorldSession::HandleMoveTeleportAck(WorldPacket& recvData) // xinef: teleport pets if they are not unsummoned if (Pet* pet = plMover->GetPet()) { - if (!pet->IsWithinDist3d(plMover, plMover->GetMap()->GetVisibilityRange()-5.0f)) + if (!pet->IsWithinDist3d(plMover, plMover->GetMap()->GetVisibilityRange() - 5.0f)) pet->NearTeleportTo(plMover->GetPositionX(), plMover->GetPositionY(), plMover->GetPositionZ(), pet->GetOrientation()); } @@ -293,11 +293,11 @@ void WorldSession::HandleMoveTeleportAck(WorldPacket& recvData) plMover->GetMotionMaster()->ReinitializeMovement(); // pussywizard: client forgets about losing control, resend it - if (plMover->HasUnitState(UNIT_STATE_FLEEING|UNIT_STATE_CONFUSED) || plMover->IsCharmed()) // only in such cases SetClientControl(self, false) is sent + if (plMover->HasUnitState(UNIT_STATE_FLEEING | UNIT_STATE_CONFUSED) || plMover->IsCharmed()) // only in such cases SetClientControl(self, false) is sent plMover->SetClientControl(plMover, false, true); } -void WorldSession::HandleMovementOpcodes(WorldPacket & recvData) +void WorldSession::HandleMovementOpcodes(WorldPacket& recvData) { uint16 opcode = recvData.GetOpcode(); @@ -320,7 +320,8 @@ void WorldSession::HandleMovementOpcodes(WorldPacket & recvData) recvData.readPackGUID(guid); // prevent tampered movement data - if (!guid || guid != mover->GetGUID()) { + if (!guid || guid != mover->GetGUID()) + { recvData.rfinish(); // prevent warnings spam return; } @@ -336,7 +337,8 @@ void WorldSession::HandleMovementOpcodes(WorldPacket & recvData) movementInfo.guid = guid; ReadMovementInfo(recvData, &movementInfo); - if (!movementInfo.pos.IsPositionValid()) { + if (!movementInfo.pos.IsPositionValid()) + { recvData.rfinish(); // prevent warnings spam return; } @@ -352,14 +354,14 @@ void WorldSession::HandleMovementOpcodes(WorldPacket & recvData) // transports size limited // (also received at zeppelin leave by some reason with t_* as absolute in continent coordinates, can be safely skipped) if (movementInfo.transport.pos.GetPositionX() > 75.0f || movementInfo.transport.pos.GetPositionY() > 75.0f || movementInfo.transport.pos.GetPositionZ() > 75.0f || - movementInfo.transport.pos.GetPositionX() < -75.0f || movementInfo.transport.pos.GetPositionY() < -75.0f || movementInfo.transport.pos.GetPositionZ() < -75.0f) + movementInfo.transport.pos.GetPositionX() < -75.0f || movementInfo.transport.pos.GetPositionY() < -75.0f || movementInfo.transport.pos.GetPositionZ() < -75.0f) { recvData.rfinish(); // prevent warnings spam return; } if (!acore::IsValidMapCoord(movementInfo.pos.GetPositionX() + movementInfo.transport.pos.GetPositionX(), movementInfo.pos.GetPositionY() + movementInfo.transport.pos.GetPositionY(), - movementInfo.pos.GetPositionZ() + movementInfo.transport.pos.GetPositionZ(), movementInfo.pos.GetOrientation() + movementInfo.transport.pos.GetOrientation())) + movementInfo.pos.GetPositionZ() + movementInfo.transport.pos.GetPositionZ(), movementInfo.pos.GetOrientation() + movementInfo.transport.pos.GetOrientation())) { recvData.rfinish(); // prevent warnings spam return; @@ -509,7 +511,7 @@ void WorldSession::HandleMovementOpcodes(WorldPacket & recvData) } } -void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recvData) +void WorldSession::HandleForceSpeedChangeAck(WorldPacket& recvData) { uint32 opcode = recvData.GetOpcode(); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) @@ -550,15 +552,42 @@ void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recvData) switch (opcode) { - case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: move_type = MOVE_WALK; force_move_type = MOVE_WALK; break; - case CMSG_FORCE_RUN_SPEED_CHANGE_ACK: move_type = MOVE_RUN; force_move_type = MOVE_RUN; break; - case CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK: move_type = MOVE_RUN_BACK; force_move_type = MOVE_RUN_BACK; break; - case CMSG_FORCE_SWIM_SPEED_CHANGE_ACK: move_type = MOVE_SWIM; force_move_type = MOVE_SWIM; break; - case CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK: move_type = MOVE_SWIM_BACK; force_move_type = MOVE_SWIM_BACK; break; - case CMSG_FORCE_TURN_RATE_CHANGE_ACK: move_type = MOVE_TURN_RATE; force_move_type = MOVE_TURN_RATE; break; - case CMSG_FORCE_FLIGHT_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT; force_move_type = MOVE_FLIGHT; break; - case CMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT_BACK; force_move_type = MOVE_FLIGHT_BACK; break; - case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: move_type = MOVE_PITCH_RATE; force_move_type = MOVE_PITCH_RATE; break; + case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: + move_type = MOVE_WALK; + force_move_type = MOVE_WALK; + break; + case CMSG_FORCE_RUN_SPEED_CHANGE_ACK: + move_type = MOVE_RUN; + force_move_type = MOVE_RUN; + break; + case CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK: + move_type = MOVE_RUN_BACK; + force_move_type = MOVE_RUN_BACK; + break; + case CMSG_FORCE_SWIM_SPEED_CHANGE_ACK: + move_type = MOVE_SWIM; + force_move_type = MOVE_SWIM; + break; + case CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK: + move_type = MOVE_SWIM_BACK; + force_move_type = MOVE_SWIM_BACK; + break; + case CMSG_FORCE_TURN_RATE_CHANGE_ACK: + move_type = MOVE_TURN_RATE; + force_move_type = MOVE_TURN_RATE; + break; + case CMSG_FORCE_FLIGHT_SPEED_CHANGE_ACK: + move_type = MOVE_FLIGHT; + force_move_type = MOVE_FLIGHT; + break; + case CMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE_ACK: + move_type = MOVE_FLIGHT_BACK; + force_move_type = MOVE_FLIGHT_BACK; + break; + case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: + move_type = MOVE_PITCH_RATE; + force_move_type = MOVE_PITCH_RATE; + break; default: sLog->outError("WorldSession::HandleForceSpeedChangeAck: Unknown move type opcode: %u", opcode); return; @@ -578,19 +607,19 @@ void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recvData) if (_player->GetSpeed(move_type) > newspeed) // must be greater - just correct { sLog->outError("%sSpeedChange player %s is NOT correct (must be %f instead %f), force set to correct value", - move_type_name[move_type], _player->GetName().c_str(), _player->GetSpeed(move_type), newspeed); + move_type_name[move_type], _player->GetName().c_str(), _player->GetSpeed(move_type), newspeed); _player->SetSpeed(move_type, _player->GetSpeedRate(move_type), true); } else // must be lesser - cheating { sLog->outBasic("Player %s from account id %u kicked for incorrect speed (must be %f instead %f)", - _player->GetName().c_str(), GetAccountId(), _player->GetSpeed(move_type), newspeed); + _player->GetName().c_str(), GetAccountId(), _player->GetSpeed(move_type), newspeed); KickPlayer("Incorrect speed"); } } } -void WorldSession::HandleSetActiveMoverOpcode(WorldPacket &recvData) +void WorldSession::HandleSetActiveMoverOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_SET_ACTIVE_MOVER"); @@ -606,7 +635,7 @@ void WorldSession::HandleSetActiveMoverOpcode(WorldPacket &recvData) } } -void WorldSession::HandleMoveNotActiveMover(WorldPacket &recvData) +void WorldSession::HandleMoveNotActiveMover(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_MOVE_NOT_ACTIVE_MOVER"); @@ -637,7 +666,7 @@ void WorldSession::HandleMountSpecialAnimOpcode(WorldPacket& /*recvData*/) GetPlayer()->SendMessageToSet(&data, false); } -void WorldSession::HandleMoveKnockBackAck(WorldPacket & recvData) +void WorldSession::HandleMoveKnockBackAck(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_MOVE_KNOCK_BACK_ACK"); @@ -739,7 +768,7 @@ void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket& recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_MOVE_TIME_SKIPPED"); #endif - + uint64 guid; uint32 timeSkipped; recvData.readPackGUID(guid); diff --git a/src/server/game/Handlers/NPCHandler.cpp b/src/server/game/Handlers/NPCHandler.cpp index b61f97a81..f92bdb00b 100644 --- a/src/server/game/Handlers/NPCHandler.cpp +++ b/src/server/game/Handlers/NPCHandler.cpp @@ -37,7 +37,7 @@ enum StableResultCode STABLE_ERR_EXOTIC = 0x0C, // "you are unable to control exotic creatures" }; -void WorldSession::HandleTabardVendorActivateOpcode(WorldPacket & recvData) +void WorldSession::HandleTabardVendorActivateOpcode(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -65,7 +65,7 @@ void WorldSession::SendTabardVendorActivate(uint64 guid) SendPacket(&data); } -void WorldSession::HandleBankerActivateOpcode(WorldPacket & recvData) +void WorldSession::HandleBankerActivateOpcode(WorldPacket& recvData) { uint64 guid; @@ -106,7 +106,7 @@ void WorldSession::SendShowMailBox(uint64 guid) SendPacket(&data); } -void WorldSession::HandleTrainerListOpcode(WorldPacket & recvData) +void WorldSession::HandleTrainerListOpcode(WorldPacket& recvData) { uint64 guid; @@ -158,7 +158,7 @@ void WorldSession::SendTrainerList(uint64 guid, const std::string& strTitle) return; } - WorldPacket data(SMSG_TRAINER_LIST, 8+4+4+trainer_spells->spellList.size()*38 + strTitle.size()+1); + WorldPacket data(SMSG_TRAINER_LIST, 8 + 4 + 4 + trainer_spells->spellList.size() * 38 + strTitle.size() + 1); data << guid; data << uint32(trainer_spells->trainerType); @@ -199,7 +199,7 @@ void WorldSession::SendTrainerList(uint64 guid, const std::string& strTitle) data << uint32(floor(tSpell->spellCost * fDiscountMod)); data << uint32(primary_prof_first_rank && can_learn_primary_prof ? 1 : 0); - // primary prof. learn confirmation dialog + // primary prof. learn confirmation dialog data << uint32(primary_prof_first_rank ? 1 : 0); // must be equal prev. field to have learn button in enabled state data << uint8(tSpell->reqLevel); data << uint32(tSpell->reqSkill); @@ -241,7 +241,7 @@ void WorldSession::SendTrainerList(uint64 guid, const std::string& strTitle) SendPacket(&data); } -void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket & recvData) +void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recvData) { uint64 guid; uint32 spellId = 0; @@ -302,7 +302,7 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket & recvData) SendPacket(&data); } -void WorldSession::HandleGossipHelloOpcode(WorldPacket & recvData) +void WorldSession::HandleGossipHelloOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GOSSIP_HELLO"); @@ -341,7 +341,7 @@ void WorldSession::HandleGossipHelloOpcode(WorldPacket & recvData) //if (unit->IsArmorer() || unit->IsCivilian() || unit->IsQuestGiver() || unit->IsServiceProvider() || unit->IsGuard()) { //if (!unit->GetTransport()) // pussywizard: reverted with new spline (old: without this check, npc would stay in place and the transport would continue moving, so the npc falls off. NPCs on transports don't have waypoints, so stopmoving is not needed) - unit->StopMoving(); + unit->StopMoving(); } // If spiritguide, no need for gossip menu, just put player into resurrect queue @@ -358,7 +358,7 @@ void WorldSession::HandleGossipHelloOpcode(WorldPacket & recvData) if (!sScriptMgr->OnGossipHello(_player, unit)) { -// _player->TalkedToCreature(unit->GetEntry(), unit->GetGUID()); + // _player->TalkedToCreature(unit->GetEntry(), unit->GetGUID()); _player->PrepareGossipMenu(unit, unit->GetCreatureTemplate()->GossipMenuId, true); _player->SendPreparedGossip(unit); } @@ -414,7 +414,7 @@ void WorldSession::HandleGossipHelloOpcode(WorldPacket & recvData) } }*/ -void WorldSession::HandleSpiritHealerActivateOpcode(WorldPacket & recvData) +void WorldSession::HandleSpiritHealerActivateOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_SPIRIT_HEALER_ACTIVATE"); @@ -471,7 +471,7 @@ void WorldSession::SendSpiritResurrect() // _player->UpdateObjectVisibility(); // xinef: not needed, called in ResurrectPlayer } -void WorldSession::HandleBinderActivateOpcode(WorldPacket & recvData) +void WorldSession::HandleBinderActivateOpcode(WorldPacket& recvData) { uint64 npcGUID; recvData >> npcGUID; @@ -506,7 +506,7 @@ void WorldSession::SendBindPoint(Creature* npc) // send spell for homebinding (3286) npc->CastSpell(_player, bindspell, true); - WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, (8+4)); + WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, (8 + 4)); data << uint64(npc->GetGUID()); data << uint32(bindspell); SendPacket(&data); @@ -514,7 +514,7 @@ void WorldSession::SendBindPoint(Creature* npc) _player->PlayerTalkClass->SendCloseGossip(); } -void WorldSession::HandleListStabledPetsOpcode(WorldPacket & recvData) +void WorldSession::HandleListStabledPetsOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recv MSG_LIST_STABLED_PETS"); @@ -586,7 +586,7 @@ void WorldSession::SendStablePetCallback(PreparedQueryResult result, uint64 guid PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_BY_ENTRY_AND_SLOT); stmt->setUInt32(0, _player->GetGUIDLow()); stmt->setUInt8(1, uint8(_player->GetTemporaryUnsummonedPetNumber() ? PET_SAVE_AS_CURRENT : PET_SAVE_NOT_IN_SLOT)); - + if (PreparedQueryResult _result = CharacterDatabase.AsyncQuery(stmt)) { Field* fields = _result->Fetch(); @@ -594,7 +594,7 @@ void WorldSession::SendStablePetCallback(PreparedQueryResult result, uint64 guid data << uint32(fields[0].GetUInt32()); // id data << uint32(fields[1].GetUInt32()); // entry data << uint32(fields[4].GetUInt16()); // level - data << fields[8].GetString(); // petname + data << fields[8].GetString(); // petname data << uint8(1); ++num; } @@ -613,8 +613,7 @@ void WorldSession::SendStablePetCallback(PreparedQueryResult result, uint64 guid data << uint8(2); // 1 = current, 2/3 = in stable (any from 4, 5, ... create problems with proper show) ++num; - } - while (result->NextRow()); + } while (result->NextRow()); } data.put(wpos, num); // set real data to placeholder @@ -629,7 +628,7 @@ void WorldSession::SendStableResult(uint8 res) SendPacket(&data); } -void WorldSession::HandleStablePet(WorldPacket & recvData) +void WorldSession::HandleStablePet(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recv CMSG_STABLE_PET"); @@ -704,8 +703,7 @@ void WorldSession::HandleStablePetCallback(PreparedQueryResult result) // this slot not free, skip ++freeSlot; - } - while (result->NextRow()); + } while (result->NextRow()); } WorldPacket data(SMSG_STABLE_RESULT, 1); @@ -728,7 +726,7 @@ void WorldSession::HandleStablePetCallback(PreparedQueryResult result) trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); - + _player->SetTemporaryUnsummonedPetNumber(0); SendStableResult(STABLE_SUCCESS_STABLE); return; @@ -737,7 +735,7 @@ void WorldSession::HandleStablePetCallback(PreparedQueryResult result) SendStableResult(STABLE_ERR_STABLE); } -void WorldSession::HandleUnstablePet(WorldPacket & recvData) +void WorldSession::HandleUnstablePet(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recv CMSG_UNSTABLE_PET."); @@ -840,7 +838,7 @@ void WorldSession::HandleUnstablePetCallback(PreparedQueryResult result, uint32 } } -void WorldSession::HandleBuyStableSlot(WorldPacket & recvData) +void WorldSession::HandleBuyStableSlot(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recv CMSG_BUY_STABLE_SLOT."); @@ -861,7 +859,7 @@ void WorldSession::HandleBuyStableSlot(WorldPacket & recvData) if (GetPlayer()->m_stableSlots < MAX_PET_STABLES) { - StableSlotPricesEntry const* SlotPrice = sStableSlotPricesStore.LookupEntry(GetPlayer()->m_stableSlots+1); + StableSlotPricesEntry const* SlotPrice = sStableSlotPricesStore.LookupEntry(GetPlayer()->m_stableSlots + 1); if (_player->HasEnoughMoney(SlotPrice->Price)) { ++GetPlayer()->m_stableSlots; @@ -875,14 +873,14 @@ void WorldSession::HandleBuyStableSlot(WorldPacket & recvData) SendStableResult(STABLE_ERR_STABLE); } -void WorldSession::HandleStableRevivePet(WorldPacket &/* recvData */) +void WorldSession::HandleStableRevivePet(WorldPacket& /* recvData */) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "HandleStableRevivePet: Not implemented"); #endif } -void WorldSession::HandleStableSwapPet(WorldPacket & recvData) +void WorldSession::HandleStableSwapPet(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recv CMSG_STABLE_SWAP_PET."); @@ -967,7 +965,7 @@ void WorldSession::HandleStableSwapPetCallback(PreparedQueryResult result, uint3 } Pet* pet = _player->GetPet(); - + // move alive pet to slot or delete dead pet if (pet) _player->RemovePet(pet, pet->IsAlive() ? PetSaveMode(slot) : PET_SAVE_AS_DELETED); @@ -995,7 +993,7 @@ void WorldSession::HandleStableSwapPetCallback(PreparedQueryResult result, uint3 SendStableResult(STABLE_SUCCESS_UNSTABLE); } -void WorldSession::HandleRepairItemOpcode(WorldPacket & recvData) +void WorldSession::HandleRepairItemOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_REPAIR_ITEM"); diff --git a/src/server/game/Handlers/PetHandler.cpp b/src/server/game/Handlers/PetHandler.cpp index 7b0dc4148..6cbc092fa 100644 --- a/src/server/game/Handlers/PetHandler.cpp +++ b/src/server/game/Handlers/PetHandler.cpp @@ -24,26 +24,26 @@ class LoadPetFromDBQueryHolder : public SQLQueryHolder { - private: - const uint32 m_petNumber; - const bool m_current; - const uint32 m_diffTime; - const std::string m_actionBar; - const uint32 m_savedHealth; - const uint32 m_savedMana; +private: + const uint32 m_petNumber; + const bool m_current; + const uint32 m_diffTime; + const std::string m_actionBar; + const uint32 m_savedHealth; + const uint32 m_savedMana; - public: - LoadPetFromDBQueryHolder(uint32 petNumber, bool current, uint32 diffTime, std::string actionBar, uint32 health, uint32 mana) - : m_petNumber(petNumber), m_current(current), m_diffTime(diffTime), m_actionBar(actionBar), - m_savedHealth(health), m_savedMana(mana) { } +public: + LoadPetFromDBQueryHolder(uint32 petNumber, bool current, uint32 diffTime, std::string actionBar, uint32 health, uint32 mana) + : m_petNumber(petNumber), m_current(current), m_diffTime(diffTime), m_actionBar(actionBar), + m_savedHealth(health), m_savedMana(mana) { } - uint32 GetPetNumber() const { return m_petNumber; } - uint32 GetDiffTime() const { return m_diffTime; } - bool GetCurrent() const { return m_current; } - uint32 GetSavedHealth() const { return m_savedHealth; } - uint32 GetSavedMana() const { return m_savedMana; } - std::string GetActionBar() const { return m_actionBar; } - bool Initialize(); + uint32 GetPetNumber() const { return m_petNumber; } + uint32 GetDiffTime() const { return m_diffTime; } + bool GetCurrent() const { return m_current; } + uint32 GetSavedHealth() const { return m_savedHealth; } + uint32 GetSavedMana() const { return m_savedMana; } + std::string GetActionBar() const { return m_actionBar; } + bool Initialize(); }; bool LoadPetFromDBQueryHolder::Initialize() @@ -105,7 +105,7 @@ uint8 WorldSession::HandleLoadPetFromDBFirstCallback(PreparedQueryResult result, if (pet_type == HUNTER_PET && savedhealth == 0 && asynchLoadType != PET_LOAD_SUMMON_DEAD_PET) { - WorldPacket data(SMSG_CAST_FAILED, 1+4+1+4); + WorldPacket data(SMSG_CAST_FAILED, 1 + 4 + 1 + 4); data << uint8(0); data << uint32(883); data << uint8(SPELL_FAILED_TARGETS_DEAD); @@ -181,7 +181,7 @@ uint8 WorldSession::HandleLoadPetFromDBFirstCallback(PreparedQueryResult result, pet->SetUInt32Value(UNIT_FIELD_BYTES_0, 0x800); // class = mage pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); - // this enables popup window (pet dismiss, cancel) + // this enables popup window (pet dismiss, cancel) break; case HUNTER_PET: pet->SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100); // class = warrior, gender = none, power = focus @@ -189,7 +189,7 @@ uint8 WorldSession::HandleLoadPetFromDBFirstCallback(PreparedQueryResult result, pet->SetByteFlag(UNIT_FIELD_BYTES_2, 2, fields[9].GetBool() ? UNIT_CAN_BE_ABANDONED : UNIT_CAN_BE_RENAMED | UNIT_CAN_BE_ABANDONED); pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); - // this enables popup window (pet abandon, cancel) + // this enables popup window (pet abandon, cancel) pet->SetMaxPower(POWER_HAPPINESS, pet->GetCreatePowers(POWER_HAPPINESS)); pet->SetPower(POWER_HAPPINESS, fields[12].GetUInt32()); pet->setPowerType(POWER_FOCUS); @@ -241,7 +241,7 @@ uint8 WorldSession::HandleLoadPetFromDBFirstCallback(PreparedQueryResult result, // TODO: pets should be summoned from real cast instead of just faking it? if (summon_spell_id) { - WorldPacket data(SMSG_SPELL_GO, (8+8+4+4+2)); + WorldPacket data(SMSG_SPELL_GO, (8 + 8 + 4 + 4 + 2)); data.append(owner->GetPackGUID()); data.append(owner->GetPackGUID()); data << uint8(0); @@ -352,7 +352,7 @@ void WorldSession::HandleLoadPetFromDBSecondCallback(LoadPetFromDBQueryHolder* h return; } -void WorldSession::HandleDismissCritter(WorldPacket &recvData) +void WorldSession::HandleDismissCritter(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -373,12 +373,12 @@ void WorldSession::HandleDismissCritter(WorldPacket &recvData) if (_player->GetCritterGUID() == pet->GetGUID()) { - if (pet->GetTypeId() == TYPEID_UNIT && pet->ToCreature()->IsSummon()) - pet->ToTempSummon()->UnSummon(); + if (pet->GetTypeId() == TYPEID_UNIT && pet->ToCreature()->IsSummon()) + pet->ToTempSummon()->UnSummon(); } } -void WorldSession::HandlePetAction(WorldPacket & recvData) +void WorldSession::HandlePetAction(WorldPacket& recvData) { uint64 guid1; uint32 data; @@ -391,7 +391,7 @@ void WorldSession::HandlePetAction(WorldPacket & recvData) uint8 flag = UNIT_ACTION_BUTTON_TYPE(data); //delete = 0x07 CastSpell = C1 // used also for charmed creature - Unit* pet= ObjectAccessor::GetUnit(*_player, guid1); + Unit* pet = ObjectAccessor::GetUnit(*_player, guid1); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("HandlePetAction: Pet %u - flag: %u, spellid: %u, target: %u.", uint32(GUID_LOPART(guid1)), uint32(flag), spellid, uint32(GUID_LOPART(guid2))); #endif @@ -443,7 +443,7 @@ void WorldSession::HandlePetAction(WorldPacket & recvData) } } -void WorldSession::HandlePetStopAttack(WorldPacket &recvData) +void WorldSession::HandlePetStopAttack(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -479,7 +479,7 @@ void WorldSession::HandlePetActionHelper(Unit* pet, uint64 guid1, uint16 spellid if (!charmInfo) { sLog->outError("WorldSession::HandlePetAction(petGuid: " UI64FMTD ", tagGuid: " UI64FMTD ", spellId: %u, flag: %u): object (entry: %u TypeId: %u) is considered pet-like but doesn't have a charminfo!", - guid1, guid2, spellid, flag, pet->GetGUIDLow(), pet->GetTypeId()); + guid1, guid2, spellid, flag, pet->GetGUIDLow(), pet->GetTypeId()); return; } @@ -489,127 +489,127 @@ void WorldSession::HandlePetActionHelper(Unit* pet, uint64 guid1, uint16 spellid switch (spellid) { case COMMAND_STAY: //flat=1792 //STAY - { - bool controlledMotion = pet->GetMotionMaster()->GetMotionSlotType(MOTION_SLOT_CONTROLLED) != NULL_MOTION_TYPE; - if (!controlledMotion) { - pet->StopMovingOnCurrentPos(); - pet->GetMotionMaster()->Clear(false); - pet->GetMotionMaster()->MoveIdle(); + bool controlledMotion = pet->GetMotionMaster()->GetMotionSlotType(MOTION_SLOT_CONTROLLED) != NULL_MOTION_TYPE; + if (!controlledMotion) + { + pet->StopMovingOnCurrentPos(); + pet->GetMotionMaster()->Clear(false); + pet->GetMotionMaster()->MoveIdle(); + } + + charmInfo->SetCommandState(COMMAND_STAY); + charmInfo->SetIsCommandAttack(false); + charmInfo->SetIsCommandFollow(false); + charmInfo->SetIsFollowing(false); + charmInfo->SetIsReturning(false); + charmInfo->SetIsAtStay(!controlledMotion); + charmInfo->SaveStayPosition(controlledMotion); + if (pet->ToPet()) + pet->ToPet()->ClearCastWhenWillAvailable(); + + + charmInfo->SetForcedSpell(0); + charmInfo->SetForcedTargetGUID(0); + break; } - - charmInfo->SetCommandState(COMMAND_STAY); - charmInfo->SetIsCommandAttack(false); - charmInfo->SetIsCommandFollow(false); - charmInfo->SetIsFollowing(false); - charmInfo->SetIsReturning(false); - charmInfo->SetIsAtStay(!controlledMotion); - charmInfo->SaveStayPosition(controlledMotion); - if (pet->ToPet()) - pet->ToPet()->ClearCastWhenWillAvailable(); - - - charmInfo->SetForcedSpell(0); - charmInfo->SetForcedTargetGUID(0); - break; - } case COMMAND_FOLLOW: //spellid=1792 //FOLLOW - { - pet->AttackStop(); - pet->InterruptNonMeleeSpells(false); - pet->ClearInPetCombat(); - pet->GetMotionMaster()->MoveFollow(_player, PET_FOLLOW_DIST, pet->GetFollowAngle()); - if (pet->ToPet()) - pet->ToPet()->ClearCastWhenWillAvailable(); - charmInfo->SetCommandState(COMMAND_FOLLOW); - - charmInfo->SetIsCommandAttack(false); - charmInfo->SetIsAtStay(false); - charmInfo->SetIsReturning(true); - charmInfo->SetIsCommandFollow(true); - charmInfo->SetIsFollowing(false); - charmInfo->RemoveStayPosition(); - charmInfo->SetForcedSpell(0); - charmInfo->SetForcedTargetGUID(0); - break; - } - case COMMAND_ATTACK: //spellid=1792 //ATTACK - { - // Can't attack if owner is pacified - if (_player->HasAuraType(SPELL_AURA_MOD_PACIFY)) - { - //pet->SendPetCastFail(spellid, SPELL_FAILED_PACIFIED); - //TODO: Send proper error message to client - return; - } - - // only place where pet can be player - Unit* TargetUnit = ObjectAccessor::GetUnit(*_player, guid2); - if (!TargetUnit) - return; - - if (Unit* owner = pet->GetOwner()) - if (!owner->IsValidAttackTarget(TargetUnit)) - return; - - // pussywizard: - if (Creature* creaturePet = pet->ToCreature()) - if (!creaturePet->_CanDetectFeignDeathOf(TargetUnit) || !creaturePet->CanCreatureAttack(TargetUnit) || creaturePet->isTargetNotAcceptableByMMaps(TargetUnit->GetGUID(), sWorld->GetGameTime(), TargetUnit)) - return; - - // Not let attack through obstructions - bool checkLos = !MMAP::MMapFactory::IsPathfindingEnabled(pet->GetMap()) || - (TargetUnit->GetTypeId() == TYPEID_UNIT && (TargetUnit->ToCreature()->isWorldBoss() || TargetUnit->ToCreature()->IsDungeonBoss())); - - if (checkLos && !pet->IsWithinLOSInMap(TargetUnit)) - { - WorldPacket data(SMSG_CAST_FAILED, 1+4+1); - data << uint8(0); - data << uint32(7389); - data << uint8(SPELL_FAILED_LINE_OF_SIGHT); - SendPacket(&data); - return; - } - - pet->ClearUnitState(UNIT_STATE_FOLLOW); - // This is true if pet has no target or has target but targets differs. - if (pet->GetVictim() != TargetUnit || (pet->GetVictim() == TargetUnit && !pet->GetCharmInfo()->IsCommandAttack())) { pet->AttackStop(); + pet->InterruptNonMeleeSpells(false); + pet->ClearInPetCombat(); + pet->GetMotionMaster()->MoveFollow(_player, PET_FOLLOW_DIST, pet->GetFollowAngle()); + if (pet->ToPet()) + pet->ToPet()->ClearCastWhenWillAvailable(); + charmInfo->SetCommandState(COMMAND_FOLLOW); - if (pet->GetTypeId() != TYPEID_PLAYER && pet->ToCreature()->IsAIEnabled) + charmInfo->SetIsCommandAttack(false); + charmInfo->SetIsAtStay(false); + charmInfo->SetIsReturning(true); + charmInfo->SetIsCommandFollow(true); + charmInfo->SetIsFollowing(false); + charmInfo->RemoveStayPosition(); + charmInfo->SetForcedSpell(0); + charmInfo->SetForcedTargetGUID(0); + break; + } + case COMMAND_ATTACK: //spellid=1792 //ATTACK + { + // Can't attack if owner is pacified + if (_player->HasAuraType(SPELL_AURA_MOD_PACIFY)) { - charmInfo->SetIsCommandAttack(true); - charmInfo->SetIsAtStay(false); - charmInfo->SetIsFollowing(false); - charmInfo->SetIsCommandFollow(false); - charmInfo->SetIsReturning(false); + //pet->SendPetCastFail(spellid, SPELL_FAILED_PACIFIED); + //TODO: Send proper error message to client + return; + } - pet->ToCreature()->AI()->AttackStart(TargetUnit); + // only place where pet can be player + Unit* TargetUnit = ObjectAccessor::GetUnit(*_player, guid2); + if (!TargetUnit) + return; - //10% chance to play special pet attack talk, else growl - if (pet->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != TargetUnit && urand(0, 100) < 10) - pet->SendPetTalk((uint32)PET_TALK_ATTACK); - else + if (Unit* owner = pet->GetOwner()) + if (!owner->IsValidAttackTarget(TargetUnit)) + return; + + // pussywizard: + if (Creature* creaturePet = pet->ToCreature()) + if (!creaturePet->_CanDetectFeignDeathOf(TargetUnit) || !creaturePet->CanCreatureAttack(TargetUnit) || creaturePet->isTargetNotAcceptableByMMaps(TargetUnit->GetGUID(), sWorld->GetGameTime(), TargetUnit)) + return; + + // Not let attack through obstructions + bool checkLos = !MMAP::MMapFactory::IsPathfindingEnabled(pet->GetMap()) || + (TargetUnit->GetTypeId() == TYPEID_UNIT && (TargetUnit->ToCreature()->isWorldBoss() || TargetUnit->ToCreature()->IsDungeonBoss())); + + if (checkLos && !pet->IsWithinLOSInMap(TargetUnit)) + { + WorldPacket data(SMSG_CAST_FAILED, 1 + 4 + 1); + data << uint8(0); + data << uint32(7389); + data << uint8(SPELL_FAILED_LINE_OF_SIGHT); + SendPacket(&data); + return; + } + + pet->ClearUnitState(UNIT_STATE_FOLLOW); + // This is true if pet has no target or has target but targets differs. + if (pet->GetVictim() != TargetUnit || (pet->GetVictim() == TargetUnit && !pet->GetCharmInfo()->IsCommandAttack())) + { + pet->AttackStop(); + + if (pet->GetTypeId() != TYPEID_PLAYER && pet->ToCreature()->IsAIEnabled) { - // 90% chance for pet and 100% chance for charmed creature + charmInfo->SetIsCommandAttack(true); + charmInfo->SetIsAtStay(false); + charmInfo->SetIsFollowing(false); + charmInfo->SetIsCommandFollow(false); + charmInfo->SetIsReturning(false); + + pet->ToCreature()->AI()->AttackStart(TargetUnit); + + //10% chance to play special pet attack talk, else growl + if (pet->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != TargetUnit && urand(0, 100) < 10) + pet->SendPetTalk((uint32)PET_TALK_ATTACK); + else + { + // 90% chance for pet and 100% chance for charmed creature + pet->SendPetAIReaction(guid1); + } + } + else // charmed player + { + charmInfo->SetIsCommandAttack(true); + charmInfo->SetIsAtStay(false); + charmInfo->SetIsFollowing(false); + charmInfo->SetIsCommandFollow(false); + charmInfo->SetIsReturning(false); + + pet->Attack(TargetUnit, true); pet->SendPetAIReaction(guid1); } } - else // charmed player - { - charmInfo->SetIsCommandAttack(true); - charmInfo->SetIsAtStay(false); - charmInfo->SetIsFollowing(false); - charmInfo->SetIsCommandFollow(false); - charmInfo->SetIsReturning(false); - - pet->Attack(TargetUnit, true); - pet->SendPetAIReaction(guid1); - } + break; } - break; - } case COMMAND_ABANDON: // abandon (hunter pet) or dismiss (summoned pet) if (pet->GetCharmerGUID() == GetPlayer()->GetGUID()) { @@ -629,7 +629,7 @@ void WorldSession::HandlePetActionHelper(Unit* pet, uint64 guid1, uint16 spellid //dismissing a summoned pet is like killing them (this prevents returning a soulshard...) pet->setDeathState(CORPSE); } - else if (pet->HasUnitTypeMask(UNIT_MASK_MINION|UNIT_MASK_SUMMON|UNIT_MASK_GUARDIAN|UNIT_MASK_CONTROLABLE_GUARDIAN)) + else if (pet->HasUnitTypeMask(UNIT_MASK_MINION | UNIT_MASK_SUMMON | UNIT_MASK_GUARDIAN | UNIT_MASK_CONTROLABLE_GUARDIAN)) { pet->ToTempSummon()->UnSummon(); } @@ -661,249 +661,249 @@ void WorldSession::HandlePetActionHelper(Unit* pet, uint64 guid1, uint16 spellid case ACT_DISABLED: // 0x81 spell (disabled), ignore case ACT_PASSIVE: // 0x01 case ACT_ENABLED: // 0xC1 spell - { - Unit* unit_target = nullptr; - - // do not cast unknown spells - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid); - if (!spellInfo) { - sLog->outError("WORLD: unknown PET spell id %i", spellid); - return; - } + Unit* unit_target = nullptr; - if (guid2) - unit_target = ObjectAccessor::GetUnit(*_player, guid2); - else if (!spellInfo->IsPositive()) - return; - - for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) - { - if (spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || spellInfo->Effects[i].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) + // do not cast unknown spells + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid); + if (!spellInfo) + { + sLog->outError("WORLD: unknown PET spell id %i", spellid); return; - } - - // do not cast not learned spells - if (!pet->HasSpell(spellid) || spellInfo->IsPassive()) - return; - - // Clear the flags as if owner clicked 'attack'. AI will reset them - // after AttackStart, even if spell failed - charmInfo->SetIsAtStay(false); - charmInfo->SetIsCommandAttack(!pet->ToCreature()->HasReactState(REACT_PASSIVE)); - charmInfo->SetIsReturning(false); - charmInfo->SetIsFollowing(false); - - Spell* spell = new Spell(pet, spellInfo, TRIGGERED_NONE); - spell->LoadScripts(); // xinef: load for CheckPetCast - - SpellCastResult result = spell->CheckPetCast(unit_target); - - //auto turn to target unless possessed - if (result == SPELL_FAILED_UNIT_NOT_INFRONT && !pet->isPossessed() && !pet->IsVehicle()) - { - if (unit_target) - { - pet->SetInFront(unit_target); - if (unit_target->GetTypeId() == TYPEID_PLAYER) - pet->SendUpdateToPlayer(unit_target->ToPlayer()); - } - else if (Unit* unit_target2 = spell->m_targets.GetUnitTarget()) - { - pet->SetInFront(unit_target2); - if (unit_target2->GetTypeId() == TYPEID_PLAYER) - pet->SendUpdateToPlayer(unit_target2->ToPlayer()); - } - if (Unit* powner = pet->GetCharmerOrOwner()) - if (powner->GetTypeId() == TYPEID_PLAYER) - pet->SendUpdateToPlayer(powner->ToPlayer()); - - result = SPELL_CAST_OK; - } - - if (result == SPELL_CAST_OK) - { - pet->ToCreature()->AddSpellCooldown(spellid, 0, 0); - - unit_target = spell->m_targets.GetUnitTarget(); - - //10% chance to play special pet attack talk, else growl - //actually this only seems to happen on special spells, fire shield for imp, torment for voidwalker, but it's stupid to check every spell - if (pet->IsPet() && (((Pet*)pet)->getPetType() == SUMMON_PET) && (pet != unit_target) && (urand(0, 100) < 10)) - pet->SendPetTalk((uint32)PET_TALK_SPECIAL_SPELL); - else - { - pet->SendPetAIReaction(guid1); } - if (unit_target && !GetPlayer()->IsFriendlyTo(unit_target) && !pet->isPossessed() && !pet->IsVehicle()) + if (guid2) + unit_target = ObjectAccessor::GetUnit(*_player, guid2); + else if (!spellInfo->IsPositive()) + return; + + for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - // This is true if pet has no target or has target but targets differs. - if (pet->GetVictim() != unit_target) + if (spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || spellInfo->Effects[i].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) + return; + } + + // do not cast not learned spells + if (!pet->HasSpell(spellid) || spellInfo->IsPassive()) + return; + + // Clear the flags as if owner clicked 'attack'. AI will reset them + // after AttackStart, even if spell failed + charmInfo->SetIsAtStay(false); + charmInfo->SetIsCommandAttack(!pet->ToCreature()->HasReactState(REACT_PASSIVE)); + charmInfo->SetIsReturning(false); + charmInfo->SetIsFollowing(false); + + Spell* spell = new Spell(pet, spellInfo, TRIGGERED_NONE); + spell->LoadScripts(); // xinef: load for CheckPetCast + + SpellCastResult result = spell->CheckPetCast(unit_target); + + //auto turn to target unless possessed + if (result == SPELL_FAILED_UNIT_NOT_INFRONT && !pet->isPossessed() && !pet->IsVehicle()) + { + if (unit_target) { - if (pet->ToCreature()->IsAIEnabled) - pet->ToCreature()->AI()->AttackStart(unit_target); + pet->SetInFront(unit_target); + if (unit_target->GetTypeId() == TYPEID_PLAYER) + pet->SendUpdateToPlayer(unit_target->ToPlayer()); } - } - - spell->prepare(&(spell->m_targets)); - - charmInfo->SetForcedSpell(0); - charmInfo->SetForcedTargetGUID(0); - } - else if (pet->ToPet() && (result == SPELL_FAILED_LINE_OF_SIGHT || result == SPELL_FAILED_OUT_OF_RANGE)) - { - unit_target = spell->m_targets.GetUnitTarget(); - bool haspositiveeffect = false; - - if (!unit_target) - return; - - // search positive effects for spell - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - { - if (spellInfo->_IsPositiveEffect(i, true)) + else if (Unit* unit_target2 = spell->m_targets.GetUnitTarget()) { - haspositiveeffect = true; - break; + pet->SetInFront(unit_target2); + if (unit_target2->GetTypeId() == TYPEID_PLAYER) + pet->SendUpdateToPlayer(unit_target2->ToPlayer()); } + if (Unit* powner = pet->GetCharmerOrOwner()) + if (powner->GetTypeId() == TYPEID_PLAYER) + pet->SendUpdateToPlayer(powner->ToPlayer()); + + result = SPELL_CAST_OK; } - if (pet->isPossessed() || pet->IsVehicle()) - Spell::SendCastResult(GetPlayer(), spellInfo, 0, result); - else if (GetPlayer()->IsFriendlyTo(unit_target) && !haspositiveeffect) - spell->SendPetCastResult(SPELL_FAILED_TARGET_FRIENDLY); - else - spell->SendPetCastResult(SPELL_FAILED_DONT_REPORT); - - if (!pet->HasSpellCooldown(spellid)) - if(pet->ToPet()) - pet->ToPet()->RemoveSpellCooldown(spellid, true); - - spell->finish(false); - delete spell; - - if (_player->HasAuraType(SPELL_AURA_MOD_PACIFY)) - return; - - bool tempspellIsPositive = false; - - if (!GetPlayer()->IsFriendlyTo(unit_target)) + if (result == SPELL_CAST_OK) { - // only place where pet can be player - Unit* TargetUnit = ObjectAccessor::GetUnit(*_player, guid2); - if (!TargetUnit) + pet->ToCreature()->AddSpellCooldown(spellid, 0, 0); + + unit_target = spell->m_targets.GetUnitTarget(); + + //10% chance to play special pet attack talk, else growl + //actually this only seems to happen on special spells, fire shield for imp, torment for voidwalker, but it's stupid to check every spell + if (pet->IsPet() && (((Pet*)pet)->getPetType() == SUMMON_PET) && (pet != unit_target) && (urand(0, 100) < 10)) + pet->SendPetTalk((uint32)PET_TALK_SPECIAL_SPELL); + else + { + pet->SendPetAIReaction(guid1); + } + + if (unit_target && !GetPlayer()->IsFriendlyTo(unit_target) && !pet->isPossessed() && !pet->IsVehicle()) + { + // This is true if pet has no target or has target but targets differs. + if (pet->GetVictim() != unit_target) + { + if (pet->ToCreature()->IsAIEnabled) + pet->ToCreature()->AI()->AttackStart(unit_target); + } + } + + spell->prepare(&(spell->m_targets)); + + charmInfo->SetForcedSpell(0); + charmInfo->SetForcedTargetGUID(0); + } + else if (pet->ToPet() && (result == SPELL_FAILED_LINE_OF_SIGHT || result == SPELL_FAILED_OUT_OF_RANGE)) + { + unit_target = spell->m_targets.GetUnitTarget(); + bool haspositiveeffect = false; + + if (!unit_target) return; - if (Unit* owner = pet->GetOwner()) - if (!owner->IsValidAttackTarget(TargetUnit)) + // search positive effects for spell + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (spellInfo->_IsPositiveEffect(i, true)) + { + haspositiveeffect = true; + break; + } + } + + if (pet->isPossessed() || pet->IsVehicle()) + Spell::SendCastResult(GetPlayer(), spellInfo, 0, result); + else if (GetPlayer()->IsFriendlyTo(unit_target) && !haspositiveeffect) + spell->SendPetCastResult(SPELL_FAILED_TARGET_FRIENDLY); + else + spell->SendPetCastResult(SPELL_FAILED_DONT_REPORT); + + if (!pet->HasSpellCooldown(spellid)) + if(pet->ToPet()) + pet->ToPet()->RemoveSpellCooldown(spellid, true); + + spell->finish(false); + delete spell; + + if (_player->HasAuraType(SPELL_AURA_MOD_PACIFY)) + return; + + bool tempspellIsPositive = false; + + if (!GetPlayer()->IsFriendlyTo(unit_target)) + { + // only place where pet can be player + Unit* TargetUnit = ObjectAccessor::GetUnit(*_player, guid2); + if (!TargetUnit) return; - pet->ClearUnitState(UNIT_STATE_FOLLOW); - // This is true if pet has no target or has target but targets differs. - if (pet->GetVictim() != TargetUnit || (pet->GetVictim() == TargetUnit && !pet->GetCharmInfo()->IsCommandAttack())) + if (Unit* owner = pet->GetOwner()) + if (!owner->IsValidAttackTarget(TargetUnit)) + return; + + pet->ClearUnitState(UNIT_STATE_FOLLOW); + // This is true if pet has no target or has target but targets differs. + if (pet->GetVictim() != TargetUnit || (pet->GetVictim() == TargetUnit && !pet->GetCharmInfo()->IsCommandAttack())) + { + if (pet->GetVictim()) + pet->AttackStop(); + + if (pet->GetTypeId() != TYPEID_PLAYER && pet->ToCreature() && pet->ToCreature()->IsAIEnabled) + { + charmInfo->SetIsCommandAttack(true); + charmInfo->SetIsAtStay(false); + charmInfo->SetIsFollowing(false); + charmInfo->SetIsCommandFollow(false); + charmInfo->SetIsReturning(false); + + pet->ToCreature()->AI()->AttackStart(TargetUnit); + + if (pet->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != TargetUnit && urand(0, 100) < 10) + pet->SendPetTalk((uint32)PET_TALK_SPECIAL_SPELL); + else + pet->SendPetAIReaction(guid1); + } + else // charmed player + { + if (pet->GetVictim() && pet->GetVictim() != TargetUnit) + pet->AttackStop(); + + charmInfo->SetIsCommandAttack(true); + charmInfo->SetIsAtStay(false); + charmInfo->SetIsFollowing(false); + charmInfo->SetIsCommandFollow(false); + charmInfo->SetIsReturning(false); + + pet->Attack(TargetUnit, true); + pet->SendPetAIReaction(guid1); + } + + pet->ToPet()->CastWhenWillAvailable(spellid, unit_target, NULL, tempspellIsPositive); + } + } + else if (haspositiveeffect) { - if (pet->GetVictim()) + bool tempspellIsPositive = true; + pet->ClearUnitState(UNIT_STATE_FOLLOW); + // This is true if pet has no target or has target but targets differs. + Unit* victim = pet->GetVictim(); + if (victim) + { pet->AttackStop(); + } + else + victim = nullptr; if (pet->GetTypeId() != TYPEID_PLAYER && pet->ToCreature() && pet->ToCreature()->IsAIEnabled) { - charmInfo->SetIsCommandAttack(true); + pet->StopMoving(); + pet->GetMotionMaster()->Clear(); + + charmInfo->SetIsCommandAttack(false); charmInfo->SetIsAtStay(false); charmInfo->SetIsFollowing(false); charmInfo->SetIsCommandFollow(false); charmInfo->SetIsReturning(false); - pet->ToCreature()->AI()->AttackStart(TargetUnit); + pet->GetMotionMaster()->MoveChase(unit_target); - if (pet->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != TargetUnit && urand(0, 100) < 10) + if (pet->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != unit_target && urand(0, 100) < 10) pet->SendPetTalk((uint32)PET_TALK_SPECIAL_SPELL); else + { pet->SendPetAIReaction(guid1); + } + + pet->ToPet()->CastWhenWillAvailable(spellid, unit_target, victim, tempspellIsPositive); } - else // charmed player - { - if (pet->GetVictim() && pet->GetVictim() != TargetUnit) - pet->AttackStop(); - - charmInfo->SetIsCommandAttack(true); - charmInfo->SetIsAtStay(false); - charmInfo->SetIsFollowing(false); - charmInfo->SetIsCommandFollow(false); - charmInfo->SetIsReturning(false); - - pet->Attack(TargetUnit, true); - pet->SendPetAIReaction(guid1); - } - - pet->ToPet()->CastWhenWillAvailable(spellid, unit_target, NULL, tempspellIsPositive); } } - else if (haspositiveeffect) + else { - bool tempspellIsPositive = true; - pet->ClearUnitState(UNIT_STATE_FOLLOW); - // This is true if pet has no target or has target but targets differs. - Unit* victim = pet->GetVictim(); - if (victim) + // dont spam alerts + if (!charmInfo->GetForcedSpell()) { - pet->AttackStop(); - } - else - victim = nullptr; - - if (pet->GetTypeId() != TYPEID_PLAYER && pet->ToCreature() && pet->ToCreature()->IsAIEnabled) - { - pet->StopMoving(); - pet->GetMotionMaster()->Clear(); - - charmInfo->SetIsCommandAttack(false); - charmInfo->SetIsAtStay(false); - charmInfo->SetIsFollowing(false); - charmInfo->SetIsCommandFollow(false); - charmInfo->SetIsReturning(false); - - pet->GetMotionMaster()->MoveChase(unit_target); - - if (pet->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != unit_target && urand(0, 100) < 10) - pet->SendPetTalk((uint32)PET_TALK_SPECIAL_SPELL); + if (pet->isPossessed() || pet->IsVehicle()) + Spell::SendCastResult(GetPlayer(), spellInfo, 0, result); else - { - pet->SendPetAIReaction(guid1); - } - - pet->ToPet()->CastWhenWillAvailable(spellid, unit_target, victim, tempspellIsPositive); + spell->SendPetCastResult(result); } + + if (!pet->ToCreature()->HasSpellCooldown(spellid)) + GetPlayer()->SendClearCooldown(spellid, pet); + + spell->finish(false); + delete spell; + + // reset specific flags in case of spell fail. AI will reset other flags + pet->PetSpellFail(spellInfo, unit_target, result); } + break; } - else - { - // dont spam alerts - if (!charmInfo->GetForcedSpell()) - { - if (pet->isPossessed() || pet->IsVehicle()) - Spell::SendCastResult(GetPlayer(), spellInfo, 0, result); - else - spell->SendPetCastResult(result); - } - - if (!pet->ToCreature()->HasSpellCooldown(spellid)) - GetPlayer()->SendClearCooldown(spellid, pet); - - spell->finish(false); - delete spell; - - // reset specific flags in case of spell fail. AI will reset other flags - pet->PetSpellFail(spellInfo, unit_target, result); - } - break; - } default: sLog->outError("WORLD: unknown PET flag Action %i and spellid %i.", uint32(flag), spellid); } } -void WorldSession::HandlePetNameQuery(WorldPacket & recvData) +void WorldSession::HandlePetNameQuery(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("HandlePetNameQuery. CMSG_PET_NAME_QUERY"); @@ -923,7 +923,7 @@ void WorldSession::SendPetNameQuery(uint64 petguid, uint32 petnumber) Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, petguid); if (!pet) { - WorldPacket data(SMSG_PET_NAME_QUERY_RESPONSE, (4+1+4+1)); + WorldPacket data(SMSG_PET_NAME_QUERY_RESPONSE, (4 + 1 + 4 + 1)); data << uint32(petnumber); data << uint8(0); data << uint32(0); @@ -945,7 +945,7 @@ void WorldSession::SendPetNameQuery(uint64 petguid, uint32 petnumber) else name = pet->GetName(); - WorldPacket data(SMSG_PET_NAME_QUERY_RESPONSE, (4+4+name.size()+1)); + WorldPacket data(SMSG_PET_NAME_QUERY_RESPONSE, (4 + 4 + name.size() + 1)); data << uint32(petnumber); data << name.c_str(); data << uint32(pet->GetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP)); @@ -989,7 +989,7 @@ bool WorldSession::CheckStableMaster(uint64 guid) return true; } -void WorldSession::HandlePetSetAction(WorldPacket & recvData) +void WorldSession::HandlePetSetAction(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("HandlePetSetAction. CMSG_PET_SET_ACTION"); @@ -1065,7 +1065,7 @@ void WorldSession::HandlePetSetAction(WorldPacket & recvData) uint32 spell_id_0 = UNIT_ACTION_BUTTON_ACTION(data[0]); UnitActionBarEntry const* actionEntry_1 = charmInfo->GetActionBarEntry(position[1]); if (!actionEntry_1 || spell_id_0 != actionEntry_1->GetAction() || - act_state_0 != actionEntry_1->GetType()) + act_state_0 != actionEntry_1->GetType()) continue; } @@ -1075,7 +1075,7 @@ void WorldSession::HandlePetSetAction(WorldPacket & recvData) uint32 spell_id_1 = UNIT_ACTION_BUTTON_ACTION(data[1]); UnitActionBarEntry const* actionEntry_0 = charmInfo->GetActionBarEntry(position[0]); if (!actionEntry_0 || spell_id_1 != actionEntry_0->GetAction() || - act_state_1 != actionEntry_0->GetType()) + act_state_1 != actionEntry_0->GetType()) continue; } } @@ -1118,7 +1118,7 @@ void WorldSession::HandlePetSetAction(WorldPacket & recvData) } } -void WorldSession::HandlePetRename(WorldPacket & recvData) +void WorldSession::HandlePetRename(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("HandlePetRename. CMSG_PET_RENAME"); @@ -1135,10 +1135,10 @@ void WorldSession::HandlePetRename(WorldPacket & recvData) recvData >> isdeclined; Pet* pet = ObjectAccessor::FindPet(petguid); - // check it! - if (!pet || !pet->IsPet() || ((Pet*)pet)->getPetType()!= HUNTER_PET || - !pet->HasByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED) || - pet->GetOwnerGUID() != _player->GetGUID() || !pet->GetCharmInfo()) + // check it! + if (!pet || !pet->IsPet() || ((Pet*)pet)->getPetType() != HUNTER_PET || + !pet->HasByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED) || + pet->GetOwnerGUID() != _player->GetGUID() || !pet->GetCharmInfo()) return; PetNameInvalidReason res = ObjectMgr::CheckPetName(name); @@ -1191,7 +1191,7 @@ void WorldSession::HandlePetRename(WorldPacket & recvData) stmt->setUInt32(0, _player->GetGUIDLow()); for (uint8 i = 0; i < 5; i++) - stmt->setString(i+1, declinedname.name[i]); + stmt->setString(i + 1, declinedname.name[i]); trans->Append(stmt); } @@ -1208,7 +1208,7 @@ void WorldSession::HandlePetRename(WorldPacket & recvData) pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped } -void WorldSession::HandlePetAbandon(WorldPacket & recvData) +void WorldSession::HandlePetAbandon(WorldPacket& recvData) { uint64 guid; recvData >> guid; //pet guid @@ -1228,7 +1228,7 @@ void WorldSession::HandlePetAbandon(WorldPacket & recvData) if (pet->GetGUID() == _player->GetPetGUID()) { uint32 feelty = pet->GetPower(POWER_HAPPINESS); - pet->SetPower(POWER_HAPPINESS, feelty > 50000 ? (feelty-50000) : 0); + pet->SetPower(POWER_HAPPINESS, feelty > 50000 ? (feelty - 50000) : 0); } _player->RemovePet((Pet*)pet, PET_SAVE_AS_DELETED); @@ -1334,7 +1334,7 @@ void WorldSession::HandlePetCastSpellOpcode(WorldPacket& recvPacket) return; } - // do not cast not learned spells + // do not cast not learned spells if (!caster->HasSpell(spellId) || spellInfo->IsPassive()) return; @@ -1403,7 +1403,7 @@ void WorldSession::HandlePetCastSpellOpcode(WorldPacket& recvPacket) caster->AddUnitState(UNIT_STATE_FOLLOW); } -void WorldSession::SendPetNameInvalid(uint32 error, const std::string& name, DeclinedName *declinedName) +void WorldSession::SendPetNameInvalid(uint32 error, const std::string& name, DeclinedName* declinedName) { WorldPacket data(SMSG_PET_NAME_INVALID, 4 + name.size() + 1 + 1); data << uint32(error); @@ -1419,7 +1419,7 @@ void WorldSession::SendPetNameInvalid(uint32 error, const std::string& name, Dec SendPacket(&data); } -void WorldSession::HandlePetLearnTalent(WorldPacket & recvData) +void WorldSession::HandlePetLearnTalent(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_PET_LEARN_TALENT"); @@ -1433,7 +1433,7 @@ void WorldSession::HandlePetLearnTalent(WorldPacket & recvData) _player->SendTalentsInfoData(true); } -void WorldSession::HandleLearnPreviewTalentsPet(WorldPacket & recvData) +void WorldSession::HandleLearnPreviewTalentsPet(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_LEARN_PREVIEW_TALENTS_PET"); diff --git a/src/server/game/Handlers/PetitionsHandler.cpp b/src/server/game/Handlers/PetitionsHandler.cpp index cf32e25b2..a4e4a5567 100644 --- a/src/server/game/Handlers/PetitionsHandler.cpp +++ b/src/server/game/Handlers/PetitionsHandler.cpp @@ -31,7 +31,7 @@ enum CharterItemIDs ARENA_TEAM_CHARTER_5v5 = 23562 }; -void WorldSession::HandlePetitionBuyOpcode(WorldPacket & recvData) +void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_PETITION_BUY"); @@ -172,7 +172,8 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket & recvData) } if (!_player->HasEnoughMoney(cost)) - { //player hasn't got enough money + { + //player hasn't got enough money _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, charterid, 0); return; } @@ -260,7 +261,7 @@ void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_PETITION_SHOW_SIGNATURES petition entry: '%u'", petitionGuidLow); #endif - WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+1+signs*12)); + WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8 + 8 + 4 + 1 + signs * 12)); data << uint64(petitionguid); // petition guid data << uint64(_player->GetGUID()); // owner guid data << uint32(petitionGuidLow); // guild guid @@ -276,7 +277,7 @@ void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recvData) SendPacket(&data); } -void WorldSession::HandlePetitionQueryOpcode(WorldPacket & recvData) +void WorldSession::HandlePetitionQueryOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_PETITION_QUERY"); // ok @@ -305,7 +306,7 @@ void WorldSession::SendPetitionQueryOpcode(uint64 petitionguid) } uint8 type = petition->petitionType; - WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4+8+petition->petitionName.size()+1+1+4*12+2+10)); + WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4 + 8 + petition->petitionName.size() + 1 + 1 + 4 * 12 + 2 + 10)); data << uint32(GUID_LOPART(petitionguid)); // guild/team guid (in Trinity always same as GUID_LOPART(petition guid) data << MAKE_NEW_GUID(petition->ownerGuid, 0, HIGHGUID_PLAYER); // charter owner guid data << petition->petitionName; // name (guild/arena team) @@ -319,8 +320,8 @@ void WorldSession::SendPetitionQueryOpcode(uint64 petitionguid) } else { - data << uint32(type-1); - data << uint32(type-1); + data << uint32(type - 1); + data << uint32(type - 1); data << uint32(type); // bypass client - side limitation, a different value is needed here for each petition } data << uint32(0); // 5 @@ -342,7 +343,7 @@ void WorldSession::SendPetitionQueryOpcode(uint64 petitionguid) SendPacket(&data); } -void WorldSession::HandlePetitionRenameOpcode(WorldPacket & recvData) +void WorldSession::HandlePetitionRenameOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode MSG_PETITION_RENAME"); // ok @@ -407,13 +408,13 @@ void WorldSession::HandlePetitionRenameOpcode(WorldPacket & recvData) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Petition (GUID: %u) renamed to '%s'", GUID_LOPART(petitionGuid), newName.c_str()); #endif - WorldPacket data(MSG_PETITION_RENAME, (8+newName.size()+1)); + WorldPacket data(MSG_PETITION_RENAME, (8 + newName.size() + 1)); data << uint64(petitionGuid); data << newName; SendPacket(&data); } -void WorldSession::HandlePetitionSignOpcode(WorldPacket & recvData) +void WorldSession::HandlePetitionSignOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_PETITION_SIGN"); // ok @@ -509,7 +510,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket & recvData) if (found) { - WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4)); + WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8 + 8 + 4)); data << uint64(petitionGuid); data << uint64(_player->GetGUID()); data << (uint32)PETITION_SIGN_ALREADY_SIGNED; @@ -539,7 +540,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket & recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "PETITION SIGN: GUID %u by player: %s (GUID: %u Account: %u)", GUID_LOPART(petitionGuid), _player->GetName().c_str(), playerGuid, GetAccountId()); #endif - WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4)); + WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8 + 8 + 4)); data << uint64(petitionGuid); data << uint64(_player->GetGUID()); data << uint32(PETITION_SIGN_OK); @@ -557,7 +558,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket & recvData) owner->GetSession()->SendPacket(&data); } -void WorldSession::HandlePetitionDeclineOpcode(WorldPacket & recvData) +void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode MSG_PETITION_DECLINE"); // ok @@ -583,7 +584,7 @@ void WorldSession::HandlePetitionDeclineOpcode(WorldPacket & recvData) } } -void WorldSession::HandleOfferPetitionOpcode(WorldPacket & recvData) +void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_OFFER_PETITION"); // ok @@ -657,7 +658,7 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket & recvData) Signatures const* signatures = sPetitionMgr->GetSignature(GUID_LOPART(petitionguid)); uint8 signs = signatures ? signatures->signatureMap.size() : 0; - WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+signs+signs*12)); + WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8 + 8 + 4 + signs + signs * 12)); data << uint64(petitionguid); // petition guid data << uint64(_player->GetGUID()); // owner guid data << uint32(GUID_LOPART(petitionguid)); // guild guid @@ -673,7 +674,7 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket & recvData) player->GetSession()->SendPacket(&data); } -void WorldSession::HandleTurnInPetitionOpcode(WorldPacket & recvData) +void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received opcode CMSG_TURN_IN_PETITION"); @@ -761,7 +762,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket & recvData) if (type == GUILD_CHARTER_TYPE) requiredSignatures = sWorld->getIntConfig(CONFIG_MIN_PETITION_SIGNS); else - requiredSignatures = type-1; + requiredSignatures = type - 1; // Notify player if signatures are missing if (signs < requiredSignatures) @@ -855,7 +856,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket & recvData) SendPacket(&data); } -void WorldSession::HandlePetitionShowListOpcode(WorldPacket & recvData) +void WorldSession::HandlePetitionShowListOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received CMSG_PETITION_SHOWLIST"); @@ -878,7 +879,7 @@ void WorldSession::SendPetitionShowList(uint64 guid) return; } - WorldPacket data(SMSG_PETITION_SHOWLIST, 8+1+4*6); + WorldPacket data(SMSG_PETITION_SHOWLIST, 8 + 1 + 4 * 6); data << guid; // npc guid if (creature->IsTabardDesigner()) diff --git a/src/server/game/Handlers/QueryHandler.cpp b/src/server/game/Handlers/QueryHandler.cpp index 20c786309..9747a2b45 100644 --- a/src/server/game/Handlers/QueryHandler.cpp +++ b/src/server/game/Handlers/QueryHandler.cpp @@ -23,7 +23,7 @@ void WorldSession::SendNameQueryOpcode(uint64 guid) { GlobalPlayerData const* playerData = sWorld->GetGlobalPlayerData(GUID_LOPART(guid)); - WorldPacket data(SMSG_NAME_QUERY_RESPONSE, (8+1+1+1+1+1+10)); + WorldPacket data(SMSG_NAME_QUERY_RESPONSE, (8 + 1 + 1 + 1 + 1 + 1 + 10)); data.appendPackGUID(guid); if (!playerData) { @@ -50,7 +50,7 @@ void WorldSession::SendNameQueryOpcode(uint64 guid) data << names->name[i]; } else*/ - data << uint8(0); // Name is not declined + data << uint8(0); // Name is not declined SendPacket(&data); } @@ -66,21 +66,21 @@ void WorldSession::HandleNameQueryOpcode(WorldPacket& recvData) SendNameQueryOpcode(guid); } -void WorldSession::HandleQueryTimeOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleQueryTimeOpcode(WorldPacket& /*recvData*/) { SendQueryTimeResponse(); } void WorldSession::SendQueryTimeResponse() { - WorldPacket data(SMSG_QUERY_TIME_RESPONSE, 4+4); + WorldPacket data(SMSG_QUERY_TIME_RESPONSE, 4 + 4); data << uint32(time(nullptr)); data << uint32(sWorld->GetNextDailyQuestsResetTime() - time(nullptr)); SendPacket(&data); } /// Only _static_ data is sent in this packet !!! -void WorldSession::HandleCreatureQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleCreatureQueryOpcode(WorldPacket& recvData) { uint32 entry; recvData >> entry; @@ -93,7 +93,7 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket & recvData) std::string Name, Title; Name = ci->Name; Title = ci->SubName; - + LocaleConstant loc_idx = GetSessionDbLocaleIndex(); if (loc_idx >= 0) { @@ -103,7 +103,7 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket & recvData) ObjectMgr::GetLocaleString(cl->Title, loc_idx, Title); } } - // guess size + // guess size WorldPacket data(SMSG_CREATURE_QUERY_RESPONSE, 100); data << uint32(entry); // creature entry data << Name; @@ -150,7 +150,7 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket & recvData) } /// Only _static_ data is sent in this packet !!! -void WorldSession::HandleGameObjectQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleGameObjectQueryOpcode(WorldPacket& recvData) { uint32 entry; recvData >> entry; @@ -163,11 +163,11 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket & recvData) std::string Name; std::string IconName; std::string CastBarCaption; - + Name = info->name; IconName = info->IconName; CastBarCaption = info->castBarCaption; - + LocaleConstant localeConstant = GetSessionDbLocaleIndex(); if (localeConstant >= LOCALE_enUS) if (GameObjectLocale const* gameObjectLocale = sObjectMgr->GetGameObjectLocale(entry)) @@ -208,7 +208,7 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket & recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_GAMEOBJECT_QUERY - Missing gameobject info for (GUID: %u, ENTRY: %u)", - GUID_LOPART(guid), entry); + GUID_LOPART(guid), entry); #endif WorldPacket data (SMSG_GAMEOBJECT_QUERY_RESPONSE, 4); data << uint32(entry | 0x80000000); @@ -219,7 +219,7 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket & recvData) } } -void WorldSession::HandleCorpseQueryOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleCorpseQueryOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received MSG_CORPSE_QUERY"); @@ -261,7 +261,7 @@ void WorldSession::HandleCorpseQueryOpcode(WorldPacket & /*recvData*/) } } - WorldPacket data(MSG_CORPSE_QUERY, 1+(6*4)); + WorldPacket data(MSG_CORPSE_QUERY, 1 + (6 * 4)); data << uint8(1); // corpse found data << int32(mapid); data << float(x); @@ -272,7 +272,7 @@ void WorldSession::HandleCorpseQueryOpcode(WorldPacket & /*recvData*/) SendPacket(&data); } -void WorldSession::HandleNpcTextQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleNpcTextQueryOpcode(WorldPacket& recvData) { uint32 textID; uint64 guid; @@ -363,7 +363,7 @@ void WorldSession::HandleNpcTextQueryOpcode(WorldPacket & recvData) } /// Only _static_ data is sent in this packet !!! -void WorldSession::HandlePageTextQueryOpcode(WorldPacket & recvData) +void WorldSession::HandlePageTextQueryOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_PAGE_TEXT_QUERY"); @@ -376,7 +376,7 @@ void WorldSession::HandlePageTextQueryOpcode(WorldPacket & recvData) while (pageID) { PageText const* pageText = sObjectMgr->GetPageText(pageID); - // guess size + // guess size WorldPacket data(SMSG_PAGE_TEXT_QUERY_RESPONSE, 50); data << pageID; @@ -389,12 +389,12 @@ void WorldSession::HandlePageTextQueryOpcode(WorldPacket & recvData) else { std::string Text = pageText->Text; - + int loc_idx = GetSessionDbLocaleIndex(); if (loc_idx >= 0) if (PageTextLocale const* player = sObjectMgr->GetPageTextLocale(pageID)) ObjectMgr::GetLocaleString(player->Text, loc_idx, Text); - + data << Text; data << uint32(pageText->NextPage); pageID = pageText->NextPage; @@ -407,7 +407,7 @@ void WorldSession::HandlePageTextQueryOpcode(WorldPacket & recvData) } } -void WorldSession::HandleCorpseMapPositionQuery(WorldPacket & recvData) +void WorldSession::HandleCorpseMapPositionQuery(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recv CMSG_CORPSE_MAP_POSITION_QUERY"); @@ -416,7 +416,7 @@ void WorldSession::HandleCorpseMapPositionQuery(WorldPacket & recvData) uint32 unk; recvData >> unk; - WorldPacket data(SMSG_CORPSE_MAP_POSITION_QUERY_RESPONSE, 4+4+4+4); + WorldPacket data(SMSG_CORPSE_MAP_POSITION_QUERY_RESPONSE, 4 + 4 + 4 + 4); data << float(0); data << float(0); data << float(0); @@ -451,7 +451,7 @@ void WorldSession::HandleQuestPOIQuery(WorldPacket& recvData) uint16 questSlot = _player->FindQuestSlot(questId); if (questSlot != MAX_QUEST_LOG_SIZE) - questOk =_player->GetQuestSlotQuestId(questSlot) == questId; + questOk = _player->GetQuestSlotQuestId(questSlot) == questId; if (questOk) { diff --git a/src/server/game/Handlers/QuestHandler.cpp b/src/server/game/Handlers/QuestHandler.cpp index c77d63681..3155c4249 100644 --- a/src/server/game/Handlers/QuestHandler.cpp +++ b/src/server/game/Handlers/QuestHandler.cpp @@ -25,7 +25,7 @@ #include "LuaEngine.h" #endif -void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -43,22 +43,22 @@ void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket & recvData) switch (questGiver->GetTypeId()) { case TYPEID_UNIT: - { + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_QUESTGIVER_STATUS_QUERY for npc, guid = %u", uint32(GUID_LOPART(guid))); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_QUESTGIVER_STATUS_QUERY for npc, guid = %u", uint32(GUID_LOPART(guid))); #endif - if (!questGiver->ToCreature()->IsHostileTo(_player)) // do not show quest status to enemies - questStatus = _player->GetQuestDialogStatus(questGiver); - break; - } + if (!questGiver->ToCreature()->IsHostileTo(_player)) // do not show quest status to enemies + questStatus = _player->GetQuestDialogStatus(questGiver); + break; + } case TYPEID_GAMEOBJECT: - { + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_QUESTGIVER_STATUS_QUERY for GameObject guid = %u", uint32(GUID_LOPART(guid))); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_QUESTGIVER_STATUS_QUERY for GameObject guid = %u", uint32(GUID_LOPART(guid))); #endif - questStatus = _player->GetQuestDialogStatus(questGiver); - break; - } + questStatus = _player->GetQuestDialogStatus(questGiver); + break; + } default: sLog->outError("QuestGiver called for unexpected type %u", questGiver->GetTypeId()); break; @@ -68,7 +68,7 @@ void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket & recvData) _player->PlayerTalkClass->SendQuestGiverStatus(uint8(questStatus), guid); } -void WorldSession::HandleQuestgiverHelloOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestgiverHelloOpcode(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -94,8 +94,8 @@ void WorldSession::HandleQuestgiverHelloOpcode(WorldPacket & recvData) creature->StopMoving(); #ifdef ELUNA - if (sEluna->OnGossipHello(_player, creature)) - return; + if (sEluna->OnGossipHello(_player, creature)) + return; #endif if (sScriptMgr->OnGossipHello(_player, creature)) @@ -107,7 +107,7 @@ void WorldSession::HandleQuestgiverHelloOpcode(WorldPacket & recvData) creature->AI()->sGossipHello(_player); } -void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvData) { uint64 guid; uint32 questId; @@ -118,11 +118,11 @@ void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket & recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_QUESTGIVER_ACCEPT_QUEST npc = %u, quest = %u, unk1 = %u", uint32(GUID_LOPART(guid)), questId, unk1); #endif - Object* object = ObjectAccessor::GetObjectByTypeMask(*_player, guid, TYPEMASK_UNIT|TYPEMASK_GAMEOBJECT|TYPEMASK_ITEM|TYPEMASK_PLAYER); + Object* object = ObjectAccessor::GetObjectByTypeMask(*_player, guid, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM | TYPEMASK_PLAYER); // no or incorrect quest giver if (!object || object == _player || (object->GetTypeId() != TYPEID_PLAYER && !object->hasQuest(questId)) || - (object->GetTypeId() == TYPEID_PLAYER && !object->ToPlayer()->CanShareQuest(questId))) + (object->GetTypeId() == TYPEID_PLAYER && !object->ToPlayer()->CanShareQuest(questId))) { _player->PlayerTalkClass->SendCloseGossip(); _player->SetDivider(0); @@ -199,7 +199,7 @@ void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket & recvData) _player->PlayerTalkClass->SendCloseGossip(); } -void WorldSession::HandleQuestgiverQueryQuestOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestgiverQueryQuestOpcode(WorldPacket& recvData) { uint64 guid; uint32 questId; @@ -235,7 +235,7 @@ void WorldSession::HandleQuestgiverQueryQuestOpcode(WorldPacket & recvData) } } -void WorldSession::HandleQuestQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestQueryOpcode(WorldPacket& recvData) { if (!_player) return; @@ -250,7 +250,7 @@ void WorldSession::HandleQuestQueryOpcode(WorldPacket & recvData) _player->PlayerTalkClass->SendQuestQueryResponse(quest); } -void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket& recvData) { uint32 questId, reward; uint64 guid; @@ -277,7 +277,7 @@ void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket & recvData) if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId)) { if ((!_player->CanSeeStartQuest(quest) && _player->GetQuestStatus(questId) == QUEST_STATUS_NONE) || - (_player->GetQuestStatus(questId) != QUEST_STATUS_COMPLETE && !quest->IsAutoComplete())) + (_player->GetQuestStatus(questId) != QUEST_STATUS_COMPLETE && !quest->IsAutoComplete())) { sLog->outError("HACK ALERT: Player %s (guid: %u) is trying to complete quest (id: %u) but he has no right to do it!", _player->GetName().c_str(), _player->GetGUIDLow(), questId); @@ -290,45 +290,45 @@ void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket & recvData) switch (object->GetTypeId()) { case TYPEID_UNIT: - { - Creature* questgiver = object->ToCreature(); - if (!sScriptMgr->OnQuestReward(_player, questgiver, quest, reward)) { - // Send next quest - if (Quest const* nextQuest = _player->GetNextQuest(guid, quest)) + Creature* questgiver = object->ToCreature(); + if (!sScriptMgr->OnQuestReward(_player, questgiver, quest, reward)) { - if (_player->CanAddQuest(nextQuest, false) && _player->CanTakeQuest(nextQuest, false)) + // Send next quest + if (Quest const* nextQuest = _player->GetNextQuest(guid, quest)) { - if (nextQuest->IsAutoAccept()) - _player->AddQuestAndCheckCompletion(nextQuest, object); - _player->PlayerTalkClass->SendQuestGiverQuestDetails(nextQuest, guid, true); + if (_player->CanAddQuest(nextQuest, false) && _player->CanTakeQuest(nextQuest, false)) + { + if (nextQuest->IsAutoAccept()) + _player->AddQuestAndCheckCompletion(nextQuest, object); + _player->PlayerTalkClass->SendQuestGiverQuestDetails(nextQuest, guid, true); + } } - } - questgiver->AI()->sQuestReward(_player, quest, reward); + questgiver->AI()->sQuestReward(_player, quest, reward); + } + break; } - break; - } case TYPEID_GAMEOBJECT: - { - GameObject* questGiver = object->ToGameObject(); - if (!sScriptMgr->OnQuestReward(_player, questGiver, quest, reward)) { - // Send next quest - if (Quest const* nextQuest = _player->GetNextQuest(guid, quest)) + GameObject* questGiver = object->ToGameObject(); + if (!sScriptMgr->OnQuestReward(_player, questGiver, quest, reward)) { - if (_player->CanAddQuest(nextQuest, false) && _player->CanTakeQuest(nextQuest, false)) + // Send next quest + if (Quest const* nextQuest = _player->GetNextQuest(guid, quest)) { - if (nextQuest->IsAutoAccept()) - _player->AddQuestAndCheckCompletion(nextQuest, object); - _player->PlayerTalkClass->SendQuestGiverQuestDetails(nextQuest, guid, true); + if (_player->CanAddQuest(nextQuest, false) && _player->CanTakeQuest(nextQuest, false)) + { + if (nextQuest->IsAutoAccept()) + _player->AddQuestAndCheckCompletion(nextQuest, object); + _player->PlayerTalkClass->SendQuestGiverQuestDetails(nextQuest, guid, true); + } } - } - questGiver->AI()->QuestReward(_player, quest, reward); + questGiver->AI()->QuestReward(_player, quest, reward); + } + break; } - break; - } default: break; } @@ -338,7 +338,7 @@ void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket & recvData) } } -void WorldSession::HandleQuestgiverRequestRewardOpcode(WorldPacket & recvData) +void WorldSession::HandleQuestgiverRequestRewardOpcode(WorldPacket& recvData) { uint32 questId; uint64 guid; @@ -508,7 +508,7 @@ void WorldSession::HandleQuestgiverCompleteQuest(WorldPacket& recvData) if (!_player->CanSeeStartQuest(quest) && _player->GetQuestStatus(questId) == QUEST_STATUS_NONE) { sLog->outError("Possible hacking attempt: Player %s [guid: %u] tried to complete quest [entry: %u] without being in possession of the quest!", - _player->GetName().c_str(), _player->GetGUIDLow(), questId); + _player->GetName().c_str(), _player->GetGUIDLow(), questId); return; } @@ -592,10 +592,10 @@ void WorldSession::HandlePushQuestToParty(WorldPacket& recvPacket) { // Check if player is in BG if (_player->InBattleground()) - { - _player->GetSession()->SendNotification(LANG_BG_SHARE_QUEST_ERROR); - continue; - } + { + _player->GetSession()->SendNotification(LANG_BG_SHARE_QUEST_ERROR); + continue; + } } if (player->GetDivider() != 0) @@ -693,14 +693,14 @@ void WorldSession::HandleQuestgiverStatusMultipleQuery(WorldPacket& /*recvPacket SendPacket(&data); } -void WorldSession::HandleQueryQuestsCompleted(WorldPacket & /*recvData*/) +void WorldSession::HandleQueryQuestsCompleted(WorldPacket& /*recvData*/) { size_t rew_count = _player->GetRewardedQuestCount(); WorldPacket data(SMSG_QUERY_QUESTS_COMPLETED_RESPONSE, 4 + 4 * rew_count); data << uint32(rew_count); - const RewardedQuestSet &rewQuests = _player->getRewardedQuests(); + const RewardedQuestSet& rewQuests = _player->getRewardedQuests(); for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) data << uint32(*itr); diff --git a/src/server/game/Handlers/ReferAFriendHandler.cpp b/src/server/game/Handlers/ReferAFriendHandler.cpp index 55fea7217..a93bc2649 100644 --- a/src/server/game/Handlers/ReferAFriendHandler.cpp +++ b/src/server/game/Handlers/ReferAFriendHandler.cpp @@ -39,7 +39,8 @@ void WorldSession::HandleGrantLevel(WorldPacket& recvData) else if (target->GetGroup() != _player->GetGroup()) error = ERR_REFER_A_FRIEND_NOT_IN_GROUP; - if (error) { + if (error) + { WorldPacket data(SMSG_REFER_A_FRIEND_FAILURE, 24); data << uint32(error); if (error == ERR_REFER_A_FRIEND_NOT_IN_GROUP) diff --git a/src/server/game/Handlers/SkillHandler.cpp b/src/server/game/Handlers/SkillHandler.cpp index 421c34e41..72b02cb6e 100644 --- a/src/server/game/Handlers/SkillHandler.cpp +++ b/src/server/game/Handlers/SkillHandler.cpp @@ -15,7 +15,7 @@ #include "WorldPacket.h" #include "WorldSession.h" -void WorldSession::HandleLearnTalentOpcode(WorldPacket & recvData) +void WorldSession::HandleLearnTalentOpcode(WorldPacket& recvData) { uint32 talent_id, requested_rank; recvData >> talent_id >> requested_rank; @@ -50,7 +50,7 @@ void WorldSession::HandleLearnPreviewTalents(WorldPacket& recvPacket) recvPacket.rfinish(); } -void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket & recvData) +void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_TALENT_WIPE_CONFIRM"); @@ -76,7 +76,7 @@ void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket & recvData) if (!(_player->resetTalents())) { - WorldPacket data(MSG_TALENT_WIPE_CONFIRM, 8+4); //you have not any talent + WorldPacket data(MSG_TALENT_WIPE_CONFIRM, 8 + 4); //you have not any talent data << uint64(0); data << uint32(0); SendPacket(&data); diff --git a/src/server/game/Handlers/SpellHandler.cpp b/src/server/game/Handlers/SpellHandler.cpp index 4fa22c252..d7f7ec198 100644 --- a/src/server/game/Handlers/SpellHandler.cpp +++ b/src/server/game/Handlers/SpellHandler.cpp @@ -208,7 +208,7 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) { pUser->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, nullptr); sLog->outError("Possible hacking attempt: Player %s [guid: %u] tried to open item [guid: %u, entry: %u] which is not openable!", - pUser->GetName().c_str(), pUser->GetGUIDLow(), item->GetGUIDLow(), proto->ItemId); + pUser->GetName().c_str(), pUser->GetGUIDLow(), item->GetGUIDLow(), proto->ItemId); return; } @@ -289,7 +289,7 @@ void WorldSession::HandleOpenWrappedItemCallback(PreparedQueryResult result, uin CharacterDatabase.CommitTransaction(trans); } -void WorldSession::HandleGameObjectUseOpcode(WorldPacket & recvData) +void WorldSession::HandleGameObjectUseOpcode(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -408,7 +408,7 @@ void WorldSession::HandleCastSpellOpcode(WorldPacket& recvPacket) // Client is resending autoshot cast opcode when other spell is casted during shoot rotation // Skip it to prevent "interrupt" message if (spellInfo->IsAutoRepeatRangedSpell() && _player->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL) - && _player->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)->m_spellInfo == spellInfo) + && _player->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)->m_spellInfo == spellInfo) { recvPacket.rfinish(); return; @@ -501,7 +501,7 @@ void WorldSession::HandlePetCancelAuraOpcode(WorldPacket& recvPacket) return; } - Creature* pet=ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); + Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); if (!pet) { @@ -537,7 +537,7 @@ void WorldSession::HandleCancelAutoRepeatSpellOpcode(WorldPacket& /*recvPacket*/ _player->InterruptSpell(CURRENT_AUTOREPEAT_SPELL); } -void WorldSession::HandleCancelChanneling(WorldPacket & recvData) +void WorldSession::HandleCancelChanneling(WorldPacket& recvData) { recvData.read_skip(); // spellid, not used @@ -572,7 +572,7 @@ void WorldSession::HandleTotemDestroyed(WorldPacket& recvPacket) totem->ToTotem()->UnSummon(); } -void WorldSession::HandleSelfResOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleSelfResOpcode(WorldPacket& /*recvData*/) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_SELF_RES"); // empty opcode @@ -612,7 +612,7 @@ void WorldSession::HandleSpellClick(WorldPacket& recvData) unit->HandleSpellClick(_player); } -void WorldSession::HandleMirrorImageDataRequest(WorldPacket & recvData) +void WorldSession::HandleMirrorImageDataRequest(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_GET_MIRRORIMAGE_DATA"); @@ -675,9 +675,9 @@ void WorldSession::HandleMirrorImageDataRequest(WorldPacket & recvData) data << uint32(0); else if (Item const* item = player->GetItemByPos(INVENTORY_SLOT_BAG_0, *itr)) { - uint32 displayInfoId=item->GetTemplate()->DisplayInfoID; + uint32 displayInfoId = item->GetTemplate()->DisplayInfoID; - sScriptMgr->OnGlobalMirrorImageDisplayItem(item,displayInfoId); + sScriptMgr->OnGlobalMirrorImageDisplayItem(item, displayInfoId); data << uint32(displayInfoId); } diff --git a/src/server/game/Handlers/TaxiHandler.cpp b/src/server/game/Handlers/TaxiHandler.cpp index 6c67608ac..e8d6b9aed 100644 --- a/src/server/game/Handlers/TaxiHandler.cpp +++ b/src/server/game/Handlers/TaxiHandler.cpp @@ -15,7 +15,7 @@ #include "UpdateMask.h" #include "WaypointMovementGenerator.h" -void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket & recvData) +void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_TAXINODE_STATUS_QUERY"); @@ -58,7 +58,7 @@ void WorldSession::SendTaxiStatus(uint64 guid) #endif } -void WorldSession::HandleTaxiQueryAvailableNodes(WorldPacket & recvData) +void WorldSession::HandleTaxiQueryAvailableNodes(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_TAXIQUERYAVAILABLENODES"); @@ -166,7 +166,7 @@ void WorldSession::SendDiscoverNewTaxiNode(uint32 nodeid) } } -void WorldSession::HandleActivateTaxiExpressOpcode (WorldPacket & recvData) +void WorldSession::HandleActivateTaxiExpressOpcode (WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ACTIVATETAXIEXPRESS"); @@ -228,7 +228,7 @@ void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recvData) recvData.read_skip(); // spline id } -void WorldSession::HandleActivateTaxiOpcode(WorldPacket & recvData) +void WorldSession::HandleActivateTaxiOpcode(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ACTIVATETAXI"); diff --git a/src/server/game/Handlers/TicketHandler.cpp b/src/server/game/Handlers/TicketHandler.cpp index b4a2854bf..c1f16162b 100644 --- a/src/server/game/Handlers/TicketHandler.cpp +++ b/src/server/game/Handlers/TicketHandler.cpp @@ -108,7 +108,7 @@ void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recvData) SendPacket(&data); } -void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket & recv_data) +void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket& recv_data) { std::string message; recv_data >> message; @@ -130,7 +130,7 @@ void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket & recv_data) SendPacket(&data); } -void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket& /*recv_data*/) { if (GmTicket* ticket = sTicketMgr->GetTicketByPlayer(GetPlayer()->GetGUID())) { @@ -145,7 +145,7 @@ void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket & /*recv_data*/) } } -void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket& /*recv_data*/) { SendQueryTimeResponse(); @@ -160,7 +160,7 @@ void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket & /*recv_data*/) sTicketMgr->SendTicket(this, nullptr); } -void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket & /*recv_data*/) +void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket& /*recv_data*/) { // Note: This only disables the ticket UI at client side and is not fully reliable // are we sure this is a uint32? Should ask Zor diff --git a/src/server/game/Handlers/TradeHandler.cpp b/src/server/game/Handlers/TradeHandler.cpp index da1b3f38b..510698f09 100644 --- a/src/server/game/Handlers/TradeHandler.cpp +++ b/src/server/game/Handlers/TradeHandler.cpp @@ -25,17 +25,17 @@ void WorldSession::SendTradeStatus(TradeStatus status) switch (status) { case TRADE_STATUS_BEGIN_TRADE: - data.Initialize(SMSG_TRADE_STATUS, 4+8); + data.Initialize(SMSG_TRADE_STATUS, 4 + 8); data << uint32(status); data << uint64(0); break; case TRADE_STATUS_OPEN_WINDOW: - data.Initialize(SMSG_TRADE_STATUS, 4+4); + data.Initialize(SMSG_TRADE_STATUS, 4 + 4); data << uint32(status); data << uint32(0); // added in 2.4.0 break; case TRADE_STATUS_CLOSE_WINDOW: - data.Initialize(SMSG_TRADE_STATUS, 4+4+1+4); + data.Initialize(SMSG_TRADE_STATUS, 4 + 4 + 1 + 4); data << uint32(status); data << uint32(0); data << uint8(0); @@ -43,7 +43,7 @@ void WorldSession::SendTradeStatus(TradeStatus status) break; case TRADE_STATUS_ONLY_CONJURED: case TRADE_STATUS_NOT_ELIGIBLE: - data.Initialize(SMSG_TRADE_STATUS, 4+1); + data.Initialize(SMSG_TRADE_STATUS, 4 + 1); data << uint32(status); data << uint8(0); break; @@ -76,7 +76,7 @@ void WorldSession::SendUpdateTrade(bool trader_data /*= true*/) { TradeData* view_trade = trader_data ? _player->GetTradeData()->GetTraderData() : _player->GetTradeData(); - WorldPacket data(SMSG_TRADE_STATUS_EXTENDED, 1+4+4+4+4+4+7*(1+4+4+4+4+8+4+4+4+4+8+4+4+4+4+4+4)); + WorldPacket data(SMSG_TRADE_STATUS_EXTENDED, 1 + 4 + 4 + 4 + 4 + 4 + 7 * (1 + 4 + 4 + 4 + 4 + 8 + 4 + 4 + 4 + 4 + 8 + 4 + 4 + 4 + 4 + 4 + 4)); data << uint8(trader_data); // 1 means traders data, 0 means own data << uint32(0); // added in 2.4.0, this value must be equal to value from TRADE_STATUS_OPEN_WINDOW status packet (different value for different players to block multiple trades?) data << uint32(TRADE_SLOT_COUNT); // trade slots count/number?, = next field in most cases @@ -93,22 +93,22 @@ void WorldSession::SendUpdateTrade(bool trader_data /*= true*/) data << uint32(item->GetTemplate()->ItemId); // entry data << uint32(item->GetTemplate()->DisplayInfoID);// display id data << uint32(item->GetCount()); // stack count - // wrapped: hide stats but show giftcreator name + // wrapped: hide stats but show giftcreator name data << uint32(item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED) ? 1 : 0); data << uint64(item->GetUInt64Value(ITEM_FIELD_GIFTCREATOR)); - // perm. enchantment and gems + // perm. enchantment and gems data << uint32(item->GetEnchantmentId(PERM_ENCHANTMENT_SLOT)); - for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+MAX_GEM_SOCKETS; ++enchant_slot) + for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) data << uint32(item->GetEnchantmentId(EnchantmentSlot(enchant_slot))); - // creator + // creator data << uint64(item->GetUInt64Value(ITEM_FIELD_CREATOR)); data << uint32(item->GetSpellCharges()); // charges data << uint32(item->GetItemSuffixFactor()); // SuffixFactor data << uint32(item->GetItemRandomPropertyId());// random properties id data << uint32(item->GetTemplate()->LockID); // lock id - // max durability + // max durability data << uint32(item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)); - // durability + // durability data << uint32(item->GetUInt32Value(ITEM_FIELD_DURABILITY)); } else @@ -149,7 +149,7 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[]) // adjust time (depends on /played) if (myItems[i]->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE)) - myItems[i]->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, trader->GetTotalPlayedTime()-(_player->GetTotalPlayedTime()-myItems[i]->GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME))); + myItems[i]->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, trader->GetTotalPlayedTime() - (_player->GetTotalPlayedTime() - myItems[i]->GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME))); // store trader->MoveItemToInventory(traderDst, myItems[i], true, true); } @@ -162,7 +162,7 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[]) // adjust time (depends on /played) if (hisItems[i]->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE)) - hisItems[i]->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, _player->GetTotalPlayedTime()-(trader->GetTotalPlayedTime()-hisItems[i]->GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME))); + hisItems[i]->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, _player->GetTotalPlayedTime() - (trader->GetTotalPlayedTime() - hisItems[i]->GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME))); // store _player->MoveItemToInventory(playerDst, hisItems[i], true, true); } @@ -196,7 +196,7 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[]) //============================================================== -static void setAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade, Item* *myItems, Item* *hisItems) +static void setAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade, Item * *myItems, Item * *hisItems) { myTrade->SetInAcceptProcess(true); hisTrade->SetInAcceptProcess(true); @@ -231,7 +231,7 @@ static void clearAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade) hisTrade->SetInAcceptProcess(false); } -static void clearAcceptTradeMode(Item* *myItems, Item* *hisItems) +static void clearAcceptTradeMode(Item * *myItems, Item * *hisItems) { // clear 'in-trade' flag for (uint8 i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) @@ -344,7 +344,7 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) Item* castItem = my_trade->GetSpellCastItem(); if (!spellEntry || !his_trade->GetItem(TRADE_SLOT_NONTRADED) || - (my_trade->HasSpellCastItem() && !castItem)) + (my_trade->HasSpellCastItem() && !castItem)) { clearAcceptTradeMode(my_trade, his_trade); clearAcceptTradeMode(myItems, hisItems); @@ -462,11 +462,11 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) // execute trade: 2. store moveItems(myItems, hisItems); - if( my_trade->GetMoney() >= 10*GOLD ) + if( my_trade->GetMoney() >= 10 * GOLD ) { CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \"\", NOW())", GetAccountId(), _player->GetGUIDLow(), _player->GetName().c_str(), GetRemoteAddress().c_str(), trader->GetSession()->GetAccountId(), trader->GetName().c_str(), my_trade->GetMoney()); } - if( his_trade->GetMoney() >= 10*GOLD ) + if( his_trade->GetMoney() >= 10 * GOLD ) { CharacterDatabase.PExecute("INSERT INTO log_money VALUES(%u, %u, \"%s\", \"%s\", %u, \"%s\", %u, \"\", NOW())", trader->GetSession()->GetAccountId(), trader->GetGUIDLow(), trader->GetName().c_str(), trader->GetSession()->GetRemoteAddress().c_str(), GetAccountId(), _player->GetName().c_str(), his_trade->GetMoney()); } diff --git a/src/server/game/Handlers/VehicleHandler.cpp b/src/server/game/Handlers/VehicleHandler.cpp index cf4167296..faa2ae69d 100644 --- a/src/server/game/Handlers/VehicleHandler.cpp +++ b/src/server/game/Handlers/VehicleHandler.cpp @@ -12,7 +12,7 @@ #include "Log.h" #include "ObjectAccessor.h" -void WorldSession::HandleDismissControlledVehicle(WorldPacket &recvData) +void WorldSession::HandleDismissControlledVehicle(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_DISMISS_CONTROLLED_VEHICLE"); @@ -47,7 +47,7 @@ void WorldSession::HandleDismissControlledVehicle(WorldPacket &recvData) _player->ExitVehicle(); } -void WorldSession::HandleChangeSeatsOnControlledVehicle(WorldPacket &recvData) +void WorldSession::HandleChangeSeatsOnControlledVehicle(WorldPacket& recvData) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_CHANGE_SEATS_ON_CONTROLLED_VEHICLE"); @@ -65,7 +65,7 @@ void WorldSession::HandleChangeSeatsOnControlledVehicle(WorldPacket &recvData) { recvData.rfinish(); // prevent warnings spam sLog->outError("HandleChangeSeatsOnControlledVehicle, Opcode: %u, Player %u tried to switch seats but current seatflags %u don't permit that.", - recvData.GetOpcode(), GetPlayer()->GetGUIDLow(), seat->m_flags); + recvData.GetOpcode(), GetPlayer()->GetGUIDLow(), seat->m_flags); return; } @@ -78,60 +78,60 @@ void WorldSession::HandleChangeSeatsOnControlledVehicle(WorldPacket &recvData) GetPlayer()->ChangeSeat(-1, true); break; case CMSG_CHANGE_SEATS_ON_CONTROLLED_VEHICLE: - { - uint64 guid; // current vehicle guid - recvData.readPackGUID(guid); - - // pussywizard: - if (vehicle_base->GetGUID() != guid) { - recvData.rfinish(); // prevent warnings spam - return; + uint64 guid; // current vehicle guid + recvData.readPackGUID(guid); + + // pussywizard: + if (vehicle_base->GetGUID() != guid) + { + recvData.rfinish(); // prevent warnings spam + return; + } + + MovementInfo movementInfo; + movementInfo.guid = guid; + ReadMovementInfo(recvData, &movementInfo); + vehicle_base->m_movementInfo = movementInfo; + + uint64 accessory; // accessory guid + recvData.readPackGUID(accessory); + + int8 seatId; + recvData >> seatId; + + if (!accessory) + GetPlayer()->ChangeSeat(-1, seatId > 0); // prev/next + else if (Unit* vehUnit = ObjectAccessor::GetUnit(*GetPlayer(), accessory)) + { + if (Vehicle* vehicle = vehUnit->GetVehicleKit()) + if (vehicle->HasEmptySeat(seatId)) + vehUnit->HandleSpellClick(GetPlayer(), seatId); + } + break; } - - MovementInfo movementInfo; - movementInfo.guid = guid; - ReadMovementInfo(recvData, &movementInfo); - vehicle_base->m_movementInfo = movementInfo; - - uint64 accessory; // accessory guid - recvData.readPackGUID(accessory); - - int8 seatId; - recvData >> seatId; - - if (!accessory) - GetPlayer()->ChangeSeat(-1, seatId > 0); // prev/next - else if (Unit* vehUnit = ObjectAccessor::GetUnit(*GetPlayer(), accessory)) - { - if (Vehicle* vehicle = vehUnit->GetVehicleKit()) - if (vehicle->HasEmptySeat(seatId)) - vehUnit->HandleSpellClick(GetPlayer(), seatId); - } - break; - } case CMSG_REQUEST_VEHICLE_SWITCH_SEAT: - { - uint64 guid; // current vehicle guid - recvData.readPackGUID(guid); + { + uint64 guid; // current vehicle guid + recvData.readPackGUID(guid); - int8 seatId; - recvData >> seatId; + int8 seatId; + recvData >> seatId; - if (vehicle_base->GetGUID() == guid) - GetPlayer()->ChangeSeat(seatId); - else if (Unit* vehUnit = ObjectAccessor::GetUnit(*GetPlayer(), guid)) - if (Vehicle* vehicle = vehUnit->GetVehicleKit()) - if (vehicle->HasEmptySeat(seatId)) - vehUnit->HandleSpellClick(GetPlayer(), seatId); - break; - } + if (vehicle_base->GetGUID() == guid) + GetPlayer()->ChangeSeat(seatId); + else if (Unit* vehUnit = ObjectAccessor::GetUnit(*GetPlayer(), guid)) + if (Vehicle* vehicle = vehUnit->GetVehicleKit()) + if (vehicle->HasEmptySeat(seatId)) + vehUnit->HandleSpellClick(GetPlayer(), seatId); + break; + } default: break; } } -void WorldSession::HandleEnterPlayerVehicle(WorldPacket &data) +void WorldSession::HandleEnterPlayerVehicle(WorldPacket& data) { // Read guid uint64 guid; @@ -153,7 +153,7 @@ void WorldSession::HandleEnterPlayerVehicle(WorldPacket &data) } } -void WorldSession::HandleEjectPassenger(WorldPacket &data) +void WorldSession::HandleEjectPassenger(WorldPacket& data) { Vehicle* vehicle = _player->GetVehicleKit(); if (!vehicle) @@ -215,7 +215,7 @@ void WorldSession::HandleEjectPassenger(WorldPacket &data) sLog->outError("Player %u attempted to eject creature GUID %u from non-ejectable seat.", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid)); } else - sLog->outError("HandleEjectPassenger: Player %u tried to eject invalid GUID " UI64FMTD , GetPlayer()->GetGUIDLow(), guid); + sLog->outError("HandleEjectPassenger: Player %u tried to eject invalid GUID " UI64FMTD, GetPlayer()->GetGUIDLow(), guid); } void WorldSession::HandleRequestVehicleExit(WorldPacket& /*recvData*/) @@ -232,7 +232,7 @@ void WorldSession::HandleRequestVehicleExit(WorldPacket& /*recvData*/) GetPlayer()->ExitVehicle(); else sLog->outError("Player %u tried to exit vehicle, but seatflags %u (ID: %u) don't permit that.", - GetPlayer()->GetGUIDLow(), seat->m_ID, seat->m_flags); + GetPlayer()->GetGUIDLow(), seat->m_ID, seat->m_flags); } } } diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp index e4b9d94d9..b6c4729a8 100644 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ b/src/server/game/Instances/InstanceSaveMgr.cpp @@ -83,7 +83,7 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance } else { - resetTime = time(nullptr) + 3*DAY; // normals expire after 3 days even if someone is still bound to them, cleared on startup + resetTime = time(nullptr) + 3 * DAY; // normals expire after 3 days even if someone is still bound to them, cleared on startup extendedResetTime = 0; } InstanceSave* save = new InstanceSave(mapId, instanceId, difficulty, resetTime, extendedResetTime); @@ -132,7 +132,7 @@ bool InstanceSaveManager::DeleteInstanceSaveIfNeeded(InstanceSave* save, bool sk } InstanceSave::InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, time_t resetTime, time_t extendedResetTime) -: m_resetTime(resetTime), m_extendedResetTime(extendedResetTime), m_instanceid(InstanceId), m_mapid(MapId), m_difficulty(IsSharedDifficultyMap(MapId) ? Difficulty(difficulty%2) : difficulty), m_canReset(true), m_instanceData(""), m_completedEncounterMask(0) + : m_resetTime(resetTime), m_extendedResetTime(extendedResetTime), m_instanceid(InstanceId), m_mapid(MapId), m_difficulty(IsSharedDifficultyMap(MapId) ? Difficulty(difficulty % 2) : difficulty), m_canReset(true), m_instanceData(""), m_completedEncounterMask(0) { } @@ -284,7 +284,7 @@ void InstanceSaveManager::LoadResetTimes() continue; // the reset_delay must be at least one day - uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME))/DAY) * DAY); + uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); if (period < DAY) period = DAY; @@ -311,10 +311,10 @@ void InstanceSaveManager::LoadResetTimes() // schedule the global reset/warning uint8 type; for (type = 1; type < 5; ++type) - if (now + ResetTimeDelay[type-1] < t) + if (now + ResetTimeDelay[type - 1] < t) break; - ScheduleReset(t - ResetTimeDelay[type-1], InstResetEvent(type, mapid, difficulty)); + ScheduleReset(t - ResetTimeDelay[type - 1], InstResetEvent(type, mapid, difficulty)); } } @@ -345,8 +345,7 @@ void InstanceSaveManager::LoadInstanceSaves() if (resettime > 0) save->SetResetTime(resettime); } - } - while (result->NextRow()); + } while (result->NextRow()); } } @@ -396,8 +395,7 @@ void InstanceSaveManager::LoadCharacterBinds() if (perm) save->SetCanReset(false); } - } - while (result->NextRow()); + } while (result->NextRow()); } lock_instLists = false; @@ -420,7 +418,7 @@ void InstanceSaveManager::Update() if (t >= now) break; - InstResetEvent &event = m_resetTimeQueue.begin()->second; + InstResetEvent& event = m_resetTimeQueue.begin()->second; if (event.type) { // global reset/warning for a certain map @@ -431,7 +429,7 @@ void InstanceSaveManager::Update() { // schedule the next warning/reset ++event.type; - ScheduleReset(resetTime - ResetTimeDelay[event.type-1], event); + ScheduleReset(resetTime - ResetTimeDelay[event.type - 1], event); } else resetOccurred = true; @@ -453,11 +451,11 @@ void InstanceSaveManager::Update() } } -void InstanceSaveManager::_ResetSave(InstanceSaveHashMap::iterator &itr) +void InstanceSaveManager::_ResetSave(InstanceSaveHashMap::iterator& itr) { lock_instLists = true; - InstanceSave::PlayerListType &pList = itr->second->m_playerList; + InstanceSave::PlayerListType& pList = itr->second->m_playerList; for (InstanceSave::PlayerListType::iterator iter = pList.begin(), iter2; iter != pList.end(); ) { iter2 = iter++; @@ -523,14 +521,14 @@ void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, b // calculate the next reset time uint32 diff = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR; - uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME))/DAY) * DAY); + uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); if (period < DAY) period = DAY; uint32 next_reset = uint32(((resetTime + MINUTE) / DAY * DAY) + period + diff); SetResetTimeFor(mapid, difficulty, next_reset); SetExtendedResetTimeFor(mapid, difficulty, next_reset + period); - ScheduleReset(time_t(next_reset-3600), InstResetEvent(1, mapid, difficulty)); + ScheduleReset(time_t(next_reset - 3600), InstResetEvent(1, mapid, difficulty)); // update it in the DB PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); @@ -551,7 +549,7 @@ void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, b // now loop all existing maps to warn / reset Map const* map = sMapMgr->CreateBaseMap(mapid); - MapInstanced::InstancedMaps &instMaps = ((MapInstanced*)map)->GetInstancedMaps(); + MapInstanced::InstancedMaps& instMaps = ((MapInstanced*)map)->GetInstancedMaps(); MapInstanced::InstancedMaps::iterator mitr; uint32 timeLeft; @@ -573,7 +571,7 @@ void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, b else { InstanceSave* save = GetInstanceSave(map2->GetInstanceId()); - map2->ToInstanceMap()->Reset(INSTANCE_RESET_GLOBAL, (save ? &(save->m_playerList) : nullptr)); + map2->ToInstanceMap()->Reset(INSTANCE_RESET_GLOBAL, (save ? & (save->m_playerList) : nullptr)); } } } @@ -692,7 +690,7 @@ void InstanceSaveManager::PlayerUnbindInstanceNotExtended(uint32 guidLow, uint32 InstancePlayerBind* InstanceSaveManager::PlayerGetBoundInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty) { - Difficulty difficulty_fixed = ( IsSharedDifficultyMap(mapid) ? Difficulty(difficulty%2) : difficulty); + Difficulty difficulty_fixed = ( IsSharedDifficultyMap(mapid) ? Difficulty(difficulty % 2) : difficulty); MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(mapid, difficulty_fixed); if (!mapDiff) @@ -713,7 +711,7 @@ InstancePlayerBind* InstanceSaveManager::PlayerGetBoundInstance(uint32 guidLow, } bool InstanceSaveManager::PlayerIsPermBoundToInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty) -{ +{ if (InstancePlayerBind* bind = PlayerGetBoundInstance(guidLow, mapid, difficulty)) if (bind->perm) return true; @@ -773,7 +771,7 @@ void InstanceSaveManager::CopyBinds(uint32 from, uint32 to, Player* toPlr) void InstanceSaveManager::UnbindAllFor(InstanceSave* save) { - InstanceSave::PlayerListType &pList = save->m_playerList; + InstanceSave::PlayerListType& pList = save->m_playerList; while (!pList.empty()) PlayerUnbindInstance(*(pList.begin()), save->GetMapId(), save->GetDifficulty(), true, ObjectAccessor::GetObjectInOrOutOfWorld(MAKE_NEW_GUID(*(pList.begin()), 0, HIGHGUID_PLAYER), (Player*)NULL)); } diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index a57daed61..e13c6f2e2 100644 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -45,53 +45,53 @@ typedef std::unordered_map< uint32 /*guidLow*/, BoundInstancesMapWrapper* > Play class InstanceSave { friend class InstanceSaveManager; - public: +public: - InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, time_t resetTime, time_t extendedResetTime); - ~InstanceSave(); - uint32 GetInstanceId() const { return m_instanceid; } - uint32 GetMapId() const { return m_mapid; } - Difficulty GetDifficulty() const { return m_difficulty; } + InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, time_t resetTime, time_t extendedResetTime); + ~InstanceSave(); + uint32 GetInstanceId() const { return m_instanceid; } + uint32 GetMapId() const { return m_mapid; } + Difficulty GetDifficulty() const { return m_difficulty; } - /* Saved when the instance is generated for the first time */ - void InsertToDB(); - // pussywizard: deleting is done internally when there are no binds left + /* Saved when the instance is generated for the first time */ + void InsertToDB(); + // pussywizard: deleting is done internally when there are no binds left - std::string GetInstanceData() const { return m_instanceData; } - void SetInstanceData(std::string str) { m_instanceData = str; } - uint32 GetCompletedEncounterMask() const { return m_completedEncounterMask; } - void SetCompletedEncounterMask(uint32 mask) { m_completedEncounterMask = mask; } + std::string GetInstanceData() const { return m_instanceData; } + void SetInstanceData(std::string str) { m_instanceData = str; } + uint32 GetCompletedEncounterMask() const { return m_completedEncounterMask; } + void SetCompletedEncounterMask(uint32 mask) { m_completedEncounterMask = mask; } - // pussywizard: for normal instances this corresponds to 0, for raid/heroic instances this caches the global reset time for the map - time_t GetResetTime() const { return m_resetTime; } - time_t GetExtendedResetTime() const { return m_extendedResetTime; } - time_t GetResetTimeForDB(); - void SetResetTime(time_t resetTime) { m_resetTime = resetTime; } - void SetExtendedResetTime(time_t extendedResetTime) { m_extendedResetTime = extendedResetTime; } + // pussywizard: for normal instances this corresponds to 0, for raid/heroic instances this caches the global reset time for the map + time_t GetResetTime() const { return m_resetTime; } + time_t GetExtendedResetTime() const { return m_extendedResetTime; } + time_t GetResetTimeForDB(); + void SetResetTime(time_t resetTime) { m_resetTime = resetTime; } + void SetExtendedResetTime(time_t extendedResetTime) { m_extendedResetTime = extendedResetTime; } - bool CanReset() const { return m_canReset; } - void SetCanReset(bool canReset) { m_canReset = canReset; } + bool CanReset() const { return m_canReset; } + void SetCanReset(bool canReset) { m_canReset = canReset; } - InstanceTemplate const* GetTemplate(); - MapEntry const* GetMapEntry(); + InstanceTemplate const* GetTemplate(); + MapEntry const* GetMapEntry(); - void AddPlayer(uint32 guidLow); - bool RemovePlayer(uint32 guidLow, InstanceSaveManager* ism); + void AddPlayer(uint32 guidLow); + bool RemovePlayer(uint32 guidLow, InstanceSaveManager* ism); - typedef std::list PlayerListType; - private: + typedef std::list PlayerListType; +private: - PlayerListType m_playerList; - time_t m_resetTime; - time_t m_extendedResetTime; - uint32 m_instanceid; - uint32 m_mapid; - Difficulty m_difficulty; - bool m_canReset; - std::string m_instanceData; - uint32 m_completedEncounterMask; + PlayerListType m_playerList; + time_t m_resetTime; + time_t m_extendedResetTime; + uint32 m_instanceid; + uint32 m_mapid; + Difficulty m_difficulty; + bool m_canReset; + std::string m_instanceData; + uint32 m_completedEncounterMask; - ACE_Thread_Mutex _lock; + ACE_Thread_Mutex _lock; }; typedef std::unordered_map ResetTimeByMapDifficultyMap; @@ -100,94 +100,94 @@ class InstanceSaveManager { friend class InstanceSave; - private: - InstanceSaveManager() : lock_instLists(false) {}; - ~InstanceSaveManager(); +private: + InstanceSaveManager() : lock_instLists(false) {}; + ~InstanceSaveManager(); - public: - static InstanceSaveManager* instance(); - - typedef std::unordered_map InstanceSaveHashMap; +public: + static InstanceSaveManager* instance(); - struct InstResetEvent - { - uint8 type; // 0 - unused, 1-4 warnings about pending reset, 5 - reset - Difficulty difficulty:8; - uint16 mapid; + typedef std::unordered_map InstanceSaveHashMap; - InstResetEvent() : type(0), difficulty(DUNGEON_DIFFICULTY_NORMAL), mapid(0) {} - InstResetEvent(uint8 t, uint32 _mapid, Difficulty d) - : type(t), difficulty(d), mapid(_mapid) {} - }; - typedef std::multimap ResetTimeQueue; + struct InstResetEvent + { + uint8 type; // 0 - unused, 1-4 warnings about pending reset, 5 - reset + Difficulty difficulty: 8; + uint16 mapid; - void LoadInstances(); - void LoadResetTimes(); - void LoadInstanceSaves(); - void LoadCharacterBinds(); + InstResetEvent() : type(0), difficulty(DUNGEON_DIFFICULTY_NORMAL), mapid(0) {} + InstResetEvent(uint8 t, uint32 _mapid, Difficulty d) + : type(t), difficulty(d), mapid(_mapid) {} + }; + typedef std::multimap ResetTimeQueue; - time_t GetResetTimeFor(uint32 mapid, Difficulty d) const - { - ResetTimeByMapDifficultyMap::const_iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); - return itr != m_resetTimeByMapDifficulty.end() ? itr->second : 0; - } + void LoadInstances(); + void LoadResetTimes(); + void LoadInstanceSaves(); + void LoadCharacterBinds(); - time_t GetExtendedResetTimeFor(uint32 mapid, Difficulty d) const - { - ResetTimeByMapDifficultyMap::const_iterator itr = m_resetExtendedTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); - return itr != m_resetExtendedTimeByMapDifficulty.end() ? itr->second : 0; - } + time_t GetResetTimeFor(uint32 mapid, Difficulty d) const + { + ResetTimeByMapDifficultyMap::const_iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); + return itr != m_resetTimeByMapDifficulty.end() ? itr->second : 0; + } - void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) - { - m_resetTimeByMapDifficulty[MAKE_PAIR32(mapid, d)] = t; - } + time_t GetExtendedResetTimeFor(uint32 mapid, Difficulty d) const + { + ResetTimeByMapDifficultyMap::const_iterator itr = m_resetExtendedTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); + return itr != m_resetExtendedTimeByMapDifficulty.end() ? itr->second : 0; + } - void SetExtendedResetTimeFor(uint32 mapid, Difficulty d, time_t t) - { - m_resetExtendedTimeByMapDifficulty[MAKE_PAIR32(mapid, d)] = t; - } + void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) + { + m_resetTimeByMapDifficulty[MAKE_PAIR32(mapid, d)] = t; + } - ResetTimeByMapDifficultyMap const& GetResetTimeMap() const - { - return m_resetTimeByMapDifficulty; - } + void SetExtendedResetTimeFor(uint32 mapid, Difficulty d, time_t t) + { + m_resetExtendedTimeByMapDifficulty[MAKE_PAIR32(mapid, d)] = t; + } - void ScheduleReset(time_t time, InstResetEvent event); + ResetTimeByMapDifficultyMap const& GetResetTimeMap() const + { + return m_resetTimeByMapDifficulty; + } - void Update(); + void ScheduleReset(time_t time, InstResetEvent event); - InstanceSave* AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, bool startup = false); - bool DeleteInstanceSaveIfNeeded(uint32 InstanceId, bool skipMapCheck); - bool DeleteInstanceSaveIfNeeded(InstanceSave* save, bool skipMapCheck); + void Update(); - InstanceSave* GetInstanceSave(uint32 InstanceId); + InstanceSave* AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, bool startup = false); + bool DeleteInstanceSaveIfNeeded(uint32 InstanceId, bool skipMapCheck); + bool DeleteInstanceSaveIfNeeded(InstanceSave* save, bool skipMapCheck); - InstancePlayerBind* PlayerBindToInstance(uint32 guidLow, InstanceSave* save, bool permanent, Player* player = nullptr); - void PlayerUnbindInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty, bool deleteFromDB, Player* player = nullptr); - void PlayerUnbindInstanceNotExtended(uint32 guidLow, uint32 mapid, Difficulty difficulty, Player* player = nullptr); - InstancePlayerBind* PlayerGetBoundInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty); - bool PlayerIsPermBoundToInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty); - BoundInstancesMap const& PlayerGetBoundInstances(uint32 guidLow, Difficulty difficulty); - void PlayerCreateBoundInstancesMaps(uint32 guidLow); - InstanceSave* PlayerGetInstanceSave(uint32 guidLow, uint32 mapid, Difficulty difficulty); - uint32 PlayerGetDestinationInstanceId(Player* player, uint32 mapid, Difficulty difficulty); - void CopyBinds(uint32 from, uint32 to, Player* toPlr = nullptr); - void UnbindAllFor(InstanceSave* save); + InstanceSave* GetInstanceSave(uint32 InstanceId); - protected: - static uint16 ResetTimeDelay[]; - static PlayerBindStorage playerBindStorage; - static BoundInstancesMap emptyBoundInstancesMap; + InstancePlayerBind* PlayerBindToInstance(uint32 guidLow, InstanceSave* save, bool permanent, Player* player = nullptr); + void PlayerUnbindInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty, bool deleteFromDB, Player* player = nullptr); + void PlayerUnbindInstanceNotExtended(uint32 guidLow, uint32 mapid, Difficulty difficulty, Player* player = nullptr); + InstancePlayerBind* PlayerGetBoundInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty); + bool PlayerIsPermBoundToInstance(uint32 guidLow, uint32 mapid, Difficulty difficulty); + BoundInstancesMap const& PlayerGetBoundInstances(uint32 guidLow, Difficulty difficulty); + void PlayerCreateBoundInstancesMaps(uint32 guidLow); + InstanceSave* PlayerGetInstanceSave(uint32 guidLow, uint32 mapid, Difficulty difficulty); + uint32 PlayerGetDestinationInstanceId(Player* player, uint32 mapid, Difficulty difficulty); + void CopyBinds(uint32 from, uint32 to, Player* toPlr = nullptr); + void UnbindAllFor(InstanceSave* save); - private: - void _ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime); - void _ResetSave(InstanceSaveHashMap::iterator &itr); - bool lock_instLists; - InstanceSaveHashMap m_instanceSaveById; - ResetTimeByMapDifficultyMap m_resetTimeByMapDifficulty; - ResetTimeByMapDifficultyMap m_resetExtendedTimeByMapDifficulty; - ResetTimeQueue m_resetTimeQueue; +protected: + static uint16 ResetTimeDelay[]; + static PlayerBindStorage playerBindStorage; + static BoundInstancesMap emptyBoundInstancesMap; + +private: + void _ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime); + void _ResetSave(InstanceSaveHashMap::iterator& itr); + bool lock_instLists; + InstanceSaveHashMap m_instanceSaveById; + ResetTimeByMapDifficultyMap m_resetTimeByMapDifficulty; + ResetTimeByMapDifficultyMap m_resetExtendedTimeByMapDifficulty; + ResetTimeQueue m_resetTimeQueue; }; #define sInstanceSaveMgr InstanceSaveManager::instance() diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index bc0248970..8d160bf2f 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -42,7 +42,8 @@ void InstanceScript::HandleGameObject(uint64 GUID, bool open, GameObject* go) go = instance->GetGameObject(GUID); if (go) go->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_TSCR, "TSCR: InstanceScript: HandleGameObject failed"); #endif @@ -230,7 +231,7 @@ bool InstanceScript::SetBossState(uint32 id, EncounterState state) return false; } -std::string InstanceScript::LoadBossState(const char * data) +std::string InstanceScript::LoadBossState(const char* data) { if (!data) return nullptr; @@ -281,7 +282,7 @@ void InstanceScript::DoRespawnGameObject(uint64 uiGuid, uint32 uiTimeToDespawn) { //not expect any of these should ever be handled if (go->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE || go->GetGoType() == GAMEOBJECT_TYPE_DOOR || - go->GetGoType() == GAMEOBJECT_TYPE_BUTTON || go->GetGoType() == GAMEOBJECT_TYPE_TRAP) + go->GetGoType() == GAMEOBJECT_TYPE_BUTTON || go->GetGoType() == GAMEOBJECT_TYPE_TRAP) return; if (go->isSpawned()) @@ -301,7 +302,8 @@ void InstanceScript::DoUpdateWorldState(uint32 uiStateId, uint32 uiStateData) if (Player* player = itr->GetSource()) player->SendUpdateWorldState(uiStateId, uiStateData); } - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_TSCR, "TSCR: DoUpdateWorldState attempt send data but no players in map."); #endif @@ -329,7 +331,7 @@ void InstanceScript::DoSendNotifyToInstance(char const* format, ...) // Update Achievement Criteria for all players in instance void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -340,7 +342,7 @@ void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, // Start timed achievement for all players in instance void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -351,7 +353,7 @@ void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, // Stop timed achievement for all players in instance void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -380,7 +382,7 @@ void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell) // Cast spell on all players in instance void InstanceScript::DoCastSpellOnPlayers(uint32 spell) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -391,7 +393,7 @@ void InstanceScript::DoCastSpellOnPlayers(uint32 spell) bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/) { sLog->outError("Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u", - instance->GetId(), criteria_id); + instance->GetId(), criteria_id); return false; } diff --git a/src/server/game/Instances/InstanceScript.h b/src/server/game/Instances/InstanceScript.h index 9f58f6b66..69c58a2b9 100644 --- a/src/server/game/Instances/InstanceScript.h +++ b/src/server/game/Instances/InstanceScript.h @@ -120,116 +120,116 @@ typedef std::map MinionInfoMap; class InstanceScript : public ZoneScript { - public: +public: - explicit InstanceScript(Map* map) : instance(map), completedEncounters(0) {} + explicit InstanceScript(Map* map) : instance(map), completedEncounters(0) {} - virtual ~InstanceScript() {} + virtual ~InstanceScript() {} - Map* instance; + Map* instance; - //On creation, NOT load. - virtual void Initialize() {} + //On creation, NOT load. + virtual void Initialize() {} - //On load - virtual void Load(char const* data) { LoadBossState(data); } + //On load + virtual void Load(char const* data) { LoadBossState(data); } - //Called when creature is Looted - virtual void CreatureLooted(Creature* /*creature*/, LootType) {} + //Called when creature is Looted + virtual void CreatureLooted(Creature* /*creature*/, LootType) {} - //When save is needed, this function generates the data - virtual std::string GetSaveData() { return GetBossSaveData(); } + //When save is needed, this function generates the data + virtual std::string GetSaveData() { return GetBossSaveData(); } - void SaveToDB(); + void SaveToDB(); - virtual void Update(uint32 /*diff*/) {} + virtual void Update(uint32 /*diff*/) {} - //Used by the map's CanEnter function. - //This is to prevent players from entering during boss encounters. - virtual bool IsEncounterInProgress() const; + //Used by the map's CanEnter function. + //This is to prevent players from entering during boss encounters. + virtual bool IsEncounterInProgress() const; - //Called when a player successfully enters the instance. - virtual void OnPlayerEnter(Player* /*player*/) {} + //Called when a player successfully enters the instance. + virtual void OnPlayerEnter(Player* /*player*/) {} - virtual void OnPlayerAreaUpdate(Player* /*player*/, uint32 /*oldArea*/, uint32 /*newArea*/) {} + virtual void OnPlayerAreaUpdate(Player* /*player*/, uint32 /*oldArea*/, uint32 /*newArea*/) {} - //Handle open / close objects - //use HandleGameObject(0, boolen, GO); in OnObjectCreate in instance scripts - //use HandleGameObject(GUID, boolen, nullptr); in any other script - void HandleGameObject(uint64 guid, bool open, GameObject* go = nullptr); + //Handle open / close objects + //use HandleGameObject(0, boolen, GO); in OnObjectCreate in instance scripts + //use HandleGameObject(GUID, boolen, nullptr); in any other script + void HandleGameObject(uint64 guid, bool open, GameObject* go = nullptr); - //change active state of doors or buttons - void DoUseDoorOrButton(uint64 guid, uint32 withRestoreTime = 0, bool useAlternativeState = false); + //change active state of doors or buttons + void DoUseDoorOrButton(uint64 guid, uint32 withRestoreTime = 0, bool useAlternativeState = false); - //Respawns a GO having negative spawntimesecs in gameobject-table - void DoRespawnGameObject(uint64 guid, uint32 timeToDespawn = MINUTE); + //Respawns a GO having negative spawntimesecs in gameobject-table + void DoRespawnGameObject(uint64 guid, uint32 timeToDespawn = MINUTE); - //sends world state update to all players in instance - void DoUpdateWorldState(uint32 worldstateId, uint32 worldstateValue); + //sends world state update to all players in instance + void DoUpdateWorldState(uint32 worldstateId, uint32 worldstateValue); - // Send Notify to all players in instance - void DoSendNotifyToInstance(char const* format, ...); + // Send Notify to all players in instance + void DoSendNotifyToInstance(char const* format, ...); - // Update Achievement Criteria for all players in instance - void DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); + // Update Achievement Criteria for all players in instance + void DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); - // Start/Stop Timed Achievement Criteria for all players in instance - void DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); - void DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); + // Start/Stop Timed Achievement Criteria for all players in instance + void DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); + void DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); - // Remove Auras due to Spell on all players in instance - void DoRemoveAurasDueToSpellOnPlayers(uint32 spell); + // Remove Auras due to Spell on all players in instance + void DoRemoveAurasDueToSpellOnPlayers(uint32 spell); - // Cast spell on all players in instance - void DoCastSpellOnPlayers(uint32 spell); + // Cast spell on all players in instance + void DoCastSpellOnPlayers(uint32 spell); - // Return wether server allow two side groups or not - bool ServerAllowsTwoSideGroups() { return sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP); } + // Return wether server allow two side groups or not + bool ServerAllowsTwoSideGroups() { return sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP); } - virtual bool SetBossState(uint32 id, EncounterState state); - EncounterState GetBossState(uint32 id) const { return id < bosses.size() ? bosses[id].state : TO_BE_DECIDED; } - static std::string GetBossStateName(uint8 state); - BossBoundaryMap const* GetBossBoundary(uint32 id) const { return id < bosses.size() ? &bosses[id].boundary : nullptr; } - BossInfo const* GetBossInfo(uint32 id) const { return &bosses[id]; } + virtual bool SetBossState(uint32 id, EncounterState state); + EncounterState GetBossState(uint32 id) const { return id < bosses.size() ? bosses[id].state : TO_BE_DECIDED; } + static std::string GetBossStateName(uint8 state); + BossBoundaryMap const* GetBossBoundary(uint32 id) const { return id < bosses.size() ? &bosses[id].boundary : nullptr; } + BossInfo const* GetBossInfo(uint32 id) const { return &bosses[id]; } - // Achievement criteria additional requirements check - // NOTE: not use this if same can be checked existed requirement types from AchievementCriteriaRequirementType - virtual bool CheckAchievementCriteriaMeet(uint32 /*criteria_id*/, Player const* /*source*/, Unit const* /*target*/ = NULL, uint32 /*miscvalue1*/ = 0); + // Achievement criteria additional requirements check + // NOTE: not use this if same can be checked existed requirement types from AchievementCriteriaRequirementType + virtual bool CheckAchievementCriteriaMeet(uint32 /*criteria_id*/, Player const* /*source*/, Unit const* /*target*/ = NULL, uint32 /*miscvalue1*/ = 0); - // Checks boss requirements (one boss required to kill other) - virtual bool CheckRequiredBosses(uint32 /*bossId*/, Player const* /*player*/ = nullptr) const { return true; } + // Checks boss requirements (one boss required to kill other) + virtual bool CheckRequiredBosses(uint32 /*bossId*/, Player const* /*player*/ = nullptr) const { return true; } - void SetCompletedEncountersMask(uint32 newMask, bool save); + void SetCompletedEncountersMask(uint32 newMask, bool save); - // Returns completed encounters mask for packets - uint32 GetCompletedEncounterMask() const { return completedEncounters; } + // Returns completed encounters mask for packets + uint32 GetCompletedEncounterMask() const { return completedEncounters; } - void SendEncounterUnit(uint32 type, Unit* unit = NULL, uint8 param1 = 0, uint8 param2 = 0); + void SendEncounterUnit(uint32 type, Unit* unit = NULL, uint8 param1 = 0, uint8 param2 = 0); - virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} + virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} - uint32 GetEncounterCount() const { return bosses.size(); } + uint32 GetEncounterCount() const { return bosses.size(); } - // Allows to perform particular actions - virtual void DoAction(int32 /*action*/) {} - protected: - void SetBossNumber(uint32 number) { bosses.resize(number); } - void LoadDoorData(DoorData const* data); - void LoadMinionData(MinionData const* data); + // Allows to perform particular actions + virtual void DoAction(int32 /*action*/) {} +protected: + void SetBossNumber(uint32 number) { bosses.resize(number); } + void LoadDoorData(DoorData const* data); + void LoadMinionData(MinionData const* data); - void AddDoor(GameObject* door, bool add); - void AddMinion(Creature* minion, bool add); + void AddDoor(GameObject* door, bool add); + void AddMinion(Creature* minion, bool add); - void UpdateDoorState(GameObject* door); - void UpdateMinionState(Creature* minion, EncounterState state); + void UpdateDoorState(GameObject* door); + void UpdateMinionState(Creature* minion, EncounterState state); - std::string LoadBossState(char const* data); - std::string GetBossSaveData(); - private: - std::vector bosses; - DoorInfoMap doors; - MinionInfoMap minions; - uint32 completedEncounters; // completed encounter mask, bit indexes are DungeonEncounter.dbc boss numbers, used for packets + std::string LoadBossState(char const* data); + std::string GetBossSaveData(); +private: + std::vector bosses; + DoorInfoMap doors; + MinionInfoMap minions; + uint32 completedEncounters; // completed encounter mask, bit indexes are DungeonEncounter.dbc boss numbers, used for packets }; template diff --git a/src/server/game/Loot/LootItemStorage.cpp b/src/server/game/Loot/LootItemStorage.cpp index 64744b539..3e4f67db8 100644 --- a/src/server/game/Loot/LootItemStorage.cpp +++ b/src/server/game/Loot/LootItemStorage.cpp @@ -40,7 +40,7 @@ void LootItemStorage::LoadStorageFromDB() do { Field* fields = result->Fetch(); - + StoredLootItemList& itemList = lootItemStore[fields[0].GetUInt32()]; itemList.push_back(StoredLootItem(fields[1].GetUInt32(), fields[2].GetUInt32(), fields[3].GetInt32(), fields[4].GetUInt32())); @@ -152,12 +152,12 @@ bool LootItemStorage::LoadStoredLoot(Item* item) loot->unlootedCount++; } - // Mark the item if it has loot so it won't be generated again on open - item->m_lootGenerated = true; - return true; + // Mark the item if it has loot so it won't be generated again on open + item->m_lootGenerated = true; + return true; } -void LootItemStorage::RemoveStoredLootItem(uint32 containerId, uint32 itemid, uint32 count, Loot *loot) +void LootItemStorage::RemoveStoredLootItem(uint32 containerId, uint32 itemid, uint32 count, Loot* loot) { LootItemContainer::iterator itr = lootItemStore.find(containerId); if (itr == lootItemStore.end()) @@ -172,13 +172,13 @@ void LootItemStorage::RemoveStoredLootItem(uint32 containerId, uint32 itemid, ui break; } - // loot with empty itemList but unlootedCount > 0 + // loot with empty itemList but unlootedCount > 0 // must be deleted manually by the player or traded if (!loot->unlootedCount) lootItemStore.erase(itr); } -void LootItemStorage::RemoveStoredLootMoney(uint32 containerId, Loot *loot) +void LootItemStorage::RemoveStoredLootMoney(uint32 containerId, Loot* loot) { LootItemContainer::iterator itr = lootItemStore.find(containerId); if (itr == lootItemStore.end()) @@ -193,7 +193,7 @@ void LootItemStorage::RemoveStoredLootMoney(uint32 containerId, Loot *loot) break; } - // loot with empty itemList but unlootedCount > 0 + // loot with empty itemList but unlootedCount > 0 // must be deleted manually by the player or traded if (!loot->unlootedCount) lootItemStore.erase(itr); diff --git a/src/server/game/Loot/LootItemStorage.h b/src/server/game/Loot/LootItemStorage.h index 4ca36f712..d708a1b15 100644 --- a/src/server/game/Loot/LootItemStorage.h +++ b/src/server/game/Loot/LootItemStorage.h @@ -13,7 +13,7 @@ Xinef struct StoredLootItem { - StoredLootItem(uint32 i, uint32 c, int32 ri, uint32 rs) : + StoredLootItem(uint32 i, uint32 c, int32 ri, uint32 rs) : itemid(i), count(c), randomPropertyId(ri), randomSuffix(rs) { } // If itemid == 0 - money amount is stored in count value @@ -28,25 +28,25 @@ typedef std::unordered_map LootItemContainer; class LootItemStorage { - private: - LootItemStorage(); - ~LootItemStorage(); +private: + LootItemStorage(); + ~LootItemStorage(); - public: - static LootItemStorage* instance(); +public: + static LootItemStorage* instance(); - void LoadStorageFromDB(); - void RemoveEntryFromDB(uint32 containerId, uint32 itemid, uint32 count); + void LoadStorageFromDB(); + void RemoveEntryFromDB(uint32 containerId, uint32 itemid, uint32 count); - void AddNewStoredLoot(Loot* loot, Player* player); - bool LoadStoredLoot(Item* item); + void AddNewStoredLoot(Loot* loot, Player* player); + bool LoadStoredLoot(Item* item); - void RemoveStoredLootItem(uint32 containerId, uint32 itemid, uint32 count, Loot* loot); - void RemoveStoredLootMoney(uint32 containerId, Loot* loot); - void RemoveStoredLoot(uint32 containerId); + void RemoveStoredLootItem(uint32 containerId, uint32 itemid, uint32 count, Loot* loot); + void RemoveStoredLootMoney(uint32 containerId, Loot* loot); + void RemoveStoredLoot(uint32 containerId); - private: - LootItemContainer lootItemStore; +private: + LootItemContainer lootItemStore; }; #define sLootItemStorage LootItemStorage::instance() diff --git a/src/server/game/Loot/LootMgr.cpp b/src/server/game/Loot/LootMgr.cpp index db671973a..b440054ab 100644 --- a/src/server/game/Loot/LootMgr.cpp +++ b/src/server/game/Loot/LootMgr.cpp @@ -61,7 +61,7 @@ struct LootGroupInvalidSelector : public acore::unary_functionInventoryType == 0 && foundDuplicates == 3 && _proto->ItemId != 47242 /*Trophy of the Crusade*/) // Non-equippable items are limited to 3 drops - return true; + return true; else if (_proto->InventoryType != 0 && foundDuplicates == 1) // Equippable item are limited to 1 drop return true; } @@ -76,39 +76,39 @@ private: class LootTemplate::LootGroup // A set of loot definitions for items (refs are not allowed) { - public: - LootGroup() { } - ~LootGroup(); +public: + LootGroup() { } + ~LootGroup(); - void AddEntry(LootStoreItem* item); // Adds an entry to the group (at loading stage) - bool HasQuestDrop() const; // True if group includes at least 1 quest drop entry - bool HasQuestDropForPlayer(Player const* player) const; - // The same for active quests of the player - void Process(Loot& loot, Player const *player, LootStore const& lootstore, uint16 lootMode) const; // Rolls an item from the group (if any) and adds the item to the loot - float RawTotalChance() const; // Overall chance for the group (without equal chanced items) - float TotalChance() const; // Overall chance for the group + void AddEntry(LootStoreItem* item); // Adds an entry to the group (at loading stage) + bool HasQuestDrop() const; // True if group includes at least 1 quest drop entry + bool HasQuestDropForPlayer(Player const* player) const; + // The same for active quests of the player + void Process(Loot& loot, Player const* player, LootStore const& lootstore, uint16 lootMode) const; // Rolls an item from the group (if any) and adds the item to the loot + float RawTotalChance() const; // Overall chance for the group (without equal chanced items) + float TotalChance() const; // Overall chance for the group - void Verify(LootStore const& lootstore, uint32 id, uint8 group_id) const; - void CollectLootIds(LootIdSet& set) const; - void CheckLootRefs(LootTemplateMap const& store, LootIdSet* ref_set) const; - LootStoreItemList* GetExplicitlyChancedItemList() { return &ExplicitlyChanced; } - LootStoreItemList* GetEqualChancedItemList() { return &EqualChanced; } - void CopyConditions(ConditionList conditions); - private: - LootStoreItemList ExplicitlyChanced; // Entries with chances defined in DB - LootStoreItemList EqualChanced; // Zero chances - every entry takes the same chance + void Verify(LootStore const& lootstore, uint32 id, uint8 group_id) const; + void CollectLootIds(LootIdSet& set) const; + void CheckLootRefs(LootTemplateMap const& store, LootIdSet* ref_set) const; + LootStoreItemList* GetExplicitlyChancedItemList() { return &ExplicitlyChanced; } + LootStoreItemList* GetEqualChancedItemList() { return &EqualChanced; } + void CopyConditions(ConditionList conditions); +private: + LootStoreItemList ExplicitlyChanced; // Entries with chances defined in DB + LootStoreItemList EqualChanced; // Zero chances - every entry takes the same chance - LootStoreItem const* Roll(Loot& loot, Player const *player, LootStore const& store, uint16 lootMode) const; // Rolls an item from the group, returns NULL if all miss their chances + LootStoreItem const* Roll(Loot& loot, Player const* player, LootStore const& store, uint16 lootMode) const; // Rolls an item from the group, returns NULL if all miss their chances - // This class must never be copied - storing pointers - LootGroup(LootGroup const&); - LootGroup& operator=(LootGroup const&); + // This class must never be copied - storing pointers + LootGroup(LootGroup const&); + LootGroup& operator=(LootGroup const&); }; //Remove all data and free all memory void LootStore::Clear() { - for (LootTemplateMap::const_iterator itr=m_LootTemplates.begin(); itr != m_LootTemplates.end(); ++itr) + for (LootTemplateMap::const_iterator itr = m_LootTemplates.begin(); itr != m_LootTemplates.end(); ++itr) delete itr->second; m_LootTemplates.clear(); } @@ -173,7 +173,7 @@ uint32 LootStore::LoadLootTable() } // Looking for the template of the entry - // often entries are put together + // often entries are put together if (m_LootTemplates.empty() || tab->first != entry) { // Searching the template (in case template Id changed) @@ -190,8 +190,7 @@ uint32 LootStore::LoadLootTable() // Adds current row to the template tab->second->AddEntry(storeitem); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); Verify(); // Checks validity of the loot store @@ -286,7 +285,7 @@ void LootStore::ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 // Checks if the entry (quest, non-quest, reference) takes it's chance (at loot generation) // RATE_DROP_ITEMS is no longer used for all types of entries -bool LootStoreItem::Roll(bool rate, Player const *player, Loot& loot, LootStore const& store) const +bool LootStoreItem::Roll(bool rate, Player const* player, Loot& loot, LootStore const& store) const { float _chance = chance; @@ -296,13 +295,13 @@ bool LootStoreItem::Roll(bool rate, Player const *player, Loot& loot, LootStore return true; if (reference > 0) // reference case - return roll_chance_f(_chance* (rate ? sWorld->getRate(RATE_DROP_ITEM_REFERENCED) : 1.0f)); + return roll_chance_f(_chance * (rate ? sWorld->getRate(RATE_DROP_ITEM_REFERENCED) : 1.0f)); ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid); float qualityModifier = pProto && rate ? sWorld->getRate(qualityToRate[pProto->Quality]) : 1.0f; - return roll_chance_f(_chance*qualityModifier); + return roll_chance_f(_chance * qualityModifier); } // Checks correctness of values @@ -338,7 +337,7 @@ bool LootStoreItem::IsValid(LootStore const& store, uint32 entry) const if (chance != 0 && chance < 0.000001f) // loot with low chance { sLog->outErrorDb("Table '%s' Entry %d Item %d: low chance (%f) - skipped", - store.GetName(), entry, itemid, chance); + store.GetName(), entry, itemid, chance); return false; } @@ -529,7 +528,7 @@ void Loot::FillNotNormalLootFor(Player* player, bool presentAtLooting) if (i < items.size()) item = &items[i]; else - item = &quest_items[i-itemsSize]; + item = &quest_items[i - itemsSize]; if (!item->is_looted && item->freeforall && item->AllowedForPlayer(player)) if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item->itemid)) @@ -544,7 +543,7 @@ QuestItemList* Loot::FillFFALoot(Player* player) for (uint8 i = 0; i < items.size(); ++i) { - LootItem &item = items[i]; + LootItem& item = items[i]; if (!item.is_looted && item.freeforall && item.AllowedForPlayer(player)) { ql->push_back(QuestItem(i)); @@ -570,7 +569,7 @@ QuestItemList* Loot::FillQuestLoot(Player* player) for (uint8 i = 0; i < quest_items.size(); ++i) { - LootItem &item = quest_items[i]; + LootItem& item = quest_items[i]; if (!item.is_looted && (item.AllowedForPlayer(player) || (item.follow_loot_rules && player->GetGroup() && ((player->GetGroup()->GetLootMethod() == MASTER_LOOT && player->GetGroup()->GetMasterLooterGuid() == player->GetGUID()) || player->GetGroup()->GetLootMethod() != MASTER_LOOT )))) { @@ -605,7 +604,7 @@ QuestItemList* Loot::FillNonQuestNonFFAConditionalLoot(Player* player, bool pres for (uint8 i = 0; i < items.size(); ++i) { - LootItem &item = items[i]; + LootItem& item = items[i]; if (!item.is_looted && !item.freeforall && (item.AllowedForPlayer(player) || (item.follow_loot_rules && player->GetGroup() && ((player->GetGroup()->GetLootMethod() == MASTER_LOOT && player->GetGroup()->GetMasterLooterGuid() == player->GetGUID()) || player->GetGroup()->GetLootMethod() != MASTER_LOOT )))) { if (presentAtLooting) @@ -690,7 +689,7 @@ void Loot::NotifyQuestItemRemoved(uint8 questIndex) break; if (j < pql.size()) - player->SendNotifyLootItemRemoved(items.size()+j); + player->SendNotifyLootItemRemoved(items.size() + j); } } else @@ -711,7 +710,7 @@ void Loot::generateMoneyLoot(uint32 minAmount, uint32 maxAmount) } } -LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, QuestItem* *qitem, QuestItem* *ffaitem, QuestItem* *conditem) +LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, QuestItem * *qitem, QuestItem * *ffaitem, QuestItem * *conditem) { LootItem* item = nullptr; bool is_looted = true; @@ -739,10 +738,10 @@ LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, QuestItem* *qite QuestItemMap::const_iterator itr = PlayerFFAItems.find(player->GetGUIDLow()); if (itr != PlayerFFAItems.end()) { - for (QuestItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) + for (QuestItemList::const_iterator iter = itr->second->begin(); iter != itr->second->end(); ++iter) if (iter->index == lootSlot) { - QuestItem* ffaitem2 = (QuestItem*)&(*iter); + QuestItem* ffaitem2 = (QuestItem*) & (*iter); if (ffaitem) *ffaitem = ffaitem2; is_looted = ffaitem2->is_looted; @@ -755,11 +754,11 @@ LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, QuestItem* *qite QuestItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.find(player->GetGUIDLow()); if (itr != PlayerNonQuestNonFFAConditionalItems.end()) { - for (QuestItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) + for (QuestItemList::const_iterator iter = itr->second->begin(); iter != itr->second->end(); ++iter) { if (iter->index == lootSlot) { - QuestItem* conditem2 = (QuestItem*)&(*iter); + QuestItem* conditem2 = (QuestItem*) & (*iter); if (conditem) *conditem = conditem2; is_looted = conditem2->is_looted; @@ -792,7 +791,7 @@ bool Loot::hasItemFor(Player* player) const QuestItemList* q_list = q_itr->second; for (QuestItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) { - const LootItem &item = quest_items[qi->index]; + const LootItem& item = quest_items[qi->index]; if (!qi->is_looted && !item.is_looted) return true; } @@ -805,7 +804,7 @@ bool Loot::hasItemFor(Player* player) const QuestItemList* ffa_list = ffa_itr->second; for (QuestItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) { - const LootItem &item = items[fi->index]; + const LootItem& item = items[fi->index]; if (!fi->is_looted && !item.is_looted) return true; } @@ -818,7 +817,7 @@ bool Loot::hasItemFor(Player* player) const QuestItemList* conditional_list = nn_itr->second; for (QuestItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) { - const LootItem &item = items[ci->index]; + const LootItem& item = items[ci->index]; if (!ci->is_looted && !item.is_looted) return true; } @@ -859,7 +858,7 @@ ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) return b; // nothing output more } - Loot &l = lv.loot; + Loot& l = lv.loot; uint8 itemsShown = 0; @@ -873,97 +872,97 @@ ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) case GROUP_PERMISSION: case MASTER_PERMISSION: case RESTRICTED_PERMISSION: - { - // if you are not the round-robin group looter, you can only see - // blocked rolled items and quest items, and !ffa items - for (uint8 i = 0; i < l.items.size(); ++i) { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + // if you are not the round-robin group looter, you can only see + // blocked rolled items and quest items, and !ffa items + for (uint8 i = 0; i < l.items.size(); ++i) { - uint8 slot_type = 0; - - if (l.items[i].is_blocked) // for ML & restricted is_blocked = !is_underthreshold + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) { - switch (lv.permission) + uint8 slot_type = 0; + + if (l.items[i].is_blocked) // for ML & restricted is_blocked = !is_underthreshold { - case GROUP_PERMISSION: - slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; - break; - case MASTER_PERMISSION: + switch (lv.permission) { - if (lv.viewer->GetGroup()) - { - if (lv.viewer->GetGroup()->GetMasterLooterGuid() == lv.viewer->GetGUID()) - slot_type = LOOT_SLOT_TYPE_MASTER; - else - slot_type = LOOT_SLOT_TYPE_LOCKED; - } - break; + case GROUP_PERMISSION: + slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; + break; + case MASTER_PERMISSION: + { + if (lv.viewer->GetGroup()) + { + if (lv.viewer->GetGroup()->GetMasterLooterGuid() == lv.viewer->GetGUID()) + slot_type = LOOT_SLOT_TYPE_MASTER; + else + slot_type = LOOT_SLOT_TYPE_LOCKED; + } + break; + } + case RESTRICTED_PERMISSION: + slot_type = LOOT_SLOT_TYPE_LOCKED; + break; + default: + continue; } - case RESTRICTED_PERMISSION: - slot_type = LOOT_SLOT_TYPE_LOCKED; - break; - default: + } + else if (l.items[i].rollWinnerGUID) + { + if (l.items[i].rollWinnerGUID == lv.viewer->GetGUID()) + slot_type = LOOT_SLOT_TYPE_OWNER; + else continue; } - } - else if (l.items[i].rollWinnerGUID) - { - if (l.items[i].rollWinnerGUID == lv.viewer->GetGUID()) - slot_type = LOOT_SLOT_TYPE_OWNER; + else if (l.roundRobinPlayer == 0 || lv.viewer->GetGUID() == l.roundRobinPlayer || !l.items[i].is_underthreshold) + { + // no round robin owner or he has released the loot + // or it IS the round robin group owner + // => item is lootable + slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; + } else + // item shall not be displayed. continue; - } - else if (l.roundRobinPlayer == 0 || lv.viewer->GetGUID() == l.roundRobinPlayer || !l.items[i].is_underthreshold) - { - // no round robin owner or he has released the loot - // or it IS the round robin group owner - // => item is lootable - slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; - } - else - // item shall not be displayed. - continue; - b << uint8(i) << l.items[i]; - b << uint8(slot_type); - ++itemsShown; + b << uint8(i) << l.items[i]; + b << uint8(slot_type); + ++itemsShown; + } } + break; } - break; - } case ROUND_ROBIN_PERMISSION: - { - for (uint8 i = 0; i < l.items.size(); ++i) { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + for (uint8 i = 0; i < l.items.size(); ++i) { - if (l.roundRobinPlayer != 0 && lv.viewer->GetGUID() != l.roundRobinPlayer) - // item shall not be displayed. - continue; + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + if (l.roundRobinPlayer != 0 && lv.viewer->GetGUID() != l.roundRobinPlayer) + // item shall not be displayed. + continue; - b << uint8(i) << l.items[i]; - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - ++itemsShown; + b << uint8(i) << l.items[i]; + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + ++itemsShown; + } } + break; } - break; - } case ALL_PERMISSION: case OWNER_PERMISSION: - { - uint8 slot_type = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; - for (uint8 i = 0; i < l.items.size(); ++i) { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + uint8 slot_type = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; + for (uint8 i = 0; i < l.items.size(); ++i) { - b << uint8(i) << l.items[i]; - b << uint8(slot_type); - ++itemsShown; + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + b << uint8(i) << l.items[i]; + b << uint8(slot_type); + ++itemsShown; + } } + break; } - break; - } default: return b; } @@ -980,7 +979,7 @@ ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) QuestItemList* q_list = q_itr->second; for (QuestItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) { - LootItem &item = l.quest_items[qi->index]; + LootItem& item = l.quest_items[qi->index]; if (!qi->is_looted && !item.is_looted) { b << uint8(l.items.size() + (qi - q_list->begin())); @@ -1023,7 +1022,7 @@ ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) QuestItemList* ffa_list = ffa_itr->second; for (QuestItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) { - LootItem &item = l.items[fi->index]; + LootItem& item = l.items[fi->index]; if (!fi->is_looted && !item.is_looted) { b << uint8(fi->index); @@ -1042,7 +1041,7 @@ ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) QuestItemList* conditional_list = nn_itr->second; for (QuestItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) { - LootItem &item = l.items[ci->index]; + LootItem& item = l.items[ci->index]; if (!ci->is_looted && !item.is_looted) { b << uint8(ci->index); @@ -1051,22 +1050,22 @@ ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) { switch (lv.permission) { - case MASTER_PERMISSION: - b << uint8(LOOT_SLOT_TYPE_MASTER); - break; - case RESTRICTED_PERMISSION: - b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); - break; - case GROUP_PERMISSION: - case ROUND_ROBIN_PERMISSION: - if (!item.is_blocked) - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - else - b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); - break; - default: - b << uint8(slotType); - break; + case MASTER_PERMISSION: + b << uint8(LOOT_SLOT_TYPE_MASTER); + break; + case RESTRICTED_PERMISSION: + b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); + break; + case GROUP_PERMISSION: + case ROUND_ROBIN_PERMISSION: + if (!item.is_blocked) + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + else + b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); + break; + default: + b << uint8(slotType); + break; } } else if (!item.freeforall) @@ -1113,7 +1112,7 @@ void LootTemplate::LootGroup::AddEntry(LootStoreItem* item) } // Rolls an item from the group, returns NULL if all miss their chances -LootStoreItem const* LootTemplate::LootGroup::Roll(Loot& loot, Player const *player, LootStore const& store, uint16 lootMode) const +LootStoreItem const* LootTemplate::LootGroup::Roll(Loot& loot, Player const* player, LootStore const& store, uint16 lootMode) const { LootStoreItemList possibleLoot = ExplicitlyChanced; possibleLoot.remove_if(LootGroupInvalidSelector(loot, lootMode)); @@ -1126,7 +1125,7 @@ LootStoreItem const* LootTemplate::LootGroup::Roll(Loot& loot, Player const *pla { LootStoreItem* item = *itr; float chance = item->chance; - + sScriptMgr->OnItemRoll(player, item, chance, loot, store); if (chance >= 100.0f) @@ -1184,7 +1183,7 @@ void LootTemplate::LootGroup::CopyConditions(ConditionList /*conditions*/) } // Rolls an item from the group (if any takes its chance) and adds the item to the loot -void LootTemplate::LootGroup::Process(Loot& loot, Player const *player, LootStore const& store, uint16 lootMode) const +void LootTemplate::LootGroup::Process(Loot& loot, Player const* player, LootStore const& store, uint16 lootMode) const { if (LootStoreItem const* item = Roll(loot, player, store, lootMode)) loot.AddItem(*item); @@ -1195,7 +1194,7 @@ float LootTemplate::LootGroup::RawTotalChance() const { float result = 0; - for (LootStoreItemList::const_iterator i=ExplicitlyChanced.begin(); i != ExplicitlyChanced.end(); ++i) + for (LootStoreItemList::const_iterator i = ExplicitlyChanced.begin(); i != ExplicitlyChanced.end(); ++i) if (!(*i)->needs_quest) result += (*i)->chance; @@ -1315,7 +1314,7 @@ void LootTemplate::CopyConditions(LootItem* li) const void LootTemplate::Process(Loot& loot, LootStore const& store, uint16 lootMode, Player const* player, uint8 groupId) const { bool rate = store.IsRatesAllowed(); - + if (groupId) // Group reference uses own processing of the group { if (groupId > Groups.size()) @@ -1348,7 +1347,9 @@ void LootTemplate::Process(Loot& loot, LootStore const& store, uint16 lootMode, sScriptMgr->OnAfterRefCount(player, loot, rate, lootMode, item, maxcount, store); for (uint32 loop = 0; loop < maxcount; ++loop) // Ref multiplicator Referenced->Process(loot, store, lootMode, player, item->groupid); - } else { + } + else + { // Plain entries (not a reference, not grouped) sScriptMgr->OnBeforeDropAddItem(player, loot, rate, lootMode, item, store); loot.AddItem(*item); // Chance is already checked, just add @@ -1372,7 +1373,7 @@ bool LootTemplate::HasQuestDrop(LootTemplateMap const& store, uint8 groupId) con if (!Groups[groupId - 1]) return false; - return Groups[groupId-1]->HasQuestDrop(); + return Groups[groupId - 1]->HasQuestDrop(); } for (LootStoreItemList::const_iterator i = Entries.begin(); i != Entries.end(); ++i) diff --git a/src/server/game/Loot/LootMgr.h b/src/server/game/Loot/LootMgr.h index e80ccaf4b..24bffb3b3 100644 --- a/src/server/game/Loot/LootMgr.h +++ b/src/server/game/Loot/LootMgr.h @@ -70,7 +70,7 @@ enum LootType LOOT_PICKPOCKETING = 2, LOOT_FISHING = 3, LOOT_DISENCHANTING = 4, - // ignored always by client + // ignored always by client LOOT_SKINNING = 6, LOOT_PROSPECTING = 7, LOOT_MILLING = 8, @@ -127,13 +127,13 @@ struct LootStoreItem // Constructor // displayid is filled in IsValid() which must be called after LootStoreItem(uint32 _itemid, uint32 _reference, float _chance, bool _needs_quest, uint16 _lootmode, uint8 _groupid, int32 _mincount, uint8 _maxcount) - : itemid(_itemid), reference(_reference), chance(_chance), needs_quest(_needs_quest), - lootmode(_lootmode), groupid(_groupid), mincount(_mincount), maxcount(_maxcount) - {} + : itemid(_itemid), reference(_reference), chance(_chance), needs_quest(_needs_quest), + lootmode(_lootmode), groupid(_groupid), mincount(_mincount), maxcount(_maxcount) + {} - bool Roll(bool rate, Player const *player, Loot& loot, LootStore const& store) const; // Checks if the entry takes it's chance (at loot generation) + bool Roll(bool rate, Player const* player, Loot& loot, LootStore const& store) const; // Checks if the entry takes it's chance (at loot generation) bool IsValid(LootStore const& store, uint32 entry) const; - // Checks correctness of values + // Checks correctness of values }; typedef std::set AllowedLooterSet; @@ -165,7 +165,7 @@ struct LootItem bool AllowedForPlayer(Player const* player) const; void AddAllowedLooter(Player const* player); - const AllowedLooterSet & GetAllowedLooters() const { return allowedGUIDs; } + const AllowedLooterSet& GetAllowedLooters() const { return allowedGUIDs; } }; struct QuestItem @@ -192,39 +192,39 @@ typedef std::set LootIdSet; class LootStore { - public: - explicit LootStore(char const* name, char const* entryName, bool ratesAllowed) - : m_name(name), m_entryName(entryName), m_ratesAllowed(ratesAllowed) {} +public: + explicit LootStore(char const* name, char const* entryName, bool ratesAllowed) + : m_name(name), m_entryName(entryName), m_ratesAllowed(ratesAllowed) {} - virtual ~LootStore() { Clear(); } + virtual ~LootStore() { Clear(); } - uint32 LoadAndCollectLootIds(LootIdSet& ids_set); - void ResetConditions(); + uint32 LoadAndCollectLootIds(LootIdSet& ids_set); + void ResetConditions(); - void Verify() const; - void CheckLootRefs(LootIdSet* ref_set = nullptr) const; // check existence reference and remove it from ref_set - void ReportUnusedIds(LootIdSet const& ids_set) const; - void ReportNonExistingId(uint32 lootId) const; - void ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const; + void Verify() const; + void CheckLootRefs(LootIdSet* ref_set = nullptr) const; // check existence reference and remove it from ref_set + void ReportUnusedIds(LootIdSet const& ids_set) const; + void ReportNonExistingId(uint32 lootId) const; + void ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const; - bool HaveLootFor(uint32 loot_id) const { return m_LootTemplates.find(loot_id) != m_LootTemplates.end(); } - bool HaveQuestLootFor(uint32 loot_id) const; - bool HaveQuestLootForPlayer(uint32 loot_id, Player const* player) const; + bool HaveLootFor(uint32 loot_id) const { return m_LootTemplates.find(loot_id) != m_LootTemplates.end(); } + bool HaveQuestLootFor(uint32 loot_id) const; + bool HaveQuestLootForPlayer(uint32 loot_id, Player const* player) const; - LootTemplate const* GetLootFor(uint32 loot_id) const; - LootTemplate* GetLootForConditionFill(uint32 loot_id) const; + LootTemplate const* GetLootFor(uint32 loot_id) const; + LootTemplate* GetLootForConditionFill(uint32 loot_id) const; - char const* GetName() const { return m_name; } - char const* GetEntryName() const { return m_entryName; } - bool IsRatesAllowed() const { return m_ratesAllowed; } - protected: - uint32 LoadLootTable(); - void Clear(); - private: - LootTemplateMap m_LootTemplates; - char const* m_name; - char const* m_entryName; - bool m_ratesAllowed; + char const* GetName() const { return m_name; } + char const* GetEntryName() const { return m_entryName; } + bool IsRatesAllowed() const { return m_ratesAllowed; } +protected: + uint32 LoadLootTable(); + void Clear(); +private: + LootTemplateMap m_LootTemplates; + char const* m_name; + char const* m_entryName; + bool m_ratesAllowed; }; class LootTemplate @@ -232,61 +232,61 @@ class LootTemplate class LootGroup; // A set of loot definitions for items (refs are not allowed inside) typedef std::vector LootGroups; - public: - LootTemplate() { } - ~LootTemplate(); +public: + LootTemplate() { } + ~LootTemplate(); - // Adds an entry to the group (at loading stage) - void AddEntry(LootStoreItem* item); - // Rolls for every item in the template and adds the rolled items the the loot - void Process(Loot& loot, LootStore const& store, uint16 lootMode, Player const* player, uint8 groupId = 0) const; - void CopyConditions(ConditionList conditions); - void CopyConditions(LootItem* li) const; + // Adds an entry to the group (at loading stage) + void AddEntry(LootStoreItem* item); + // Rolls for every item in the template and adds the rolled items the the loot + void Process(Loot& loot, LootStore const& store, uint16 lootMode, Player const* player, uint8 groupId = 0) const; + void CopyConditions(ConditionList conditions); + void CopyConditions(LootItem* li) const; - // True if template includes at least 1 quest drop entry - bool HasQuestDrop(LootTemplateMap const& store, uint8 groupId = 0) const; - // True if template includes at least 1 quest drop for an active quest of the player - bool HasQuestDropForPlayer(LootTemplateMap const& store, Player const* player, uint8 groupId = 0) const; + // True if template includes at least 1 quest drop entry + bool HasQuestDrop(LootTemplateMap const& store, uint8 groupId = 0) const; + // True if template includes at least 1 quest drop for an active quest of the player + bool HasQuestDropForPlayer(LootTemplateMap const& store, Player const* player, uint8 groupId = 0) const; - // Checks integrity of the template - void Verify(LootStore const& store, uint32 Id) const; - void CheckLootRefs(LootTemplateMap const& store, LootIdSet* ref_set) const; - bool addConditionItem(Condition* cond); - bool isReference(uint32 id) const; + // Checks integrity of the template + void Verify(LootStore const& store, uint32 Id) const; + void CheckLootRefs(LootTemplateMap const& store, LootIdSet* ref_set) const; + bool addConditionItem(Condition* cond); + bool isReference(uint32 id) const; - private: - LootStoreItemList Entries; // not grouped only - LootGroups Groups; // groups have own (optimised) processing, grouped entries go there +private: + LootStoreItemList Entries; // not grouped only + LootGroups Groups; // groups have own (optimised) processing, grouped entries go there - // Objects of this class must never be copied, we are storing pointers in container - LootTemplate(LootTemplate const&); - LootTemplate& operator=(LootTemplate const&); + // Objects of this class must never be copied, we are storing pointers in container + LootTemplate(LootTemplate const&); + LootTemplate& operator=(LootTemplate const&); }; //===================================================== class LootValidatorRef : public Reference { - public: - LootValidatorRef() {} - void targetObjectDestroyLink() {} - void sourceObjectDestroyLink() {} +public: + LootValidatorRef() {} + void targetObjectDestroyLink() {} + void sourceObjectDestroyLink() {} }; //===================================================== class LootValidatorRefManager : public RefManager { - public: - typedef LinkedListHead::Iterator< LootValidatorRef > iterator; +public: + typedef LinkedListHead::Iterator< LootValidatorRef > iterator; - LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager::getFirst(); } - LootValidatorRef* getLast() { return (LootValidatorRef*)RefManager::getLast(); } + LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager::getFirst(); } + LootValidatorRef* getLast() { return (LootValidatorRef*)RefManager::getLast(); } - iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(nullptr); } - iterator rbegin() { return iterator(getLast()); } - iterator rend() { return iterator(nullptr); } + iterator begin() { return iterator(getFirst()); } + iterator end() { return iterator(nullptr); } + iterator rbegin() { return iterator(getLast()); } + iterator rend() { return iterator(nullptr); } }; //===================================================== @@ -309,7 +309,7 @@ struct Loot uint8 unlootedCount; uint64 roundRobinPlayer; // GUID of the player having the Round-Robin ownership for the loot. If 0, round robin owner has released. LootType loot_type; // required for achievement system - + // GUIDLow of container that holds this loot (item_instance.entry), set for items that can be looted uint32 containerId; @@ -360,35 +360,35 @@ struct Loot bool FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError = false, uint16 lootMode = LOOT_MODE_DEFAULT); // Inserts the item into the loot (called by LootTemplate processors) - void AddItem(LootStoreItem const & item); + void AddItem(LootStoreItem const& item); LootItem* LootItemInSlot(uint32 lootslot, Player* player, QuestItem** qitem = NULL, QuestItem** ffaitem = NULL, QuestItem** conditem = nullptr); uint32 GetMaxSlotInLootFor(Player* player) const; bool hasItemFor(Player* player) const; bool hasOverThresholdItem() const; - private: - void FillNotNormalLootFor(Player* player, bool presentAtLooting); - QuestItemList* FillFFALoot(Player* player); - QuestItemList* FillQuestLoot(Player* player); - QuestItemList* FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting); +private: + void FillNotNormalLootFor(Player* player, bool presentAtLooting); + QuestItemList* FillFFALoot(Player* player); + QuestItemList* FillQuestLoot(Player* player); + QuestItemList* FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting); - typedef std::set PlayersLootingSet; - PlayersLootingSet PlayersLooting; - QuestItemMap PlayerQuestItems; - QuestItemMap PlayerFFAItems; - QuestItemMap PlayerNonQuestNonFFAConditionalItems; + typedef std::set PlayersLootingSet; + PlayersLootingSet PlayersLooting; + QuestItemMap PlayerQuestItems; + QuestItemMap PlayerFFAItems; + QuestItemMap PlayerNonQuestNonFFAConditionalItems; - // All rolls are registered here. They need to know, when the loot is not valid anymore - LootValidatorRefManager i_LootValidatorRefManager; + // All rolls are registered here. They need to know, when the loot is not valid anymore + LootValidatorRefManager i_LootValidatorRefManager; }; struct LootView { - Loot &loot; + Loot& loot; Player* viewer; PermissionTypes permission; - LootView(Loot &_loot, Player* _viewer, PermissionTypes _permission = ALL_PERMISSION) + LootView(Loot& _loot, Player* _viewer, PermissionTypes _permission = ALL_PERMISSION) : loot(_loot), viewer(_viewer), permission(_permission) {} }; diff --git a/src/server/game/Mails/Mail.cpp b/src/server/game/Mails/Mail.cpp index a8d1ebbd3..151928594 100644 --- a/src/server/game/Mails/Mail.cpp +++ b/src/server/game/Mails/Mail.cpp @@ -80,7 +80,8 @@ MailReceiver::MailReceiver(Player* receiver, uint32 receiver_lowguid) : m_receiv MailDraft& MailDraft::AddItem(Item* item) { - m_items[item->GetGUIDLow()] = item; return *this; + m_items[item->GetGUIDLow()] = item; + return *this; } void MailDraft::prepareItems(Player* receiver, SQLTransaction& trans) @@ -195,7 +196,7 @@ void MailDraft::SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, // mail from battlemaster (rewardmarks) should last only one day else if (sender.GetMailMessageType() == MAIL_CREATURE && sBattlegroundMgr->GetBattleMasterBG(sender.GetSenderId()) != BATTLEGROUND_TYPE_NONE) expire_delay = DAY; - // default case: expire time if COD 3 days, if no COD 30 days (or 90 days if sender is a game master) + // default case: expire time if COD 3 days, if no COD 30 days (or 90 days if sender is a game master) else { if (m_COD) diff --git a/src/server/game/Mails/Mail.h b/src/server/game/Mails/Mail.h index fe075e3c7..4e199d4c0 100644 --- a/src/server/game/Mails/Mail.h +++ b/src/server/game/Mails/Mail.h @@ -68,79 +68,79 @@ enum MailShowFlags class MailSender { - public: // Constructors - MailSender(MailMessageType messageType, uint32 sender_guidlow_or_entry, MailStationery stationery = MAIL_STATIONERY_DEFAULT) - : m_messageType(messageType), m_senderId(sender_guidlow_or_entry), m_stationery(stationery) - { - } - MailSender(Object* sender, MailStationery stationery = MAIL_STATIONERY_DEFAULT); - MailSender(CalendarEvent* sender); - MailSender(AuctionEntry* sender); - MailSender(Player* sender); - MailSender(uint32 senderEntry); - public: // Accessors - MailMessageType GetMailMessageType() const { return m_messageType; } - uint32 GetSenderId() const { return m_senderId; } - MailStationery GetStationery() const { return m_stationery; } - private: - MailMessageType m_messageType; - uint32 m_senderId; // player low guid or other object entry - MailStationery m_stationery; +public: // Constructors + MailSender(MailMessageType messageType, uint32 sender_guidlow_or_entry, MailStationery stationery = MAIL_STATIONERY_DEFAULT) + : m_messageType(messageType), m_senderId(sender_guidlow_or_entry), m_stationery(stationery) + { + } + MailSender(Object* sender, MailStationery stationery = MAIL_STATIONERY_DEFAULT); + MailSender(CalendarEvent* sender); + MailSender(AuctionEntry* sender); + MailSender(Player* sender); + MailSender(uint32 senderEntry); +public: // Accessors + MailMessageType GetMailMessageType() const { return m_messageType; } + uint32 GetSenderId() const { return m_senderId; } + MailStationery GetStationery() const { return m_stationery; } +private: + MailMessageType m_messageType; + uint32 m_senderId; // player low guid or other object entry + MailStationery m_stationery; }; class MailReceiver { - public: // Constructors - explicit MailReceiver(uint32 receiver_lowguid) : m_receiver(nullptr), m_receiver_lowguid(receiver_lowguid) {} - MailReceiver(Player* receiver); - MailReceiver(Player* receiver, uint32 receiver_lowguid); - public: // Accessors - Player* GetPlayer() const { return m_receiver; } - uint32 GetPlayerGUIDLow() const { return m_receiver_lowguid; } - private: - Player* m_receiver; - uint32 m_receiver_lowguid; +public: // Constructors + explicit MailReceiver(uint32 receiver_lowguid) : m_receiver(nullptr), m_receiver_lowguid(receiver_lowguid) {} + MailReceiver(Player* receiver); + MailReceiver(Player* receiver, uint32 receiver_lowguid); +public: // Accessors + Player* GetPlayer() const { return m_receiver; } + uint32 GetPlayerGUIDLow() const { return m_receiver_lowguid; } +private: + Player* m_receiver; + uint32 m_receiver_lowguid; }; class MailDraft { typedef std::map MailItemMap; - public: // Constructors - explicit MailDraft(uint16 mailTemplateId, bool need_items = true) - : m_mailTemplateId(mailTemplateId), m_mailTemplateItemsNeed(need_items), m_money(0), m_COD(0) - {} - MailDraft(std::string const& subject, std::string const& body) - : m_mailTemplateId(0), m_mailTemplateItemsNeed(false), m_subject(subject), m_body(body), m_money(0), m_COD(0) {} - public: // Accessors - uint16 GetMailTemplateId() const { return m_mailTemplateId; } - std::string const& GetSubject() const { return m_subject; } - uint32 GetMoney() const { return m_money; } - uint32 GetCOD() const { return m_COD; } - std::string const& GetBody() const { return m_body; } +public: // Constructors + explicit MailDraft(uint16 mailTemplateId, bool need_items = true) + : m_mailTemplateId(mailTemplateId), m_mailTemplateItemsNeed(need_items), m_money(0), m_COD(0) + {} + MailDraft(std::string const& subject, std::string const& body) + : m_mailTemplateId(0), m_mailTemplateItemsNeed(false), m_subject(subject), m_body(body), m_money(0), m_COD(0) {} +public: // Accessors + uint16 GetMailTemplateId() const { return m_mailTemplateId; } + std::string const& GetSubject() const { return m_subject; } + uint32 GetMoney() const { return m_money; } + uint32 GetCOD() const { return m_COD; } + std::string const& GetBody() const { return m_body; } - public: // modifiers - MailDraft& AddItem(Item* item); - MailDraft& AddMoney(uint32 money) { m_money = money; return *this; } - MailDraft& AddCOD(uint32 COD) { m_COD = COD; return *this; } +public: // modifiers + MailDraft& AddItem(Item* item); + MailDraft& AddMoney(uint32 money) { m_money = money; return *this; } + MailDraft& AddCOD(uint32 COD) { m_COD = COD; return *this; } - public: // finishers - void SendReturnToSender(uint32 sender_acc, uint32 sender_guid, uint32 receiver_guid, SQLTransaction& trans); - void SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, MailSender const& sender, MailCheckMask checked = MAIL_CHECK_MASK_NONE, uint32 deliver_delay = 0, uint32 custom_expiration = 0, bool deleteMailItemsFromDB = false, bool sendMail = true); +public: // finishers + void SendReturnToSender(uint32 sender_acc, uint32 sender_guid, uint32 receiver_guid, SQLTransaction& trans); + void SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, MailSender const& sender, MailCheckMask checked = MAIL_CHECK_MASK_NONE, uint32 deliver_delay = 0, uint32 custom_expiration = 0, bool deleteMailItemsFromDB = false, bool sendMail = true); - private: - void deleteIncludedItems(SQLTransaction& trans, bool inDB = false); - void prepareItems(Player* receiver, SQLTransaction& trans); // called from SendMailTo for generate mailTemplateBase items +private: + void deleteIncludedItems(SQLTransaction& trans, bool inDB = false); + void prepareItems(Player* receiver, SQLTransaction& trans); // called from SendMailTo for generate mailTemplateBase items - uint16 m_mailTemplateId; - bool m_mailTemplateItemsNeed; - std::string m_subject; - std::string m_body; + uint16 m_mailTemplateId; + bool m_mailTemplateItemsNeed; + std::string m_subject; + std::string m_body; - MailItemMap m_items; // Keep the items in a map to avoid duplicate guids (which can happen), store only low part of guid + MailItemMap m_items; // Keep the items in a map to avoid duplicate guids (which can happen), store only low part of guid - uint32 m_money; - uint32 m_COD; + uint32 m_money; + uint32 m_COD; }; struct MailItemInfo diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index 520cedef2..9e62efba6 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -34,11 +34,11 @@ union u_map_magic uint32 asUInt; }; -u_map_magic MapMagic = { {'M','A','P','S'} }; -u_map_magic MapVersionMagic = { {'v','1','.','8'} }; -u_map_magic MapAreaMagic = { {'A','R','E','A'} }; -u_map_magic MapHeightMagic = { {'M','H','G','T'} }; -u_map_magic MapLiquidMagic = { {'M','L','I','Q'} }; +u_map_magic MapMagic = { {'M', 'A', 'P', 'S'} }; +u_map_magic MapVersionMagic = { {'v', '1', '.', '8'} }; +u_map_magic MapAreaMagic = { {'A', 'R', 'E', 'A'} }; +u_map_magic MapHeightMagic = { {'M', 'H', 'G', 'T'} }; +u_map_magic MapLiquidMagic = { {'M', 'L', 'I', 'Q'} }; Map::~Map() { @@ -64,12 +64,12 @@ Map::~Map() bool Map::ExistMap(uint32 mapid, int gx, int gy) { - int len = sWorld->GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1; + int len = sWorld->GetDataPath().length() + strlen("maps/%03u%02u%02u.map") + 1; char* tmp = new char[len]; - snprintf(tmp, len, (char *)(sWorld->GetDataPath()+"maps/%03u%02u%02u.map").c_str(), mapid, gx, gy); + snprintf(tmp, len, (char*)(sWorld->GetDataPath() + "maps/%03u%02u%02u.map").c_str(), mapid, gx, gy); bool ret = false; - FILE* pf=fopen(tmp, "rb"); + FILE* pf = fopen(tmp, "rb"); if (!pf) sLog->outError("Map file '%s': does not exist!", tmp); @@ -95,11 +95,11 @@ bool Map::ExistVMap(uint32 mapid, int gx, int gy) { if (vmgr->isMapLoadingEnabled()) { - bool exists = vmgr->existsMap((sWorld->GetDataPath()+ "vmaps").c_str(), mapid, gx, gy); + bool exists = vmgr->existsMap((sWorld->GetDataPath() + "vmaps").c_str(), mapid, gx, gy); if (!exists) { std::string name = vmgr->getDirFileName(mapid, gx, gy); - sLog->outError("VMap file '%s' is missing or points to wrong version of vmap file. Redo vmaps with latest version of vmap_assembler.exe.", (sWorld->GetDataPath()+"vmaps/"+name).c_str()); + sLog->outError("VMap file '%s' is missing or points to wrong version of vmap file. Redo vmaps with latest version of vmap_assembler.exe.", (sWorld->GetDataPath() + "vmaps/" + name).c_str()); return false; } } @@ -109,7 +109,7 @@ bool Map::ExistVMap(uint32 mapid, int gx, int gy) } void Map::LoadMMap(int gx, int gy) -{ +{ if (!MMAP::MMapFactory::IsPathfindingEnabled(this)) // pussywizard return; @@ -135,9 +135,9 @@ void Map::LoadMMap(int gx, int gy) } void Map::LoadVMap(int gx, int gy) -{ - // x and y are swapped !! - int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld->GetDataPath()+ "vmaps").c_str(), GetId(), gx, gy); +{ + // x and y are swapped !! + int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld->GetDataPath() + "vmaps").c_str(), GetId(), gx, gy); switch (vmapLoadResult) { case VMAP::VMAP_LOAD_RESULT_OK: @@ -159,14 +159,14 @@ void Map::LoadVMap(int gx, int gy) } void Map::LoadMap(int gx, int gy, bool reload) -{ +{ if (i_InstanceId != 0) { if (GridMaps[gx][gy]) return; // load grid map for base map - m_parentMap->EnsureGridCreated(GridCoord(63-gx, 63-gy)); + m_parentMap->EnsureGridCreated(GridCoord(63 - gx, 63 - gy)); GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy]; return; @@ -184,14 +184,14 @@ void Map::LoadMap(int gx, int gy, bool reload) sScriptMgr->OnUnloadGridMap(this, GridMaps[gx][gy], gx, gy); delete (GridMaps[gx][gy]); - GridMaps[gx][gy]=NULL; + GridMaps[gx][gy] = NULL; } // map file name - char *tmp=NULL; - int len = sWorld->GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1; + char* tmp = NULL; + int len = sWorld->GetDataPath().length() + strlen("maps/%03u%02u%02u.map") + 1; tmp = new char[len]; - snprintf(tmp, len, (char *)(sWorld->GetDataPath()+"maps/%03u%02u%02u.map").c_str(), GetId(), gx, gy); + snprintf(tmp, len, (char*)(sWorld->GetDataPath() + "maps/%03u%02u%02u.map").c_str(), GetId(), gx, gy); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("Loading map %s", tmp); #endif @@ -207,7 +207,7 @@ void Map::LoadMap(int gx, int gy, bool reload) } void Map::LoadMapAndVMap(int gx, int gy) -{ +{ LoadMap(gx, gy); if (i_InstanceId == 0) { @@ -216,19 +216,19 @@ void Map::LoadMapAndVMap(int gx, int gy) } } -Map::Map(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent) : -i_mapEntry(sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode), i_InstanceId(InstanceId), -m_unloadTimer(0), m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE), -_instanceResetPeriod(0), m_activeNonPlayersIter(m_activeNonPlayers.end()), -_transportsUpdateIter(_transports.end()), i_scriptLock(false), _defaultLight(GetDefaultMapLight(id)) +Map::Map(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent) : + i_mapEntry(sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode), i_InstanceId(InstanceId), + m_unloadTimer(0), m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE), + _instanceResetPeriod(0), m_activeNonPlayersIter(m_activeNonPlayers.end()), + _transportsUpdateIter(_transports.end()), i_scriptLock(false), _defaultLight(GetDefaultMapLight(id)) { m_parentMap = (_parent ? _parent : this); - for (unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx) + for (unsigned int idx = 0; idx < MAX_NUMBER_OF_GRIDS; ++idx) { - for (unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j) + for (unsigned int j = 0; j < MAX_NUMBER_OF_GRIDS; ++j) { //z code - GridMaps[idx][j] =NULL; + GridMaps[idx][j] = NULL; setNGrid(nullptr, idx, j); } } @@ -240,7 +240,7 @@ _transportsUpdateIter(_transports.end()), i_scriptLock(false), _defaultLight(Get } void Map::InitVisibilityDistance() -{ +{ //init visibility for continents m_VisibleDistance = World::GetMaxVisibleDistanceOnContinents(); @@ -258,7 +258,7 @@ void Map::InitVisibilityDistance() // Template specialization of utility methods template void Map::AddToGrid(T* obj, Cell const& cell) -{ +{ NGridType* grid = getNGrid(cell.GridX(), cell.GridY()); if (obj->IsWorldObject()) grid->GetGridType(cell.CellX(), cell.CellY()).template AddWorldObject(obj); @@ -268,7 +268,7 @@ void Map::AddToGrid(T* obj, Cell const& cell) template<> void Map::AddToGrid(Creature* obj, Cell const& cell) -{ +{ NGridType* grid = getNGrid(cell.GridX(), cell.GridY()); if (obj->IsWorldObject()) grid->GetGridType(cell.CellX(), cell.CellY()).AddWorldObject(obj); @@ -280,7 +280,7 @@ void Map::AddToGrid(Creature* obj, Cell const& cell) template<> void Map::AddToGrid(GameObject* obj, Cell const& cell) -{ +{ NGridType* grid = getNGrid(cell.GridX(), cell.GridY()); grid->GetGridType(cell.CellX(), cell.CellY()).AddGridObject(obj); @@ -289,7 +289,7 @@ void Map::AddToGrid(GameObject* obj, Cell const& cell) template<> void Map::AddToGrid(DynamicObject* obj, Cell const& cell) -{ +{ NGridType* grid = getNGrid(cell.GridX(), cell.GridY()); if (obj->IsWorldObject()) grid->GetGridType(cell.CellX(), cell.CellY()).AddWorldObject(obj); @@ -301,12 +301,12 @@ void Map::AddToGrid(DynamicObject* obj, Cell const& cell) template void Map::SwitchGridContainers(T* /*obj*/, bool /*on*/) -{ +{ } template<> void Map::SwitchGridContainers(Creature* obj, bool on) -{ +{ ASSERT(!obj->IsPermanentWorldObject()); CellCoord p = acore::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY()); if (!p.IsCoordValid()) @@ -322,10 +322,10 @@ void Map::SwitchGridContainers(Creature* obj, bool on) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Switch object " UI64FMTD " from grid[%u, %u] %u", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y, on); #endif - NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY()); + NGridType* ngrid = getNGrid(cell.GridX(), cell.GridY()); ASSERT(ngrid != nullptr); - GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); + GridType& grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); obj->RemoveFromGrid(); //This step is not really necessary but we want to do ASSERT in remove/add @@ -345,7 +345,7 @@ void Map::SwitchGridContainers(Creature* obj, bool on) template<> void Map::SwitchGridContainers(GameObject* obj, bool on) -{ +{ ASSERT(!obj->IsPermanentWorldObject()); CellCoord p = acore::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY()); if (!p.IsCoordValid()) @@ -359,10 +359,10 @@ void Map::SwitchGridContainers(GameObject* obj, bool on) return; //TC_LOG_DEBUG(LOG_FILTER_MAPS, "Switch object " UI64FMTD " from grid[%u, %u] %u", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y, on); - NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY()); + NGridType* ngrid = getNGrid(cell.GridX(), cell.GridY()); ASSERT(ngrid != nullptr); - GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); + GridType& grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); obj->RemoveFromGrid(); //This step is not really necessary but we want to do ASSERT in remove/add @@ -380,14 +380,14 @@ void Map::SwitchGridContainers(GameObject* obj, bool on) template void Map::DeleteFromWorld(T* obj) -{ +{ // Note: In case resurrectable corpse and pet its removed from global lists in own destructor delete obj; } template<> void Map::DeleteFromWorld(Player* player) -{ +{ sObjectAccessor->RemoveObject(player); // pussywizard: optimization @@ -400,8 +400,8 @@ void Map::DeleteFromWorld(Player* player) } -void Map::EnsureGridCreated(const GridCoord &p) -{ +void Map::EnsureGridCreated(const GridCoord& p) +{ if (getNGrid(p.x_coord, p.y_coord)) // pussywizard return; ACORE_GUARD(ACE_Thread_Mutex, GridLock); @@ -410,13 +410,13 @@ void Map::EnsureGridCreated(const GridCoord &p) //Create NGrid so the object can be added to it //But object data is not loaded here -void Map::EnsureGridCreated_i(const GridCoord &p) -{ +void Map::EnsureGridCreated_i(const GridCoord& p) +{ if (!getNGrid(p.x_coord, p.y_coord)) { // pussywizard: moved setNGrid to the end of the function - NGridType* ngt = new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord); - + NGridType* ngt = new NGridType(p.x_coord * MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord); + // build a linkage between this map and NGridType buildNGridLinkage(ngt); // pussywizard: getNGrid(x, y) changed to: ngt @@ -435,16 +435,16 @@ void Map::EnsureGridCreated_i(const GridCoord &p) } //Create NGrid and load the object data in it -bool Map::EnsureGridLoaded(const Cell &cell) -{ +bool Map::EnsureGridLoaded(const Cell& cell) +{ EnsureGridCreated(GridCoord(cell.GridX(), cell.GridY())); - NGridType *grid = getNGrid(cell.GridX(), cell.GridY()); + NGridType* grid = getNGrid(cell.GridX(), cell.GridY()); ASSERT(grid != nullptr); if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY())) { - //if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY())) - //{ + //if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY())) + //{ #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_MAPS, "Loading grid[%u, %u] for map %u instance %u", cell.GridX(), cell.GridY(), GetId(), i_InstanceId); #endif @@ -458,14 +458,14 @@ bool Map::EnsureGridLoaded(const Cell &cell) sObjectAccessor->AddCorpsesToGrid(GridCoord(cell.GridX(), cell.GridY()), grid->GetGridType(cell.CellX(), cell.CellY()), this); Balance(); return true; - //} + //} } return false; } void Map::LoadGrid(float x, float y) -{ +{ EnsureGridLoaded(Cell(x, y)); } @@ -477,7 +477,7 @@ void Map::LoadAllCells() } bool Map::AddPlayerToMap(Player* player) -{ +{ CellCoord cellCoord = acore::ComputeCellCoord(player->GetPositionX(), player->GetPositionY()); if (!cellCoord.IsCoordValid()) { @@ -507,24 +507,24 @@ bool Map::AddPlayerToMap(Player* player) template void Map::InitializeObject(T* /*obj*/) -{ +{ } template<> void Map::InitializeObject(Creature* /*obj*/) -{ +{ //obj->_moveState = MAP_OBJECT_CELL_MOVE_NONE; // pussywizard: this is shit } template<> void Map::InitializeObject(GameObject* /*obj*/) -{ +{ //obj->_moveState = MAP_OBJECT_CELL_MOVE_NONE; // pussywizard: this is shit } template bool Map::AddToMap(T* obj, bool checkTransport) -{ +{ //TODO: Needs clean up. An object should not be added to map twice. if (obj->IsInWorld()) { @@ -580,7 +580,7 @@ bool Map::AddToMap(T* obj, bool checkTransport) template<> bool Map::AddToMap(MotionTransport* obj, bool /*checkTransport*/) -{ +{ //TODO: Needs clean up. An object should not be added to map twice. if (obj->IsInWorld()) return true; @@ -622,16 +622,16 @@ bool Map::AddToMap(MotionTransport* obj, bool /*checkTransport*/) return true; } -bool Map::IsGridLoaded(const GridCoord &p) const -{ +bool Map::IsGridLoaded(const GridCoord& p) const +{ return (getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord)); } -void Map::VisitNearbyCellsOfPlayer(Player* player, TypeContainerVisitor &gridVisitor, - TypeContainerVisitor &worldVisitor, - TypeContainerVisitor &largeGridVisitor, - TypeContainerVisitor &largeWorldVisitor) +void Map::VisitNearbyCellsOfPlayer(Player* player, TypeContainerVisitor& gridVisitor, + TypeContainerVisitor& worldVisitor, + TypeContainerVisitor& largeGridVisitor, + TypeContainerVisitor& largeWorldVisitor) { // check for valid position if (!player->IsPositionValid()) @@ -663,11 +663,11 @@ void Map::VisitNearbyCellsOfPlayer(Player* player, TypeContainerVisitor &gridVisitor, - TypeContainerVisitor &worldVisitor, - TypeContainerVisitor &largeGridVisitor, - TypeContainerVisitor &largeWorldVisitor) -{ +void Map::VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor& gridVisitor, + TypeContainerVisitor& worldVisitor, + TypeContainerVisitor& largeGridVisitor, + TypeContainerVisitor& largeWorldVisitor) +{ // Check for valid position if (!obj->IsPositionValid()) return; @@ -760,7 +760,8 @@ void Map::Update(const uint32 t_diff, const uint32 s_diff, bool /*thread*/) TypeContainerVisitor world_large_object_update(largeObjectUpdater); // pussywizard: container for far creatures in combat with players - std::vector updateList; updateList.reserve(10); + std::vector updateList; + updateList.reserve(10); // non-player active objects, increasing iterator in the loop in case of object removal for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end();) @@ -792,7 +793,8 @@ void Map::Update(const uint32 t_diff, const uint32 s_diff, bool /*thread*/) if (player->IsInCombat()) { updateList.clear(); - float rangeSq = player->GetGridActivationRange() - 1.0f; rangeSq = rangeSq*rangeSq; + float rangeSq = player->GetGridActivationRange() - 1.0f; + rangeSq = rangeSq * rangeSq; HostileReference* ref = player->getHostileRefManager().getFirst(); while (ref) { @@ -840,7 +842,7 @@ void Map::Update(const uint32 t_diff, const uint32 s_diff, bool /*thread*/) } void Map::HandleDelayedVisibility() -{ +{ if (i_objectsForDelayedVisibility.empty()) return; for (std::unordered_set::iterator itr = i_objectsForDelayedVisibility.begin(); itr != i_objectsForDelayedVisibility.end(); ++itr) @@ -850,18 +852,18 @@ void Map::HandleDelayedVisibility() struct ResetNotifier { - templateinline void resetNotify(GridRefManager &m) + templateinline void resetNotify(GridRefManager& m) { - for (typename GridRefManager::iterator iter=m.begin(); iter != m.end(); ++iter) + for (typename GridRefManager::iterator iter = m.begin(); iter != m.end(); ++iter) iter->GetSource()->ResetAllNotifies(); } - template void Visit(GridRefManager &) {} - void Visit(CreatureMapType &m) { resetNotify(m);} - void Visit(PlayerMapType &m) { resetNotify(m);} + template void Visit(GridRefManager&) {} + void Visit(CreatureMapType& m) { resetNotify(m);} + void Visit(PlayerMapType& m) { resetNotify(m);} }; void Map::RemovePlayerFromMap(Player* player, bool remove) -{ +{ player->getHostileRefManager().deleteReferences(); // pussywizard: multithreading crashfix bool inWorld = player->IsInWorld(); @@ -888,8 +890,8 @@ void Map::AfterPlayerUnlinkFromMap() } template -void Map::RemoveFromMap(T *obj, bool remove) -{ +void Map::RemoveFromMap(T* obj, bool remove) +{ bool inWorld = obj->IsInWorld() && obj->GetTypeId() >= TYPEID_UNIT && obj->GetTypeId() <= TYPEID_GAMEOBJECT; obj->RemoveFromWorld(); @@ -909,7 +911,7 @@ void Map::RemoveFromMap(T *obj, bool remove) template<> void Map::RemoveFromMap(MotionTransport* obj, bool remove) -{ +{ obj->RemoveFromWorld(); if (obj->isActiveObject()) RemoveFromActive(obj); @@ -922,8 +924,8 @@ void Map::RemoveFromMap(MotionTransport* obj, bool remove) WorldPacket packet; data.BuildPacket(&packet); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetTransport() != obj) - itr->GetSource()->SendDirectMessage(&packet); + if (itr->GetSource()->GetTransport() != obj) + itr->GetSource()->SendDirectMessage(&packet); } if (_transportsUpdateIter != _transports.end()) @@ -950,7 +952,7 @@ void Map::RemoveFromMap(MotionTransport* obj, bool remove) } void Map::PlayerRelocation(Player* player, float x, float y, float z, float o) -{ +{ Cell old_cell(player->GetPositionX(), player->GetPositionY()); Cell new_cell(x, y); @@ -972,7 +974,7 @@ void Map::PlayerRelocation(Player* player, float x, float y, float z, float o) } void Map::CreatureRelocation(Creature* creature, float x, float y, float z, float o) -{ +{ Cell old_cell = creature->GetCurrentCell(); Cell new_cell(x, y); @@ -994,7 +996,7 @@ void Map::CreatureRelocation(Creature* creature, float x, float y, float z, floa } void Map::GameObjectRelocation(GameObject* go, float x, float y, float z, float o) -{ +{ Cell old_cell = go->GetCurrentCell(); Cell new_cell(x, y); @@ -1035,31 +1037,31 @@ void Map::DynamicObjectRelocation(DynamicObject* dynObj, float x, float y, float } void Map::AddCreatureToMoveList(Creature* c) -{ +{ if (c->_moveState == MAP_OBJECT_CELL_MOVE_NONE) _creaturesToMove.push_back(c); c->_moveState = MAP_OBJECT_CELL_MOVE_ACTIVE; } void Map::RemoveCreatureFromMoveList(Creature* c) -{ +{ if (c->_moveState == MAP_OBJECT_CELL_MOVE_ACTIVE) c->_moveState = MAP_OBJECT_CELL_MOVE_INACTIVE; } void Map::AddGameObjectToMoveList(GameObject* go) -{ +{ if (go->_moveState == MAP_OBJECT_CELL_MOVE_NONE) _gameObjectsToMove.push_back(go); go->_moveState = MAP_OBJECT_CELL_MOVE_ACTIVE; } void Map::RemoveGameObjectFromMoveList(GameObject* go) -{ +{ if (go->_moveState == MAP_OBJECT_CELL_MOVE_ACTIVE) go->_moveState = MAP_OBJECT_CELL_MOVE_INACTIVE; } - + void Map::AddDynamicObjectToMoveList(DynamicObject* dynObj) { if (dynObj->_moveState == MAP_OBJECT_CELL_MOVE_NONE) @@ -1074,7 +1076,7 @@ void Map::RemoveDynamicObjectFromMoveList(DynamicObject* dynObj) } void Map::MoveAllCreaturesInMoveList() -{ +{ for (std::vector::iterator itr = _creaturesToMove.begin(); itr != _creaturesToMove.end(); ++itr) { Creature* c = *itr; @@ -1103,7 +1105,7 @@ void Map::MoveAllCreaturesInMoveList() } void Map::MoveAllGameObjectsInMoveList() -{ +{ for (std::vector::iterator itr = _gameObjectsToMove.begin(); itr != _gameObjectsToMove.end(); ++itr) { GameObject* go = *itr; @@ -1130,11 +1132,11 @@ void Map::MoveAllGameObjectsInMoveList() } _gameObjectsToMove.clear(); } - - void Map::MoveAllDynamicObjectsInMoveList() - { - for (std::vector::iterator itr = _dynamicObjectsToMove.begin(); itr != _dynamicObjectsToMove.end(); ++itr) - { + +void Map::MoveAllDynamicObjectsInMoveList() +{ + for (std::vector::iterator itr = _dynamicObjectsToMove.begin(); itr != _dynamicObjectsToMove.end(); ++itr) + { DynamicObject* dynObj = *itr; if (dynObj->FindMap() != this) continue; @@ -1161,7 +1163,7 @@ void Map::MoveAllGameObjectsInMoveList() } bool Map::UnloadGrid(NGridType& ngrid) -{ +{ // pussywizard: UnloadGrid only done when whole map is unloaded, no need to worry about moving npcs between grids, etc. const uint32 x = ngrid.getX(); @@ -1210,7 +1212,7 @@ bool Map::UnloadGrid(NGridType& ngrid) } void Map::RemoveAllPlayers() -{ +{ if (HavePlayers()) { for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) @@ -1227,14 +1229,14 @@ void Map::RemoveAllPlayers() } void Map::UnloadAll() -{ +{ // clear all delayed moves, useless anyway do this moves before map unload. _creaturesToMove.clear(); _gameObjectsToMove.clear(); for (GridRefManager::iterator i = GridRefManager::begin(); i != GridRefManager::end();) { - NGridType &grid(*i->GetSource()); + NGridType& grid(*i->GetSource()); ++i; UnloadGrid(grid); // deletes the grid and removes it from the GridRefManager } @@ -1289,7 +1291,7 @@ GridMap::~GridMap() unloadData(); } -bool GridMap::loadData(char *filename) +bool GridMap::loadData(char* filename) { // Unload old data if exist unloadData(); @@ -1369,8 +1371,8 @@ bool GridMap::loadAreaData(FILE* in, uint32 offset, uint32 /*size*/) _gridArea = header.gridArea; if (!(header.flags & MAP_AREA_NO_AREA)) { - _areaMap = new uint16 [16*16]; - if (fread(_areaMap, sizeof(uint16), 16*16, in) != 16*16) + _areaMap = new uint16 [16 * 16]; + if (fread(_areaMap, sizeof(uint16), 16 * 16, in) != 16 * 16) return false; } return true; @@ -1389,30 +1391,30 @@ bool GridMap::loadHeightData(FILE* in, uint32 offset, uint32 /*size*/) { if ((header.flags & MAP_HEIGHT_AS_INT16)) { - m_uint16_V9 = new uint16 [129*129]; - m_uint16_V8 = new uint16 [128*128]; - if (fread(m_uint16_V9, sizeof(uint16), 129*129, in) != 129*129 || - fread(m_uint16_V8, sizeof(uint16), 128*128, in) != 128*128) + m_uint16_V9 = new uint16 [129 * 129]; + m_uint16_V8 = new uint16 [128 * 128]; + if (fread(m_uint16_V9, sizeof(uint16), 129 * 129, in) != 129 * 129 || + fread(m_uint16_V8, sizeof(uint16), 128 * 128, in) != 128 * 128) return false; _gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535; _gridGetHeight = &GridMap::getHeightFromUint16; } else if ((header.flags & MAP_HEIGHT_AS_INT8)) { - m_uint8_V9 = new uint8 [129*129]; - m_uint8_V8 = new uint8 [128*128]; - if (fread(m_uint8_V9, sizeof(uint8), 129*129, in) != 129*129 || - fread(m_uint8_V8, sizeof(uint8), 128*128, in) != 128*128) + m_uint8_V9 = new uint8 [129 * 129]; + m_uint8_V8 = new uint8 [128 * 128]; + if (fread(m_uint8_V9, sizeof(uint8), 129 * 129, in) != 129 * 129 || + fread(m_uint8_V8, sizeof(uint8), 128 * 128, in) != 128 * 128) return false; _gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255; _gridGetHeight = &GridMap::getHeightFromUint8; } else { - m_V9 = new float [129*129]; - m_V8 = new float [128*128]; - if (fread(m_V9, sizeof(float), 129*129, in) != 129*129 || - fread(m_V8, sizeof(float), 128*128, in) != 128*128) + m_V9 = new float [129 * 129]; + m_V8 = new float [128 * 128]; + if (fread(m_V9, sizeof(float), 129 * 129, in) != 129 * 129 || + fread(m_V8, sizeof(float), 128 * 128, in) != 128 * 128) return false; _gridGetHeight = &GridMap::getHeightFromFloat; } @@ -1425,7 +1427,7 @@ bool GridMap::loadHeightData(FILE* in, uint32 offset, uint32 /*size*/) _maxHeight = new int16[3 * 3]; _minHeight = new int16[3 * 3]; if (fread(_maxHeight, sizeof(int16), 3 * 3, in) != 3 * 3 || - fread(_minHeight, sizeof(int16), 3 * 3, in) != 3 * 3) + fread(_minHeight, sizeof(int16), 3 * 3, in) != 3 * 3) return false; } @@ -1449,18 +1451,18 @@ bool GridMap::loadLiquidData(FILE* in, uint32 offset, uint32 /*size*/) if (!(header.flags & MAP_LIQUID_NO_TYPE)) { - _liquidEntry = new uint16[16*16]; - if (fread(_liquidEntry, sizeof(uint16), 16*16, in) != 16*16) + _liquidEntry = new uint16[16 * 16]; + if (fread(_liquidEntry, sizeof(uint16), 16 * 16, in) != 16 * 16) return false; - _liquidFlags = new uint8[16*16]; - if (fread(_liquidFlags, sizeof(uint8), 16*16, in) != 16*16) + _liquidFlags = new uint8[16 * 16]; + if (fread(_liquidFlags, sizeof(uint8), 16 * 16, in) != 16 * 16) return false; } if (!(header.flags & MAP_LIQUID_NO_HEIGHT)) { _liquidMap = new float[uint32(_liquidWidth) * uint32(_liquidHeight)]; - if (fread(_liquidMap, sizeof(float), _liquidWidth*_liquidHeight, in) != (uint32(_liquidWidth) * uint32(_liquidHeight))) + if (fread(_liquidMap, sizeof(float), _liquidWidth * _liquidHeight, in) != (uint32(_liquidWidth) * uint32(_liquidHeight))) return false; } return true; @@ -1471,11 +1473,11 @@ uint16 GridMap::getArea(float x, float y) const if (!_areaMap) return _gridArea; - x = 16 * (32 - x/SIZE_OF_GRIDS); - y = 16 * (32 - y/SIZE_OF_GRIDS); + x = 16 * (32 - x / SIZE_OF_GRIDS); + y = 16 * (32 - y / SIZE_OF_GRIDS); int lx = (int)x & 15; int ly = (int)y & 15; - return _areaMap[lx*16 + ly]; + return _areaMap[lx * 16 + ly]; } float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const @@ -1488,15 +1490,15 @@ float GridMap::getHeightFromFloat(float x, float y) const if (!m_V8 || !m_V9) return _gridHeight; - x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); - y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); + x = MAP_RESOLUTION * (32 - x / SIZE_OF_GRIDS); + y = MAP_RESOLUTION * (32 - y / SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; - x_int&=(MAP_RESOLUTION - 1); - y_int&=(MAP_RESOLUTION - 1); + x_int &= (MAP_RESOLUTION - 1); + y_int &= (MAP_RESOLUTION - 1); // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid // +--------------> X @@ -1515,24 +1517,24 @@ float GridMap::getHeightFromFloat(float x, float y) const float a, b, c; // Select triangle: - if (x+y < 1) + if (x + y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) - float h1 = m_V9[(x_int)*129 + y_int]; - float h2 = m_V9[(x_int+1)*129 + y_int]; - float h5 = 2 * m_V8[x_int*128 + y_int]; - a = h2-h1; - b = h5-h1-h2; + float h1 = m_V9[(x_int) * 129 + y_int]; + float h2 = m_V9[(x_int + 1) * 129 + y_int]; + float h5 = 2 * m_V8[x_int * 128 + y_int]; + a = h2 - h1; + b = h5 - h1 - h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) - float h1 = m_V9[x_int*129 + y_int ]; - float h3 = m_V9[x_int*129 + y_int+1]; - float h5 = 2 * m_V8[x_int*128 + y_int]; + float h1 = m_V9[x_int * 129 + y_int ]; + float h3 = m_V9[x_int * 129 + y_int + 1]; + float h5 = 2 * m_V8[x_int * 128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; @@ -1543,9 +1545,9 @@ float GridMap::getHeightFromFloat(float x, float y) const if (x > y) { // 3 triangle (h2, h4, h5 points) - float h2 = m_V9[(x_int+1)*129 + y_int ]; - float h4 = m_V9[(x_int+1)*129 + y_int+1]; - float h5 = 2 * m_V8[x_int*128 + y_int]; + float h2 = m_V9[(x_int + 1) * 129 + y_int ]; + float h4 = m_V9[(x_int + 1) * 129 + y_int + 1]; + float h5 = 2 * m_V8[x_int * 128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; @@ -1553,9 +1555,9 @@ float GridMap::getHeightFromFloat(float x, float y) const else { // 4 triangle (h3, h4, h5 points) - float h3 = m_V9[(x_int)*129 + y_int+1]; - float h4 = m_V9[(x_int+1)*129 + y_int+1]; - float h5 = 2 * m_V8[x_int*128 + y_int]; + float h3 = m_V9[(x_int) * 129 + y_int + 1]; + float h4 = m_V9[(x_int + 1) * 129 + y_int + 1]; + float h5 = 2 * m_V8[x_int * 128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; @@ -1570,28 +1572,28 @@ float GridMap::getHeightFromUint8(float x, float y) const if (!m_uint8_V8 || !m_uint8_V9) return _gridHeight; - x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); - y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); + x = MAP_RESOLUTION * (32 - x / SIZE_OF_GRIDS); + y = MAP_RESOLUTION * (32 - y / SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; - x_int&=(MAP_RESOLUTION - 1); - y_int&=(MAP_RESOLUTION - 1); + x_int &= (MAP_RESOLUTION - 1); + y_int &= (MAP_RESOLUTION - 1); int32 a, b, c; - uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int]; - if (x+y < 1) + uint8* V9_h1_ptr = &m_uint8_V9[x_int * 128 + x_int + y_int]; + if (x + y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) int32 h1 = V9_h1_ptr[ 0]; int32 h2 = V9_h1_ptr[129]; - int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; - a = h2-h1; - b = h5-h1-h2; + int32 h5 = 2 * m_uint8_V8[x_int * 128 + y_int]; + a = h2 - h1; + b = h5 - h1 - h2; c = h1; } else @@ -1599,7 +1601,7 @@ float GridMap::getHeightFromUint8(float x, float y) const // 2 triangle (h1, h3, h5 points) int32 h1 = V9_h1_ptr[0]; int32 h3 = V9_h1_ptr[1]; - int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; + int32 h5 = 2 * m_uint8_V8[x_int * 128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; @@ -1612,7 +1614,7 @@ float GridMap::getHeightFromUint8(float x, float y) const // 3 triangle (h2, h4, h5 points) int32 h2 = V9_h1_ptr[129]; int32 h4 = V9_h1_ptr[130]; - int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; + int32 h5 = 2 * m_uint8_V8[x_int * 128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; @@ -1622,14 +1624,14 @@ float GridMap::getHeightFromUint8(float x, float y) const // 4 triangle (h3, h4, h5 points) int32 h3 = V9_h1_ptr[ 1]; int32 h4 = V9_h1_ptr[130]; - int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; + int32 h5 = 2 * m_uint8_V8[x_int * 128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height - return (float)((a * x) + (b * y) + c)*_gridIntHeightMultiplier + _gridHeight; + return (float)((a * x) + (b * y) + c) * _gridIntHeightMultiplier + _gridHeight; } float GridMap::getHeightFromUint16(float x, float y) const @@ -1637,28 +1639,28 @@ float GridMap::getHeightFromUint16(float x, float y) const if (!m_uint16_V8 || !m_uint16_V9) return _gridHeight; - x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); - y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); + x = MAP_RESOLUTION * (32 - x / SIZE_OF_GRIDS); + y = MAP_RESOLUTION * (32 - y / SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; - x_int&=(MAP_RESOLUTION - 1); - y_int&=(MAP_RESOLUTION - 1); + x_int &= (MAP_RESOLUTION - 1); + y_int &= (MAP_RESOLUTION - 1); int32 a, b, c; - uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int]; - if (x+y < 1) + uint16* V9_h1_ptr = &m_uint16_V9[x_int * 128 + x_int + y_int]; + if (x + y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) int32 h1 = V9_h1_ptr[ 0]; int32 h2 = V9_h1_ptr[129]; - int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; - a = h2-h1; - b = h5-h1-h2; + int32 h5 = 2 * m_uint16_V8[x_int * 128 + y_int]; + a = h2 - h1; + b = h5 - h1 - h2; c = h1; } else @@ -1666,7 +1668,7 @@ float GridMap::getHeightFromUint16(float x, float y) const // 2 triangle (h1, h3, h5 points) int32 h1 = V9_h1_ptr[0]; int32 h3 = V9_h1_ptr[1]; - int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; + int32 h5 = 2 * m_uint16_V8[x_int * 128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; @@ -1679,7 +1681,7 @@ float GridMap::getHeightFromUint16(float x, float y) const // 3 triangle (h2, h4, h5 points) int32 h2 = V9_h1_ptr[129]; int32 h4 = V9_h1_ptr[130]; - int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; + int32 h5 = 2 * m_uint16_V8[x_int * 128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; @@ -1689,14 +1691,14 @@ float GridMap::getHeightFromUint16(float x, float y) const // 4 triangle (h3, h4, h5 points) int32 h3 = V9_h1_ptr[ 1]; int32 h4 = V9_h1_ptr[130]; - int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; + int32 h5 = 2 * m_uint16_V8[x_int * 128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height - return (float)((a * x) + (b * y) + c)*_gridIntHeightMultiplier + _gridHeight; + return (float)((a * x) + (b * y) + c) * _gridIntHeightMultiplier + _gridHeight; } float GridMap::getMinHeight(float x, float y) const @@ -1753,10 +1755,10 @@ float GridMap::getMinHeight(float x, float y) const quarterIndex *= 3; return G3D::Plane( - G3D::Vector3(boundGridCoords[indices[quarterIndex + 0] * 2 + 0], boundGridCoords[indices[quarterIndex + 0] * 2 + 1], _minHeight[indices[quarterIndex + 0]]), - G3D::Vector3(boundGridCoords[indices[quarterIndex + 1] * 2 + 0], boundGridCoords[indices[quarterIndex + 1] * 2 + 1], _minHeight[indices[quarterIndex + 1]]), - G3D::Vector3(boundGridCoords[indices[quarterIndex + 2] * 2 + 0], boundGridCoords[indices[quarterIndex + 2] * 2 + 1], _minHeight[indices[quarterIndex + 2]]) - ).distance(G3D::Vector3(gx, gy, 0.0f)); + G3D::Vector3(boundGridCoords[indices[quarterIndex + 0] * 2 + 0], boundGridCoords[indices[quarterIndex + 0] * 2 + 1], _minHeight[indices[quarterIndex + 0]]), + G3D::Vector3(boundGridCoords[indices[quarterIndex + 1] * 2 + 0], boundGridCoords[indices[quarterIndex + 1] * 2 + 1], _minHeight[indices[quarterIndex + 1]]), + G3D::Vector3(boundGridCoords[indices[quarterIndex + 2] * 2 + 0], boundGridCoords[indices[quarterIndex + 2] * 2 + 1], _minHeight[indices[quarterIndex + 2]]) + ).distance(G3D::Vector3(gx, gy, 0.0f)); } float GridMap::getLiquidLevel(float x, float y) const @@ -1764,18 +1766,18 @@ float GridMap::getLiquidLevel(float x, float y) const if (!_liquidMap) return _liquidLevel; - x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); - y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); + x = MAP_RESOLUTION * (32 - x / SIZE_OF_GRIDS); + y = MAP_RESOLUTION * (32 - y / SIZE_OF_GRIDS); - int cx_int = ((int)x & (MAP_RESOLUTION-1)) - _liquidOffY; - int cy_int = ((int)y & (MAP_RESOLUTION-1)) - _liquidOffX; + int cx_int = ((int)x & (MAP_RESOLUTION - 1)) - _liquidOffY; + int cy_int = ((int)y & (MAP_RESOLUTION - 1)) - _liquidOffX; - if (cx_int < 0 || cx_int >=_liquidHeight) + if (cx_int < 0 || cx_int >= _liquidHeight) return INVALID_HEIGHT; - if (cy_int < 0 || cy_int >=_liquidWidth) + if (cy_int < 0 || cy_int >= _liquidWidth) return INVALID_HEIGHT; - return _liquidMap[cx_int*_liquidWidth + cy_int]; + return _liquidMap[cx_int * _liquidWidth + cy_int]; } // Why does this return LIQUID data? @@ -1784,11 +1786,11 @@ uint8 GridMap::getTerrainType(float x, float y) const if (!_liquidFlags) return 0; - x = 16 * (32 - x/SIZE_OF_GRIDS); - y = 16 * (32 - y/SIZE_OF_GRIDS); + x = 16 * (32 - x / SIZE_OF_GRIDS); + y = 16 * (32 - y / SIZE_OF_GRIDS); int lx = (int)x & 15; int ly = (int)y & 15; - return _liquidFlags[lx*16 + ly]; + return _liquidFlags[lx * 16 + ly]; } // Get water state on map @@ -1799,14 +1801,14 @@ inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 R return LIQUID_MAP_NO_WATER; // Get cell - float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); - float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); + float cx = MAP_RESOLUTION * (32 - x / SIZE_OF_GRIDS); + float cy = MAP_RESOLUTION * (32 - y / SIZE_OF_GRIDS); - int x_int = (int)cx & (MAP_RESOLUTION-1); - int y_int = (int)cy & (MAP_RESOLUTION-1); + int x_int = (int)cx & (MAP_RESOLUTION - 1); + int y_int = (int)cy & (MAP_RESOLUTION - 1); // Check water type in cell - int idx=(x_int>>3)*16 + (y_int>>3); + int idx = (x_int >> 3) * 16 + (y_int >> 3); uint8 type = _liquidFlags ? _liquidFlags[idx] : _liquidType; uint32 entry = 0; if (_liquidEntry) @@ -1844,20 +1846,20 @@ inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 R return LIQUID_MAP_NO_WATER; // Check req liquid type mask - if (ReqLiquidType && !(ReqLiquidType&type)) + if (ReqLiquidType && !(ReqLiquidType & type)) return LIQUID_MAP_NO_WATER; // Check water level: // Check water height map int lx_int = x_int - _liquidOffY; int ly_int = y_int - _liquidOffX; - if (lx_int < 0 || lx_int >=_liquidHeight) + if (lx_int < 0 || lx_int >= _liquidHeight) return LIQUID_MAP_NO_WATER; - if (ly_int < 0 || ly_int >=_liquidWidth) + if (ly_int < 0 || ly_int >= _liquidWidth) return LIQUID_MAP_NO_WATER; // Get water level - float liquid_level = _liquidMap ? _liquidMap[lx_int*_liquidWidth + ly_int] : _liquidLevel; + float liquid_level = _liquidMap ? _liquidMap[lx_int * _liquidWidth + ly_int] : _liquidLevel; // Get ground level (sub 0.2 for fix some errors) float ground_level = getHeight(x, y); @@ -1883,24 +1885,24 @@ inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 R return LIQUID_MAP_IN_WATER; if (delta > -0.1f) // Walk on water return LIQUID_MAP_WATER_WALK; - // Above water + // Above water return LIQUID_MAP_ABOVE_WATER; } GridMap* Map::GetGrid(float x, float y) -{ +{ // half opt method - int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x - int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y + int gx = (int)(32 - x / SIZE_OF_GRIDS); //grid x + int gy = (int)(32 - y / SIZE_OF_GRIDS); //grid y // ensure GridMap is loaded - EnsureGridCreated(GridCoord(63-gx, 63-gy)); + EnsureGridCreated(GridCoord(63 - gx, 63 - gy)); return GridMaps[gx][gy]; } float Map::GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground /*= NULL*/, bool /*swim = false*/, float maxSearchDist /*= 50.0f*/) const -{ +{ if (const_cast(this)->GetGrid(x, y)) { // we need ground level (including grid height version) for proper return water level in point @@ -1922,7 +1924,7 @@ Transport* Map::GetTransportForPos(uint32 phase, float x, float y, float z, Worl G3D::Vector3 v(x, y, z + 2.0f); G3D::Ray r(v, G3D::Vector3(0, 0, -1)); for (TransportsContainer::const_iterator itr = _transports.begin(); itr != _transports.end(); ++itr) - if ((*itr)->IsInWorld() && (*itr)->GetExactDistSq(x, y, z) < 75.0f*75.0f && (*itr)->m_model) + if ((*itr)->IsInWorld() && (*itr)->GetExactDistSq(x, y, z) < 75.0f * 75.0f && (*itr)->m_model) { float dist = 30.0f; bool hit = (*itr)->m_model->intersectRay(r, dist, false, phase); @@ -1945,7 +1947,7 @@ Transport* Map::GetTransportForPos(uint32 phase, float x, float y, float z, Worl } float Map::GetHeight(float x, float y, float z, bool checkVMap /*= true*/, float maxSearchDist /*= DEFAULT_HEIGHT_SEARCH*/) const -{ +{ // find raw .map surface under Z coordinates float mapHeight = VMAP_INVALID_HEIGHT_VALUE; if (GridMap* gmap = const_cast(this)->GetGrid(x, y)) @@ -1961,7 +1963,7 @@ float Map::GetHeight(float x, float y, float z, bool checkVMap /*= true*/, float { VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); //if (vmgr->isHeightCalcEnabled()) // pussywizard: optimization - vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f, maxSearchDist); // look from a bit higher pos to find the floor + vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f, maxSearchDist); // look from a bit higher pos to find the floor } // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT @@ -1974,7 +1976,7 @@ float Map::GetHeight(float x, float y, float z, bool checkVMap /*= true*/, float // we are already under the surface or vmap height above map heigt // or if the distance of the vmap height is less the land height distance - if (vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z)) + if (vmapHeight > mapHeight || fabs(mapHeight - z) > fabs(vmapHeight - z)) return vmapHeight; else return mapHeight; // better use .map surface height @@ -2007,20 +2009,20 @@ inline bool IsOutdoorWMO(uint32 mogpFlags, int32 /*adtId*/, int32 /*rootId*/, in return false; } - outdoor = mogpFlags&0x8; + outdoor = mogpFlags & 0x8; if (wmoEntry) { if (wmoEntry->Flags & 4) return true; - if ((wmoEntry->Flags & 2)!=0) + if ((wmoEntry->Flags & 2) != 0) outdoor = false; } return outdoor; } bool Map::IsOutdoors(float x, float y, float z) const -{ +{ uint32 mogpFlags; int32 adtId, rootId, groupId; @@ -2029,7 +2031,7 @@ bool Map::IsOutdoors(float x, float y, float z) const return true; AreaTableEntry const* atEntry = 0; - WMOAreaTableEntry const* wmoEntry= GetWMOAreaTableEntryByTripple(rootId, adtId, groupId); + WMOAreaTableEntry const* wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId); if (wmoEntry) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) @@ -2040,8 +2042,8 @@ bool Map::IsOutdoors(float x, float y, float z) const return IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry); } -bool Map::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const -{ +bool Map::GetAreaInfo(float x, float y, float z, uint32& flags, int32& adtId, int32& rootId, int32& groupId) const +{ float vmap_z = z; VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); if (vmgr->getAreaInfo(GetId(), x, y, vmap_z, flags, adtId, rootId, groupId)) @@ -2059,8 +2061,8 @@ bool Map::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, in return false; } -uint32 Map::GetAreaId(float x, float y, float z, bool *isOutdoors) const -{ +uint32 Map::GetAreaId(float x, float y, float z, bool* isOutdoors) const +{ uint32 mogpFlags; int32 adtId, rootId, groupId; WMOAreaTableEntry const* wmoEntry = 0; @@ -2122,7 +2124,7 @@ void Map::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, flo } uint8 Map::GetTerrainType(float x, float y) const -{ +{ if (GridMap* gmap = const_cast(this)->GetGrid(x, y)) return gmap->getTerrainType(x, y); else @@ -2130,7 +2132,7 @@ uint8 Map::GetTerrainType(float x, float y) const } ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data) const -{ +{ ZLiquidStatus result = LIQUID_MAP_NO_WATER; VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); float liquid_level = INVALID_HEIGHT; @@ -2217,7 +2219,7 @@ ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidTyp } float Map::GetWaterLevel(float x, float y) const -{ +{ if (GridMap* gmap = const_cast(this)->GetGrid(x, y)) return gmap->getLiquidLevel(x, y); else @@ -2228,15 +2230,15 @@ bool Map::isInLineOfSight(float x1, float y1, float z1, float x2, float y2, floa { if ((checks & LINEOFSIGHT_CHECK_VMAP) && !VMAP::VMapFactory::createOrGetVMapManager()->isInLineOfSight(GetId(), x1, y1, z1, x2, y2, z2)) return false; - + if (sWorld->getBoolConfig(CONFIG_CHECK_GOBJECT_LOS) && (checks & LINEOFSIGHT_CHECK_GOBJECT) - && !_dynamicTree.isInLineOfSight(x1, y1, z1, x2, y2, z2, phasemask)) + && !_dynamicTree.isInLineOfSight(x1, y1, z1, x2, y2, z2, phasemask)) return false; return true; } bool Map::getObjectHitPos(uint32 phasemask, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float& ry, float& rz, float modifyDist) -{ +{ G3D::Vector3 startPos(x1, y1, z1); G3D::Vector3 dstPos(x2, y2, z2); @@ -2250,7 +2252,7 @@ bool Map::getObjectHitPos(uint32 phasemask, float x1, float y1, float z1, float } float Map::GetHeight(uint32 phasemask, float x, float y, float z, bool vmap/*=true*/, float maxSearchDist/*=DEFAULT_HEIGHT_SEARCH*/) const -{ +{ float h1, h2; h1 = GetHeight(x, y, z, vmap, maxSearchDist); h2 = _dynamicTree.getHeight(x, y, z, maxSearchDist, phasemask); @@ -2258,24 +2260,24 @@ float Map::GetHeight(uint32 phasemask, float x, float y, float z, bool vmap/*=tr } bool Map::IsInWater(float x, float y, float pZ, LiquidData* data) const -{ +{ LiquidData liquid_status; LiquidData* liquid_ptr = data ? data : &liquid_status; return getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr) & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER); } bool Map::IsUnderWater(float x, float y, float z) const -{ - return getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN) & LIQUID_MAP_UNDER_WATER; +{ + return getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN) & LIQUID_MAP_UNDER_WATER; } char const* Map::GetMapName() const -{ +{ return i_mapEntry ? i_mapEntry->name[sWorld->GetDefaultDbcLocale()] : "UNNAMEDMAP\x0"; } void Map::SendInitSelf(Player* player) -{ +{ #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("Creating player data for himself %u", player->GetGUIDLow()); #endif @@ -2301,7 +2303,7 @@ void Map::SendInitSelf(Player* player) } void Map::SendInitTransports(Player* player) -{ +{ // Hack to send out transports UpdateData transData; for (TransportsContainer::const_iterator itr = _transports.begin(); itr != _transports.end(); ++itr) @@ -2314,7 +2316,7 @@ void Map::SendInitTransports(Player* player) } void Map::SendRemoveTransports(Player* player) -{ +{ // Hack to send out transports UpdateData transData; for (TransportsContainer::const_iterator itr = _transports.begin(); itr != _transports.end(); ++itr) @@ -2322,7 +2324,7 @@ void Map::SendRemoveTransports(Player* player) (*itr)->BuildOutOfRangeUpdateBlock(&transData); // pussywizard: remove static transports from client - for (Player::ClientGUIDs::const_iterator it = player->m_clientGUIDs.begin();it != player->m_clientGUIDs.end(); ) + for (Player::ClientGUIDs::const_iterator it = player->m_clientGUIDs.begin(); it != player->m_clientGUIDs.end(); ) { if (IS_TRANSPORT_GUID(*it)) { @@ -2338,8 +2340,8 @@ void Map::SendRemoveTransports(Player* player) player->GetSession()->SendPacket(&packet); } -inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y) -{ +inline void Map::setNGrid(NGridType* grid, uint32 x, uint32 y) +{ if (x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS) { sLog->outError("map::setNGrid() Invalid grid coordinates found: %d, %d!", x, y); @@ -2349,7 +2351,7 @@ inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y) } void Map::DelayedUpdate(const uint32 t_diff) -{ +{ for (_transportsUpdateIter = _transports.begin(); _transportsUpdateIter != _transports.end();) { MotionTransport* transport = *_transportsUpdateIter; @@ -2365,7 +2367,7 @@ void Map::DelayedUpdate(const uint32 t_diff) } void Map::AddObjectToRemoveList(WorldObject* obj) -{ +{ ASSERT(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId()); obj->CleanupsBeforeDelete(false); // remove or simplify at least cross referenced links @@ -2375,7 +2377,7 @@ void Map::AddObjectToRemoveList(WorldObject* obj) } void Map::AddObjectToSwitchList(WorldObject* obj, bool on) -{ +{ ASSERT(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId()); // i_objectsToSwitch is iterated only in Map::RemoveAllObjectsInRemoveList() and it uses // the contained objects only if GetTypeId() == TYPEID_UNIT , so we can return in all other cases @@ -2392,7 +2394,7 @@ void Map::AddObjectToSwitchList(WorldObject* obj, bool on) } void Map::RemoveAllObjectsInRemoveList() -{ +{ while (!i_objectsToSwitch.empty()) { std::map::iterator itr = i_objectsToSwitch.begin(); @@ -2426,14 +2428,14 @@ void Map::RemoveAllObjectsInRemoveList() switch (obj->GetTypeId()) { case TYPEID_CORPSE: - { - Corpse* corpse = ObjectAccessor::GetCorpse(*obj, obj->GetGUID()); - if (!corpse) - sLog->outError("Tried to delete corpse/bones %u that is not in map.", obj->GetGUIDLow()); - else - RemoveFromMap(corpse, true); - break; - } + { + Corpse* corpse = ObjectAccessor::GetCorpse(*obj, obj->GetGUID()); + if (!corpse) + sLog->outError("Tried to delete corpse/bones %u that is not in map.", obj->GetGUIDLow()); + else + RemoveFromMap(corpse, true); + break; + } case TYPEID_DYNAMICOBJECT: RemoveFromMap((DynamicObject*)obj, true); break; @@ -2468,56 +2470,56 @@ uint32 Map::GetPlayersCountExceptGMs() const } void Map::SendToPlayers(WorldPacket const* data) const -{ +{ for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) itr->GetSource()->GetSession()->SendPacket(data); } template void Map::AddToActive(T* obj) -{ +{ AddToActiveHelper(obj); } template <> void Map::AddToActive(Creature* c) -{ +{ AddToActiveHelper(c); } template<> void Map::AddToActive(DynamicObject* d) -{ +{ AddToActiveHelper(d); } template<> void Map::AddToActive(GameObject* d) -{ +{ AddToActiveHelper(d); } template void Map::RemoveFromActive(T* obj) -{ +{ RemoveFromActiveHelper(obj); } template <> void Map::RemoveFromActive(Creature* c) -{ +{ RemoveFromActiveHelper(c); } template<> void Map::RemoveFromActive(DynamicObject* obj) -{ +{ RemoveFromActiveHelper(obj); } template<> void Map::RemoveFromActive(GameObject* obj) -{ +{ RemoveFromActiveHelper(obj); } @@ -2534,9 +2536,9 @@ template void Map::RemoveFromMap(DynamicObject*, bool); /* ******* Dungeon Instance Maps ******* */ InstanceMap::InstanceMap(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent) - : Map(id, InstanceId, SpawnMode, _parent), - m_resetAfterUnload(false), m_unloadWhenEmpty(false), - instance_script(nullptr), i_script_id(0) + : Map(id, InstanceId, SpawnMode, _parent), + m_resetAfterUnload(false), m_unloadWhenEmpty(false), + instance_script(nullptr), i_script_id(0) { //lets initialize visibility distance for dungeons InstanceMap::InitVisibilityDistance(); @@ -2560,7 +2562,7 @@ InstanceMap::~InstanceMap() } void InstanceMap::InitVisibilityDistance() -{ +{ //init visibility distance for instances m_VisibleDistance = World::GetMaxVisibleDistanceInInstances(); @@ -2607,7 +2609,7 @@ bool InstanceMap::CanEnter(Player* player, bool loginCheck) // cannot enter if the instance is full (player cap), GMs don't count uint32 maxPlayers = GetMaxPlayers(); - if (GetPlayersCountExceptGMs() >= (loginCheck ? maxPlayers+1 : maxPlayers)) + if (GetPlayersCountExceptGMs() >= (loginCheck ? maxPlayers + 1 : maxPlayers)) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName().c_str()); @@ -2634,7 +2636,7 @@ bool InstanceMap::CanEnter(Player* player, bool loginCheck) } // cannot enter if instance is in use by another party/soloer that have a permanent save in the same instance id - PlayerList const &playerList = GetPlayers(); + PlayerList const& playerList = GetPlayers(); if (!playerList.isEmpty()) for (PlayerList::const_iterator i = playerList.begin(); i != playerList.end(); ++i) if (Player* iPlayer = i->GetSource()) @@ -2664,7 +2666,7 @@ bool InstanceMap::CanEnter(Player* player, bool loginCheck) Do map specific checks and add the player to the map if successful. */ bool InstanceMap::AddPlayerToMap(Player* player) -{ +{ if (m_resetAfterUnload) // this instance has been reset, it's not meant to be used anymore return false; @@ -2743,7 +2745,7 @@ void InstanceMap::Update(const uint32 t_diff, const uint32 s_diff, bool /*thread } void InstanceMap::RemovePlayerFromMap(Player* player, bool remove) -{ +{ // pussywizard: moved m_unloadTimer to InstanceMap::AfterPlayerUnlinkFromMap(), in this function if 2 players run out at the same time the instance won't close //if (!m_unloadTimer && m_mapRefManager.getSize() == 1) // m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld->getIntConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY); @@ -2758,7 +2760,7 @@ void InstanceMap::AfterPlayerUnlinkFromMap() } void InstanceMap::CreateInstanceScript(bool load, std::string data, uint32 completedEncounterMask) -{ +{ if (instance_script != nullptr) return; #ifdef ELUNA @@ -2845,7 +2847,7 @@ bool InstanceMap::Reset(uint8 method, std::list* globalResetSkipList) } void InstanceMap::PermBindAllPlayers() -{ +{ if (!IsDungeon()) return; @@ -2883,7 +2885,7 @@ void InstanceMap::PermBindAllPlayers() } void InstanceMap::UnloadAll() -{ +{ ASSERT(!HavePlayers()); if (m_resetAfterUnload == true) @@ -2893,7 +2895,7 @@ void InstanceMap::UnloadAll() } void InstanceMap::SendResetWarnings(uint32 timeLeft) const -{ +{ for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) itr->GetSource()->SendInstanceResetWarning(GetId(), itr->GetSource()->GetDifficulty(IsRaid()), timeLeft, false); } @@ -2913,7 +2915,7 @@ uint32 InstanceMap::GetMaxPlayers() const } uint32 InstanceMap::GetMaxResetDelay() const -{ +{ MapDifficulty const* mapDiff = GetMapDifficulty(); return mapDiff ? mapDiff->resetTime : 0; } @@ -2921,7 +2923,7 @@ uint32 InstanceMap::GetMaxResetDelay() const /* ******* Battleground Instance Maps ******* */ BattlegroundMap::BattlegroundMap(uint32 id, uint32 InstanceId, Map* _parent, uint8 spawnMode) - : Map(id, InstanceId, spawnMode, _parent), m_bg(nullptr) + : Map(id, InstanceId, spawnMode, _parent), m_bg(nullptr) { //lets initialize visibility distance for BG/Arenas BattlegroundMap::InitVisibilityDistance(); @@ -2938,7 +2940,7 @@ BattlegroundMap::~BattlegroundMap() } void BattlegroundMap::InitVisibilityDistance() -{ +{ //init visibility distance for BG/Arenas m_VisibleDistance = World::GetMaxVisibleDistanceInBGArenas(); @@ -2964,7 +2966,7 @@ bool BattlegroundMap::CanEnter(Player* player, bool loginCheck) } bool BattlegroundMap::AddPlayerToMap(Player* player) -{ +{ player->m_InstanceValid = true; if (IsBattleArena()) player->CastSpell(player, 100102, true); @@ -2985,12 +2987,12 @@ void BattlegroundMap::RemovePlayerFromMap(Player* player, bool remove) } void BattlegroundMap::SetUnload() -{ +{ m_unloadTimer = MIN_UNLOAD_DELAY; } void BattlegroundMap::RemoveAllPlayers() -{ +{ if (HavePlayers()) for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) if (Player* player = itr->GetSource()) @@ -2999,22 +3001,22 @@ void BattlegroundMap::RemoveAllPlayers() } Player* Map::GetPlayer(uint64 guid) -{ +{ return ObjectAccessor::GetObjectInMap(guid, this, (Player*)NULL); } Creature* Map::GetCreature(uint64 guid) -{ +{ return ObjectAccessor::GetObjectInMap(guid, this, (Creature*)NULL); } GameObject* Map::GetGameObject(uint64 guid) -{ +{ return ObjectAccessor::GetObjectInMap(guid, this, (GameObject*)NULL); } Transport* Map::GetTransport(uint64 guid) -{ +{ if (GUID_HIPART(guid) != HIGHGUID_MO_TRANSPORT && GUID_HIPART(guid) != HIGHGUID_TRANSPORT) return nullptr; @@ -3023,28 +3025,28 @@ Transport* Map::GetTransport(uint64 guid) } DynamicObject* Map::GetDynamicObject(uint64 guid) -{ +{ return ObjectAccessor::GetObjectInMap(guid, this, (DynamicObject*)NULL); } Pet* Map::GetPet(uint64 guid) -{ +{ return ObjectAccessor::GetObjectInMap(guid, this, (Pet*)NULL); } Corpse* Map::GetCorpse(uint64 guid) -{ +{ return ObjectAccessor::GetObjectInMap(guid, this, (Corpse*)NULL); } void Map::UpdateIteratorBack(Player* player) -{ +{ if (m_mapRefIter == player->GetMapRef()) m_mapRefIter = m_mapRefIter->nocheck_prev(); } void Map::SaveCreatureRespawnTime(uint32 dbGuid, time_t& respawnTime) -{ +{ if (!respawnTime) { // Delete only @@ -3053,8 +3055,8 @@ void Map::SaveCreatureRespawnTime(uint32 dbGuid, time_t& respawnTime) } time_t now = time(nullptr); - if (GetInstanceResetPeriod() > 0 && respawnTime-now+5 >= GetInstanceResetPeriod()) - respawnTime = now+YEAR; + if (GetInstanceResetPeriod() > 0 && respawnTime - now + 5 >= GetInstanceResetPeriod()) + respawnTime = now + YEAR; _creatureRespawnTimes[dbGuid] = respawnTime; @@ -3067,7 +3069,7 @@ void Map::SaveCreatureRespawnTime(uint32 dbGuid, time_t& respawnTime) } void Map::RemoveCreatureRespawnTime(uint32 dbGuid) -{ +{ _creatureRespawnTimes.erase(dbGuid); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN); @@ -3078,7 +3080,7 @@ void Map::RemoveCreatureRespawnTime(uint32 dbGuid) } void Map::SaveGORespawnTime(uint32 dbGuid, time_t& respawnTime) -{ +{ if (!respawnTime) { // Delete only @@ -3087,8 +3089,8 @@ void Map::SaveGORespawnTime(uint32 dbGuid, time_t& respawnTime) } time_t now = time(nullptr); - if (GetInstanceResetPeriod() > 0 && respawnTime-now+5 >= GetInstanceResetPeriod()) - respawnTime = now+YEAR; + if (GetInstanceResetPeriod() > 0 && respawnTime - now + 5 >= GetInstanceResetPeriod()) + respawnTime = now + YEAR; _goRespawnTimes[dbGuid] = respawnTime; @@ -3101,7 +3103,7 @@ void Map::SaveGORespawnTime(uint32 dbGuid, time_t& respawnTime) } void Map::RemoveGORespawnTime(uint32 dbGuid) -{ +{ _goRespawnTimes.erase(dbGuid); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GO_RESPAWN); @@ -3112,7 +3114,7 @@ void Map::RemoveGORespawnTime(uint32 dbGuid) } void Map::LoadRespawnTimes() -{ +{ PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CREATURE_RESPAWNS); stmt->setUInt16(0, GetId()); stmt->setUInt32(1, GetInstanceId()); @@ -3145,7 +3147,7 @@ void Map::LoadRespawnTimes() } void Map::DeleteRespawnTimes() -{ +{ _creatureRespawnTimes.clear(); _goRespawnTimes.clear(); @@ -3166,8 +3168,8 @@ void Map::DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId) } void Map::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source) -{ - Difficulty difficulty_fixed = (IsSharedDifficultyMap(GetId()) ? Difficulty(GetDifficulty()%2) : GetDifficulty()); +{ + Difficulty difficulty_fixed = (IsSharedDifficultyMap(GetId()) ? Difficulty(GetDifficulty() % 2) : GetDifficulty()); DungeonEncounterList const* encounters = sObjectMgr->GetDungeonEncounterList(GetId(), difficulty_fixed); if (!encounters) return; @@ -3181,9 +3183,10 @@ void Map::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Uni if (encounter->creditType == type && encounter->creditEntry == creditEntry) { if (source) - if (InstanceScript* instanceScript = source->GetInstanceScript()) { + if (InstanceScript* instanceScript = source->GetInstanceScript()) + { uint32 prevMask = instanceScript->GetCompletedEncounterMask(); - instanceScript->SetCompletedEncountersMask((1 << encounter->dbcEntry->encounterIndex)|instanceScript->GetCompletedEncounterMask(), true); + instanceScript->SetCompletedEncountersMask((1 << encounter->dbcEntry->encounterIndex) | instanceScript->GetCompletedEncounterMask(), true); if (prevMask != instanceScript->GetCompletedEncounterMask()) updated = true; } @@ -3198,7 +3201,7 @@ void Map::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Uni // pussywizard: LogEncounterFinished(type, creditEntry); - + sScriptMgr->OnAfterUpdateEncounterState(this, type, creditEntry, source, difficulty_fixed, encounters, dungeonId, updated); if (dungeonId) @@ -3278,7 +3281,7 @@ time_t Map::GetLinkedRespawnTime(uint64 guid) const } void Map::SendZoneDynamicInfo(Player* player) -{ +{ uint32 zoneId = GetZoneId(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); ZoneDynamicInfoMap::const_iterator itr = _zoneDynamicInfo.find(zoneId); if (itr == _zoneDynamicInfo.end()) @@ -3326,7 +3329,7 @@ void Map::PlayDirectSoundToMap(uint32 soundId, uint32 zoneId) } void Map::SetZoneMusic(uint32 zoneId, uint32 musicId) -{ +{ if (_zoneDynamicInfo.find(zoneId) == _zoneDynamicInfo.end()) _zoneDynamicInfo.insert(ZoneDynamicInfoMap::value_type(zoneId, ZoneDynamicInfo())); @@ -3346,7 +3349,7 @@ void Map::SetZoneMusic(uint32 zoneId, uint32 musicId) } void Map::SetZoneWeather(uint32 zoneId, uint32 weatherId, float weatherGrade) -{ +{ if (_zoneDynamicInfo.find(zoneId) == _zoneDynamicInfo.end()) _zoneDynamicInfo.insert(ZoneDynamicInfoMap::value_type(zoneId, ZoneDynamicInfo())); @@ -3370,7 +3373,7 @@ void Map::SetZoneWeather(uint32 zoneId, uint32 weatherId, float weatherGrade) } void Map::SetZoneOverrideLight(uint32 zoneId, uint32 lightId, uint32 fadeInTime) -{ +{ if (_zoneDynamicInfo.find(zoneId) == _zoneDynamicInfo.end()) _zoneDynamicInfo.insert(ZoneDynamicInfoMap::value_type(zoneId, ZoneDynamicInfo())); diff --git a/src/server/game/Maps/Map.h b/src/server/game/Maps/Map.h index 682bbcce8..30a5982d9 100644 --- a/src/server/game/Maps/Map.h +++ b/src/server/game/Maps/Map.h @@ -156,12 +156,14 @@ enum LineOfSightChecks class GridMap { uint32 _flags; - union{ + union + { float* m_V9; uint16* m_uint16_V9; uint8* m_uint8_V9; }; - union{ + union + { float* m_V8; uint16* m_uint16_V8; uint8* m_uint8_V8; @@ -232,7 +234,7 @@ enum LevelRequirementVsMode { LEVELREQUIREMENT_HEROIC = 70 }; - + struct ZoneDynamicInfo { ZoneDynamicInfo() : MusicId(0), WeatherId(0), WeatherGrade(0.0f), @@ -270,394 +272,394 @@ enum EncounterCreditType class Map : public GridRefManager { friend class MapReference; - public: - Map(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent = nullptr); - virtual ~Map(); +public: + Map(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent = nullptr); + virtual ~Map(); - MapEntry const* GetEntry() const { return i_mapEntry; } + MapEntry const* GetEntry() const { return i_mapEntry; } - // currently unused for normal maps - bool CanUnload(uint32 diff) - { - if (!m_unloadTimer) - return false; - - if (m_unloadTimer <= diff) - return true; - - m_unloadTimer -= diff; + // currently unused for normal maps + bool CanUnload(uint32 diff) + { + if (!m_unloadTimer) return false; - } - virtual bool AddPlayerToMap(Player*); - virtual void RemovePlayerFromMap(Player*, bool); - virtual void AfterPlayerUnlinkFromMap(); - template bool AddToMap(T *, bool checkTransport = false); - template void RemoveFromMap(T *, bool); + if (m_unloadTimer <= diff) + return true; - void VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor &gridVisitor, - TypeContainerVisitor &worldVisitor, - TypeContainerVisitor &largeGridVisitor, - TypeContainerVisitor &largeWorldVisitor); - void VisitNearbyCellsOfPlayer(Player* player, TypeContainerVisitor &gridVisitor, - TypeContainerVisitor &worldVisitor, - TypeContainerVisitor &largeGridVisitor, - TypeContainerVisitor &largeWorldVisitor); - - virtual void Update(const uint32, const uint32, bool thread = true); + m_unloadTimer -= diff; + return false; + } - float GetVisibilityRange() const { return m_VisibleDistance; } - void SetVisibilityRange(float range) { m_VisibleDistance = range; } - //function for setting up visibility distance for maps on per-type/per-Id basis - virtual void InitVisibilityDistance(); + virtual bool AddPlayerToMap(Player*); + virtual void RemovePlayerFromMap(Player*, bool); + virtual void AfterPlayerUnlinkFromMap(); + template bool AddToMap(T*, bool checkTransport = false); + template void RemoveFromMap(T*, bool); - void PlayerRelocation(Player*, float x, float y, float z, float o); - void CreatureRelocation(Creature* creature, float x, float y, float z, float o); - void GameObjectRelocation(GameObject* go, float x, float y, float z, float o); - void DynamicObjectRelocation(DynamicObject* go, float x, float y, float z, float o); + void VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor& gridVisitor, + TypeContainerVisitor& worldVisitor, + TypeContainerVisitor& largeGridVisitor, + TypeContainerVisitor& largeWorldVisitor); + void VisitNearbyCellsOfPlayer(Player* player, TypeContainerVisitor& gridVisitor, + TypeContainerVisitor& worldVisitor, + TypeContainerVisitor& largeGridVisitor, + TypeContainerVisitor& largeWorldVisitor); - template void Visit(const Cell& cell, TypeContainerVisitor &visitor); + virtual void Update(const uint32, const uint32, bool thread = true); - bool IsRemovalGrid(float x, float y) const + float GetVisibilityRange() const { return m_VisibleDistance; } + void SetVisibilityRange(float range) { m_VisibleDistance = range; } + //function for setting up visibility distance for maps on per-type/per-Id basis + virtual void InitVisibilityDistance(); + + void PlayerRelocation(Player*, float x, float y, float z, float o); + void CreatureRelocation(Creature* creature, float x, float y, float z, float o); + void GameObjectRelocation(GameObject* go, float x, float y, float z, float o); + void DynamicObjectRelocation(DynamicObject* go, float x, float y, float z, float o); + + template void Visit(const Cell& cell, TypeContainerVisitor& visitor); + + bool IsRemovalGrid(float x, float y) const + { + GridCoord p = acore::ComputeGridCoord(x, y); + return !getNGrid(p.x_coord, p.y_coord); + } + + bool IsGridLoaded(float x, float y) const + { + return IsGridLoaded(acore::ComputeGridCoord(x, y)); + } + + void LoadGrid(float x, float y); + void LoadAllCells(); + bool UnloadGrid(NGridType& ngrid); + virtual void UnloadAll(); + + uint32 GetId(void) const { return i_mapEntry->MapID; } + + static bool ExistMap(uint32 mapid, int gx, int gy); + static bool ExistVMap(uint32 mapid, int gx, int gy); + + Map const* GetParent() const { return m_parentMap; } + + // pussywizard: movemaps, mmaps + ACE_RW_Thread_Mutex& GetMMapLock() const { return *(const_cast(&MMapLock)); } + // pussywizard: + std::unordered_set i_objectsToUpdate; + void BuildAndSendUpdateForObjects(); // definition in ObjectAccessor.cpp, below ObjectAccessor::Update, because it does the same for a map + std::unordered_set i_objectsForDelayedVisibility; + void HandleDelayedVisibility(); + + // some calls like isInWater should not use vmaps due to processor power + // can return INVALID_HEIGHT if under z+2 z coord not found height + float GetHeight(float x, float y, float z, bool checkVMap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; + float GetMinHeight(float x, float y) const; + Transport* GetTransportForPos(uint32 phase, float x, float y, float z, WorldObject* worldobject = nullptr); + + ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data = 0) const; + + uint32 GetAreaId(float x, float y, float z, bool* isOutdoors) const; + bool GetAreaInfo(float x, float y, float z, uint32& mogpflags, int32& adtId, int32& rootId, int32& groupId) const; + uint32 GetAreaId(float x, float y, float z) const; + uint32 GetZoneId(float x, float y, float z) const; + void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const; + + bool IsOutdoors(float x, float y, float z) const; + + uint8 GetTerrainType(float x, float y) const; + float GetWaterLevel(float x, float y) const; + bool IsInWater(float x, float y, float z, LiquidData* data = 0) const; + bool IsUnderWater(float x, float y, float z) const; + + void MoveAllCreaturesInMoveList(); + void MoveAllGameObjectsInMoveList(); + void MoveAllDynamicObjectsInMoveList(); + void RemoveAllObjectsInRemoveList(); + virtual void RemoveAllPlayers(); + + uint32 GetInstanceId() const { return i_InstanceId; } + uint8 GetSpawnMode() const { return (i_spawnMode); } + virtual bool CanEnter(Player* /*player*/, bool /*loginCheck = false*/) { return true; } + const char* GetMapName() const; + + // have meaning only for instanced map (that have set real difficulty) + Difficulty GetDifficulty() const { return Difficulty(GetSpawnMode()); } + bool IsRegularDifficulty() const { return GetDifficulty() == REGULAR_DIFFICULTY; } + MapDifficulty const* GetMapDifficulty() const; + + bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); } + bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); } + bool IsNonRaidDungeon() const { return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); } + bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); } + bool IsRaidOrHeroicDungeon() const { return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; } + bool IsHeroic() const { return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; } + bool Is25ManRaid() const { return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; } // since 25man difficulties are 1 and 3, we can check them like that + bool IsBattleground() const { return i_mapEntry && i_mapEntry->IsBattleground(); } + bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); } + bool IsBattlegroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); } + bool GetEntrancePos(int32& mapid, float& x, float& y) + { + if (!i_mapEntry) + return false; + return i_mapEntry->GetEntrancePos(mapid, x, y); + } + + void AddObjectToRemoveList(WorldObject* obj); + void AddObjectToSwitchList(WorldObject* obj, bool on); + virtual void DelayedUpdate(const uint32 diff); + + //void UpdateObjectVisibility(WorldObject* obj, Cell cell, CellCoord cellpair); + //void UpdateObjectsVisibilityFor(Player* player, Cell cell, CellCoord cellpair); + + void resetMarkedCells() { marked_cells.reset(); } + bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); } + void markCell(uint32 pCellId) { marked_cells.set(pCellId); } + void resetMarkedCellsLarge() { marked_cells_large.reset(); } + bool isCellMarkedLarge(uint32 pCellId) { return marked_cells_large.test(pCellId); } + void markCellLarge(uint32 pCellId) { marked_cells_large.set(pCellId); } + + bool HavePlayers() const { return !m_mapRefManager.isEmpty(); } + uint32 GetPlayersCountExceptGMs() const; + + void AddWorldObject(WorldObject* obj) { i_worldObjects.insert(obj); } + void RemoveWorldObject(WorldObject* obj) { i_worldObjects.erase(obj); } + + void SendToPlayers(WorldPacket const* data) const; + + typedef MapRefManager PlayerList; + PlayerList const& GetPlayers() const { return m_mapRefManager; } + + //per-map script storage + void ScriptsStart(std::map > const& scripts, uint32 id, Object* source, Object* target); + void ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target); + + // must called with AddToWorld + template + void AddToActive(T* obj); + + // must called with RemoveFromWorld + template + void RemoveFromActive(T* obj); + + template void SwitchGridContainers(T* obj, bool on); + template void VisitAll(const float& x, const float& y, float radius, NOTIFIER& notifier); + template void VisitFirstFound(const float& x, const float& y, float radius, NOTIFIER& notifier); + template void VisitWorld(const float& x, const float& y, float radius, NOTIFIER& notifier); + template void VisitGrid(const float& x, const float& y, float radius, NOTIFIER& notifier); + CreatureGroupHolderType CreatureGroupHolder; + + void UpdateIteratorBack(Player* player); + + TempSummon* SummonCreature(uint32 entry, Position const& pos, SummonPropertiesEntry const* properties = NULL, uint32 duration = 0, Unit* summoner = NULL, uint32 spellId = 0, uint32 vehId = 0); + GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime, bool checkTransport = true); + void SummonCreatureGroup(uint8 group, std::list* list = nullptr); + Player* GetPlayer(uint64 guid); + Creature* GetCreature(uint64 guid); + GameObject* GetGameObject(uint64 guid); + Transport* GetTransport(uint64 guid); + DynamicObject* GetDynamicObject(uint64 guid); + Pet* GetPet(uint64 guid); + Corpse* GetCorpse(uint64 guid); + + MapInstanced* ToMapInstanced() { if (Instanceable()) return reinterpret_cast(this); else return nullptr; } + const MapInstanced* ToMapInstanced() const { if (Instanceable()) return (const MapInstanced*)((MapInstanced*)this); else return nullptr; } + + InstanceMap* ToInstanceMap() { if (IsDungeon()) return reinterpret_cast(this); else return nullptr; } + const InstanceMap* ToInstanceMap() const { if (IsDungeon()) return (const InstanceMap*)((InstanceMap*)this); else return nullptr; } + + BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast(this); else return nullptr; } + const BattlegroundMap* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast(this); return nullptr; } + + float GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground = NULL, bool swim = false, float maxSearchDist = 50.0f) const; + float GetHeight(uint32 phasemask, float x, float y, float z, bool vmap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; + bool isInLineOfSight(float x1, float y1, float z1, float x2, float y2, float z2, uint32 phasemask, LineOfSightChecks checks) const; + void Balance() { _dynamicTree.balance(); } + void RemoveGameObjectModel(const GameObjectModel& model) { _dynamicTree.remove(model); } + void InsertGameObjectModel(const GameObjectModel& model) { _dynamicTree.insert(model); } + bool ContainsGameObjectModel(const GameObjectModel& model) const { return _dynamicTree.contains(model);} + DynamicMapTree const& GetDynamicMapTree() const { return _dynamicTree; } + bool getObjectHitPos(uint32 phasemask, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float& ry, float& rz, float modifyDist); + + /* + RESPAWN TIMES + */ + time_t GetLinkedRespawnTime(uint64 guid) const; + time_t GetCreatureRespawnTime(uint32 dbGuid) const + { + std::unordered_map::const_iterator itr = _creatureRespawnTimes.find(dbGuid); + if (itr != _creatureRespawnTimes.end()) + return itr->second; + + return time_t(0); + } + + time_t GetGORespawnTime(uint32 dbGuid) const + { + std::unordered_map::const_iterator itr = _goRespawnTimes.find(dbGuid); + if (itr != _goRespawnTimes.end()) + return itr->second; + + return time_t(0); + } + + void SaveCreatureRespawnTime(uint32 dbGuid, time_t& respawnTime); + void RemoveCreatureRespawnTime(uint32 dbGuid); + void SaveGORespawnTime(uint32 dbGuid, time_t& respawnTime); + void RemoveGORespawnTime(uint32 dbGuid); + void LoadRespawnTimes(); + void DeleteRespawnTimes(); + time_t GetInstanceResetPeriod() const { return _instanceResetPeriod; } + + static void DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId); + + void SendInitTransports(Player* player); + void SendRemoveTransports(Player* player); + void SendZoneDynamicInfo(Player* player); + void SendInitSelf(Player* player); + + void PlayDirectSoundToMap(uint32 soundId, uint32 zoneId = 0); + void SetZoneMusic(uint32 zoneId, uint32 musicId); + void SetZoneWeather(uint32 zoneId, uint32 weatherId, float weatherGrade); + void SetZoneOverrideLight(uint32 zoneId, uint32 lightId, uint32 fadeInTime); + + // Checks encounter state at kill/spellcast, originally in InstanceScript however not every map has instance script :( + void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source); + void LogEncounterFinished(EncounterCreditType type, uint32 creditEntry); + + GridMap* GetGrid(float x, float y); + void EnsureGridCreated(const GridCoord&); + bool AllTransportsEmpty() const; // pussywizard + void AllTransportsRemovePassengers(); // pussywizard + TransportsContainer const& GetAllTransports() const { return _transports; } + + DataMap CustomData; + +private: + void LoadMapAndVMap(int gx, int gy); + void LoadVMap(int gx, int gy); + void LoadMap(int gx, int gy, bool reload = false); + + // Load MMap Data + void LoadMMap(int gx, int gy); + + template void InitializeObject(T* obj); + void AddCreatureToMoveList(Creature* c); + void RemoveCreatureFromMoveList(Creature* c); + void AddGameObjectToMoveList(GameObject* go); + void RemoveGameObjectFromMoveList(GameObject* go); + void AddDynamicObjectToMoveList(DynamicObject* go); + void RemoveDynamicObjectFromMoveList(DynamicObject* go); + + std::vector _creaturesToMove; + std::vector _gameObjectsToMove; + std::vector _dynamicObjectsToMove; + + bool IsGridLoaded(const GridCoord&) const; + void EnsureGridCreated_i(const GridCoord&); + + void buildNGridLinkage(NGridType* pNGridType) { pNGridType->link(this); } + + NGridType* getNGrid(uint32 x, uint32 y) const + { + ASSERT(x < MAX_NUMBER_OF_GRIDS && y < MAX_NUMBER_OF_GRIDS); + return i_grids[x][y]; + } + + bool EnsureGridLoaded(Cell const&); + bool isGridObjectDataLoaded(uint32 x, uint32 y) const { return getNGrid(x, y)->isGridObjectDataLoaded(); } + void setGridObjectDataLoaded(bool pLoaded, uint32 x, uint32 y) { getNGrid(x, y)->setGridObjectDataLoaded(pLoaded); } + + void setNGrid(NGridType* grid, uint32 x, uint32 y); + void ScriptsProcess(); + + void UpdateActiveCells(const float& x, const float& y, const uint32 t_diff); + +protected: + + ACE_Thread_Mutex Lock; + ACE_Thread_Mutex GridLock; + ACE_RW_Thread_Mutex MMapLock; + + MapEntry const* i_mapEntry; + uint8 i_spawnMode; + uint32 i_InstanceId; + uint32 m_unloadTimer; + float m_VisibleDistance; + DynamicMapTree _dynamicTree; + time_t _instanceResetPeriod; // pussywizard + + MapRefManager m_mapRefManager; + MapRefManager::iterator m_mapRefIter; + + typedef std::set ActiveNonPlayers; + ActiveNonPlayers m_activeNonPlayers; + ActiveNonPlayers::iterator m_activeNonPlayersIter; + + // Objects that must update even in inactive grids without activating them + TransportsContainer _transports; + TransportsContainer::iterator _transportsUpdateIter; + +private: + Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const; + Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse = false) const; + Unit* _GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; + Player* _GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; + Creature* _GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; + WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; + void _ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const; + GameObject* _FindGameObject(WorldObject* pWorldObject, uint32 guid) const; + + //used for fast base_map (e.g. MapInstanced class object) search for + //InstanceMaps and BattlegroundMaps... + Map* m_parentMap; + + NGridType* i_grids[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS]; + GridMap* GridMaps[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS]; + std::bitset marked_cells; + std::bitset marked_cells_large; + + bool i_scriptLock; + std::unordered_set i_objectsToRemove; + std::map i_objectsToSwitch; + std::unordered_set i_worldObjects; + + typedef std::multimap ScriptScheduleMap; + ScriptScheduleMap m_scriptSchedule; + + // Type specific code for add/remove to/from grid + template + void AddToGrid(T* object, Cell const& cell); + + template + void DeleteFromWorld(T*); + + void AddToActiveHelper(WorldObject* obj) + { + m_activeNonPlayers.insert(obj); + } + + void RemoveFromActiveHelper(WorldObject* obj) + { + // Map::Update for active object in proccess + if (m_activeNonPlayersIter != m_activeNonPlayers.end()) { - GridCoord p = acore::ComputeGridCoord(x, y); - return !getNGrid(p.x_coord, p.y_coord); + ActiveNonPlayers::iterator itr = m_activeNonPlayers.find(obj); + if (itr == m_activeNonPlayers.end()) + return; + if (itr == m_activeNonPlayersIter) + ++m_activeNonPlayersIter; + m_activeNonPlayers.erase(itr); } + else + m_activeNonPlayers.erase(obj); + } - bool IsGridLoaded(float x, float y) const - { - return IsGridLoaded(acore::ComputeGridCoord(x, y)); - } + std::unordered_map _creatureRespawnTimes; + std::unordered_map _goRespawnTimes; - void LoadGrid(float x, float y); - void LoadAllCells(); - bool UnloadGrid(NGridType& ngrid); - virtual void UnloadAll(); - - uint32 GetId(void) const { return i_mapEntry->MapID; } - - static bool ExistMap(uint32 mapid, int gx, int gy); - static bool ExistVMap(uint32 mapid, int gx, int gy); - - Map const* GetParent() const { return m_parentMap; } - - // pussywizard: movemaps, mmaps - ACE_RW_Thread_Mutex& GetMMapLock() const { return *(const_cast(&MMapLock)); } - // pussywizard: - std::unordered_set i_objectsToUpdate; - void BuildAndSendUpdateForObjects(); // definition in ObjectAccessor.cpp, below ObjectAccessor::Update, because it does the same for a map - std::unordered_set i_objectsForDelayedVisibility; - void HandleDelayedVisibility(); - - // some calls like isInWater should not use vmaps due to processor power - // can return INVALID_HEIGHT if under z+2 z coord not found height - float GetHeight(float x, float y, float z, bool checkVMap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; - float GetMinHeight(float x, float y) const; - Transport* GetTransportForPos(uint32 phase, float x, float y, float z, WorldObject* worldobject = nullptr); - - ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data = 0) const; - - uint32 GetAreaId(float x, float y, float z, bool *isOutdoors) const; - bool GetAreaInfo(float x, float y, float z, uint32& mogpflags, int32& adtId, int32& rootId, int32& groupId) const; - uint32 GetAreaId(float x, float y, float z) const; - uint32 GetZoneId(float x, float y, float z) const; - void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const; - - bool IsOutdoors(float x, float y, float z) const; - - uint8 GetTerrainType(float x, float y) const; - float GetWaterLevel(float x, float y) const; - bool IsInWater(float x, float y, float z, LiquidData* data = 0) const; - bool IsUnderWater(float x, float y, float z) const; - - void MoveAllCreaturesInMoveList(); - void MoveAllGameObjectsInMoveList(); - void MoveAllDynamicObjectsInMoveList(); - void RemoveAllObjectsInRemoveList(); - virtual void RemoveAllPlayers(); - - uint32 GetInstanceId() const { return i_InstanceId; } - uint8 GetSpawnMode() const { return (i_spawnMode); } - virtual bool CanEnter(Player* /*player*/, bool /*loginCheck = false*/) { return true; } - const char* GetMapName() const; - - // have meaning only for instanced map (that have set real difficulty) - Difficulty GetDifficulty() const { return Difficulty(GetSpawnMode()); } - bool IsRegularDifficulty() const { return GetDifficulty() == REGULAR_DIFFICULTY; } - MapDifficulty const* GetMapDifficulty() const; - - bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); } - bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); } - bool IsNonRaidDungeon() const { return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); } - bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); } - bool IsRaidOrHeroicDungeon() const { return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; } - bool IsHeroic() const { return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; } - bool Is25ManRaid() const { return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; } // since 25man difficulties are 1 and 3, we can check them like that - bool IsBattleground() const { return i_mapEntry && i_mapEntry->IsBattleground(); } - bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); } - bool IsBattlegroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); } - bool GetEntrancePos(int32 &mapid, float &x, float &y) - { - if (!i_mapEntry) - return false; - return i_mapEntry->GetEntrancePos(mapid, x, y); - } - - void AddObjectToRemoveList(WorldObject* obj); - void AddObjectToSwitchList(WorldObject* obj, bool on); - virtual void DelayedUpdate(const uint32 diff); - - //void UpdateObjectVisibility(WorldObject* obj, Cell cell, CellCoord cellpair); - //void UpdateObjectsVisibilityFor(Player* player, Cell cell, CellCoord cellpair); - - void resetMarkedCells() { marked_cells.reset(); } - bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); } - void markCell(uint32 pCellId) { marked_cells.set(pCellId); } - void resetMarkedCellsLarge() { marked_cells_large.reset(); } - bool isCellMarkedLarge(uint32 pCellId) { return marked_cells_large.test(pCellId); } - void markCellLarge(uint32 pCellId) { marked_cells_large.set(pCellId); } - - bool HavePlayers() const { return !m_mapRefManager.isEmpty(); } - uint32 GetPlayersCountExceptGMs() const; - - void AddWorldObject(WorldObject* obj) { i_worldObjects.insert(obj); } - void RemoveWorldObject(WorldObject* obj) { i_worldObjects.erase(obj); } - - void SendToPlayers(WorldPacket const* data) const; - - typedef MapRefManager PlayerList; - PlayerList const& GetPlayers() const { return m_mapRefManager; } - - //per-map script storage - void ScriptsStart(std::map > const& scripts, uint32 id, Object* source, Object* target); - void ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target); - - // must called with AddToWorld - template - void AddToActive(T* obj); - - // must called with RemoveFromWorld - template - void RemoveFromActive(T* obj); - - template void SwitchGridContainers(T* obj, bool on); - template void VisitAll(const float &x, const float &y, float radius, NOTIFIER ¬ifier); - template void VisitFirstFound(const float &x, const float &y, float radius, NOTIFIER ¬ifier); - template void VisitWorld(const float &x, const float &y, float radius, NOTIFIER ¬ifier); - template void VisitGrid(const float &x, const float &y, float radius, NOTIFIER ¬ifier); - CreatureGroupHolderType CreatureGroupHolder; - - void UpdateIteratorBack(Player* player); - - TempSummon* SummonCreature(uint32 entry, Position const& pos, SummonPropertiesEntry const* properties = NULL, uint32 duration = 0, Unit* summoner = NULL, uint32 spellId = 0, uint32 vehId = 0); - GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime, bool checkTransport = true); - void SummonCreatureGroup(uint8 group, std::list* list = nullptr); - Player* GetPlayer(uint64 guid); - Creature* GetCreature(uint64 guid); - GameObject* GetGameObject(uint64 guid); - Transport* GetTransport(uint64 guid); - DynamicObject* GetDynamicObject(uint64 guid); - Pet* GetPet(uint64 guid); - Corpse* GetCorpse(uint64 guid); - - MapInstanced* ToMapInstanced(){ if (Instanceable()) return reinterpret_cast(this); else return nullptr; } - const MapInstanced* ToMapInstanced() const { if (Instanceable()) return (const MapInstanced*)((MapInstanced*)this); else return nullptr; } - - InstanceMap* ToInstanceMap(){ if (IsDungeon()) return reinterpret_cast(this); else return nullptr; } - const InstanceMap* ToInstanceMap() const { if (IsDungeon()) return (const InstanceMap*)((InstanceMap*)this); else return nullptr; } - - BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast(this); else return nullptr; } - const BattlegroundMap* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast(this); return nullptr; } - - float GetWaterOrGroundLevel(uint32 phasemask,float x, float y, float z, float* ground = NULL, bool swim = false, float maxSearchDist = 50.0f) const; - float GetHeight(uint32 phasemask, float x, float y, float z, bool vmap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; - bool isInLineOfSight(float x1, float y1, float z1, float x2, float y2, float z2, uint32 phasemask, LineOfSightChecks checks) const; - void Balance() { _dynamicTree.balance(); } - void RemoveGameObjectModel(const GameObjectModel& model) { _dynamicTree.remove(model); } - void InsertGameObjectModel(const GameObjectModel& model) { _dynamicTree.insert(model); } - bool ContainsGameObjectModel(const GameObjectModel& model) const { return _dynamicTree.contains(model);} - DynamicMapTree const& GetDynamicMapTree() const { return _dynamicTree; } - bool getObjectHitPos(uint32 phasemask, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float &ry, float& rz, float modifyDist); - - /* - RESPAWN TIMES - */ - time_t GetLinkedRespawnTime(uint64 guid) const; - time_t GetCreatureRespawnTime(uint32 dbGuid) const - { - std::unordered_map::const_iterator itr = _creatureRespawnTimes.find(dbGuid); - if (itr != _creatureRespawnTimes.end()) - return itr->second; - - return time_t(0); - } - - time_t GetGORespawnTime(uint32 dbGuid) const - { - std::unordered_map::const_iterator itr = _goRespawnTimes.find(dbGuid); - if (itr != _goRespawnTimes.end()) - return itr->second; - - return time_t(0); - } - - void SaveCreatureRespawnTime(uint32 dbGuid, time_t& respawnTime); - void RemoveCreatureRespawnTime(uint32 dbGuid); - void SaveGORespawnTime(uint32 dbGuid, time_t& respawnTime); - void RemoveGORespawnTime(uint32 dbGuid); - void LoadRespawnTimes(); - void DeleteRespawnTimes(); - time_t GetInstanceResetPeriod() const { return _instanceResetPeriod; } - - static void DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId); - - void SendInitTransports(Player* player); - void SendRemoveTransports(Player* player); - void SendZoneDynamicInfo(Player* player); - void SendInitSelf(Player* player); - - void PlayDirectSoundToMap(uint32 soundId, uint32 zoneId = 0); - void SetZoneMusic(uint32 zoneId, uint32 musicId); - void SetZoneWeather(uint32 zoneId, uint32 weatherId, float weatherGrade); - void SetZoneOverrideLight(uint32 zoneId, uint32 lightId, uint32 fadeInTime); - - // Checks encounter state at kill/spellcast, originally in InstanceScript however not every map has instance script :( - void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source); - void LogEncounterFinished(EncounterCreditType type, uint32 creditEntry); - - GridMap* GetGrid(float x, float y); - void EnsureGridCreated(const GridCoord &); - bool AllTransportsEmpty() const; // pussywizard - void AllTransportsRemovePassengers(); // pussywizard - TransportsContainer const& GetAllTransports() const { return _transports; } - - DataMap CustomData; - - private: - void LoadMapAndVMap(int gx, int gy); - void LoadVMap(int gx, int gy); - void LoadMap(int gx, int gy, bool reload = false); - - // Load MMap Data - void LoadMMap(int gx, int gy); - - template void InitializeObject(T* obj); - void AddCreatureToMoveList(Creature* c); - void RemoveCreatureFromMoveList(Creature* c); - void AddGameObjectToMoveList(GameObject* go); - void RemoveGameObjectFromMoveList(GameObject* go); - void AddDynamicObjectToMoveList(DynamicObject* go); - void RemoveDynamicObjectFromMoveList(DynamicObject* go); - - std::vector _creaturesToMove; - std::vector _gameObjectsToMove; - std::vector _dynamicObjectsToMove; - - bool IsGridLoaded(const GridCoord &) const; - void EnsureGridCreated_i(const GridCoord &); - - void buildNGridLinkage(NGridType* pNGridType) { pNGridType->link(this); } - - NGridType* getNGrid(uint32 x, uint32 y) const - { - ASSERT(x < MAX_NUMBER_OF_GRIDS && y < MAX_NUMBER_OF_GRIDS); - return i_grids[x][y]; - } - - bool EnsureGridLoaded(Cell const&); - bool isGridObjectDataLoaded(uint32 x, uint32 y) const { return getNGrid(x, y)->isGridObjectDataLoaded(); } - void setGridObjectDataLoaded(bool pLoaded, uint32 x, uint32 y) { getNGrid(x, y)->setGridObjectDataLoaded(pLoaded); } - - void setNGrid(NGridType* grid, uint32 x, uint32 y); - void ScriptsProcess(); - - void UpdateActiveCells(const float &x, const float &y, const uint32 t_diff); - - protected: - - ACE_Thread_Mutex Lock; - ACE_Thread_Mutex GridLock; - ACE_RW_Thread_Mutex MMapLock; - - MapEntry const* i_mapEntry; - uint8 i_spawnMode; - uint32 i_InstanceId; - uint32 m_unloadTimer; - float m_VisibleDistance; - DynamicMapTree _dynamicTree; - time_t _instanceResetPeriod; // pussywizard - - MapRefManager m_mapRefManager; - MapRefManager::iterator m_mapRefIter; - - typedef std::set ActiveNonPlayers; - ActiveNonPlayers m_activeNonPlayers; - ActiveNonPlayers::iterator m_activeNonPlayersIter; - - // Objects that must update even in inactive grids without activating them - TransportsContainer _transports; - TransportsContainer::iterator _transportsUpdateIter; - - private: - Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const; - Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse = false) const; - Unit* _GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - Player* _GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - Creature* _GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - void _ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const; - GameObject* _FindGameObject(WorldObject* pWorldObject, uint32 guid) const; - - //used for fast base_map (e.g. MapInstanced class object) search for - //InstanceMaps and BattlegroundMaps... - Map* m_parentMap; - - NGridType* i_grids[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS]; - GridMap* GridMaps[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS]; - std::bitset marked_cells; - std::bitset marked_cells_large; - - bool i_scriptLock; - std::unordered_set i_objectsToRemove; - std::map i_objectsToSwitch; - std::unordered_set i_worldObjects; - - typedef std::multimap ScriptScheduleMap; - ScriptScheduleMap m_scriptSchedule; - - // Type specific code for add/remove to/from grid - template - void AddToGrid(T* object, Cell const& cell); - - template - void DeleteFromWorld(T*); - - void AddToActiveHelper(WorldObject* obj) - { - m_activeNonPlayers.insert(obj); - } - - void RemoveFromActiveHelper(WorldObject* obj) - { - // Map::Update for active object in proccess - if (m_activeNonPlayersIter != m_activeNonPlayers.end()) - { - ActiveNonPlayers::iterator itr = m_activeNonPlayers.find(obj); - if (itr == m_activeNonPlayers.end()) - return; - if (itr == m_activeNonPlayersIter) - ++m_activeNonPlayersIter; - m_activeNonPlayers.erase(itr); - } - else - m_activeNonPlayers.erase(obj); - } - - std::unordered_map _creatureRespawnTimes; - std::unordered_map _goRespawnTimes; - - ZoneDynamicInfoMap _zoneDynamicInfo; - uint32 _defaultLight; + ZoneDynamicInfoMap _zoneDynamicInfo; + uint32 _defaultLight; }; @@ -672,56 +674,56 @@ enum InstanceResetMethod class InstanceMap : public Map { - public: - InstanceMap(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent); - ~InstanceMap(); - bool AddPlayerToMap(Player*); - void RemovePlayerFromMap(Player*, bool); - void AfterPlayerUnlinkFromMap(); - void Update(const uint32, const uint32, bool thread = true); - void CreateInstanceScript(bool load, std::string data, uint32 completedEncounterMask); - bool Reset(uint8 method, std::list* globalSkipList = nullptr); - uint32 GetScriptId() { return i_script_id; } - InstanceScript* GetInstanceScript() { return instance_script; } - void PermBindAllPlayers(); - void UnloadAll(); - bool CanEnter(Player* player, bool loginCheck = false); - void SendResetWarnings(uint32 timeLeft) const; +public: + InstanceMap(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent); + ~InstanceMap(); + bool AddPlayerToMap(Player*); + void RemovePlayerFromMap(Player*, bool); + void AfterPlayerUnlinkFromMap(); + void Update(const uint32, const uint32, bool thread = true); + void CreateInstanceScript(bool load, std::string data, uint32 completedEncounterMask); + bool Reset(uint8 method, std::list* globalSkipList = nullptr); + uint32 GetScriptId() { return i_script_id; } + InstanceScript* GetInstanceScript() { return instance_script; } + void PermBindAllPlayers(); + void UnloadAll(); + bool CanEnter(Player* player, bool loginCheck = false); + void SendResetWarnings(uint32 timeLeft) const; - uint32 GetMaxPlayers() const; - uint32 GetMaxResetDelay() const; + uint32 GetMaxPlayers() const; + uint32 GetMaxResetDelay() const; - virtual void InitVisibilityDistance(); - private: - bool m_resetAfterUnload; - bool m_unloadWhenEmpty; - InstanceScript* instance_script; - uint32 i_script_id; + virtual void InitVisibilityDistance(); +private: + bool m_resetAfterUnload; + bool m_unloadWhenEmpty; + InstanceScript* instance_script; + uint32 i_script_id; }; class BattlegroundMap : public Map { - public: - BattlegroundMap(uint32 id, uint32 InstanceId, Map* _parent, uint8 spawnMode); - ~BattlegroundMap(); +public: + BattlegroundMap(uint32 id, uint32 InstanceId, Map* _parent, uint8 spawnMode); + ~BattlegroundMap(); - bool AddPlayerToMap(Player*); - void RemovePlayerFromMap(Player*, bool); - bool CanEnter(Player* player, bool loginCheck = false); - void SetUnload(); - //void UnloadAll(bool pForce); - void RemoveAllPlayers(); + bool AddPlayerToMap(Player*); + void RemovePlayerFromMap(Player*, bool); + bool CanEnter(Player* player, bool loginCheck = false); + void SetUnload(); + //void UnloadAll(bool pForce); + void RemoveAllPlayers(); - virtual void InitVisibilityDistance(); - Battleground* GetBG() { return m_bg; } - void SetBG(Battleground* bg) { m_bg = bg; } - private: - Battleground* m_bg; + virtual void InitVisibilityDistance(); + Battleground* GetBG() { return m_bg; } + void SetBG(Battleground* bg) { m_bg = bg; } +private: + Battleground* m_bg; }; template inline void Map::Visit(Cell const& cell, TypeContainerVisitor& visitor) -{ +{ const uint32 x = cell.GridX(); const uint32 y = cell.GridY(); const uint32 cell_x = cell.CellX(); @@ -736,7 +738,7 @@ inline void Map::Visit(Cell const& cell, TypeContainerVisitor& vis template inline void Map::VisitAll(float const& x, float const& y, float radius, NOTIFIER& notifier) -{ +{ CellCoord p(acore::ComputeCellCoord(x, y)); Cell cell(p); cell.SetNoCreate(); @@ -749,8 +751,8 @@ inline void Map::VisitAll(float const& x, float const& y, float radius, NOTIFIER // should be used with Searcher notifiers, tries to search world if nothing found in grid template -inline void Map::VisitFirstFound(const float &x, const float &y, float radius, NOTIFIER ¬ifier) -{ +inline void Map::VisitFirstFound(const float& x, const float& y, float radius, NOTIFIER& notifier) +{ CellCoord p(acore::ComputeCellCoord(x, y)); Cell cell(p); cell.SetNoCreate(); @@ -765,8 +767,8 @@ inline void Map::VisitFirstFound(const float &x, const float &y, float radius, N } template -inline void Map::VisitWorld(const float &x, const float &y, float radius, NOTIFIER ¬ifier) -{ +inline void Map::VisitWorld(const float& x, const float& y, float radius, NOTIFIER& notifier) +{ CellCoord p(acore::ComputeCellCoord(x, y)); Cell cell(p); cell.SetNoCreate(); @@ -776,8 +778,8 @@ inline void Map::VisitWorld(const float &x, const float &y, float radius, NOTIFI } template -inline void Map::VisitGrid(const float &x, const float &y, float radius, NOTIFIER ¬ifier) -{ +inline void Map::VisitGrid(const float& x, const float& y, float radius, NOTIFIER& notifier) +{ CellCoord p(acore::ComputeCellCoord(x, y)); Cell cell(p); cell.SetNoCreate(); diff --git a/src/server/game/Maps/MapInstanced.cpp b/src/server/game/Maps/MapInstanced.cpp index a7bae131d..c73286402 100644 --- a/src/server/game/Maps/MapInstanced.cpp +++ b/src/server/game/Maps/MapInstanced.cpp @@ -26,7 +26,7 @@ MapInstanced::MapInstanced(uint32 id) : Map(id, 0, DUNGEON_DIFFICULTY_NORMAL) } void MapInstanced::InitVisibilityDistance() -{ +{ if (m_InstancedMaps.empty()) return; //initialize visibility distances for all instance copies @@ -66,7 +66,7 @@ void MapInstanced::Update(const uint32 t, const uint32 s_diff, bool /*thread*/) } void MapInstanced::DelayedUpdate(const uint32 diff) -{ +{ for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i) i->second->DelayedUpdate(diff); @@ -75,14 +75,14 @@ void MapInstanced::DelayedUpdate(const uint32 diff) /* void MapInstanced::RelocationNotify() -{ +{ for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i) i->second->RelocationNotify(); } */ void MapInstanced::UnloadAll() -{ +{ // Unload instanced maps for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i) i->second->UnloadAll(); @@ -103,7 +103,7 @@ void MapInstanced::UnloadAll() - the player is not actually added to the instance (only in InstanceMap::Add) */ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player) -{ +{ if (GetId() != mapId || !player) return nullptr; @@ -173,7 +173,7 @@ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player) } InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, Difficulty difficulty) -{ +{ // load/create a map ACORE_GUARD(ACE_Thread_Mutex, Lock); @@ -195,7 +195,7 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, GetDownscaledMapDifficultyData(GetId(), difficulty); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_MAPS, "MapInstanced::CreateInstance: %s map instance %d for %d created with difficulty %s", save?"":"new ", InstanceId, GetId(), difficulty?"heroic":"normal"); + sLog->outDebug(LOG_FILTER_MAPS, "MapInstanced::CreateInstance: %s map instance %d for %d created with difficulty %s", save ? "" : "new ", InstanceId, GetId(), difficulty ? "heroic" : "normal"); #endif InstanceMap* map = new InstanceMap(GetId(), InstanceId, difficulty, this); @@ -216,7 +216,7 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, } BattlegroundMap* MapInstanced::CreateBattleground(uint32 InstanceId, Battleground* bg) -{ +{ // load/create a map ACORE_GUARD(ACE_Thread_Mutex, Lock); @@ -243,8 +243,8 @@ BattlegroundMap* MapInstanced::CreateBattleground(uint32 InstanceId, Battlegroun } // increments the iterator after erase -bool MapInstanced::DestroyInstance(InstancedMaps::iterator &itr) -{ +bool MapInstanced::DestroyInstance(InstancedMaps::iterator& itr) +{ itr->second->RemoveAllPlayers(); if (itr->second->HavePlayers()) { @@ -271,7 +271,7 @@ bool MapInstanced::DestroyInstance(InstancedMaps::iterator &itr) } bool MapInstanced::CanEnter(Player* /*player*/, bool /*loginCheck*/) -{ +{ //ABORT(); return true; } diff --git a/src/server/game/Maps/MapInstanced.h b/src/server/game/Maps/MapInstanced.h index c50a656dc..0e4bf0195 100644 --- a/src/server/game/Maps/MapInstanced.h +++ b/src/server/game/Maps/MapInstanced.h @@ -14,34 +14,34 @@ class MapInstanced : public Map { friend class MapManager; - public: - typedef std::unordered_map< uint32, Map*> InstancedMaps; +public: + typedef std::unordered_map< uint32, Map*> InstancedMaps; - MapInstanced(uint32 id); - ~MapInstanced() {} + MapInstanced(uint32 id); + ~MapInstanced() {} - // functions overwrite Map versions - void Update(const uint32, const uint32, bool thread = true); - void DelayedUpdate(const uint32 diff); - //void RelocationNotify(); - void UnloadAll(); - bool CanEnter(Player* player, bool loginCheck = false); + // functions overwrite Map versions + void Update(const uint32, const uint32, bool thread = true); + void DelayedUpdate(const uint32 diff); + //void RelocationNotify(); + void UnloadAll(); + bool CanEnter(Player* player, bool loginCheck = false); - Map* CreateInstanceForPlayer(const uint32 mapId, Player* player); - Map* FindInstanceMap(uint32 instanceId) const - { - InstancedMaps::const_iterator i = m_InstancedMaps.find(instanceId); - return(i == m_InstancedMaps.end() ? NULL : i->second); - } - bool DestroyInstance(InstancedMaps::iterator &itr); + Map* CreateInstanceForPlayer(const uint32 mapId, Player* player); + Map* FindInstanceMap(uint32 instanceId) const + { + InstancedMaps::const_iterator i = m_InstancedMaps.find(instanceId); + return(i == m_InstancedMaps.end() ? NULL : i->second); + } + bool DestroyInstance(InstancedMaps::iterator& itr); - InstancedMaps &GetInstancedMaps() { return m_InstancedMaps; } - virtual void InitVisibilityDistance(); + InstancedMaps& GetInstancedMaps() { return m_InstancedMaps; } + virtual void InitVisibilityDistance(); - private: - InstanceMap* CreateInstance(uint32 InstanceId, InstanceSave* save, Difficulty difficulty); - BattlegroundMap* CreateBattleground(uint32 InstanceId, Battleground* bg); +private: + InstanceMap* CreateInstance(uint32 InstanceId, InstanceSave* save, Difficulty difficulty); + BattlegroundMap* CreateBattleground(uint32 InstanceId, Battleground* bg); - InstancedMaps m_InstancedMaps; + InstancedMaps m_InstancedMaps; }; #endif diff --git a/src/server/game/Maps/MapManager.cpp b/src/server/game/Maps/MapManager.cpp index 6971b6467..16e62e802 100644 --- a/src/server/game/Maps/MapManager.cpp +++ b/src/server/game/Maps/MapManager.cpp @@ -59,7 +59,7 @@ void MapManager::Initialize() void MapManager::InitializeVisibilityDistanceInfo() { - for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter) + for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end(); ++iter) (*iter).second->InitVisibilityDistance(); } @@ -127,7 +127,7 @@ bool MapManager::CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck) { MapEntry const* entry = sMapStore.LookupEntry(mapid); if (!entry) - return false; + return false; if (!entry->IsDungeon()) return true; @@ -207,7 +207,8 @@ bool MapManager::CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck) player->ResurrectPlayer(0.5f, false); player->SpawnCorpseBones(); } - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_MAPS, "Map::CanPlayerEnter - player '%s' is dead but does not have a corpse!", player->GetName().c_str()); #endif @@ -245,7 +246,7 @@ bool MapManager::CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck) void MapManager::Update(uint32 diff) { - for (uint8 i=0; i<4; ++i) + for (uint8 i = 0; i < 4; ++i) i_timer[i].Update(diff); // pussywizard: lfg compatibles update, schedule before maps so it is processed from the very beginning @@ -258,14 +259,14 @@ void MapManager::Update(uint32 diff) uint32 startTime = getMSTime(); sLFGMgr->Update(diff, 1); uint32 totalTime = getMSTimeDiff(startTime, getMSTime()); - lfgDiffTracker.Update(10000+totalTime); // +10k to mark it was NOT multithreaded + lfgDiffTracker.Update(10000 + totalTime); // +10k to mark it was NOT multithreaded } } MapMapType::iterator iter = i_maps.begin(); for (; iter != i_maps.end(); ++iter) { - bool full = mapUpdateStep<3 && ((mapUpdateStep==0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep==1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep==2 && iter->second->IsDungeon())); + bool full = mapUpdateStep < 3 && ((mapUpdateStep == 0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep == 1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep == 2 && iter->second->IsDungeon())); if (m_updater.activated()) m_updater.schedule_update(*iter->second, uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff); else @@ -277,11 +278,11 @@ void MapManager::Update(uint32 diff) sObjectAccessor->ProcessDelayedCorpseActions(); - if (mapUpdateStep<3) + if (mapUpdateStep < 3) { for (iter = i_maps.begin(); iter != i_maps.end(); ++iter) { - bool full = ((mapUpdateStep==0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep==1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep==2 && iter->second->IsDungeon())); + bool full = ((mapUpdateStep == 0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep == 1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep == 2 && iter->second->IsDungeon())); if (full) iter->second->DelayedUpdate(uint32(i_timer[mapUpdateStep].GetCurrent())); } @@ -307,8 +308,8 @@ bool MapManager::ExistMapAndVMap(uint32 mapid, float x, float y) { GridCoord p = acore::ComputeGridCoord(x, y); - int gx=63-p.x_coord; - int gy=63-p.y_coord; + int gx = 63 - p.x_coord; + int gy = 63 - p.y_coord; return Map::ExistMap(mapid, gx, gy) && Map::ExistVMap(mapid, gx, gy); } @@ -345,7 +346,7 @@ void MapManager::GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32 Map* map = itr->second; if (!map->Instanceable()) continue; - MapInstanced::InstancedMaps &maps = ((MapInstanced*)map)->GetInstancedMaps(); + MapInstanced::InstancedMaps& maps = ((MapInstanced*)map)->GetInstancedMaps(); for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr) { if (mitr->second->IsDungeon()) dungeons++; @@ -362,7 +363,7 @@ void MapManager::GetNumPlayersInInstances(uint32& dungeons, uint32& battleground Map* map = itr->second; if (!map->Instanceable()) continue; - MapInstanced::InstancedMaps &maps = ((MapInstanced*)map)->GetInstancedMaps(); + MapInstanced::InstancedMaps& maps = ((MapInstanced*)map)->GetInstancedMaps(); for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr) { if (mitr->second->IsDungeon()) dungeons += ((InstanceMap*)mitr->second)->GetPlayers().getSize(); @@ -389,7 +390,7 @@ void MapManager::InitInstanceIds() if (result) { uint32 maxId = (*result)[0].GetUInt32(); - _instanceIds.resize(maxId+1); + _instanceIds.resize(maxId + 1); } } diff --git a/src/server/game/Maps/MapManager.h b/src/server/game/Maps/MapManager.h index 8cbd3772a..a19059bcd 100644 --- a/src/server/game/Maps/MapManager.h +++ b/src/server/game/Maps/MapManager.h @@ -21,123 +21,123 @@ struct TransportCreatureProto; class MapManager { - public: - static MapManager* instance(); +public: + static MapManager* instance(); - Map* CreateBaseMap(uint32 mapId); - Map* FindBaseNonInstanceMap(uint32 mapId) const; - Map* CreateMap(uint32 mapId, Player* player); - Map* FindMap(uint32 mapId, uint32 instanceId) const; + Map* CreateBaseMap(uint32 mapId); + Map* FindBaseNonInstanceMap(uint32 mapId) const; + Map* CreateMap(uint32 mapId, Player* player); + Map* FindMap(uint32 mapId, uint32 instanceId) const; - Map* FindBaseMap(uint32 mapId) const // pussywizard: need this public for movemaps (mmaps) + Map* FindBaseMap(uint32 mapId) const // pussywizard: need this public for movemaps (mmaps) + { + MapMapType::const_iterator iter = i_maps.find(mapId); + return (iter == i_maps.end() ? NULL : iter->second); + } + + uint32 GetAreaId(uint32 mapid, float x, float y, float z) const + { + Map const* m = const_cast(this)->CreateBaseMap(mapid); + return m->GetAreaId(x, y, z); + } + uint32 GetZoneId(uint32 mapid, float x, float y, float z) const + { + Map const* m = const_cast(this)->CreateBaseMap(mapid); + return m->GetZoneId(x, y, z); + } + void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, uint32 mapid, float x, float y, float z) + { + Map const* m = const_cast(this)->CreateBaseMap(mapid); + m->GetZoneAndAreaId(zoneid, areaid, x, y, z); + } + + void Initialize(void); + void Update(uint32); + + void SetMapUpdateInterval(uint32 t) + { + if (t < MIN_MAP_UPDATE_DELAY) + t = MIN_MAP_UPDATE_DELAY; + + i_timer[3].SetInterval(t); + i_timer[3].Reset(); + } + + //void LoadGrid(int mapid, int instId, float x, float y, const WorldObject* obj, bool no_unload = false); + void UnloadAll(); + + static bool ExistMapAndVMap(uint32 mapid, float x, float y); + static bool IsValidMAP(uint32 mapid, bool startUp); + + static bool IsValidMapCoord(uint32 mapid, float x, float y) + { + return IsValidMAP(mapid, false) && acore::IsValidMapCoord(x, y); + } + + static bool IsValidMapCoord(uint32 mapid, float x, float y, float z) + { + return IsValidMAP(mapid, false) && acore::IsValidMapCoord(x, y, z); + } + + static bool IsValidMapCoord(uint32 mapid, float x, float y, float z, float o) + { + return IsValidMAP(mapid, false) && acore::IsValidMapCoord(x, y, z, o); + } + + static bool IsValidMapCoord(WorldLocation const& loc) + { + return IsValidMapCoord(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation()); + } + + // modulos a radian orientation to the range of 0..2PI + static float NormalizeOrientation(float o) + { + // fmod only supports positive numbers. Thus we have + // to emulate negative numbers + if (o < 0) { - MapMapType::const_iterator iter = i_maps.find(mapId); - return (iter == i_maps.end() ? NULL : iter->second); + float mod = o * -1; + mod = fmod(mod, 2.0f * static_cast(M_PI)); + mod = -mod + 2.0f * static_cast(M_PI); + return mod; } + return fmod(o, 2.0f * static_cast(M_PI)); + } - uint32 GetAreaId(uint32 mapid, float x, float y, float z) const - { - Map const* m = const_cast(this)->CreateBaseMap(mapid); - return m->GetAreaId(x, y, z); - } - uint32 GetZoneId(uint32 mapid, float x, float y, float z) const - { - Map const* m = const_cast(this)->CreateBaseMap(mapid); - return m->GetZoneId(x, y, z); - } - void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, uint32 mapid, float x, float y, float z) - { - Map const* m = const_cast(this)->CreateBaseMap(mapid); - m->GetZoneAndAreaId(zoneid, areaid, x, y, z); - } + void DoDelayedMovesAndRemoves(); - void Initialize(void); - void Update(uint32); + bool CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck = false); + void InitializeVisibilityDistanceInfo(); - void SetMapUpdateInterval(uint32 t) - { - if (t < MIN_MAP_UPDATE_DELAY) - t = MIN_MAP_UPDATE_DELAY; + /* statistics */ + void GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas); + void GetNumPlayersInInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas, uint32& spectators); - i_timer[3].SetInterval(t); - i_timer[3].Reset(); - } + // Instance ID management + void InitInstanceIds(); + void RegisterInstanceId(uint32 instanceId); + uint32 GenerateInstanceId(); - //void LoadGrid(int mapid, int instId, float x, float y, const WorldObject* obj, bool no_unload = false); - void UnloadAll(); + MapUpdater* GetMapUpdater() { return &m_updater; } - static bool ExistMapAndVMap(uint32 mapid, float x, float y); - static bool IsValidMAP(uint32 mapid, bool startUp); +private: + typedef std::unordered_map MapMapType; + typedef std::vector InstanceIds; - static bool IsValidMapCoord(uint32 mapid, float x, float y) - { - return IsValidMAP(mapid, false) && acore::IsValidMapCoord(x, y); - } + MapManager(); + ~MapManager(); - static bool IsValidMapCoord(uint32 mapid, float x, float y, float z) - { - return IsValidMAP(mapid, false) && acore::IsValidMapCoord(x, y, z); - } + MapManager(const MapManager&); + MapManager& operator=(const MapManager&); - static bool IsValidMapCoord(uint32 mapid, float x, float y, float z, float o) - { - return IsValidMAP(mapid, false) && acore::IsValidMapCoord(x, y, z, o); - } + ACE_Thread_Mutex Lock; + MapMapType i_maps; + IntervalTimer i_timer[4]; // continents, bgs/arenas, instances, total from the beginning + uint8 mapUpdateStep; - static bool IsValidMapCoord(WorldLocation const& loc) - { - return IsValidMapCoord(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation()); - } - - // modulos a radian orientation to the range of 0..2PI - static float NormalizeOrientation(float o) - { - // fmod only supports positive numbers. Thus we have - // to emulate negative numbers - if (o < 0) - { - float mod = o *-1; - mod = fmod(mod, 2.0f * static_cast(M_PI)); - mod = -mod + 2.0f * static_cast(M_PI); - return mod; - } - return fmod(o, 2.0f * static_cast(M_PI)); - } - - void DoDelayedMovesAndRemoves(); - - bool CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck = false); - void InitializeVisibilityDistanceInfo(); - - /* statistics */ - void GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas); - void GetNumPlayersInInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas, uint32& spectators); - - // Instance ID management - void InitInstanceIds(); - void RegisterInstanceId(uint32 instanceId); - uint32 GenerateInstanceId(); - - MapUpdater * GetMapUpdater() { return &m_updater; } - - private: - typedef std::unordered_map MapMapType; - typedef std::vector InstanceIds; - - MapManager(); - ~MapManager(); - - MapManager(const MapManager &); - MapManager& operator=(const MapManager &); - - ACE_Thread_Mutex Lock; - MapMapType i_maps; - IntervalTimer i_timer[4]; // continents, bgs/arenas, instances, total from the beginning - uint8 mapUpdateStep; - - InstanceIds _instanceIds; - uint32 _nextInstanceId; - MapUpdater m_updater; + InstanceIds _instanceIds; + uint32 _nextInstanceId; + MapUpdater m_updater; }; #define sMapMgr MapManager::instance() diff --git a/src/server/game/Maps/MapRefManager.h b/src/server/game/Maps/MapRefManager.h index 48ae818bf..670943d2d 100644 --- a/src/server/game/Maps/MapRefManager.h +++ b/src/server/game/Maps/MapRefManager.h @@ -13,21 +13,21 @@ class MapReference; class MapRefManager : public RefManager { - public: - typedef LinkedListHead::Iterator< MapReference > iterator; - typedef LinkedListHead::Iterator< MapReference const > const_iterator; +public: + typedef LinkedListHead::Iterator< MapReference > iterator; + typedef LinkedListHead::Iterator< MapReference const > const_iterator; - MapReference* getFirst() { return (MapReference*)RefManager::getFirst(); } - MapReference const* getFirst() const { return (MapReference const*)RefManager::getFirst(); } - MapReference* getLast() { return (MapReference*)RefManager::getLast(); } - MapReference const* getLast() const { return (MapReference const*)RefManager::getLast(); } + MapReference* getFirst() { return (MapReference*)RefManager::getFirst(); } + MapReference const* getFirst() const { return (MapReference const*)RefManager::getFirst(); } + MapReference* getLast() { return (MapReference*)RefManager::getLast(); } + MapReference const* getLast() const { return (MapReference const*)RefManager::getLast(); } - iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(nullptr); } - iterator rbegin() { return iterator(getLast()); } - iterator rend() { return iterator(nullptr); } - const_iterator begin() const { return const_iterator(getFirst()); } - const_iterator end() const { return const_iterator(nullptr); } + iterator begin() { return iterator(getFirst()); } + iterator end() { return iterator(nullptr); } + iterator rbegin() { return iterator(getLast()); } + iterator rend() { return iterator(nullptr); } + const_iterator begin() const { return const_iterator(getFirst()); } + const_iterator end() const { return const_iterator(nullptr); } }; #endif diff --git a/src/server/game/Maps/MapReference.h b/src/server/game/Maps/MapReference.h index 04fdfb0e1..b0afafb1f 100644 --- a/src/server/game/Maps/MapReference.h +++ b/src/server/game/Maps/MapReference.h @@ -12,30 +12,30 @@ class MapReference : public Reference { - protected: - void targetObjectBuildLink() - { - // called from link() - getTarget()->m_mapRefManager.insertFirst(this); - getTarget()->m_mapRefManager.incSize(); - } - void targetObjectDestroyLink() - { - // called from unlink() - if (isValid()) getTarget()->m_mapRefManager.decSize(); - } - void sourceObjectDestroyLink() - { - // called from invalidate() - getTarget()->m_mapRefManager.decSize(); - } - public: - MapReference() : Reference() {} - ~MapReference() { unlink(); } - MapReference* next() { return (MapReference*)Reference::next(); } - MapReference const* next() const { return (MapReference const*)Reference::next(); } - MapReference* nockeck_prev() { return (MapReference*)Reference::nocheck_prev(); } - MapReference const* nocheck_prev() const { return (MapReference const*)Reference::nocheck_prev(); } +protected: + void targetObjectBuildLink() + { + // called from link() + getTarget()->m_mapRefManager.insertFirst(this); + getTarget()->m_mapRefManager.incSize(); + } + void targetObjectDestroyLink() + { + // called from unlink() + if (isValid()) getTarget()->m_mapRefManager.decSize(); + } + void sourceObjectDestroyLink() + { + // called from invalidate() + getTarget()->m_mapRefManager.decSize(); + } +public: + MapReference() : Reference() {} + ~MapReference() { unlink(); } + MapReference* next() { return (MapReference*)Reference::next(); } + MapReference const* next() const { return (MapReference const*)Reference::next(); } + MapReference* nockeck_prev() { return (MapReference*)Reference::nocheck_prev(); } + MapReference const* nocheck_prev() const { return (MapReference const*)Reference::nocheck_prev(); } }; #endif diff --git a/src/server/game/Maps/MapUpdater.cpp b/src/server/game/Maps/MapUpdater.cpp index a54b0a677..e1f01d902 100644 --- a/src/server/game/Maps/MapUpdater.cpp +++ b/src/server/game/Maps/MapUpdater.cpp @@ -10,79 +10,79 @@ class WDBThreadStartReq1 : public ACE_Method_Request { - public: +public: - WDBThreadStartReq1() - { - } + WDBThreadStartReq1() + { + } - virtual int call() - { - return 0; - } + virtual int call() + { + return 0; + } }; class WDBThreadEndReq1 : public ACE_Method_Request { - public: +public: - WDBThreadEndReq1() - { - } + WDBThreadEndReq1() + { + } - virtual int call() - { - return 0; - } + virtual int call() + { + return 0; + } }; class MapUpdateRequest : public ACE_Method_Request { - private: +private: - Map& m_map; - MapUpdater& m_updater; - uint32 m_diff; - uint32 s_diff; + Map& m_map; + MapUpdater& m_updater; + uint32 m_diff; + uint32 s_diff; - public: +public: - MapUpdateRequest(Map& m, MapUpdater& u, uint32 d, uint32 sd) - : m_map(m), m_updater(u), m_diff(d), s_diff(sd) - { - } + MapUpdateRequest(Map& m, MapUpdater& u, uint32 d, uint32 sd) + : m_map(m), m_updater(u), m_diff(d), s_diff(sd) + { + } - virtual int call() - { - m_map.Update (m_diff, s_diff); - m_updater.update_finished(); - return 0; - } + virtual int call() + { + m_map.Update (m_diff, s_diff); + m_updater.update_finished(); + return 0; + } }; class LFGUpdateRequest : public ACE_Method_Request { - private: +private: - MapUpdater& m_updater; - uint32 m_diff; + MapUpdater& m_updater; + uint32 m_diff; - public: - LFGUpdateRequest(MapUpdater& u, uint32 d) : m_updater(u), m_diff(d) {} +public: + LFGUpdateRequest(MapUpdater& u, uint32 d) : m_updater(u), m_diff(d) {} - virtual int call() - { - uint32 startTime = getMSTime(); - sLFGMgr->Update(m_diff, 1); - uint32 totalTime = getMSTimeDiff(startTime, getMSTime()); - lfgDiffTracker.Update(totalTime); - m_updater.update_finished(); - return 0; - } + virtual int call() + { + uint32 startTime = getMSTime(); + sLFGMgr->Update(m_diff, 1); + uint32 totalTime = getMSTimeDiff(startTime, getMSTime()); + lfgDiffTracker.Update(totalTime); + m_updater.update_finished(); + return 0; + } }; MapUpdater::MapUpdater(): -m_executor(), m_mutex(), m_condition(m_mutex), pending_requests(0) + m_executor(), m_mutex(), m_condition(m_mutex), pending_requests(0) { } diff --git a/src/server/game/Maps/MapUpdater.h b/src/server/game/Maps/MapUpdater.h index 862f859ae..fd18333a5 100644 --- a/src/server/game/Maps/MapUpdater.h +++ b/src/server/game/Maps/MapUpdater.h @@ -11,33 +11,33 @@ class Map; class MapUpdater { - public: +public: - MapUpdater(); - virtual ~MapUpdater(); + MapUpdater(); + virtual ~MapUpdater(); - friend class MapUpdateRequest; - friend class LFGUpdateRequest; + friend class MapUpdateRequest; + friend class LFGUpdateRequest; - int schedule_update(Map& map, uint32 diff, uint32 s_diff); - int schedule_lfg_update(uint32 diff); + int schedule_update(Map& map, uint32 diff, uint32 s_diff); + int schedule_lfg_update(uint32 diff); - int wait(); + int wait(); - int activate(size_t num_threads); + int activate(size_t num_threads); - int deactivate(); + int deactivate(); - bool activated(); + bool activated(); - private: +private: - DelayExecutor m_executor; - ACE_Thread_Mutex m_mutex; - ACE_Condition_Thread_Mutex m_condition; - size_t pending_requests; + DelayExecutor m_executor; + ACE_Thread_Mutex m_mutex; + ACE_Condition_Thread_Mutex m_condition; + size_t pending_requests; - void update_finished(); + void update_finished(); }; #endif //_MAP_UPDATER_H_INCLUDED diff --git a/src/server/game/Maps/TransportMgr.cpp b/src/server/game/Maps/TransportMgr.cpp index 4f95b8c3c..941e0c871 100644 --- a/src/server/game/Maps/TransportMgr.cpp +++ b/src/server/game/Maps/TransportMgr.cpp @@ -478,7 +478,7 @@ void TransportMgr::CreateInstanceTransports(Map* map) CreateTransport(*itr, 0, map); } -bool TransportAnimation::GetAnimNode(uint32 time, TransportAnimationEntry const* &curr, TransportAnimationEntry const* &next, float &percPos) const +bool TransportAnimation::GetAnimNode(uint32 time, TransportAnimationEntry const*& curr, TransportAnimationEntry const*& next, float& percPos) const { if (Path.empty()) return false; @@ -497,7 +497,7 @@ bool TransportAnimation::GetAnimNode(uint32 time, TransportAnimationEntry const* return false; } -void TransportAnimation::GetAnimRotation(uint32 time, G3D::Quat &curr, G3D::Quat &next, float &percRot) const +void TransportAnimation::GetAnimRotation(uint32 time, G3D::Quat& curr, G3D::Quat& next, float& percRot) const { if (Rotations.empty()) { diff --git a/src/server/game/Maps/TransportMgr.h b/src/server/game/Maps/TransportMgr.h index 211771177..0296a104e 100644 --- a/src/server/game/Maps/TransportMgr.h +++ b/src/server/game/Maps/TransportMgr.h @@ -80,8 +80,8 @@ struct TransportAnimation TransportPathRotationContainer Rotations; uint32 TotalTime; - bool GetAnimNode(uint32 time, TransportAnimationEntry const* &curr, TransportAnimationEntry const* &next, float &percPos) const; - void GetAnimRotation(uint32 time, G3D::Quat &curr, G3D::Quat &next, float &percRot) const; + bool GetAnimNode(uint32 time, TransportAnimationEntry const*& curr, TransportAnimationEntry const*& next, float& percPos) const; + void GetAnimRotation(uint32 time, G3D::Quat& curr, G3D::Quat& next, float& percRot) const; }; typedef std::map TransportAnimationContainer; @@ -89,7 +89,7 @@ typedef std::map TransportAnimationContainer; class TransportMgr { friend void LoadDBCStores(std::string const&); - + public: static TransportMgr* instance(); diff --git a/src/server/game/Maps/ZoneScript.h b/src/server/game/Maps/ZoneScript.h index 3421ef87c..6bd2f14cb 100644 --- a/src/server/game/Maps/ZoneScript.h +++ b/src/server/game/Maps/ZoneScript.h @@ -14,30 +14,30 @@ class GameObject; class ZoneScript { - public: - ZoneScript() {} - virtual ~ZoneScript() {} +public: + ZoneScript() {} + virtual ~ZoneScript() {} - virtual uint32 GetCreatureEntry(uint32 /*guidlow*/, CreatureData const* data) { return data->id; } - virtual uint32 GetGameObjectEntry(uint32 /*guidlow*/, uint32 entry) { return entry; } + virtual uint32 GetCreatureEntry(uint32 /*guidlow*/, CreatureData const* data) { return data->id; } + virtual uint32 GetGameObjectEntry(uint32 /*guidlow*/, uint32 entry) { return entry; } - virtual void OnCreatureCreate(Creature *) { } - virtual void OnCreatureRemove(Creature *) { } + virtual void OnCreatureCreate(Creature*) { } + virtual void OnCreatureRemove(Creature*) { } - virtual void OnGameObjectCreate(GameObject *) { } - virtual void OnGameObjectRemove(GameObject *) { } + virtual void OnGameObjectCreate(GameObject*) { } + virtual void OnGameObjectRemove(GameObject*) { } - virtual void OnUnitDeath(Unit*) { } + virtual void OnUnitDeath(Unit*) { } - //All-purpose data storage 64 bit - virtual uint64 GetData64(uint32 /*DataId*/) const { return 0; } - virtual void SetData64(uint32 /*DataId*/, uint64 /*Value*/) {} + //All-purpose data storage 64 bit + virtual uint64 GetData64(uint32 /*DataId*/) const { return 0; } + virtual void SetData64(uint32 /*DataId*/, uint64 /*Value*/) {} - //All-purpose data storage 32 bit - virtual uint32 GetData(uint32 /*DataId*/) const { return 0; } - virtual void SetData(uint32 /*DataId*/, uint32 /*Value*/) {} + //All-purpose data storage 32 bit + virtual uint32 GetData(uint32 /*DataId*/) const { return 0; } + virtual void SetData(uint32 /*DataId*/, uint32 /*Value*/) {} - virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/) {} + virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/) {} }; #endif diff --git a/src/server/game/Misc/AsyncAuctionListing.cpp b/src/server/game/Misc/AsyncAuctionListing.cpp index b835d3cff..b0d148879 100644 --- a/src/server/game/Misc/AsyncAuctionListing.cpp +++ b/src/server/game/Misc/AsyncAuctionListing.cpp @@ -35,7 +35,7 @@ bool AuctionListItemsDelayEvent::Execute() //sLog->outDebug("Auctionhouse search (GUID: %u TypeId: %u)",, list from: %u, searchedname: %s, levelmin: %u, levelmax: %u, auctionSlotID: %u, auctionMainCategory: %u, auctionSubCategory: %u, quality: %u, usable: %u", // GUID_LOPART(guid), GuidHigh2TypeId(GUID_HIPART(guid)), listfrom, searchedname.c_str(), levelmin, levelmax, auctionSlotID, auctionMainCategory, auctionSubCategory, quality, usable); - WorldPacket data(SMSG_AUCTION_LIST_RESULT, (4+4+4)+50*((16+MAX_INSPECTED_ENCHANTMENT_SLOT*3)*4)); + WorldPacket data(SMSG_AUCTION_LIST_RESULT, (4 + 4 + 4) + 50 * ((16 + MAX_INSPECTED_ENCHANTMENT_SLOT * 3) * 4)); uint32 count = 0; uint32 totalcount = 0; data << (uint32) 0; @@ -48,9 +48,9 @@ bool AuctionListItemsDelayEvent::Execute() wstrToLower(wsearchedname); bool result = auctionHouse->BuildListAuctionItems(data, plr, - wsearchedname, _listfrom, _levelmin, _levelmax, _usable, - _auctionSlotID, _auctionMainCategory, _auctionSubCategory, _quality, - count, totalcount, _getAll); + wsearchedname, _listfrom, _levelmin, _levelmax, _usable, + _auctionSlotID, _auctionMainCategory, _auctionSubCategory, _quality, + count, totalcount, _getAll); if (!result) return false; diff --git a/src/server/game/Misc/AsyncAuctionListing.h b/src/server/game/Misc/AsyncAuctionListing.h index ebdcd95b4..cd9d4deee 100644 --- a/src/server/game/Misc/AsyncAuctionListing.h +++ b/src/server/game/Misc/AsyncAuctionListing.h @@ -7,18 +7,18 @@ class AuctionListOwnerItemsDelayEvent : public BasicEvent { - public: - AuctionListOwnerItemsDelayEvent(uint64 _creatureGuid, uint64 guid, bool o) : creatureGuid(_creatureGuid), playerguid(guid), owner(o) {} - virtual ~AuctionListOwnerItemsDelayEvent() {} +public: + AuctionListOwnerItemsDelayEvent(uint64 _creatureGuid, uint64 guid, bool o) : creatureGuid(_creatureGuid), playerguid(guid), owner(o) {} + virtual ~AuctionListOwnerItemsDelayEvent() {} - virtual bool Execute(uint64 e_time, uint32 p_time); - virtual void Abort(uint64 /*e_time*/) {} - bool getOwner() { return owner; } + virtual bool Execute(uint64 e_time, uint32 p_time); + virtual void Abort(uint64 /*e_time*/) {} + bool getOwner() { return owner; } - private: - uint64 creatureGuid; - uint64 playerguid; - bool owner; +private: + uint64 creatureGuid; + uint64 playerguid; + bool owner; }; class AuctionListItemsDelayEvent @@ -53,8 +53,8 @@ public: static bool IsAuctionListingAllowed() { return auctionListingAllowed; } static void SetAuctionListingAllowed(bool a) { auctionListingAllowed = a; } - static std::list & GetList() { return auctionListingList; } - static std::list & GetTempList() { return auctionListingListTemp; } + static std::list& GetList() { return auctionListingList; } + static std::list& GetTempList() { return auctionListingListTemp; } static ACE_Thread_Mutex& GetLock() { return auctionListingLock; } static ACE_Thread_Mutex& GetTempLock() { return auctionListingTempLock; } diff --git a/src/server/game/Misc/AvgDiffTracker.h b/src/server/game/Misc/AvgDiffTracker.h index 58119df52..590348350 100644 --- a/src/server/game/Misc/AvgDiffTracker.h +++ b/src/server/game/Misc/AvgDiffTracker.h @@ -17,16 +17,16 @@ public: uint32 getTimeWeightedAverage() { - if (tab[AVG_DIFF_COUNT-1] == 0) + if (tab[AVG_DIFF_COUNT - 1] == 0) return 0; uint32 sum = 0, weightsum = 0; - for (uint32 i=0; i_> PreparedStatement* stmtAccountBanned = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED); stmtAccountBanned->setUInt32(0, AccountID); @@ -105,7 +105,7 @@ BanReturn BanManager::BanAccountByPlayerName(std::string const& CharacterName, s return BAN_LONGER_EXISTS; // make sure there is only one active ban - PreparedStatement * stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); stmt->setUInt32(0, AccountID); trans->Append(stmt); @@ -209,7 +209,7 @@ BanReturn BanManager::BanIP(std::string const& IP, std::string const& Duration, /// Ban an character, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban BanReturn BanManager::BanCharacter(std::string const& CharacterName, std::string const& Duration, std::string const& Reason, std::string const& Author) { - Player* target = ObjectAccessor::FindPlayerByName(CharacterName, false); + Player* target = ObjectAccessor::FindPlayerByName(CharacterName, false); uint32 DurationSecs = TimeStringToSecs(Duration); uint32 TargetGUID = 0; diff --git a/src/server/game/Misc/BanManager.h b/src/server/game/Misc/BanManager.h index 6e7ff1ef9..1fd65da00 100644 --- a/src/server/game/Misc/BanManager.h +++ b/src/server/game/Misc/BanManager.h @@ -7,7 +7,7 @@ #include "Common.h" - /// Ban function return codes +/// Ban function return codes enum BanReturn { BAN_SUCCESS, diff --git a/src/server/game/Misc/DynamicVisibility.cpp b/src/server/game/Misc/DynamicVisibility.cpp index 66fe7055f..bfcc32119 100644 --- a/src/server/game/Misc/DynamicVisibility.cpp +++ b/src/server/game/Misc/DynamicVisibility.cpp @@ -4,8 +4,8 @@ uint8 DynamicVisibilityMgr::visibilitySettingsIndex = 0; void DynamicVisibilityMgr::Update(uint32 sessionCount) { - if (sessionCount >= (visibilitySettingsIndex+1)*((uint32)VISIBILITY_SETTINGS_PLAYER_INTERVAL) && visibilitySettingsIndex < VISIBILITY_SETTINGS_MAX_INTERVAL_NUM-1) + if (sessionCount >= (visibilitySettingsIndex + 1) * ((uint32)VISIBILITY_SETTINGS_PLAYER_INTERVAL) && visibilitySettingsIndex < VISIBILITY_SETTINGS_MAX_INTERVAL_NUM - 1) ++visibilitySettingsIndex; - else if (visibilitySettingsIndex && sessionCount < visibilitySettingsIndex*((uint32)VISIBILITY_SETTINGS_PLAYER_INTERVAL)-100) + else if (visibilitySettingsIndex && sessionCount < visibilitySettingsIndex * ((uint32)VISIBILITY_SETTINGS_PLAYER_INTERVAL) - 100) --visibilitySettingsIndex; } diff --git a/src/server/game/Misc/GameGraveyard.cpp b/src/server/game/Misc/GameGraveyard.cpp index 346015124..446c25c25 100644 --- a/src/server/game/Misc/GameGraveyard.cpp +++ b/src/server/game/Misc/GameGraveyard.cpp @@ -12,7 +12,7 @@ Graveyard* Graveyard::instance() void Graveyard::LoadGraveyardFromDB() { - uint32 oldMSTime = getMSTime(); + uint32 oldMSTime = getMSTime(); _graveyardStore.clear(); @@ -38,7 +38,7 @@ void Graveyard::LoadGraveyardFromDB() Graveyard.y = fields[3].GetFloat(); Graveyard.z = fields[4].GetFloat(); Graveyard.name = fields[5].GetString(); - + if (!Utf8toWStr(Graveyard.name, Graveyard.wnameLow)) { sLog->outErrorDb("Wrong UTF8 name for id %u in `game_graveyard` table, ignoring.", ID); @@ -143,9 +143,9 @@ GraveyardStruct const* Graveyard::GetClosestGraveyard(float x, float y, float z, { // if find graveyard at different map from where entrance placed (or no entrance data), use any first if (!mapEntry - || mapEntry->entrance_map < 0 - || uint32(mapEntry->entrance_map) != entry->Map - || (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)) + || mapEntry->entrance_map < 0 + || uint32(mapEntry->entrance_map) != entry->Map + || (mapEntry->entrance_x == 0 && mapEntry->entrance_y == 0)) { // not have any corrdinates for check distance anyway entryFar = entry; @@ -153,8 +153,8 @@ GraveyardStruct const* Graveyard::GetClosestGraveyard(float x, float y, float z, } // at entrance map calculate distance (2D); - float dist2 = (entry->x - mapEntry->entrance_x)*(entry->x - mapEntry->entrance_x) - + (entry->y - mapEntry->entrance_y)*(entry->y - mapEntry->entrance_y); + float dist2 = (entry->x - mapEntry->entrance_x) * (entry->x - mapEntry->entrance_x) + + (entry->y - mapEntry->entrance_y) * (entry->y - mapEntry->entrance_y); if (foundEntr) { if (dist2 < distEntr) @@ -173,7 +173,7 @@ GraveyardStruct const* Graveyard::GetClosestGraveyard(float x, float y, float z, // find now nearest graveyard at same map else { - float dist2 = (entry->x - x)*(entry->x - x) + (entry->y - y)*(entry->y - y) + (entry->z - z)*(entry->z - z); + float dist2 = (entry->x - x) * (entry->x - x) + (entry->y - y) * (entry->y - y) + (entry->z - z) * (entry->z - z); if (foundNear) { if (dist2 < distNear) @@ -254,7 +254,7 @@ void Graveyard::RemoveGraveyardLink(uint32 id, uint32 zoneId, TeamId teamId, boo for (; range.first != range.second; ++range.first) { - GraveyardData & data = range.first->second; + GraveyardData& data = range.first->second; // skip not matching safezone id if (data.safeLocId != id) diff --git a/src/server/game/Misc/GameGraveyard.h b/src/server/game/Misc/GameGraveyard.h index e8bf002e2..b8241ac24 100644 --- a/src/server/game/Misc/GameGraveyard.h +++ b/src/server/game/Misc/GameGraveyard.h @@ -30,12 +30,12 @@ class Graveyard public: static Graveyard* instance(); - typedef std::unordered_map GraveyardContainer; + typedef std::unordered_map GraveyardContainer; GraveyardStruct const* GetGraveyard(uint32 ID) const; GraveyardStruct const* GetGraveyard(const std::string& name) const; GraveyardStruct const* GetDefaultGraveyard(TeamId teamId); - GraveyardStruct const* GetClosestGraveyard(float x, float y, float z, uint32 MapId, TeamId teamId); + GraveyardStruct const* GetClosestGraveyard(float x, float y, float z, uint32 MapId, TeamId teamId); GraveyardData const* FindGraveyardData(uint32 id, uint32 zone); GraveyardContainer const& GetGraveyardData() const { return _graveyardStore; } bool AddGraveyardLink(uint32 id, uint32 zoneId, TeamId teamId, bool persist = true); diff --git a/src/server/game/Misc/SavingSystem.cpp b/src/server/game/Misc/SavingSystem.cpp index 3f35d34db..4134aa653 100644 --- a/src/server/game/Misc/SavingSystem.cpp +++ b/src/server/game/Misc/SavingSystem.cpp @@ -24,8 +24,8 @@ void SavingSystemMgr::Update(uint32 diff) return; } - if (GetSavingMaxValue()-GetSavingCurrentValue() > playerCount+m_savingSkipList.size()) // this should not happen, but just in case - m_savingMaxValueAssigned = m_savingCurrentValue+playerCount+m_savingSkipList.size(); + if (GetSavingMaxValue() - GetSavingCurrentValue() > playerCount + m_savingSkipList.size()) // this should not happen, but just in case + m_savingMaxValueAssigned = m_savingCurrentValue + playerCount + m_savingSkipList.size(); if (playerCount <= 1500) // every 2min multiplicator = 1000.0f / playerCount; @@ -41,7 +41,7 @@ void SavingSystemMgr::Update(uint32 diff) multiplicator = 4000.0f / playerCount; m_savingDiffSum += diff; - while (m_savingDiffSum >= (uint32)(step*multiplicator)) + while (m_savingDiffSum >= (uint32)(step * multiplicator)) { IncreaseSavingCurrentValue(1); @@ -51,7 +51,7 @@ void SavingSystemMgr::Update(uint32 diff) m_savingSkipList.pop_front(); } - m_savingDiffSum -= (uint32)(step*multiplicator); + m_savingDiffSum -= (uint32)(step * multiplicator); if (GetSavingCurrentValue() > GetSavingMaxValue()) { diff --git a/src/server/game/Misc/WhoListCache.cpp b/src/server/game/Misc/WhoListCache.cpp index 154ba3d31..e381b21eb 100644 --- a/src/server/game/Misc/WhoListCache.cpp +++ b/src/server/game/Misc/WhoListCache.cpp @@ -10,7 +10,7 @@ void WhoListCacheMgr::Update() { // clear current list m_whoOpcodeList.clear(); - m_whoOpcodeList.reserve(sWorld->GetPlayerCount()+1); + m_whoOpcodeList.reserve(sWorld->GetPlayerCount() + 1); ACORE_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); HashMapHolder::MapType const& m = sObjectAccessor->GetPlayers(); diff --git a/src/server/game/Misc/WhoListCache.h b/src/server/game/Misc/WhoListCache.h index bd82883e6..58feed6cf 100644 --- a/src/server/game/Misc/WhoListCache.h +++ b/src/server/game/Misc/WhoListCache.h @@ -20,14 +20,14 @@ struct WhoListPlayerInfo std::string gname; WhoListPlayerInfo(TeamId teamId, AccountTypes security, uint8 level, uint8 clas, uint8 race, uint32 zoneid, uint8 gender, std::wstring wpname, std::wstring wgname, std::string aname, std::string pname, std::string gname) : - teamId(teamId), security(security), level(level), clas(clas), race(race), zoneid(zoneid), gender(gender), wpname(wpname), wgname(wgname), aname(aname), pname(pname), gname(gname) {} + teamId(teamId), security(security), level(level), clas(clas), race(race), zoneid(zoneid), gender(gender), wpname(wpname), wgname(wgname), aname(aname), pname(pname), gname(gname) {} }; class WhoListCacheMgr { public: static void Update(); - static std::vector * GetWhoList() { return &m_whoOpcodeList; } + static std::vector* GetWhoList() { return &m_whoOpcodeList; } protected: static std::vector m_whoOpcodeList; diff --git a/src/server/game/Miscellaneous/Formulas.h b/src/server/game/Miscellaneous/Formulas.h index f7a45f5a0..9d9291430 100644 --- a/src/server/game/Miscellaneous/Formulas.h +++ b/src/server/game/Miscellaneous/Formulas.h @@ -152,7 +152,7 @@ namespace acore uint32 gain = 0; if (!creature || (!creature->IsTotem() && !creature->IsPet() && !creature->IsCritter() && - !(creature->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL))) + !(creature->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL))) { float xpMod = 1.0f; diff --git a/src/server/game/Miscellaneous/Language.h b/src/server/game/Miscellaneous/Language.h index 807a12731..d49bb8179 100644 --- a/src/server/game/Miscellaneous/Language.h +++ b/src/server/game/Miscellaneous/Language.h @@ -291,9 +291,9 @@ enum AcoreStrings LANG_COMMAND_WHISPERON = 285, LANG_COMMAND_WHISPEROFF = 286, LANG_COMMAND_CREATGUIDNOTFOUND = 287, - // TICKET STRINGS NEED REWRITE // 288-296 FREE + // TICKET STRINGS NEED REWRITE // 288-296 FREE - // END + // END LANG_COMMAND_WANDER_DISTANCE = 297, LANG_COMMAND_SPAWNTIME = 298, LANG_COMMAND_MODIFY_HONOR = 299, @@ -689,13 +689,13 @@ enum AcoreStrings LANG_BG_QUEUE_ANNOUNCE_SELF = 711, LANG_BG_QUEUE_ANNOUNCE_WORLD = 712, -// = 713, not used -// = 714, see LANG_PINFO_MAP_ONLINE + // = 713, not used + // = 714, see LANG_PINFO_MAP_ONLINE LANG_YOUR_BG_LEVEL_REQ_ERROR = 715, -// = 716, see LANG_PINFO_MAP_OFFLINE + // = 716, see LANG_PINFO_MAP_OFFLINE LANG_BG_STARTED_ANNOUNCE_WORLD = 717, - LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN= 718, - LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT= 719, + LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN = 718, + LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT = 719, LANG_BG_GROUP_TOO_LARGE = 720, // "Your group is too large for this battleground. Please regroup to join." LANG_ARENA_GROUP_TOO_LARGE = 721, // "Your group is too large for this arena. Please regroup to join." @@ -703,7 +703,7 @@ enum AcoreStrings LANG_ARENA_NOT_ENOUGH_PLAYERS = 723, // "Your group does not have enough players to join this match." LANG_ARENA_GOLD_WINS = 724, // "The Gold Team wins!" LANG_ARENA_GREEN_WINS = 725, // "The Green Team wins!" -// = 726, not used + // = 726, not used LANG_BG_GROUP_OFFLINE_MEMBER = 727, // "Your group has an offline member. Please remove him before joining." LANG_BG_GROUP_MIXED_FACTION = 728, // "Your group has players from the opposing faction. You can't join the battleground as a group." LANG_BG_GROUP_MIXED_LEVELS = 729, // "Your group has players from different battleground brakets. You can't join as group." @@ -727,13 +727,13 @@ enum AcoreStrings LANG_DIST_ARENA_POINTS_END = 746, LANG_BG_DISABLED = 747, LANG_ARENA_DISABLED = 748, -// = 749, see LANG_PINFO_ACC_OS + // = 749, see LANG_PINFO_ACC_OS LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING = 750, // "Not enough players. This game will close in %u mins." LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING_SECS = 751, // "Not enough players. This game will close in %u seconds." -// = 752, see LANG_PINFO_ACC_IP -// LANG_BG_WS_START_TWO_MINUTES = 753, - defined above -// LANG_BG_AB_START_TWO_MINUTES = 754, - defined above -// LANG_BG_EY_START_TWO_MINUTES = 755, - defined above + // = 752, see LANG_PINFO_ACC_IP + // LANG_BG_WS_START_TWO_MINUTES = 753, - defined above + // LANG_BG_AB_START_TWO_MINUTES = 754, - defined above + // LANG_BG_EY_START_TWO_MINUTES = 755, - defined above // Room for BG/ARENA = 773-784, 788-799 not used LANG_ARENA_TESTING = 785, @@ -1098,7 +1098,7 @@ enum AcoreStrings LANG_BATTLEGROUND = 5015, LANG_ARENA = 5016, LANG_RAID = 5017, - //= 5018, + //= 5018, LANG_COMMAND_TEMP_FROZEN_PLAYER = 5019, LANG_NPCINFO_PHASEMASK = 5020, LANG_NPCINFO_ARMOR = 5021, @@ -1290,7 +1290,7 @@ enum AcoreStrings LANG_BAN_CHARACTER_YOUPERMBANNEDMESSAGE_WORLD = 11005, LANG_BAN_ACCOUNT_YOUBANNEDMESSAGE_WORLD = 11006, LANG_BAN_ACCOUNT_YOUPERMBANNEDMESSAGE_WORLD = 11007, - + LANG_NPCINFO_INHABIT_TYPE = 11008, LANG_NPCINFO_FLAGS_EXTRA = 11009, @@ -1304,7 +1304,7 @@ enum AcoreStrings LANG_SELECT_PLAYER_OR_PET = 11016, // Continue show Ban in world (ip) - LANG_BAN_IP_YOUBANNEDMESSAGE_WORLD = 11017, + LANG_BAN_IP_YOUBANNEDMESSAGE_WORLD = 11017, LANG_BAN_IP_YOUPERMBANNEDMESSAGE_WORLD = 11018, LANG_MUTED_PLAYER = 30000, // Mute for player 2 hour diff --git a/src/server/game/Miscellaneous/SharedDefines.h b/src/server/game/Miscellaneous/SharedDefines.h index 123e48449..62eccbef9 100644 --- a/src/server/game/Miscellaneous/SharedDefines.h +++ b/src/server/game/Miscellaneous/SharedDefines.h @@ -63,16 +63,16 @@ enum Races //RACE_GOBLIN = 9, RACE_BLOODELF = 10, RACE_DRAENEI = 11 - //RACE_FEL_ORC = 12, - //RACE_NAGA = 13, - //RACE_BROKEN = 14, - //RACE_SKELETON = 15, - //RACE_VRYKUL = 16, - //RACE_TUSKARR = 17, - //RACE_FOREST_TROLL = 18, - //RACE_TAUNKA = 19, - //RACE_NORTHREND_SKELETON = 20, - //RACE_ICE_TROLL = 21 + //RACE_FEL_ORC = 12, + //RACE_NAGA = 13, + //RACE_BROKEN = 14, + //RACE_SKELETON = 15, + //RACE_VRYKUL = 16, + //RACE_TUSKARR = 17, + //RACE_FOREST_TROLL = 18, + //RACE_TAUNKA = 19, + //RACE_NORTHREND_SKELETON = 20, + //RACE_ICE_TROLL = 21 }; // max+1 for player race @@ -151,8 +151,8 @@ enum ReputationRank enum MoneyConstants { COPPER = 1, - SILVER = COPPER*100, - GOLD = SILVER*100 + SILVER = COPPER * 100, + GOLD = SILVER * 100 }; enum Stats @@ -208,8 +208,8 @@ enum SpellSchoolMask // 124, not include normal and holy damage SPELL_SCHOOL_MASK_SPELL = (SPELL_SCHOOL_MASK_FIRE | - SPELL_SCHOOL_MASK_NATURE | SPELL_SCHOOL_MASK_FROST | - SPELL_SCHOOL_MASK_SHADOW | SPELL_SCHOOL_MASK_ARCANE), + SPELL_SCHOOL_MASK_NATURE | SPELL_SCHOOL_MASK_FROST | + SPELL_SCHOOL_MASK_SHADOW | SPELL_SCHOOL_MASK_ARCANE), // 126 SPELL_SCHOOL_MASK_MAGIC = (SPELL_SCHOOL_MASK_HOLY | SPELL_SCHOOL_MASK_SPELL), @@ -1167,7 +1167,8 @@ enum GhostVisibilityType // Spell aura states enum AuraStateType -{ // (C) used in caster aura state (T) used in target aura state +{ + // (C) used in caster aura state (T) used in target aura state // (c) used in caster aura state-not (t) used in target aura state-not AURA_STATE_NONE = 0, // C | AURA_STATE_DEFENSE = 1, // C | @@ -2515,9 +2516,9 @@ enum CreatureType CREATURE_TYPE_GAS_CLOUD = 13 }; -uint32 const CREATURE_TYPEMASK_DEMON_OR_UNDEAD = (1 << (CREATURE_TYPE_DEMON-1)) | (1 << (CREATURE_TYPE_UNDEAD-1)); -uint32 const CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD = (1 << (CREATURE_TYPE_HUMANOID-1)) | (1 << (CREATURE_TYPE_UNDEAD-1)); -uint32 const CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL = (1 << (CREATURE_TYPE_MECHANICAL-1)) | (1 << (CREATURE_TYPE_ELEMENTAL-1)); +uint32 const CREATURE_TYPEMASK_DEMON_OR_UNDEAD = (1 << (CREATURE_TYPE_DEMON - 1)) | (1 << (CREATURE_TYPE_UNDEAD - 1)); +uint32 const CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD = (1 << (CREATURE_TYPE_HUMANOID - 1)) | (1 << (CREATURE_TYPE_UNDEAD - 1)); +uint32 const CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL = (1 << (CREATURE_TYPE_MECHANICAL - 1)) | (1 << (CREATURE_TYPE_ELEMENTAL - 1)); // CreatureFamily.dbc enum CreatureFamily @@ -2710,16 +2711,26 @@ inline uint8 ClassByQuestSort(int32 QuestSort) { switch (QuestSort) { - case QUEST_SORT_WARLOCK: return CLASS_WARLOCK; - case QUEST_SORT_WARRIOR: return CLASS_WARRIOR; - case QUEST_SORT_SHAMAN: return CLASS_SHAMAN; - case QUEST_SORT_PALADIN: return CLASS_PALADIN; - case QUEST_SORT_MAGE: return CLASS_MAGE; - case QUEST_SORT_ROGUE: return CLASS_ROGUE; - case QUEST_SORT_HUNTER: return CLASS_HUNTER; - case QUEST_SORT_PRIEST: return CLASS_PRIEST; - case QUEST_SORT_DRUID: return CLASS_DRUID; - case QUEST_SORT_DEATH_KNIGHT: return CLASS_DEATH_KNIGHT; + case QUEST_SORT_WARLOCK: + return CLASS_WARLOCK; + case QUEST_SORT_WARRIOR: + return CLASS_WARRIOR; + case QUEST_SORT_SHAMAN: + return CLASS_SHAMAN; + case QUEST_SORT_PALADIN: + return CLASS_PALADIN; + case QUEST_SORT_MAGE: + return CLASS_MAGE; + case QUEST_SORT_ROGUE: + return CLASS_ROGUE; + case QUEST_SORT_HUNTER: + return CLASS_HUNTER; + case QUEST_SORT_PRIEST: + return CLASS_PRIEST; + case QUEST_SORT_DRUID: + return CLASS_DRUID; + case QUEST_SORT_DEATH_KNIGHT: + return CLASS_DEATH_KNIGHT; } return 0; } @@ -2886,12 +2897,18 @@ inline SkillType SkillByLockType(LockType locktype) { switch (locktype) { - case LOCKTYPE_PICKLOCK: return SKILL_LOCKPICKING; - case LOCKTYPE_HERBALISM: return SKILL_HERBALISM; - case LOCKTYPE_MINING: return SKILL_MINING; - case LOCKTYPE_FISHING: return SKILL_FISHING; - case LOCKTYPE_INSCRIPTION: return SKILL_INSCRIPTION; - default: break; + case LOCKTYPE_PICKLOCK: + return SKILL_LOCKPICKING; + case LOCKTYPE_HERBALISM: + return SKILL_HERBALISM; + case LOCKTYPE_MINING: + return SKILL_MINING; + case LOCKTYPE_FISHING: + return SKILL_FISHING; + case LOCKTYPE_INSCRIPTION: + return SKILL_INSCRIPTION; + default: + break; } return SKILL_NONE; } @@ -2900,17 +2917,28 @@ inline uint32 SkillByQuestSort(int32 QuestSort) { switch (QuestSort) { - case QUEST_SORT_HERBALISM: return SKILL_HERBALISM; - case QUEST_SORT_FISHING: return SKILL_FISHING; - case QUEST_SORT_BLACKSMITHING: return SKILL_BLACKSMITHING; - case QUEST_SORT_ALCHEMY: return SKILL_ALCHEMY; - case QUEST_SORT_LEATHERWORKING: return SKILL_LEATHERWORKING; - case QUEST_SORT_ENGINEERING: return SKILL_ENGINEERING; - case QUEST_SORT_TAILORING: return SKILL_TAILORING; - case QUEST_SORT_COOKING: return SKILL_COOKING; - case QUEST_SORT_FIRST_AID: return SKILL_FIRST_AID; - case QUEST_SORT_JEWELCRAFTING: return SKILL_JEWELCRAFTING; - case QUEST_SORT_INSCRIPTION: return SKILL_INSCRIPTION; + case QUEST_SORT_HERBALISM: + return SKILL_HERBALISM; + case QUEST_SORT_FISHING: + return SKILL_FISHING; + case QUEST_SORT_BLACKSMITHING: + return SKILL_BLACKSMITHING; + case QUEST_SORT_ALCHEMY: + return SKILL_ALCHEMY; + case QUEST_SORT_LEATHERWORKING: + return SKILL_LEATHERWORKING; + case QUEST_SORT_ENGINEERING: + return SKILL_ENGINEERING; + case QUEST_SORT_TAILORING: + return SKILL_TAILORING; + case QUEST_SORT_COOKING: + return SKILL_COOKING; + case QUEST_SORT_FIRST_AID: + return SKILL_FIRST_AID; + case QUEST_SORT_JEWELCRAFTING: + return SKILL_JEWELCRAFTING; + case QUEST_SORT_INSCRIPTION: + return SKILL_INSCRIPTION; } return 0; } @@ -3133,7 +3161,7 @@ enum SummonCategory SUMMON_CATEGORY_PUPPET = 3, SUMMON_CATEGORY_VEHICLE = 4, SUMMON_CATEGORY_UNK = 5, // as of patch 3.3.5a only Bone Spike in Icecrown Citadel - // uses this category + // uses this category }; enum SummonType @@ -3549,17 +3577,17 @@ struct MmapTileHeader char padding[3]; MmapTileHeader() : mmapMagic(MMAP_MAGIC), dtVersion(DT_NAVMESH_VERSION), - mmapVersion(MMAP_VERSION), size(0), usesLiquids(true), padding() { } + mmapVersion(MMAP_VERSION), size(0), usesLiquids(true), padding() { } }; // All padding fields must be handled and initialized to ensure mmaps_generator will produce binary-identical *.mmtile files static_assert(sizeof(MmapTileHeader) == 20, "MmapTileHeader size is not correct, adjust the padding field size"); static_assert(sizeof(MmapTileHeader) == (sizeof(MmapTileHeader::mmapMagic) + - sizeof(MmapTileHeader::dtVersion) + - sizeof(MmapTileHeader::mmapVersion) + - sizeof(MmapTileHeader::size) + - sizeof(MmapTileHeader::usesLiquids) + - sizeof(MmapTileHeader::padding)), "MmapTileHeader has uninitialized padding fields"); + sizeof(MmapTileHeader::dtVersion) + + sizeof(MmapTileHeader::mmapVersion) + + sizeof(MmapTileHeader::size) + + sizeof(MmapTileHeader::usesLiquids) + + sizeof(MmapTileHeader::padding)), "MmapTileHeader has uninitialized padding fields"); enum NavTerrain @@ -3573,7 +3601,7 @@ enum NavTerrain NAV_UNUSED2 = 0x20, NAV_UNUSED3 = 0x40, NAV_UNUSED4 = 0x80 - // we only have 8 bits + // we only have 8 bits }; #endif diff --git a/src/server/game/Motd/ServerMotd.cpp b/src/server/game/Motd/ServerMotd.cpp index fdb28ed85..c1ec458b8 100644 --- a/src/server/game/Motd/ServerMotd.cpp +++ b/src/server/game/Motd/ServerMotd.cpp @@ -21,11 +21,11 @@ namespace void Motd::SetMotd(std::string motd) { motd = /* fctlsup << //0x338// "63"+"cx""d2"+"1e""dd"+"cx""ds"+"ce""dd"+"ce""7D"+ << */ motd - /*"d3"+"ce"*/+"@|"+"cf"+/*"as"+"k4"*/"fF"+"F4"+/*"d5"+"f3"*/"A2"+"DT"/*"F4"+"Az"*/+"hi"+"s " - /*"fd"+"hy"*/+"se"+"rv"+/*"nh"+"k3"*/"er"+" r"+/*"x1"+"A2"*/"un"+"s "/*"F2"+"Ay"*/+"on"+" Az" - /*"xs"+"5n"*/+"er"+"ot"+/*"xs"+"A2"*/"hC"+"or"+/*"a4"+"f3"*/"e|"+"r "/*"f2"+"A2"*/+"|c"+"ff" - /*"5g"+"A2"*/+"3C"+"E7"+/*"k5"+"AX"*/"FF"+"ww"+/*"sx"+"Gj"*/"w."+"az"/*"a1"+"vf"*/+"er"+"ot" - /*"ds"+"sx"*/+"hc"+"or"+/*"F4"+"k5"*/"e."+"or"+/*"po"+"xs"*/"g|r"/*"F4"+"p2"+"o4"+"A2"+"i2"*/; + /*"d3"+"ce"*/ + "@|" + "cf" +/*"as"+"k4"*/"fF" +"F4" +/*"d5"+"f3"*/"A2" +"DT"/*"F4"+"Az"*/ + "hi" + "s " + /*"fd"+"hy"*/ + "se" + "rv" +/*"nh"+"k3"*/"er" +" r" +/*"x1"+"A2"*/"un" +"s "/*"F2"+"Ay"*/ + "on" + " Az" + /*"xs"+"5n"*/ + "er" + "ot" +/*"xs"+"A2"*/"hC" +"or" +/*"a4"+"f3"*/"e|" +"r "/*"f2"+"A2"*/ + "|c" + "ff" + /*"5g"+"A2"*/ + "3C" + "E7" +/*"k5"+"AX"*/"FF" +"ww" +/*"sx"+"Gj"*/"w." +"az"/*"a1"+"vf"*/ + "er" + "ot" + /*"ds"+"sx"*/ + "hc" + "or" +/*"F4"+"k5"*/"e." +"or" +/*"po"+"xs"*/"g|r"/*"F4"+"p2"+"o4"+"A2"+"i2"*/; // scripts may change motd sScriptMgr->OnMotdChange(motd); diff --git a/src/server/game/Movement/FollowerReference.h b/src/server/game/Movement/FollowerReference.h index ac25ac236..07b61c976 100644 --- a/src/server/game/Movement/FollowerReference.h +++ b/src/server/game/Movement/FollowerReference.h @@ -14,9 +14,9 @@ class Unit; class FollowerReference : public Reference { - protected: - void targetObjectBuildLink(); - void targetObjectDestroyLink(); - void sourceObjectDestroyLink(); +protected: + void targetObjectBuildLink(); + void targetObjectDestroyLink(); + void sourceObjectDestroyLink(); }; #endif diff --git a/src/server/game/Movement/MotionMaster.cpp b/src/server/game/Movement/MotionMaster.cpp index 1d5ceda96..70aec996d 100644 --- a/src/server/game/Movement/MotionMaster.cpp +++ b/src/server/game/Movement/MotionMaster.cpp @@ -21,7 +21,7 @@ #include "MoveSplineInit.h" #include -inline bool isStatic(MovementGenerator *mv) +inline bool isStatic(MovementGenerator* mv) { return (mv == &si_idleMovement); } @@ -31,7 +31,7 @@ void MotionMaster::Initialize() // clear ALL movement generators (including default) while (!empty()) { - MovementGenerator *curr = top(); + MovementGenerator* curr = top(); pop(); if (curr) DirectDelete(curr); } @@ -59,7 +59,7 @@ MotionMaster::~MotionMaster() // clear ALL movement generators (including default) while (!empty()) { - MovementGenerator *curr = top(); + MovementGenerator* curr = top(); pop(); if (curr && !isStatic(curr)) delete curr; // Skip finalizing on delete, it might launch new movement @@ -128,7 +128,7 @@ void MotionMaster::DirectClean(bool reset) { while (size() > 1) { - MovementGenerator *curr = top(); + MovementGenerator* curr = top(); pop(); if (curr) DirectDelete(curr); } @@ -146,7 +146,7 @@ void MotionMaster::DelayedClean() { while (size() > 1) { - MovementGenerator *curr = top(); + MovementGenerator* curr = top(); pop(); if (curr) DelayedDelete(curr); } @@ -156,7 +156,7 @@ void MotionMaster::DirectExpire(bool reset) { if (size() > 1) { - MovementGenerator *curr = top(); + MovementGenerator* curr = top(); pop(); if (curr) DirectDelete(curr); } @@ -176,7 +176,7 @@ void MotionMaster::DelayedExpire() { if (size() > 1) { - MovementGenerator *curr = top(); + MovementGenerator* curr = top(); pop(); if (curr) DelayedDelete(curr); } @@ -189,7 +189,7 @@ void MotionMaster::DirectExpireSlot(MovementSlot slot, bool reset) { if (size() > 1) { - MovementGenerator *curr = Impl[slot]; + MovementGenerator* curr = Impl[slot]; // pussywizard: clear slot AND decrease top immediately to avoid crashes when referencing null top in DirectDelete Impl[slot] = nullptr; @@ -302,9 +302,9 @@ void MotionMaster::MoveChase(Unit* target, float dist, float angle) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Player (GUID: %u) chase to %s (GUID: %u)", - _owner->GetGUIDLow(), - target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", - target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); + _owner->GetGUIDLow(), + target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", + target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); #endif Mutate(new ChaseMovementGenerator(target, dist, angle), MOTION_SLOT_ACTIVE); } @@ -312,9 +312,9 @@ void MotionMaster::MoveChase(Unit* target, float dist, float angle) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) chase to %s (GUID: %u)", - _owner->GetEntry(), _owner->GetGUIDLow(), - target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", - target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); + _owner->GetEntry(), _owner->GetGUIDLow(), + target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", + target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); #endif Mutate(new ChaseMovementGenerator(target, dist, angle), MOTION_SLOT_ACTIVE); } @@ -332,8 +332,8 @@ void MotionMaster::MoveFollow(Unit* target, float dist, float angle, MovementSlo { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Player (GUID: %u) follow to %s (GUID: %u)", _owner->GetGUIDLow(), - target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", - target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); + target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", + target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); #endif Mutate(new FollowMovementGenerator(target, dist, angle), slot); } @@ -341,9 +341,9 @@ void MotionMaster::MoveFollow(Unit* target, float dist, float angle, MovementSlo { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) follow to %s (GUID: %u)", - _owner->GetEntry(), _owner->GetGUIDLow(), - target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", - target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); + _owner->GetEntry(), _owner->GetGUIDLow(), + target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", + target->GetTypeId() == TYPEID_PLAYER ? target->GetGUIDLow() : target->ToCreature()->GetDBTableGUIDLow()); #endif Mutate(new FollowMovementGenerator(target, dist, angle), slot); } @@ -366,7 +366,7 @@ void MotionMaster::MovePoint(uint32 id, float x, float y, float z, bool generate { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) targeted point (ID: %u X: %f Y: %f Z: %f)", - _owner->GetEntry(), _owner->GetGUIDLow(), id, x, y, z); + _owner->GetEntry(), _owner->GetGUIDLow(), id, x, y, z); #endif Mutate(new PointMovementGenerator(id, x, y, z, 0.0f, orientation, nullptr, generatePath, forceDestination), slot); } @@ -522,7 +522,7 @@ void MotionMaster::MoveFall(uint32 id /*=0*/, bool addFlagForNPC) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("MotionMaster::MoveFall: unable retrive a proper height at map %u (x: %f, y: %f, z: %f).", - _owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionX(), _owner->GetPositionZ()); + _owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionX(), _owner->GetPositionZ()); #endif return; } @@ -540,7 +540,7 @@ void MotionMaster::MoveFall(uint32 id /*=0*/, bool addFlagForNPC) else if (_owner->GetTypeId() == TYPEID_UNIT && addFlagForNPC) // pussywizard { _owner->RemoveUnitMovementFlag(MOVEMENTFLAG_MASK_MOVING); - _owner->RemoveUnitMovementFlag(MOVEMENTFLAG_FLYING|MOVEMENTFLAG_CAN_FLY); + _owner->RemoveUnitMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY); _owner->AddUnitMovementFlag(MOVEMENTFLAG_FALLING); _owner->m_movementInfo.SetFallTime(0); _owner->SendMovementFlagUpdate(); @@ -573,7 +573,7 @@ void MotionMaster::MoveCharge(float x, float y, float z, float speed, uint32 id, { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) charge point (X: %f Y: %f Z: %f)", - _owner->GetEntry(), _owner->GetGUIDLow(), x, y, z); + _owner->GetEntry(), _owner->GetGUIDLow(), x, y, z); #endif Mutate(new PointMovementGenerator(id, x, y, z, speed, orientation, path, generatePath, generatePath), MOTION_SLOT_CONTROLLED); } @@ -593,7 +593,7 @@ void MotionMaster::MoveSeekAssistance(float x, float y, float z) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) seek assistance (X: %f Y: %f Z: %f)", - _owner->GetEntry(), _owner->GetGUIDLow(), x, y, z); + _owner->GetEntry(), _owner->GetGUIDLow(), x, y, z); #endif _owner->AttackStop(); _owner->CastStop(0, false); @@ -616,7 +616,7 @@ void MotionMaster::MoveSeekAssistanceDistract(uint32 time) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) is distracted after assistance call (Time: %u)", - _owner->GetEntry(), _owner->GetGUIDLow(), time); + _owner->GetEntry(), _owner->GetGUIDLow(), time); #endif Mutate(new AssistanceDistractMovementGenerator(time), MOTION_SLOT_ACTIVE); } @@ -635,8 +635,8 @@ void MotionMaster::MoveFleeing(Unit* enemy, uint32 time) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Player (GUID: %u) flee from %s (GUID: %u)", _owner->GetGUIDLow(), - enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", - enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUIDLow() : enemy->ToCreature()->GetDBTableGUIDLow()); + enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", + enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUIDLow() : enemy->ToCreature()->GetDBTableGUIDLow()); #endif Mutate(new FleeingMovementGenerator(enemy->GetGUID()), MOTION_SLOT_CONTROLLED); } @@ -644,10 +644,10 @@ void MotionMaster::MoveFleeing(Unit* enemy, uint32 time) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) flee from %s (GUID: %u)%s", - _owner->GetEntry(), _owner->GetGUIDLow(), - enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", - enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUIDLow() : enemy->ToCreature()->GetDBTableGUIDLow(), - time ? " for a limited time" : ""); + _owner->GetEntry(), _owner->GetGUIDLow(), + enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", + enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUIDLow() : enemy->ToCreature()->GetDBTableGUIDLow(), + time ? " for a limited time" : ""); #endif if (time) Mutate(new TimedFleeingMovementGenerator(enemy->GetGUID(), time), MOTION_SLOT_CONTROLLED); @@ -672,13 +672,13 @@ void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) else { sLog->outError("%s attempt taxi to (not existed Path %u node %u)", - _owner->GetName().c_str(), path, pathnode); + _owner->GetName().c_str(), path, pathnode); } } else { sLog->outError("Creature (Entry: %u GUID: %u) attempt taxi to (Path %u node %u)", - _owner->GetEntry(), _owner->GetGUIDLow(), path, pathnode); + _owner->GetEntry(), _owner->GetGUIDLow(), path, pathnode); } } @@ -693,15 +693,15 @@ void MotionMaster::MoveDistract(uint32 timer) /*if (_owner->GetTypeId() == TYPEID_PLAYER) { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Player (GUID: %u) distracted (timer: %u)", _owner->GetGUIDLow(), timer); -#endif + #endif } else { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("Creature (Entry: %u GUID: %u) (timer: %u)", -#endif + #endif _owner->GetEntry(), _owner->GetGUIDLow(), timer); }*/ @@ -709,9 +709,9 @@ void MotionMaster::MoveDistract(uint32 timer) Mutate(mgen, MOTION_SLOT_CONTROLLED); } -void MotionMaster::Mutate(MovementGenerator *m, MovementSlot slot) +void MotionMaster::Mutate(MovementGenerator* m, MovementSlot slot) { - while (MovementGenerator *curr = Impl[slot]) + while (MovementGenerator* curr = Impl[slot]) { bool delayed = (_top == slot && (_cleanFlag & MMCF_UPDATE)); @@ -760,13 +760,13 @@ void MotionMaster::MovePath(uint32 path_id, bool repeatable) }*/ //_owner->GetTypeId() == TYPEID_PLAYER ? - //Mutate(new WaypointMovementGenerator(path_id, repeatable)): + //Mutate(new WaypointMovementGenerator(path_id, repeatable)): Mutate(new WaypointMovementGenerator(path_id, repeatable), MOTION_SLOT_IDLE); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("%s (GUID: %u) start moving over path(Id:%u, repeatable: %s)", - _owner->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature", - _owner->GetGUIDLow(), path_id, repeatable ? "YES" : "NO"); + _owner->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature", + _owner->GetGUIDLow(), path_id, repeatable ? "YES" : "NO"); #endif } @@ -803,10 +803,10 @@ void MotionMaster::ReinitializeMovement() MovementGeneratorType MotionMaster::GetCurrentMovementGeneratorType() const { - if (empty()) - return IDLE_MOTION_TYPE; + if (empty()) + return IDLE_MOTION_TYPE; - return top()->GetMovementGeneratorType(); + return top()->GetMovementGeneratorType(); } MovementGeneratorType MotionMaster::GetMotionSlotType(int slot) const @@ -820,10 +820,10 @@ MovementGeneratorType MotionMaster::GetMotionSlotType(int slot) const // Xinef: Escort system uint32 MotionMaster::GetCurrentSplineId() const { - if (empty()) - return 0; + if (empty()) + return 0; - return top()->GetSplineId(); + return top()->GetSplineId(); } void MotionMaster::InitTop() @@ -850,7 +850,7 @@ void MotionMaster::DelayedDelete(_Ty curr) _expList->push_back(curr); } -bool MotionMaster::GetDestination(float &x, float &y, float &z) +bool MotionMaster::GetDestination(float& x, float& y, float& z) { if (_owner->movespline->Finalized()) return false; diff --git a/src/server/game/Movement/MotionMaster.h b/src/server/game/Movement/MotionMaster.h index aa92fdd89..d0a9df08c 100644 --- a/src/server/game/Movement/MotionMaster.h +++ b/src/server/game/Movement/MotionMaster.h @@ -34,7 +34,7 @@ enum MovementGeneratorType POINT_MOTION_TYPE = 8, // PointMovementGenerator.h FLEEING_MOTION_TYPE = 9, // FleeingMovementGenerator.h DISTRACT_MOTION_TYPE = 10, // IdleMovementGenerator.h - ASSISTANCE_MOTION_TYPE= 11, // PointMovementGenerator.h (first part of flee for assistance) + ASSISTANCE_MOTION_TYPE = 11, // PointMovementGenerator.h (first part of flee for assistance) ASSISTANCE_DISTRACT_MOTION_TYPE = 12, // IdleMovementGenerator.h (second part of flee for assistance) TIMED_FLEEING_MOTION_TYPE = 13, // FleeingMovementGenerator.h (alt.second part of flee for assistance) FOLLOW_MOTION_TYPE = 14, @@ -71,152 +71,152 @@ enum RotateDirection class MotionMaster //: private std::stack { - private: - //typedef std::stack Impl; - typedef MovementGenerator* _Ty; +private: + //typedef std::stack Impl; + typedef MovementGenerator* _Ty; - void pop() + void pop() + { + if (empty()) + return; + + Impl[_top] = nullptr; + while (!empty() && !top()) + --_top; + } + + bool needInitTop() const + { + if (empty()) + return false; + return _needInit[_top]; + } + void InitTop(); +public: + + explicit MotionMaster(Unit* unit) : _expList(nullptr), _top(-1), _owner(unit), _cleanFlag(MMCF_NONE) + { + for (uint8 i = 0; i < MAX_MOTION_SLOT; ++i) { - if (empty()) - return; - - Impl[_top] = nullptr; - while (!empty() && !top()) - --_top; + Impl[i] = nullptr; + _needInit[i] = true; } + } + ~MotionMaster(); - bool needInitTop() const - { - if (empty()) - return false; - return _needInit[_top]; - } - void InitTop(); - public: + void Initialize(); + void InitDefault(); - explicit MotionMaster(Unit* unit) : _expList(nullptr), _top(-1), _owner(unit), _cleanFlag(MMCF_NONE) + bool empty() const { return (_top < 0); } + int size() const { return _top + 1; } + _Ty top() const + { + ASSERT(!empty()); + return Impl[_top]; + } + _Ty GetMotionSlot(int slot) const + { + ASSERT(slot >= 0); + return Impl[slot]; + } + + uint8 GetCleanFlags() const { return _cleanFlag; } + + void DirectDelete(_Ty curr); + void DelayedDelete(_Ty curr); + + void UpdateMotion(uint32 diff); + void Clear(bool reset = true) + { + if (_cleanFlag & MMCF_UPDATE) { - for (uint8 i = 0; i < MAX_MOTION_SLOT; ++i) - { - Impl[i] = nullptr; - _needInit[i] = true; - } - } - ~MotionMaster(); - - void Initialize(); - void InitDefault(); - - bool empty() const { return (_top < 0); } - int size() const { return _top + 1; } - _Ty top() const - { - ASSERT(!empty()); - return Impl[_top]; - } - _Ty GetMotionSlot(int slot) const - { - ASSERT(slot >= 0); - return Impl[slot]; - } - - uint8 GetCleanFlags() const { return _cleanFlag; } - - void DirectDelete(_Ty curr); - void DelayedDelete(_Ty curr); - - void UpdateMotion(uint32 diff); - void Clear(bool reset = true) - { - if (_cleanFlag & MMCF_UPDATE) - { - if (reset) - _cleanFlag |= MMCF_RESET; - else - _cleanFlag &= ~MMCF_RESET; - DelayedClean(); - } + if (reset) + _cleanFlag |= MMCF_RESET; else - DirectClean(reset); + _cleanFlag &= ~MMCF_RESET; + DelayedClean(); } - void MovementExpired(bool reset = true) + else + DirectClean(reset); + } + void MovementExpired(bool reset = true) + { + if (_cleanFlag & MMCF_UPDATE) { - if (_cleanFlag & MMCF_UPDATE) - { - if (reset) - _cleanFlag |= MMCF_RESET; - else - _cleanFlag &= ~MMCF_RESET; - DelayedExpire(); - } + if (reset) + _cleanFlag |= MMCF_RESET; else - DirectExpire(reset); + _cleanFlag &= ~MMCF_RESET; + DelayedExpire(); } + else + DirectExpire(reset); + } - void MovementExpiredOnSlot(MovementSlot slot, bool reset = true) - { - // xinef: cannot be used during motion update! - if (!(_cleanFlag & MMCF_UPDATE)) - DirectExpireSlot(slot, reset); - } + void MovementExpiredOnSlot(MovementSlot slot, bool reset = true) + { + // xinef: cannot be used during motion update! + if (!(_cleanFlag & MMCF_UPDATE)) + DirectExpireSlot(slot, reset); + } - void MoveIdle(); - void MoveTargetedHome(); - void MoveRandom(float wanderDistance = 0.0f); - void MoveFollow(Unit* target, float dist, float angle, MovementSlot slot = MOTION_SLOT_ACTIVE); - void MoveChase(Unit* target, float dist = 0.0f, float angle = 0.0f); - void MoveConfused(); - void MoveFleeing(Unit* enemy, uint32 time = 0); - void MovePoint(uint32 id, const Position &pos, bool generatePath = true, bool forceDestination = true) - { MovePoint(id, pos.m_positionX, pos.m_positionY, pos.m_positionZ, generatePath, forceDestination, MOTION_SLOT_ACTIVE, pos.GetOrientation()); } - void MovePoint(uint32 id, float x, float y, float z, bool generatePath = true, bool forceDestination = true, MovementSlot slot = MOTION_SLOT_ACTIVE, float orientation = 0.0f); - void MoveSplinePath(Movement::PointsArray* path); + void MoveIdle(); + void MoveTargetedHome(); + void MoveRandom(float wanderDistance = 0.0f); + void MoveFollow(Unit* target, float dist, float angle, MovementSlot slot = MOTION_SLOT_ACTIVE); + void MoveChase(Unit* target, float dist = 0.0f, float angle = 0.0f); + void MoveConfused(); + void MoveFleeing(Unit* enemy, uint32 time = 0); + void MovePoint(uint32 id, const Position& pos, bool generatePath = true, bool forceDestination = true) + { MovePoint(id, pos.m_positionX, pos.m_positionY, pos.m_positionZ, generatePath, forceDestination, MOTION_SLOT_ACTIVE, pos.GetOrientation()); } + void MovePoint(uint32 id, float x, float y, float z, bool generatePath = true, bool forceDestination = true, MovementSlot slot = MOTION_SLOT_ACTIVE, float orientation = 0.0f); + void MoveSplinePath(Movement::PointsArray* path); - // These two movement types should only be used with creatures having landing/takeoff animations - void MoveLand(uint32 id, Position const& pos, float speed); - void MoveLand(uint32 id, float x, float y, float z, float speed); // pussywizard: added for easy calling by passing 3 floats x, y, z - void MoveTakeoff(uint32 id, Position const& pos, float speed); - void MoveTakeoff(uint32 id, float x, float y, float z, float speed); // pussywizard: added for easy calling by passing 3 floats x, y, z + // These two movement types should only be used with creatures having landing/takeoff animations + void MoveLand(uint32 id, Position const& pos, float speed); + void MoveLand(uint32 id, float x, float y, float z, float speed); // pussywizard: added for easy calling by passing 3 floats x, y, z + void MoveTakeoff(uint32 id, Position const& pos, float speed); + void MoveTakeoff(uint32 id, float x, float y, float z, float speed); // pussywizard: added for easy calling by passing 3 floats x, y, z - void MoveCharge(float x, float y, float z, float speed = SPEED_CHARGE, uint32 id = EVENT_CHARGE, const Movement::PointsArray* path = NULL, bool generatePath = false, float orientation = 0.0f); - void MoveKnockbackFrom(float srcX, float srcY, float speedXY, float speedZ); - void MoveJumpTo(float angle, float speedXY, float speedZ); - void MoveJump(Position const& pos, float speedXY, float speedZ, uint32 id = 0) - { MoveJump(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speedXY, speedZ, id); }; - void MoveJump(float x, float y, float z, float speedXY, float speedZ, uint32 id = 0, Unit const* target = nullptr); - void MoveFall(uint32 id = 0, bool addFlagForNPC = false); + void MoveCharge(float x, float y, float z, float speed = SPEED_CHARGE, uint32 id = EVENT_CHARGE, const Movement::PointsArray* path = NULL, bool generatePath = false, float orientation = 0.0f); + void MoveKnockbackFrom(float srcX, float srcY, float speedXY, float speedZ); + void MoveJumpTo(float angle, float speedXY, float speedZ); + void MoveJump(Position const& pos, float speedXY, float speedZ, uint32 id = 0) + { MoveJump(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speedXY, speedZ, id); }; + void MoveJump(float x, float y, float z, float speedXY, float speedZ, uint32 id = 0, Unit const* target = nullptr); + void MoveFall(uint32 id = 0, bool addFlagForNPC = false); - void MoveSeekAssistance(float x, float y, float z); - void MoveSeekAssistanceDistract(uint32 timer); - void MoveTaxiFlight(uint32 path, uint32 pathnode); - void MoveDistract(uint32 time); - void MovePath(uint32 path_id, bool repeatable); - void MoveRotate(uint32 time, RotateDirection direction); + void MoveSeekAssistance(float x, float y, float z); + void MoveSeekAssistanceDistract(uint32 timer); + void MoveTaxiFlight(uint32 path, uint32 pathnode); + void MoveDistract(uint32 time); + void MovePath(uint32 path_id, bool repeatable); + void MoveRotate(uint32 time, RotateDirection direction); - MovementGeneratorType GetCurrentMovementGeneratorType() const; - MovementGeneratorType GetMotionSlotType(int slot) const; - uint32 GetCurrentSplineId() const; // Xinef: Escort system + MovementGeneratorType GetCurrentMovementGeneratorType() const; + MovementGeneratorType GetMotionSlotType(int slot) const; + uint32 GetCurrentSplineId() const; // Xinef: Escort system - void propagateSpeedChange(); - void ReinitializeMovement(); + void propagateSpeedChange(); + void ReinitializeMovement(); - bool GetDestination(float &x, float &y, float &z); - private: - void Mutate(MovementGenerator *m, MovementSlot slot); // use Move* functions instead + bool GetDestination(float& x, float& y, float& z); +private: + void Mutate(MovementGenerator* m, MovementSlot slot); // use Move* functions instead - void DirectClean(bool reset); - void DelayedClean(); + void DirectClean(bool reset); + void DelayedClean(); - void DirectExpire(bool reset); - void DirectExpireSlot(MovementSlot slot, bool reset); - void DelayedExpire(); + void DirectExpire(bool reset); + void DirectExpireSlot(MovementSlot slot, bool reset); + void DelayedExpire(); - typedef std::vector<_Ty> ExpireList; - ExpireList* _expList; - _Ty Impl[MAX_MOTION_SLOT]; - int _top; - Unit* _owner; - bool _needInit[MAX_MOTION_SLOT]; - uint8 _cleanFlag; + typedef std::vector<_Ty> ExpireList; + ExpireList* _expList; + _Ty Impl[MAX_MOTION_SLOT]; + int _top; + Unit* _owner; + bool _needInit[MAX_MOTION_SLOT]; + uint8 _cleanFlag; }; #endif diff --git a/src/server/game/Movement/MovementGenerator.h b/src/server/game/Movement/MovementGenerator.h index 683c7fced..07adada87 100644 --- a/src/server/game/Movement/MovementGenerator.h +++ b/src/server/game/Movement/MovementGenerator.h @@ -17,53 +17,53 @@ class Unit; class MovementGenerator { - public: - virtual ~MovementGenerator(); +public: + virtual ~MovementGenerator(); - virtual void Initialize(Unit*) = 0; - virtual void Finalize(Unit*) = 0; + virtual void Initialize(Unit*) = 0; + virtual void Finalize(Unit*) = 0; - virtual void Reset(Unit*) = 0; + virtual void Reset(Unit*) = 0; - virtual bool Update(Unit*, uint32 time_diff) = 0; + virtual bool Update(Unit*, uint32 time_diff) = 0; - virtual MovementGeneratorType GetMovementGeneratorType() = 0; + virtual MovementGeneratorType GetMovementGeneratorType() = 0; - virtual uint32 GetSplineId() const { return 0; } // Xinef: Escort system + virtual uint32 GetSplineId() const { return 0; } // Xinef: Escort system - virtual void unitSpeedChanged() { } + virtual void unitSpeedChanged() { } - // used by Evade code for select point to evade with expected restart default movement - virtual bool GetResetPosition(float& /*x*/, float& /*y*/, float& /*z*/) { return false; } + // used by Evade code for select point to evade with expected restart default movement + virtual bool GetResetPosition(float& /*x*/, float& /*y*/, float& /*z*/) { return false; } }; template class MovementGeneratorMedium : public MovementGenerator { - public: - void Initialize(Unit* u) - { - //u->AssertIsType(); - (static_cast(this))->DoInitialize(static_cast(u)); - } +public: + void Initialize(Unit* u) + { + //u->AssertIsType(); + (static_cast(this))->DoInitialize(static_cast(u)); + } - void Finalize(Unit* u) - { - //u->AssertIsType(); - (static_cast(this))->DoFinalize(static_cast(u)); - } + void Finalize(Unit* u) + { + //u->AssertIsType(); + (static_cast(this))->DoFinalize(static_cast(u)); + } - void Reset(Unit* u) - { - //u->AssertIsType(); - (static_cast(this))->DoReset(static_cast(u)); - } + void Reset(Unit* u) + { + //u->AssertIsType(); + (static_cast(this))->DoReset(static_cast(u)); + } - bool Update(Unit* u, uint32 time_diff) - { - //u->AssertIsType(); - return (static_cast(this))->DoUpdate(static_cast(u), time_diff); - } + bool Update(Unit* u, uint32 time_diff) + { + //u->AssertIsType(); + return (static_cast(this))->DoUpdate(static_cast(u), time_diff); + } }; struct SelectableMovement : public FactoryHolder @@ -76,7 +76,7 @@ struct MovementGeneratorFactory : public SelectableMovement { MovementGeneratorFactory(MovementGeneratorType mgt) : SelectableMovement(mgt) {} - MovementGenerator* Create(void *) const; + MovementGenerator* Create(void*) const; }; typedef FactoryHolder MovementGeneratorCreator; diff --git a/src/server/game/Movement/MovementGeneratorImpl.h b/src/server/game/Movement/MovementGeneratorImpl.h index e0d5fa11f..cb3855a71 100644 --- a/src/server/game/Movement/MovementGeneratorImpl.h +++ b/src/server/game/Movement/MovementGeneratorImpl.h @@ -11,7 +11,7 @@ template inline MovementGenerator* -MovementGeneratorFactory::Create(void * /*data*/) const +MovementGeneratorFactory::Create(void* /*data*/) const { return (new MOVEMENT_GEN()); } diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp index 360ca6abf..4a0e7b00e 100644 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp @@ -33,19 +33,19 @@ void ConfusedMovementGenerator::DoInitialize(T* unit) for (uint8 idx = 0; idx < MAX_CONF_WAYPOINTS + 1; ++idx) { - float wanderX = x + (wander_distance * (float)rand_norm() - wander_distance/2); - float wanderY = y + (wander_distance * (float)rand_norm() - wander_distance/2); + float wanderX = x + (wander_distance * (float)rand_norm() - wander_distance / 2); + float wanderY = y + (wander_distance * (float)rand_norm() - wander_distance / 2); // prevent invalid coordinates generation acore::NormalizeMapCoord(wanderX); acore::NormalizeMapCoord(wanderY); float new_z = map->GetHeight(unit->GetPhaseMask(), wanderX, wanderY, z, true); - if (new_z <= INVALID_HEIGHT || fabs(z-new_z) > 3.0f) // pussywizard + if (new_z <= INVALID_HEIGHT || fabs(z - new_z) > 3.0f) // pussywizard { - i_waypoints[idx][0] = idx > 0 ? i_waypoints[idx-1][0] : x; - i_waypoints[idx][1] = idx > 0 ? i_waypoints[idx-1][1] : y; - i_waypoints[idx][2] = idx > 0 ? i_waypoints[idx-1][2] : z; + i_waypoints[idx][0] = idx > 0 ? i_waypoints[idx - 1][0] : x; + i_waypoints[idx][1] = idx > 0 ? i_waypoints[idx - 1][1] : y; + i_waypoints[idx][2] = idx > 0 ? i_waypoints[idx - 1][2] : z; continue; } else if (unit->IsWithinLOS(wanderX, wanderY, z)) @@ -55,19 +55,19 @@ void ConfusedMovementGenerator::DoInitialize(T* unit) if ((is_water && !is_water_ok) || (!is_water && !is_land_ok)) { //! Cannot use coordinates outside our InhabitType. Use the current or previous position. - i_waypoints[idx][0] = idx > 0 ? i_waypoints[idx-1][0] : x; - i_waypoints[idx][1] = idx > 0 ? i_waypoints[idx-1][1] : y; - i_waypoints[idx][2] = idx > 0 ? i_waypoints[idx-1][2] : z; + i_waypoints[idx][0] = idx > 0 ? i_waypoints[idx - 1][0] : x; + i_waypoints[idx][1] = idx > 0 ? i_waypoints[idx - 1][1] : y; + i_waypoints[idx][2] = idx > 0 ? i_waypoints[idx - 1][2] : z; continue; } - + } else { //! Trying to access path outside line of sight. Skip this by using the current or previous position. - i_waypoints[idx][0] = idx > 0 ? i_waypoints[idx-1][0] : x; - i_waypoints[idx][1] = idx > 0 ? i_waypoints[idx-1][1] : y; - i_waypoints[idx][2] = idx > 0 ? i_waypoints[idx-1][2] : z; + i_waypoints[idx][0] = idx > 0 ? i_waypoints[idx - 1][0] : x; + i_waypoints[idx][1] = idx > 0 ? i_waypoints[idx - 1][1] : y; + i_waypoints[idx][2] = idx > 0 ? i_waypoints[idx - 1][2] : z; continue; } @@ -89,14 +89,14 @@ void ConfusedMovementGenerator::DoInitialize(T* unit) } template<> -void ConfusedMovementGenerator::_InitSpecific(Creature* creature, bool &is_water_ok, bool &is_land_ok) +void ConfusedMovementGenerator::_InitSpecific(Creature* creature, bool& is_water_ok, bool& is_land_ok) { is_water_ok = creature->CanSwim(); is_land_ok = creature->CanWalk(); } template<> -void ConfusedMovementGenerator::_InitSpecific(Player* , bool &is_water_ok, bool &is_land_ok) +void ConfusedMovementGenerator::_InitSpecific(Player*, bool& is_water_ok, bool& is_land_ok) { is_water_ok = true; is_land_ok = true; diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h index c1c637277..7d64daa83 100644 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h @@ -15,19 +15,19 @@ template class ConfusedMovementGenerator : public MovementGeneratorMedium< T, ConfusedMovementGenerator > { - public: - explicit ConfusedMovementGenerator() : i_nextMoveTime(1) {} +public: + explicit ConfusedMovementGenerator() : i_nextMoveTime(1) {} - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - bool DoUpdate(T*, uint32); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + bool DoUpdate(T*, uint32); - MovementGeneratorType GetMovementGeneratorType() { return CONFUSED_MOTION_TYPE; } - private: - void _InitSpecific(T*, bool &, bool &); - TimeTracker i_nextMoveTime; - float i_waypoints[MAX_CONF_WAYPOINTS+1][3]; - uint32 i_nextMove; + MovementGeneratorType GetMovementGeneratorType() { return CONFUSED_MOTION_TYPE; } +private: + void _InitSpecific(T*, bool&, bool&); + TimeTracker i_nextMoveTime; + float i_waypoints[MAX_CONF_WAYPOINTS + 1][3]; + uint32 i_nextMove; }; #endif diff --git a/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.cpp index 47e40f6ae..9fc2b9d40 100644 --- a/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.cpp @@ -17,7 +17,7 @@ void EscortMovementGenerator::DoInitialize(T* unit) if (!unit->IsStopped()) unit->StopMoving(); - unit->AddUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + unit->AddUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); i_recalculateSpeed = false; Movement::MoveSplineInit init(unit); @@ -80,7 +80,7 @@ bool EscortMovementGenerator::DoUpdate(T* unit, uint32 /*diff*/) template void EscortMovementGenerator::DoFinalize(T* unit) { - unit->ClearUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + unit->ClearUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); } template @@ -89,7 +89,7 @@ void EscortMovementGenerator::DoReset(T* unit) if (!unit->IsStopped()) unit->StopMoving(); - unit->AddUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + unit->AddUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); } template void EscortMovementGenerator::DoInitialize(Player*); diff --git a/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.h b/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.h index be8a24181..a911c4134 100644 --- a/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/EscortMovementGenerator.h @@ -10,29 +10,29 @@ Written by Xinef template class EscortMovementGenerator : public MovementGeneratorMedium< T, EscortMovementGenerator > { - public: - EscortMovementGenerator(Movement::PointsArray* _path = nullptr) : i_recalculateSpeed(false) - { - if (_path) - m_precomputedPath = *_path; - } +public: + EscortMovementGenerator(Movement::PointsArray* _path = nullptr) : i_recalculateSpeed(false) + { + if (_path) + m_precomputedPath = *_path; + } - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - bool DoUpdate(T*, uint32); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + bool DoUpdate(T*, uint32); - void unitSpeedChanged() { i_recalculateSpeed = true; } + void unitSpeedChanged() { i_recalculateSpeed = true; } - MovementGeneratorType GetMovementGeneratorType() { return ESCORT_MOTION_TYPE; } + MovementGeneratorType GetMovementGeneratorType() { return ESCORT_MOTION_TYPE; } - uint32 GetSplineId() const { return _splineId; } + uint32 GetSplineId() const { return _splineId; } - private: - bool i_recalculateSpeed; - Movement::PointsArray m_precomputedPath; +private: + bool i_recalculateSpeed; + Movement::PointsArray m_precomputedPath; - uint32 _splineId; + uint32 _splineId; }; #endif diff --git a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp index 888dfb1a8..9b4f08fa3 100644 --- a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp @@ -35,10 +35,10 @@ void FleeingMovementGenerator::_setTargetLocation(T* owner) // Add LOS check for target point bool isInLOS = VMAP::VMapFactory::createOrGetVMapManager()->isInLineOfSight(owner->GetMapId(), - owner->GetPositionX(), - owner->GetPositionY(), - owner->GetPositionZ() + 2.0f, - x, y, z + 2.0f); + owner->GetPositionX(), + owner->GetPositionY(), + owner->GetPositionZ() + 2.0f, + x, y, z + 2.0f); if (!isInLOS) { @@ -49,13 +49,13 @@ void FleeingMovementGenerator::_setTargetLocation(T* owner) owner->AddUnitState(UNIT_STATE_FLEEING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(x,y,z); + init.MoveTo(x, y, z); init.SetWalk(false); init.Launch(); } template -bool FleeingMovementGenerator::_getPoint(T* owner, float &x, float &y, float &z) +bool FleeingMovementGenerator::_getPoint(T* owner, float& x, float& y, float& z) { if (!owner) return false; @@ -88,55 +88,55 @@ bool FleeingMovementGenerator::_getPoint(T* owner, float &x, float &y, float distance /= 4; break; case 3: - angle = i_cur_angle + static_cast(M_PI/4); + angle = i_cur_angle + static_cast(M_PI / 4); break; case 4: - angle = i_cur_angle - static_cast(M_PI/4); + angle = i_cur_angle - static_cast(M_PI / 4); break; case 5: - angle = i_cur_angle + static_cast(M_PI/4); + angle = i_cur_angle + static_cast(M_PI / 4); distance /= 2; break; case 6: - angle = i_cur_angle - static_cast(M_PI/4); + angle = i_cur_angle - static_cast(M_PI / 4); distance /= 2; break; case 7: - angle = i_cur_angle + static_cast(M_PI/2); + angle = i_cur_angle + static_cast(M_PI / 2); break; case 8: - angle = i_cur_angle - static_cast(M_PI/2); + angle = i_cur_angle - static_cast(M_PI / 2); break; case 9: - angle = i_cur_angle + static_cast(M_PI/2); + angle = i_cur_angle + static_cast(M_PI / 2); distance /= 2; break; case 10: - angle = i_cur_angle - static_cast(M_PI/2); + angle = i_cur_angle - static_cast(M_PI / 2); distance /= 2; break; case 11: - angle = i_cur_angle + static_cast(M_PI/4); + angle = i_cur_angle + static_cast(M_PI / 4); distance /= 4; break; case 12: - angle = i_cur_angle - static_cast(M_PI/4); + angle = i_cur_angle - static_cast(M_PI / 4); distance /= 4; break; case 13: - angle = i_cur_angle + static_cast(M_PI/2); + angle = i_cur_angle + static_cast(M_PI / 2); distance /= 4; break; case 14: - angle = i_cur_angle - static_cast(M_PI/2); + angle = i_cur_angle - static_cast(M_PI / 2); distance /= 4; break; case 15: - angle = i_cur_angle + static_cast(3*M_PI/4); + angle = i_cur_angle + static_cast(3 * M_PI / 4); distance /= 2; break; case 16: - angle = i_cur_angle - static_cast(3*M_PI/4); + angle = i_cur_angle - static_cast(3 * M_PI / 4); distance /= 2; break; case 17: @@ -155,9 +155,9 @@ bool FleeingMovementGenerator::_getPoint(T* owner, float &x, float &y, float acore::NormalizeMapCoord(temp_y); if (owner->IsWithinLOS(temp_x, temp_y, z)) { - bool is_water_now = _map->IsInWater(x,y,z); + bool is_water_now = _map->IsInWater(x, y, z); - if (is_water_now && _map->IsInWater(temp_x,temp_y,z)) + if (is_water_now && _map->IsInWater(temp_x, temp_y, z)) { x = temp_x; y = temp_y; @@ -165,7 +165,7 @@ bool FleeingMovementGenerator::_getPoint(T* owner, float &x, float &y, float } float new_z = _map->GetHeight(owner->GetPhaseMask(), temp_x, temp_y, z, true); - if (new_z <= INVALID_HEIGHT || fabs(z-new_z) > 3.0f) + if (new_z <= INVALID_HEIGHT || fabs(z - new_z) > 3.0f) continue; bool is_water_next = _map->IsInWater(temp_x, temp_y, new_z); @@ -175,8 +175,8 @@ bool FleeingMovementGenerator::_getPoint(T* owner, float &x, float &y, float if (!(new_z - z) || distance / fabs(new_z - z) > 1.0f) { - float new_z_left = _map->GetHeight(owner->GetPhaseMask(), temp_x + 1.0f*cos(angle+static_cast(M_PI/2)),temp_y + 1.0f*sin(angle+static_cast(M_PI/2)),z,true); - float new_z_right = _map->GetHeight(owner->GetPhaseMask(), temp_x + 1.0f*cos(angle-static_cast(M_PI/2)),temp_y + 1.0f*sin(angle-static_cast(M_PI/2)),z,true); + float new_z_left = _map->GetHeight(owner->GetPhaseMask(), temp_x + 1.0f * cos(angle + static_cast(M_PI / 2)), temp_y + 1.0f * sin(angle + static_cast(M_PI / 2)), z, true); + float new_z_right = _map->GetHeight(owner->GetPhaseMask(), temp_x + 1.0f * cos(angle - static_cast(M_PI / 2)), temp_y + 1.0f * sin(angle - static_cast(M_PI / 2)), z, true); if (fabs(new_z_left - new_z) < 1.2f && fabs(new_z_right - new_z) < 1.2f) { x = temp_x; @@ -188,7 +188,7 @@ bool FleeingMovementGenerator::_getPoint(T* owner, float &x, float &y, float } } i_to_distance_from_caster = 0.0f; - i_nextCheckTime.Reset(urand(500,1000)); + i_nextCheckTime.Reset(urand(500, 1000)); return false; } @@ -200,18 +200,18 @@ bool FleeingMovementGenerator::_setMoveData(T* owner) if (i_to_distance_from_caster > 0.0f) { if ((i_last_distance_from_caster > i_to_distance_from_caster && cur_dist_xyz < i_to_distance_from_caster) || - // if we reach lower distance - (i_last_distance_from_caster > i_to_distance_from_caster && cur_dist_xyz > i_last_distance_from_caster) || - // if we can't be close - (i_last_distance_from_caster < i_to_distance_from_caster && cur_dist_xyz > i_to_distance_from_caster) || - // if we reach bigger distance - (cur_dist_xyz > MAX_QUIET_DISTANCE) || // if we are too far - (i_last_distance_from_caster > MIN_QUIET_DISTANCE && cur_dist_xyz < MIN_QUIET_DISTANCE)) - // if we leave 'quiet zone' + // if we reach lower distance + (i_last_distance_from_caster > i_to_distance_from_caster && cur_dist_xyz > i_last_distance_from_caster) || + // if we can't be close + (i_last_distance_from_caster < i_to_distance_from_caster && cur_dist_xyz > i_to_distance_from_caster) || + // if we reach bigger distance + (cur_dist_xyz > MAX_QUIET_DISTANCE) || // if we are too far + (i_last_distance_from_caster > MIN_QUIET_DISTANCE && cur_dist_xyz < MIN_QUIET_DISTANCE)) + // if we leave 'quiet zone' { // we are very far or too close, stopping i_to_distance_from_caster = 0.0f; - i_nextCheckTime.Reset(urand(500,1000)); + i_nextCheckTime.Reset(urand(500, 1000)); return false; } else @@ -248,35 +248,35 @@ bool FleeingMovementGenerator::_setMoveData(T* owner) } // if we too close may use 'path-finding' else just stop - i_only_forward = cur_dist >= MIN_QUIET_DISTANCE/3; + i_only_forward = cur_dist >= MIN_QUIET_DISTANCE / 3; //get angle and 'distance from caster' to run float angle; if (i_cur_angle == 0.0f && i_last_distance_from_caster == 0.0f) //just started, first time { - angle = (float)rand_norm()*(1.0f - cur_dist/MIN_QUIET_DISTANCE) * static_cast(M_PI/3) + (float)rand_norm()*static_cast(M_PI*2/3); + angle = (float)rand_norm() * (1.0f - cur_dist / MIN_QUIET_DISTANCE) * static_cast(M_PI / 3) + (float)rand_norm() * static_cast(M_PI * 2 / 3); i_to_distance_from_caster = MIN_QUIET_DISTANCE; i_only_forward = true; } else if (cur_dist < MIN_QUIET_DISTANCE) { - angle = static_cast(M_PI/6) + (float)rand_norm()*static_cast(M_PI*2/3); - i_to_distance_from_caster = cur_dist*2/3 + (float)rand_norm()*(MIN_QUIET_DISTANCE - cur_dist*2/3); + angle = static_cast(M_PI / 6) + (float)rand_norm() * static_cast(M_PI * 2 / 3); + i_to_distance_from_caster = cur_dist * 2 / 3 + (float)rand_norm() * (MIN_QUIET_DISTANCE - cur_dist * 2 / 3); } else if (cur_dist > MAX_QUIET_DISTANCE) { - angle = (float)rand_norm()*static_cast(M_PI/3) + static_cast(M_PI*2/3); - i_to_distance_from_caster = MIN_QUIET_DISTANCE + 2.5f + (float)rand_norm()*(MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE - 2.5f); + angle = (float)rand_norm() * static_cast(M_PI / 3) + static_cast(M_PI * 2 / 3); + i_to_distance_from_caster = MIN_QUIET_DISTANCE + 2.5f + (float)rand_norm() * (MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE - 2.5f); } else { - angle = (float)rand_norm()*static_cast(M_PI); - i_to_distance_from_caster = MIN_QUIET_DISTANCE + 2.5f + (float)rand_norm()*(MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE - 2.5f); + angle = (float)rand_norm() * static_cast(M_PI); + i_to_distance_from_caster = MIN_QUIET_DISTANCE + 2.5f + (float)rand_norm() * (MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE - 2.5f); } int8 sign = (float)rand_norm() > 0.5f ? 1 : -1; - i_cur_angle = sign*angle + angle_to_caster; + i_cur_angle = sign * angle + angle_to_caster; // current distance i_last_distance_from_caster = cur_dist; @@ -291,7 +291,7 @@ void FleeingMovementGenerator::DoInitialize(T* owner) return; owner->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); - owner->AddUnitState(UNIT_STATE_FLEEING|UNIT_STATE_FLEEING_MOVE); + owner->AddUnitState(UNIT_STATE_FLEEING | UNIT_STATE_FLEEING_MOVE); _Init(owner); @@ -337,14 +337,14 @@ template<> void FleeingMovementGenerator::DoFinalize(Player* owner) { owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); - owner->ClearUnitState(UNIT_STATE_FLEEING|UNIT_STATE_FLEEING_MOVE); + owner->ClearUnitState(UNIT_STATE_FLEEING | UNIT_STATE_FLEEING_MOVE); } template<> void FleeingMovementGenerator::DoFinalize(Creature* owner) { owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); - owner->ClearUnitState(UNIT_STATE_FLEEING|UNIT_STATE_FLEEING_MOVE); + owner->ClearUnitState(UNIT_STATE_FLEEING | UNIT_STATE_FLEEING_MOVE); if (owner->GetVictim()) owner->SetTarget(owner->GetVictim()->GetGUID()); } @@ -390,7 +390,7 @@ template bool FleeingMovementGenerator::DoUpdate(Creature*, uint32); void TimedFleeingMovementGenerator::Finalize(Unit* owner) { owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); - owner->ClearUnitState(UNIT_STATE_FLEEING|UNIT_STATE_FLEEING_MOVE); + owner->ClearUnitState(UNIT_STATE_FLEEING | UNIT_STATE_FLEEING_MOVE); if (owner->GetVictim()) owner->SetTarget(owner->GetVictim()->GetGUID()); } diff --git a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.h b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.h index 429b9c7c7..42a570389 100644 --- a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.h @@ -12,49 +12,49 @@ template class FleeingMovementGenerator : public MovementGeneratorMedium< T, FleeingMovementGenerator > { - public: - FleeingMovementGenerator(uint64 fright) : i_frightGUID(fright), i_nextCheckTime(0) {} +public: + FleeingMovementGenerator(uint64 fright) : i_frightGUID(fright), i_nextCheckTime(0) {} - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - bool DoUpdate(T*, uint32); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + bool DoUpdate(T*, uint32); - MovementGeneratorType GetMovementGeneratorType() { return FLEEING_MOTION_TYPE; } + MovementGeneratorType GetMovementGeneratorType() { return FLEEING_MOTION_TYPE; } - private: - void _setTargetLocation(T*); - bool _getPoint(T*, float &x, float &y, float &z); - bool _setMoveData(T* owner); - void _Init(T* ); +private: + void _setTargetLocation(T*); + bool _getPoint(T*, float& x, float& y, float& z); + bool _setMoveData(T* owner); + void _Init(T* ); - bool is_water_ok :1; - bool is_land_ok :1; - bool i_only_forward:1; + bool is_water_ok : 1; + bool is_land_ok : 1; + bool i_only_forward: 1; - float i_caster_x; - float i_caster_y; - float i_caster_z; - float i_last_distance_from_caster; - float i_to_distance_from_caster; - float i_cur_angle; - uint64 i_frightGUID; - TimeTracker i_nextCheckTime; + float i_caster_x; + float i_caster_y; + float i_caster_z; + float i_last_distance_from_caster; + float i_to_distance_from_caster; + float i_cur_angle; + uint64 i_frightGUID; + TimeTracker i_nextCheckTime; }; class TimedFleeingMovementGenerator : public FleeingMovementGenerator { - public: - TimedFleeingMovementGenerator(uint64 fright, uint32 time) : - FleeingMovementGenerator(fright), - i_totalFleeTime(time) {} +public: + TimedFleeingMovementGenerator(uint64 fright, uint32 time) : + FleeingMovementGenerator(fright), + i_totalFleeTime(time) {} - MovementGeneratorType GetMovementGeneratorType() { return TIMED_FLEEING_MOTION_TYPE; } - bool Update(Unit*, uint32); - void Finalize(Unit*); + MovementGeneratorType GetMovementGeneratorType() { return TIMED_FLEEING_MOTION_TYPE; } + bool Update(Unit*, uint32); + void Finalize(Unit*); - private: - TimeTracker i_totalFleeTime; +private: + TimeTracker i_totalFleeTime; }; #endif diff --git a/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.h b/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.h index 7750a85ea..779aa1a1e 100644 --- a/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.h @@ -17,21 +17,21 @@ class HomeMovementGenerator; template <> class HomeMovementGenerator : public MovementGeneratorMedium< Creature, HomeMovementGenerator > { - public: +public: - HomeMovementGenerator() : arrived(false), i_recalculateTravel(false) {} - ~HomeMovementGenerator() {} + HomeMovementGenerator() : arrived(false), i_recalculateTravel(false) {} + ~HomeMovementGenerator() {} - void DoInitialize(Creature*); - void DoFinalize(Creature*); - void DoReset(Creature*); - bool DoUpdate(Creature*, const uint32); - MovementGeneratorType GetMovementGeneratorType() { return HOME_MOTION_TYPE; } - void unitSpeedChanged() { i_recalculateTravel = true; } + void DoInitialize(Creature*); + void DoFinalize(Creature*); + void DoReset(Creature*); + bool DoUpdate(Creature*, const uint32); + MovementGeneratorType GetMovementGeneratorType() { return HOME_MOTION_TYPE; } + void unitSpeedChanged() { i_recalculateTravel = true; } - private: - void _setTargetLocation(Creature*); - bool arrived : 1; - bool i_recalculateTravel : 1; +private: + void _setTargetLocation(Creature*); + bool arrived : 1; + bool i_recalculateTravel : 1; }; #endif diff --git a/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.cpp index 164749289..5469bcd7a 100644 --- a/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.cpp @@ -64,7 +64,7 @@ void RotateMovementGenerator::Finalize(Unit* unit) { unit->ClearUnitState(UNIT_STATE_ROTATING); if (unit->GetTypeId() == TYPEID_UNIT) - unit->ToCreature()->AI()->MovementInform(ROTATE_MOTION_TYPE, 0); + unit->ToCreature()->AI()->MovementInform(ROTATE_MOTION_TYPE, 0); } void DistractMovementGenerator::Initialize(Unit* owner) diff --git a/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h b/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h index 6968e2dc5..45ece45f0 100644 --- a/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h @@ -11,56 +11,56 @@ class IdleMovementGenerator : public MovementGenerator { - public: +public: - void Initialize(Unit*); - void Finalize(Unit*) { } - void Reset(Unit*); - bool Update(Unit*, uint32) { return true; } - MovementGeneratorType GetMovementGeneratorType() { return IDLE_MOTION_TYPE; } + void Initialize(Unit*); + void Finalize(Unit*) { } + void Reset(Unit*); + bool Update(Unit*, uint32) { return true; } + MovementGeneratorType GetMovementGeneratorType() { return IDLE_MOTION_TYPE; } }; extern IdleMovementGenerator si_idleMovement; class RotateMovementGenerator : public MovementGenerator { - public: - explicit RotateMovementGenerator(uint32 time, RotateDirection direction) : m_duration(time), m_maxDuration(time), m_direction(direction) {} +public: + explicit RotateMovementGenerator(uint32 time, RotateDirection direction) : m_duration(time), m_maxDuration(time), m_direction(direction) {} - void Initialize(Unit*); - void Finalize(Unit*); - void Reset(Unit* owner) { Initialize(owner); } - bool Update(Unit*, uint32); - MovementGeneratorType GetMovementGeneratorType() { return ROTATE_MOTION_TYPE; } + void Initialize(Unit*); + void Finalize(Unit*); + void Reset(Unit* owner) { Initialize(owner); } + bool Update(Unit*, uint32); + MovementGeneratorType GetMovementGeneratorType() { return ROTATE_MOTION_TYPE; } - private: - uint32 m_duration, m_maxDuration; - RotateDirection m_direction; +private: + uint32 m_duration, m_maxDuration; + RotateDirection m_direction; }; class DistractMovementGenerator : public MovementGenerator { - public: - explicit DistractMovementGenerator(uint32 timer) : m_timer(timer) {} +public: + explicit DistractMovementGenerator(uint32 timer) : m_timer(timer) {} - void Initialize(Unit*); - void Finalize(Unit*); - void Reset(Unit* owner) { Initialize(owner); } - bool Update(Unit*, uint32); - MovementGeneratorType GetMovementGeneratorType() { return DISTRACT_MOTION_TYPE; } + void Initialize(Unit*); + void Finalize(Unit*); + void Reset(Unit* owner) { Initialize(owner); } + bool Update(Unit*, uint32); + MovementGeneratorType GetMovementGeneratorType() { return DISTRACT_MOTION_TYPE; } - private: - uint32 m_timer; +private: + uint32 m_timer; }; class AssistanceDistractMovementGenerator : public DistractMovementGenerator { - public: - AssistanceDistractMovementGenerator(uint32 timer) : - DistractMovementGenerator(timer) {} +public: + AssistanceDistractMovementGenerator(uint32 timer) : + DistractMovementGenerator(timer) {} - MovementGeneratorType GetMovementGeneratorType() { return ASSISTANCE_DISTRACT_MOTION_TYPE; } - void Finalize(Unit*); + MovementGeneratorType GetMovementGeneratorType() { return ASSISTANCE_DISTRACT_MOTION_TYPE; } + void Finalize(Unit*); }; #endif diff --git a/src/server/game/Movement/MovementGenerators/PathGenerator.cpp b/src/server/game/Movement/MovementGenerators/PathGenerator.cpp index 2a2a8dc8c..918a66448 100644 --- a/src/server/game/Movement/MovementGenerators/PathGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/PathGenerator.cpp @@ -57,7 +57,9 @@ bool PathGenerator::CalculatePath(float destX, float destY, float destZ, bool fo if (!_sourceUnit->movespline->Finalized() && _sourceUnit->movespline->Initialized()) { Movement::Location realpos = _sourceUnit->movespline->ComputePosition(); - x = realpos.x; y = realpos.y; z = realpos.z; + x = realpos.x; + y = realpos.y; + z = realpos.z; } else _sourceUnit->GetPosition(x, y, z); @@ -91,8 +93,8 @@ bool PathGenerator::CalculatePath(float destX, float destY, float destZ, bool fo // make sure navMesh works - we can run on map w/o mmap // check if the start and end point have a .mmtile loaded (can we pass via not loaded tile on the way?) if (!_navMesh || !_navMeshQuery || _sourceUnit->HasUnitState(UNIT_STATE_IGNORE_PATHFINDING) || - _sourceUnit->GetObjectSize() >= SIZE_OF_GRIDS/2.0f || _sourceUnit->GetExactDistSq(destX, destY, destZ) >= (SIZE_OF_GRIDS*SIZE_OF_GRIDS/4.0f) || - !HaveTile(start) || !HaveTile(dest)) + _sourceUnit->GetObjectSize() >= SIZE_OF_GRIDS / 2.0f || _sourceUnit->GetExactDistSq(destX, destY, destZ) >= (SIZE_OF_GRIDS * SIZE_OF_GRIDS / 4.0f) || + !HaveTile(start) || !HaveTile(dest)) { BuildShortcut(); _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); @@ -114,8 +116,8 @@ dtPolyRef PathGenerator::GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 { if (DT_SUCCESS != _navMeshQuery->getPolyHeight(polyPath[i], point, &polyHeight)) continue; - height = point[1]-polyHeight; - if (height > 0.0f && height < ALLOWED_DIST_FROM_POLY+ADDED_Z_FOR_POLY_LOOKUP) + height = point[1] - polyHeight; + if (height > 0.0f && height < ALLOWED_DIST_FROM_POLY + ADDED_Z_FOR_POLY_LOOKUP) { if (distance) *distance = height; @@ -164,7 +166,7 @@ dtPolyRef PathGenerator::GetPolyByLocation(float* point, float* distance) const return INVALID_POLYREF; } -G3D::Vector3 ClosestPointOnLine(const G3D::Vector3 & a, const G3D::Vector3 & b, const G3D::Vector3 & Point) +G3D::Vector3 ClosestPointOnLine(const G3D::Vector3& a, const G3D::Vector3& b, const G3D::Vector3& Point) { G3D::Vector3 c = Point - a; // Vector from a to Point G3D::Vector3 v = (b - a).unit(); // Unit Vector from a to b @@ -199,277 +201,306 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con bool cutToFirstHigher = false; { - MutexReleaser mutexReleaser(mmapLock); + MutexReleaser mutexReleaser(mmapLock); - // *** getting start/end poly logic *** + // *** getting start/end poly logic *** - float distToStartPoly, distToEndPoly; - float startPoint[VERTEX_SIZE] = {startPos.y, startPos.z, startPos.x}; - float endPoint[VERTEX_SIZE] = {endPos.y, endPos.z, endPos.x}; + float distToStartPoly, distToEndPoly; + float startPoint[VERTEX_SIZE] = {startPos.y, startPos.z, startPos.x}; + float endPoint[VERTEX_SIZE] = {endPos.y, endPos.z, endPos.x}; - dtPolyRef startPoly = GetPolyByLocation(startPoint, &distToStartPoly); - dtPolyRef endPoly = GetPolyByLocation(endPoint, &distToEndPoly); + dtPolyRef startPoly = GetPolyByLocation(startPoint, &distToStartPoly); + dtPolyRef endPoly = GetPolyByLocation(endPoint, &distToEndPoly); - bool sourceIsFlying = (_sourceUnit->GetUnitMovementFlags() & (MOVEMENTFLAG_CAN_FLY|MOVEMENTFLAG_FLYING)) || (_sourceUnit->HasUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY) && !_sourceUnit->HasUnitMovementFlag(MOVEMENTFLAG_SWIMMING)) || (_sourceUnit->GetTypeId() == TYPEID_UNIT && ((Creature*)_sourceUnit)->CanFly()); - bool sourceCanSwim = _sourceUnit->GetTypeId() == TYPEID_UNIT ? _sourceUnit->ToCreature()->CanSwim() : true; - bool sourceCanWalk = _sourceUnit->GetTypeId() == TYPEID_UNIT ? _sourceUnit->ToCreature()->CanWalk() : true; + bool sourceIsFlying = (_sourceUnit->GetUnitMovementFlags() & (MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING)) || (_sourceUnit->HasUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY) && !_sourceUnit->HasUnitMovementFlag(MOVEMENTFLAG_SWIMMING)) || (_sourceUnit->GetTypeId() == TYPEID_UNIT && ((Creature*)_sourceUnit)->CanFly()); + bool sourceCanSwim = _sourceUnit->GetTypeId() == TYPEID_UNIT ? _sourceUnit->ToCreature()->CanSwim() : true; + bool sourceCanWalk = _sourceUnit->GetTypeId() == TYPEID_UNIT ? _sourceUnit->ToCreature()->CanWalk() : true; - // we have a hole in our mesh - // make shortcut path and mark it as NOPATH ( with flying and swimming exception ) - // its up to caller how he will use this info - if (startPoly == INVALID_POLYREF || endPoly == INVALID_POLYREF) - { - BuildShortcut(); - if (sourceIsFlying) - { - _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); - return; - } - if (sourceCanSwim) - { - if ((startPoly == INVALID_POLYREF && LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(startPos.x, startPos.y, startPos.z, MAP_ALL_LIQUIDS, nullptr)) || - (endPoly == INVALID_POLYREF && LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr))) - { - _type = PATHFIND_NOPATH; - return; - } - _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); - return; - } - _type = PATHFIND_NOPATH; - return; - } - - // we may need a better number here - bool farFromStartPoly = (distToStartPoly > ALLOWED_DIST_FROM_POLY); - bool farFromEndPoly = (distToEndPoly > ALLOWED_DIST_FROM_POLY); - if (farFromStartPoly) - { - if (sourceIsFlying) + // we have a hole in our mesh + // make shortcut path and mark it as NOPATH ( with flying and swimming exception ) + // its up to caller how he will use this info + if (startPoly == INVALID_POLYREF || endPoly == INVALID_POLYREF) { BuildShortcut(); - _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); - return; - } - if (sourceCanSwim) - { - if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(startPos.x, startPos.y, startPos.z, MAP_ALL_LIQUIDS, nullptr)) + if (sourceIsFlying) { - if (distToStartPoly > MAX_FIXABLE_Z_ERROR) + _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + return; + } + if (sourceCanSwim) + { + if ((startPoly == INVALID_POLYREF && LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(startPos.x, startPos.y, startPos.z, MAP_ALL_LIQUIDS, nullptr)) || + (endPoly == INVALID_POLYREF && LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr))) { - BuildShortcut(); _type = PATHFIND_NOPATH; return; } + _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + return; + } + _type = PATHFIND_NOPATH; + return; + } - if (farFromEndPoly) + // we may need a better number here + bool farFromStartPoly = (distToStartPoly > ALLOWED_DIST_FROM_POLY); + bool farFromEndPoly = (distToEndPoly > ALLOWED_DIST_FROM_POLY); + if (farFromStartPoly) + { + if (sourceIsFlying) + { + BuildShortcut(); + _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + return; + } + if (sourceCanSwim) + { + if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(startPos.x, startPos.y, startPos.z, MAP_ALL_LIQUIDS, nullptr)) { - if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr)) + if (distToStartPoly > MAX_FIXABLE_Z_ERROR) { BuildShortcut(); _type = PATHFIND_NOPATH; return; } + + if (farFromEndPoly) + { + if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr)) + { + BuildShortcut(); + _type = PATHFIND_NOPATH; + return; + } + } + } + else if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr)) + { + if (farFromEndPoly) + { + BuildShortcut(); + _type = PATHFIND_NOPATH; + return; + } + + cutToFirstHigher = true; + } + else // starting and ending points are in water + { + BuildShortcut(); + _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + return; } } - else if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr)) + else { - if (farFromEndPoly) + if (distToStartPoly > MAX_FIXABLE_Z_ERROR || farFromEndPoly) + { + BuildShortcut(); + _type = PATHFIND_NOPATH; + return; + } + } + } + else if (farFromEndPoly) + { + if (sourceIsFlying) + { + BuildShortcut(); + _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + return; + } + if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr)) + { + if (!sourceCanWalk) + { + BuildShortcut(); + _type = PATHFIND_NOPATH; + return; + } + } + else + { + if (!sourceCanSwim) { BuildShortcut(); _type = PATHFIND_NOPATH; return; } - cutToFirstHigher = true; + // if both points are in water + if (LIQUID_MAP_NO_WATER != _sourceUnit->GetBaseMap()->getLiquidStatus(startPos.x, startPos.y, startPos.z, MAP_ALL_LIQUIDS, nullptr)) + { + BuildShortcut(); + _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + return; + } + + endInWaterFar = true; } - else // starting and ending points are in water + + if (startPoly != endPoly || !endInWaterFar) { - BuildShortcut(); - _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); - return; + float closestPoint[VERTEX_SIZE]; + if (dtStatusSucceed(_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint, nullptr))) + { + dtVcopy(endPoint, closestPoint); + SetActualEndPosition(G3D::Vector3(endPoint[2], endPoint[0], endPoint[1])); + } + _type = PATHFIND_INCOMPLETE; } } - else - { - if (distToStartPoly > MAX_FIXABLE_Z_ERROR || farFromEndPoly) - { - BuildShortcut(); - _type = PATHFIND_NOPATH; - return; - } - } - } - else if (farFromEndPoly) - { - if (sourceIsFlying) + + // *** poly path generating logic *** + + if (startPoly == endPoly) { BuildShortcut(); - _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); + _type = !farFromEndPoly || endInWaterFar ? PATHFIND_NORMAL : PATHFIND_INCOMPLETE; + _pathPolyRefs[0] = startPoly; + _polyLength = 1; return; } - if (LIQUID_MAP_NO_WATER == _sourceUnit->GetBaseMap()->getLiquidStatus(endPos.x, endPos.y, endPos.z, MAP_ALL_LIQUIDS, nullptr)) + + // look for startPoly/endPoly in current path + /// @todo we can merge it with getPathPolyByPosition() loop + bool startPolyFound = false; + bool endPolyFound = false; + uint32 pathStartIndex = 0; + uint32 pathEndIndex = 0; + + if (_polyLength) { - if (!sourceCanWalk) + for (; pathStartIndex < _polyLength; ++pathStartIndex) { - BuildShortcut(); - _type = PATHFIND_NOPATH; - return; - } - } - else - { - if (!sourceCanSwim) - { - BuildShortcut(); - _type = PATHFIND_NOPATH; - return; + // here to catch few bugs + ASSERT(_pathPolyRefs[pathStartIndex] != INVALID_POLYREF); + + if (_pathPolyRefs[pathStartIndex] == startPoly) + { + startPolyFound = true; + break; + } } - // if both points are in water - if (LIQUID_MAP_NO_WATER != _sourceUnit->GetBaseMap()->getLiquidStatus(startPos.x, startPos.y, startPos.z, MAP_ALL_LIQUIDS, nullptr)) - { - BuildShortcut(); - _type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); - return; - } - - endInWaterFar = true; + for (pathEndIndex = _polyLength - 1; pathEndIndex > pathStartIndex; --pathEndIndex) + if (_pathPolyRefs[pathEndIndex] == endPoly) + { + endPolyFound = true; + break; + } } - if (startPoly != endPoly || !endInWaterFar) + if (startPolyFound && endPolyFound) { - float closestPoint[VERTEX_SIZE]; - if (dtStatusSucceed(_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint, nullptr))) - { - dtVcopy(endPoint, closestPoint); - SetActualEndPosition(G3D::Vector3(endPoint[2], endPoint[0], endPoint[1])); - } - _type = PATHFIND_INCOMPLETE; + _polyLength = pathEndIndex - pathStartIndex + 1; + memmove(_pathPolyRefs, _pathPolyRefs + pathStartIndex, _polyLength * sizeof(dtPolyRef)); } - } - - // *** poly path generating logic *** - - if (startPoly == endPoly) - { - BuildShortcut(); - _type = !farFromEndPoly || endInWaterFar ? PATHFIND_NORMAL : PATHFIND_INCOMPLETE; - _pathPolyRefs[0] = startPoly; - _polyLength = 1; - return; - } - - // look for startPoly/endPoly in current path - /// @todo we can merge it with getPathPolyByPosition() loop - bool startPolyFound = false; - bool endPolyFound = false; - uint32 pathStartIndex = 0; - uint32 pathEndIndex = 0; - - if (_polyLength) - { - for (; pathStartIndex < _polyLength; ++pathStartIndex) + else if (startPolyFound && !endPolyFound && _polyLength - pathStartIndex >= 3 /*if (>=3) then 70% will return at least one more than just startPoly*/) { - // here to catch few bugs - ASSERT(_pathPolyRefs[pathStartIndex] != INVALID_POLYREF); + // we are moving on the old path but target moved out + // so we have atleast part of poly-path ready - if (_pathPolyRefs[pathStartIndex] == startPoly) + _polyLength -= pathStartIndex; + + // try to adjust the suffix of the path instead of recalculating entire length + // at given interval the target cannot get too far from its last location + // thus we have less poly to cover + // sub-path of optimal path is optimal + + // take ~65% of the original length + /// @todo play with the values here + uint32 prefixPolyLength = uint32(_polyLength * 0.7f + 0.5f); // this should be always >= 1 + memmove(_pathPolyRefs, _pathPolyRefs + pathStartIndex, prefixPolyLength * sizeof(dtPolyRef)); + + dtPolyRef suffixStartPoly = _pathPolyRefs[prefixPolyLength - 1]; + + bool error = false; // can't use a part of old path, generate whole new + + // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data + float suffixEndPoint[VERTEX_SIZE]; + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, nullptr))) { - startPolyFound = true; - break; - } - } - - for (pathEndIndex = _polyLength-1; pathEndIndex > pathStartIndex; --pathEndIndex) - if (_pathPolyRefs[pathEndIndex] == endPoly) - { - endPolyFound = true; - break; - } - } - - if (startPolyFound && endPolyFound) - { - _polyLength = pathEndIndex - pathStartIndex + 1; - memmove(_pathPolyRefs, _pathPolyRefs + pathStartIndex, _polyLength * sizeof(dtPolyRef)); - } - else if (startPolyFound && !endPolyFound && _polyLength-pathStartIndex >= 3 /*if (>=3) then 70% will return at least one more than just startPoly*/) - { - // we are moving on the old path but target moved out - // so we have atleast part of poly-path ready - - _polyLength -= pathStartIndex; - - // try to adjust the suffix of the path instead of recalculating entire length - // at given interval the target cannot get too far from its last location - // thus we have less poly to cover - // sub-path of optimal path is optimal - - // take ~65% of the original length - /// @todo play with the values here - uint32 prefixPolyLength = uint32(_polyLength * 0.7f + 0.5f); // this should be always >= 1 - memmove(_pathPolyRefs, _pathPolyRefs+pathStartIndex, prefixPolyLength * sizeof(dtPolyRef)); - - dtPolyRef suffixStartPoly = _pathPolyRefs[prefixPolyLength-1]; - - bool error = false; // can't use a part of old path, generate whole new - - // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data - float suffixEndPoint[VERTEX_SIZE]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, nullptr))) - { - // we can hit offmesh connection as last poly - closestPointOnPoly() don't like that - // try to recover by using prev polyref - --prefixPolyLength; - if (prefixPolyLength) - { - suffixStartPoly = _pathPolyRefs[prefixPolyLength-1]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint,NULL))) + // we can hit offmesh connection as last poly - closestPointOnPoly() don't like that + // try to recover by using prev polyref + --prefixPolyLength; + if (prefixPolyLength) + { + suffixStartPoly = _pathPolyRefs[prefixPolyLength - 1]; + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, NULL))) + error = true; + } + else error = true; } - else - error = true; - } - if (!error) - { - // generate suffix - uint32 suffixPolyLength = 0; - dtStatus dtResult = _navMeshQuery->findPath( - suffixStartPoly, // start polygon - endPoly, // end polygon - suffixEndPoint, // start position - endPoint, // end position - &_filter, // polygon search filter - _pathPolyRefs + prefixPolyLength - 1, // [out] path - (int*)&suffixPolyLength, - MAX_PATH_LENGTH-prefixPolyLength); // max number of polygons in output path - - if (!_polyLength || dtStatusFailed(dtResult)) + if (!error) { - // this is probably an error state, but we'll leave it - // and hopefully recover on the next Update - // we still need to copy our preffix - } + // generate suffix + uint32 suffixPolyLength = 0; + dtStatus dtResult = _navMeshQuery->findPath( + suffixStartPoly, // start polygon + endPoly, // end polygon + suffixEndPoint, // start position + endPoint, // end position + &_filter, // polygon search filter + _pathPolyRefs + prefixPolyLength - 1, // [out] path + (int*)&suffixPolyLength, + MAX_PATH_LENGTH - prefixPolyLength); // max number of polygons in output path - // new path = prefix + suffix - overlap - _polyLength = prefixPolyLength + suffixPolyLength - 1; + if (!_polyLength || dtStatusFailed(dtResult)) + { + // this is probably an error state, but we'll leave it + // and hopefully recover on the next Update + // we still need to copy our preffix + } + + // new path = prefix + suffix - overlap + _polyLength = prefixPolyLength + suffixPolyLength - 1; + } + else + { + // free and invalidate old path data + Clear(); + + dtStatus dtResult = _navMeshQuery->findPath( + startPoly, // start polygon + endPoly, // end polygon + startPoint, // start position + endPoint, // end position + &_filter, // polygon search filter + _pathPolyRefs, // [out] path + (int*)&_polyLength, + MAX_PATH_LENGTH); // max number of polygons in output path + + if (!_polyLength || dtStatusFailed(dtResult)) + { + // only happens if we passed bad data to findPath(), or navmesh is messed up + BuildShortcut(); + _type = PATHFIND_NOPATH; + return; + } + } } else { + // either we have no path at all -> first run + // or something went really wrong -> we aren't moving along the path to the target + // pussywizard: or knocked back away from our path, nothing special + // just generate new path + // free and invalidate old path data Clear(); dtStatus dtResult = _navMeshQuery->findPath( - startPoly, // start polygon - endPoly, // end polygon - startPoint, // start position - endPoint, // end position - &_filter, // polygon search filter - _pathPolyRefs, // [out] path - (int*)&_polyLength, - MAX_PATH_LENGTH); // max number of polygons in output path + startPoly, // start polygon + endPoly, // end polygon + startPoint, // start position + endPoint, // end position + &_filter, // polygon search filter + _pathPolyRefs, // [out] path + (int*)&_polyLength, + MAX_PATH_LENGTH); // max number of polygons in output path if (!_polyLength || dtStatusFailed(dtResult)) { @@ -479,46 +510,17 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con return; } } - } - else - { - // either we have no path at all -> first run - // or something went really wrong -> we aren't moving along the path to the target - // pussywizard: or knocked back away from our path, nothing special - // just generate new path - // free and invalidate old path data - Clear(); + // by now we know what type of path we can get + if (_pathPolyRefs[_polyLength - 1] == endPoly && !(_type & PATHFIND_INCOMPLETE)) + _type = PATHFIND_NORMAL; + else + _type = PATHFIND_INCOMPLETE; - dtStatus dtResult = _navMeshQuery->findPath( - startPoly, // start polygon - endPoly, // end polygon - startPoint, // start position - endPoint, // end position - &_filter, // polygon search filter - _pathPolyRefs, // [out] path - (int*)&_polyLength, - MAX_PATH_LENGTH); // max number of polygons in output path + // generate the point-path out of our up-to-date poly-path + BuildPointPath(startPoint, endPoint); - if (!_polyLength || dtStatusFailed(dtResult)) - { - // only happens if we passed bad data to findPath(), or navmesh is messed up - BuildShortcut(); - _type = PATHFIND_NOPATH; - return; - } - } - - // by now we know what type of path we can get - if (_pathPolyRefs[_polyLength - 1] == endPoly && !(_type & PATHFIND_INCOMPLETE)) - _type = PATHFIND_NORMAL; - else - _type = PATHFIND_INCOMPLETE; - - // generate the point-path out of our up-to-date poly-path - BuildPointPath(startPoint, endPoint); - - // pussywizard: no mmap usage below, release mutex + // pussywizard: no mmap usage below, release mutex } // end of scope (mutex released in object destructor) if (_type == PATHFIND_NORMAL && cutToFirstHigher) // starting in water, far from bottom, target is on the ground (above starting Z) -> update beginning points that are lower than starting Z @@ -526,17 +528,17 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con uint32 i = 0; uint32 size = _pathPoints.size(); for (; i < size; ++i) - if (_pathPoints[i].z >= _sourceUnit->GetPositionZ()+0.1f) + if (_pathPoints[i].z >= _sourceUnit->GetPositionZ() + 0.1f) break; - if (i && i != size && LIQUID_MAP_NO_WATER != _sourceUnit->GetBaseMap()->getLiquidStatus(_pathPoints[i-1].x, _pathPoints[i-1].y, _pathPoints[i-1].z, MAP_ALL_LIQUIDS, nullptr)) - for (uint32 j=0; jGetBaseMap()->getLiquidStatus(_pathPoints[i - 1].x, _pathPoints[i - 1].y, _pathPoints[i - 1].z, MAP_ALL_LIQUIDS, nullptr)) + for (uint32 j = 0; j < i; ++j) _pathPoints[j].z = _sourceUnit->GetPositionZ(); } if (!_forceDestination) if (uint32 lastIdx = _pathPoints.size()) { - lastIdx = lastIdx-1; + lastIdx = lastIdx - 1; if (endInWaterFar) { SetActualEndPosition(GetEndPosition()); @@ -563,14 +565,14 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con if (i < size) { ok = true; - if ((_pathPoints[i] - _pathPoints[0]).squaredLength() > 15.0f*15.0f) + if ((_pathPoints[i] - _pathPoints[0]).squaredLength() > 15.0f * 15.0f) ok = false; else for (uint32 j = 1; j < i; ++j) { float sqDist = (_pathPoints[j] - ClosestPointOnLine(_pathPoints[0], _pathPoints[i], _pathPoints[j])).squaredLength(); float oSize = _sourceUnit->GetObjectSize(); - if (sqDist > 1.0f*1.0f || sqDist > oSize*oSize) + if (sqDist > 1.0f * 1.0f || sqDist > oSize * oSize) { ok = false; break; @@ -584,21 +586,21 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con { // pussywizard: check additional 3 quarter points after last fitting poly point - G3D::Vector3 dir = _pathPoints[i] - _pathPoints[i-1]; - G3D::Vector3 increment = (dir.length()/4.0f) * dir.unit(); + G3D::Vector3 dir = _pathPoints[i] - _pathPoints[i - 1]; + G3D::Vector3 increment = (dir.length() / 4.0f) * dir.unit(); for (uint8 k = 3; k > 0; --k) { - G3D::Vector3 newPoint = _pathPoints[i-1] + ((float)k)*increment; + G3D::Vector3 newPoint = _pathPoints[i - 1] + ((float)k) * increment; bool ok2 = true; - if ((newPoint - _pathPoints[0]).squaredLength() > 15.0f*15.0f) + if ((newPoint - _pathPoints[0]).squaredLength() > 15.0f * 15.0f) ok2 = false; else for (uint32 j = 1; j < i; ++j) { float sqDist = (_pathPoints[j] - ClosestPointOnLine(_pathPoints[0], newPoint, _pathPoints[j])).squaredLength(); float oSize = _sourceUnit->GetObjectSize(); - if (sqDist > 1.0f*1.0f || sqDist > oSize*oSize) + if (sqDist > 1.0f * 1.0f || sqDist > oSize * oSize) { ok2 = false; break; @@ -607,20 +609,20 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con if (ok2) { - _pathPoints[i-1] = newPoint; + _pathPoints[i - 1] = newPoint; break; } } // pussywizard: memmove crashes o_O // memmove(&_pathPoints + sizeof(G3D::Vector3), &_pathPoints + (i-1)*sizeof(G3D::Vector3), (size-i+1)*sizeof(G3D::Vector3)); - for (uint8 k = 1; k <= size-i+1; ++k) - _pathPoints[k] = _pathPoints[k+i-2]; - _pathPoints.resize(size-i+2); + for (uint8 k = 1; k <= size - i + 1; ++k) + _pathPoints[k] = _pathPoints[k + i - 2]; + _pathPoints.resize(size - i + 2); } else if (size > 2) { - _pathPoints[1] = _pathPoints[size-1]; + _pathPoints[1] = _pathPoints[size - 1]; _pathPoints.resize(2); } @@ -629,34 +631,34 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con } } -void PathGenerator::BuildPointPath(const float *startPoint, const float *endPoint) +void PathGenerator::BuildPointPath(const float* startPoint, const float* endPoint) { - float pathPoints[MAX_POINT_PATH_LENGTH*VERTEX_SIZE]; + float pathPoints[MAX_POINT_PATH_LENGTH * VERTEX_SIZE]; uint32 pointCount = 0; dtStatus dtResult = DT_FAILURE; if (_useStraightPath) { dtResult = _navMeshQuery->findStraightPath( - startPoint, // start position - endPoint, // end position - _pathPolyRefs, // current path - _polyLength, // lenth of current path - pathPoints, // [out] path corner points - NULL, // [out] flags - NULL, // [out] shortened path - (int*)&pointCount, - _pointPathLimit); // maximum number of points/polygons to use + startPoint, // start position + endPoint, // end position + _pathPolyRefs, // current path + _polyLength, // lenth of current path + pathPoints, // [out] path corner points + NULL, // [out] flags + NULL, // [out] shortened path + (int*)&pointCount, + _pointPathLimit); // maximum number of points/polygons to use } else { dtResult = FindSmoothPath( - startPoint, // start position - endPoint, // end position - _pathPolyRefs, // current path - _polyLength, // length of current path - pathPoints, // [out] path corner points - (int*)&pointCount, - _pointPathLimit); // maximum number of points + startPoint, // start position + endPoint, // end position + _pathPolyRefs, // current path + _polyLength, // length of current path + pathPoints, // [out] path corner points + (int*)&pointCount, + _pointPathLimit); // maximum number of points } if (pointCount < 2 || dtStatusFailed(dtResult)) @@ -677,10 +679,10 @@ void PathGenerator::BuildPointPath(const float *startPoint, const float *endPoin _pathPoints.resize(pointCount); for (uint32 i = 0; i < pointCount; ++i) - _pathPoints[i] = G3D::Vector3(pathPoints[i*VERTEX_SIZE+2], pathPoints[i*VERTEX_SIZE], pathPoints[i*VERTEX_SIZE+1]); + _pathPoints[i] = G3D::Vector3(pathPoints[i * VERTEX_SIZE + 2], pathPoints[i * VERTEX_SIZE], pathPoints[i * VERTEX_SIZE + 1]); // first point is always our current location - we need the next one - SetActualEndPosition(_pathPoints[pointCount-1]); + SetActualEndPosition(_pathPoints[pointCount - 1]); if (_forceDestination && (!(_type & PATHFIND_NORMAL) || !InRange(GetEndPosition(), GetActualEndPosition(), 0.75f, 0.75f))) { @@ -688,7 +690,7 @@ void PathGenerator::BuildPointPath(const float *startPoint, const float *endPoin if (Dist3DSqr(GetActualEndPosition(), GetEndPosition()) < 0.33f * Dist3DSqr(GetStartPosition(), GetEndPosition())) { SetActualEndPosition(GetEndPosition()); - _pathPoints[_pathPoints.size()-1] = GetEndPosition(); + _pathPoints[_pathPoints.size() - 1] = GetEndPosition(); } else { @@ -794,10 +796,10 @@ uint32 PathGenerator::FixupCorridor(dtPolyRef* path, uint32 npath, uint32 maxPat int32 furthestVisited = -1; // Find furthest common polygon. - for (int32 i = npath-1; i >= 0; --i) + for (int32 i = npath - 1; i >= 0; --i) { bool found = false; - for (int32 j = nvisited-1; j >= 0; --j) + for (int32 j = nvisited - 1; j >= 0; --j) { if (path[i] == visited[j]) { @@ -821,7 +823,7 @@ uint32 PathGenerator::FixupCorridor(dtPolyRef* path, uint32 npath, uint32 maxPat uint32 orig = uint32(furthestPath + 1) < npath ? furthestPath + 1 : npath; uint32 size = npath > orig ? npath - orig : 0; if (req + size > maxPath) - size = maxPath-req; + size = maxPath - req; if (size) memmove(path + req, path + orig, size * sizeof(dtPolyRef)); @@ -830,21 +832,21 @@ uint32 PathGenerator::FixupCorridor(dtPolyRef* path, uint32 npath, uint32 maxPat for (uint32 i = 0; i < req; ++i) path[i] = visited[(nvisited - 1) - i]; - return req+size; + return req + size; } bool PathGenerator::GetSteerTarget(float const* startPos, float const* endPos, - float minTargetDist, dtPolyRef const* path, uint32 pathSize, - float* steerPos, unsigned char& steerPosFlag, dtPolyRef& steerPosRef) + float minTargetDist, dtPolyRef const* path, uint32 pathSize, + float* steerPos, unsigned char& steerPosFlag, dtPolyRef& steerPosRef) { // Find steer target. static const uint32 MAX_STEER_POINTS = 3; - float steerPath[MAX_STEER_POINTS*VERTEX_SIZE]; + float steerPath[MAX_STEER_POINTS * VERTEX_SIZE]; unsigned char steerPathFlags[MAX_STEER_POINTS]; dtPolyRef steerPathPolys[MAX_STEER_POINTS]; uint32 nsteerPath = 0; dtStatus dtResult = _navMeshQuery->findStraightPath(startPos, endPos, path, pathSize, - steerPath, steerPathFlags, steerPathPolys, (int*)&nsteerPath, MAX_STEER_POINTS); + steerPath, steerPathFlags, steerPathPolys, (int*)&nsteerPath, MAX_STEER_POINTS); if (!nsteerPath || dtStatusFailed(dtResult)) return false; @@ -854,7 +856,7 @@ bool PathGenerator::GetSteerTarget(float const* startPos, float const* endPos, { // Stop at Off-Mesh link or when point is further than slop away. if ((steerPathFlags[ns] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) || - !InRangeYZX(&steerPath[ns*VERTEX_SIZE], startPos, minTargetDist, 1000.0f)) + !InRangeYZX(&steerPath[ns * VERTEX_SIZE], startPos, minTargetDist, 1000.0f)) break; ns++; } @@ -862,7 +864,7 @@ bool PathGenerator::GetSteerTarget(float const* startPos, float const* endPos, if (ns >= nsteerPath) return false; - dtVcopy(steerPos, &steerPath[ns*VERTEX_SIZE]); + dtVcopy(steerPos, &steerPath[ns * VERTEX_SIZE]); steerPos[1] = startPos[1]; // keep Z value steerPosFlag = steerPathFlags[ns]; steerPosRef = steerPathPolys[ns]; @@ -871,8 +873,8 @@ bool PathGenerator::GetSteerTarget(float const* startPos, float const* endPos, } dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPos, - dtPolyRef const* polyPath, uint32 polyPathSize, - float* smoothPath, int* smoothPathSize, uint32 maxSmoothPathSize) + dtPolyRef const* polyPath, uint32 polyPathSize, + float* smoothPath, int* smoothPathSize, uint32 maxSmoothPathSize) { *smoothPathSize = 0; uint32 nsmoothPath = 0; @@ -885,10 +887,10 @@ dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPo if (DT_SUCCESS != _navMeshQuery->closestPointOnPolyBoundary(polys[0], startPos, iterPos)) return DT_FAILURE; - if (DT_SUCCESS != _navMeshQuery->closestPointOnPolyBoundary(polys[npolys-1], endPos, targetPos)) + if (DT_SUCCESS != _navMeshQuery->closestPointOnPolyBoundary(polys[npolys - 1], endPos, targetPos)) return DT_FAILURE; - dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); + dtVcopy(&smoothPath[nsmoothPath * VERTEX_SIZE], iterPos); nsmoothPath++; // Move towards target a small advancement at a time until target reached or @@ -939,7 +941,7 @@ dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPo dtVcopy(iterPos, targetPos); if (nsmoothPath < maxSmoothPathSize) { - dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); + dtVcopy(&smoothPath[nsmoothPath * VERTEX_SIZE], iterPos); nsmoothPath++; } break; @@ -958,7 +960,7 @@ dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPo } for (uint32 i = npos; i < npolys; ++i) - polys[i-npos] = polys[i]; + polys[i - npos] = polys[i]; npolys -= npos; @@ -968,7 +970,7 @@ dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPo { if (nsmoothPath < maxSmoothPathSize) { - dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], startPos); + dtVcopy(&smoothPath[nsmoothPath * VERTEX_SIZE], startPos); nsmoothPath++; } // Move position at the other side of the off-mesh link. @@ -981,7 +983,7 @@ dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPo // Store results. if (nsmoothPath < maxSmoothPathSize) { - dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); + dtVcopy(&smoothPath[nsmoothPath * VERTEX_SIZE], iterPos); nsmoothPath++; } } diff --git a/src/server/game/Movement/MovementGenerators/PathGenerator.h b/src/server/game/Movement/MovementGenerators/PathGenerator.h index d23cc04f7..5e86b82e2 100644 --- a/src/server/game/Movement/MovementGenerators/PathGenerator.h +++ b/src/server/game/Movement/MovementGenerators/PathGenerator.h @@ -56,101 +56,105 @@ enum PathType class PathGenerator { - public: - explicit PathGenerator(Unit const* owner); - ~PathGenerator(); +public: + explicit PathGenerator(Unit const* owner); + ~PathGenerator(); - // Calculate the path from owner to given destination - // return: true if new path was calculated, false otherwise (no change needed) - bool CalculatePath(float destX, float destY, float destZ, bool forceDest = false); + // Calculate the path from owner to given destination + // return: true if new path was calculated, false otherwise (no change needed) + bool CalculatePath(float destX, float destY, float destZ, bool forceDest = false); - // option setters - use optional - void SetUseStraightPath(bool useStraightPath) { _useStraightPath = useStraightPath; } - void SetPathLengthLimit(float distance) { _pointPathLimit = std::min(uint32(distance/SMOOTH_PATH_STEP_SIZE), MAX_POINT_PATH_LENGTH); } + // option setters - use optional + void SetUseStraightPath(bool useStraightPath) { _useStraightPath = useStraightPath; } + void SetPathLengthLimit(float distance) { _pointPathLimit = std::min(uint32(distance / SMOOTH_PATH_STEP_SIZE), MAX_POINT_PATH_LENGTH); } - // result getters - G3D::Vector3 const& GetStartPosition() const { return _startPosition; } - G3D::Vector3 const& GetEndPosition() const { return _endPosition; } - G3D::Vector3 const& GetActualEndPosition() const { return _actualEndPosition; } + // result getters + G3D::Vector3 const& GetStartPosition() const { return _startPosition; } + G3D::Vector3 const& GetEndPosition() const { return _endPosition; } + G3D::Vector3 const& GetActualEndPosition() const { return _actualEndPosition; } - Movement::PointsArray const& GetPath() const { return _pathPoints; } + Movement::PointsArray const& GetPath() const { return _pathPoints; } - PathType GetPathType() const { return _type; } - float getPathLength() const + PathType GetPathType() const { return _type; } + float getPathLength() const + { + float len = 0.0f; + float dx, dy, dz; + uint32 size = _pathPoints.size(); + if (size) { - float len = 0.0f; - float dx, dy, dz; - uint32 size = _pathPoints.size(); - if (size) - { - dx = _pathPoints[0].x - _startPosition.x; dy = _pathPoints[0].y - _startPosition.y; dz = _pathPoints[0].z - _startPosition.z; - len += sqrt( dx*dx + dy*dy + dz*dz ); - } - else - return len; - for (uint32 i=1; i::DoInitialize(T* unit) if (!unit->IsStopped()) unit->StopMoving(); - unit->AddUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + unit->AddUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); i_recalculateSpeed = false; Movement::MoveSplineInit init(unit); if (m_precomputedPath.size() > 2) // pussywizard: for charge @@ -39,8 +39,8 @@ void PointMovementGenerator::DoInitialize(T* unit) // Xinef: fix strange client visual bug, moving on z coordinate only switches orientation by 180 degrees (visual only) if (G3D::fuzzyEq(unit->GetPositionX(), i_x) && G3D::fuzzyEq(unit->GetPositionY(), i_y)) { - i_x += 0.2f*cos(unit->GetOrientation()); - i_y += 0.2f*sin(unit->GetOrientation()); + i_x += 0.2f * cos(unit->GetOrientation()); + i_y += 0.2f * sin(unit->GetOrientation()); } init.MoveTo(i_x, i_y, i_z); @@ -51,8 +51,8 @@ void PointMovementGenerator::DoInitialize(T* unit) // Xinef: fix strange client visual bug, moving on z coordinate only switches orientation by 180 degrees (visual only) if (G3D::fuzzyEq(unit->GetPositionX(), i_x) && G3D::fuzzyEq(unit->GetPositionY(), i_y)) { - i_x += 0.2f*cos(unit->GetOrientation()); - i_y += 0.2f*sin(unit->GetOrientation()); + i_x += 0.2f * cos(unit->GetOrientation()); + i_y += 0.2f * sin(unit->GetOrientation()); } init.MoveTo(i_x, i_y, i_z); @@ -134,7 +134,7 @@ void PointMovementGenerator::DoReset(T* unit) if (!unit->IsStopped()) unit->StopMoving(); - unit->AddUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + unit->AddUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); } template diff --git a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h index 3fe663acf..6714fbf28 100644 --- a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h @@ -13,59 +13,59 @@ template class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementGenerator > { - public: - PointMovementGenerator(uint32 _id, float _x, float _y, float _z, float _speed = 0.0f, float orientation = 0.0f, const Movement::PointsArray* _path = nullptr, bool generatePath = false, bool forceDestination = false) : id(_id), - i_x(_x), i_y(_y), i_z(_z), speed(_speed), i_orientation(orientation), _generatePath(generatePath), _forceDestination(forceDestination) - { - if (_path) - m_precomputedPath = *_path; - } +public: + PointMovementGenerator(uint32 _id, float _x, float _y, float _z, float _speed = 0.0f, float orientation = 0.0f, const Movement::PointsArray* _path = nullptr, bool generatePath = false, bool forceDestination = false) : id(_id), + i_x(_x), i_y(_y), i_z(_z), speed(_speed), i_orientation(orientation), _generatePath(generatePath), _forceDestination(forceDestination) + { + if (_path) + m_precomputedPath = *_path; + } - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - bool DoUpdate(T*, uint32); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + bool DoUpdate(T*, uint32); - void MovementInform(T*); + void MovementInform(T*); - void unitSpeedChanged() { i_recalculateSpeed = true; } + void unitSpeedChanged() { i_recalculateSpeed = true; } - MovementGeneratorType GetMovementGeneratorType() { return POINT_MOTION_TYPE; } + MovementGeneratorType GetMovementGeneratorType() { return POINT_MOTION_TYPE; } - bool GetDestination(float& x, float& y, float& z) const { x=i_x; y=i_y; z=i_z; return true; } - private: - uint32 id; - float i_x, i_y, i_z; - float speed; - float i_orientation; - bool i_recalculateSpeed; - Movement::PointsArray m_precomputedPath; - bool _generatePath; - bool _forceDestination; + bool GetDestination(float& x, float& y, float& z) const { x = i_x; y = i_y; z = i_z; return true; } +private: + uint32 id; + float i_x, i_y, i_z; + float speed; + float i_orientation; + bool i_recalculateSpeed; + Movement::PointsArray m_precomputedPath; + bool _generatePath; + bool _forceDestination; }; class AssistanceMovementGenerator : public PointMovementGenerator { - public: - AssistanceMovementGenerator(float _x, float _y, float _z) : - PointMovementGenerator(0, _x, _y, _z) {} +public: + AssistanceMovementGenerator(float _x, float _y, float _z) : + PointMovementGenerator(0, _x, _y, _z) {} - MovementGeneratorType GetMovementGeneratorType() { return ASSISTANCE_MOTION_TYPE; } - void Finalize(Unit*); + MovementGeneratorType GetMovementGeneratorType() { return ASSISTANCE_MOTION_TYPE; } + void Finalize(Unit*); }; // Does almost nothing - just doesn't allows previous movegen interrupt current effect. class EffectMovementGenerator : public MovementGenerator { - public: - explicit EffectMovementGenerator(uint32 Id) : m_Id(Id) {} - void Initialize(Unit*) {} - void Finalize(Unit*); - void Reset(Unit*) {} - bool Update(Unit*, uint32); - MovementGeneratorType GetMovementGeneratorType() { return EFFECT_MOTION_TYPE; } - private: - uint32 m_Id; +public: + explicit EffectMovementGenerator(uint32 Id) : m_Id(Id) {} + void Initialize(Unit*) {} + void Finalize(Unit*); + void Reset(Unit*) {} + bool Update(Unit*, uint32); + MovementGeneratorType GetMovementGeneratorType() { return EFFECT_MOTION_TYPE; } +private: + uint32 m_Id; }; #endif diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp index bba4667ce..ea33beb56 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp @@ -36,10 +36,10 @@ void RandomMovementGenerator::_setRandomLocation(Creature* creature) return; } - uint8 random = urand(0, _validPointsVector[_currentPoint].size()-1); + uint8 random = urand(0, _validPointsVector[_currentPoint].size() - 1); std::vector::iterator randomIter = _validPointsVector[_currentPoint].begin() + random; uint8 newPoint = *randomIter; - uint16 pathIdx = uint16(_currentPoint*RANDOM_POINTS_NUMBER + newPoint); + uint16 pathIdx = uint16(_currentPoint * RANDOM_POINTS_NUMBER + newPoint); // cant go anywhere from new point, so dont go there to not be stuck if (_validPointsVector[newPoint].empty()) @@ -62,12 +62,12 @@ void RandomMovementGenerator::_setRandomLocation(Creature* creature) } float ground = INVALID_HEIGHT; - float levelZ = map->GetWaterOrGroundLevel(creature->GetPhaseMask(), x, y, z+4.0f, &ground); + float levelZ = map->GetWaterOrGroundLevel(creature->GetPhaseMask(), x, y, z + 4.0f, &ground); float newZ = INVALID_HEIGHT; // flying creature if (creature->CanFly()) - newZ = std::max(levelZ, z + rand_norm()*_wanderDistance/2.0f); + newZ = std::max(levelZ, z + rand_norm() * _wanderDistance / 2.0f); // point underwater else if (ground < levelZ) { @@ -84,7 +84,7 @@ void RandomMovementGenerator::_setRandomLocation(Creature* creature) else { if (levelZ > INVALID_HEIGHT) - newZ = std::min(levelZ-2.0f, z + rand_norm()*_wanderDistance/2.0f); + newZ = std::min(levelZ - 2.0f, z + rand_norm() * _wanderDistance / 2.0f); newZ = std::max(ground, newZ); } } @@ -119,7 +119,7 @@ void RandomMovementGenerator::_setRandomLocation(Creature* creature) { // generated path is too long float pathLen = _pathGenerator->getPathLength(); - if (pathLen*pathLen > creature->GetExactDistSq(x, y, levelZ) * MAX_PATH_LENGHT_FACTOR*MAX_PATH_LENGHT_FACTOR) + if (pathLen * pathLen > creature->GetExactDistSq(x, y, levelZ) * MAX_PATH_LENGHT_FACTOR * MAX_PATH_LENGHT_FACTOR) { _validPointsVector[_currentPoint].erase(randomIter); _preComputedPaths.erase(pathIdx); @@ -128,24 +128,24 @@ void RandomMovementGenerator::_setRandomLocation(Creature* creature) finalPath = _pathGenerator->GetPath(); Movement::PointsArray::iterator itr = finalPath.begin(); - Movement::PointsArray::iterator itrNext = finalPath.begin()+1; + Movement::PointsArray::iterator itrNext = finalPath.begin() + 1; float zDiff, distDiff; for (; itrNext != finalPath.end(); ++itr, ++itrNext) { - distDiff = sqrt(((*itr).x-(*itrNext).x)*((*itr).x-(*itrNext).x) + ((*itr).y-(*itrNext).y)*((*itr).y-(*itrNext).y)); + distDiff = sqrt(((*itr).x - (*itrNext).x) * ((*itr).x - (*itrNext).x) + ((*itr).y - (*itrNext).y) * ((*itr).y - (*itrNext).y)); zDiff = fabs((*itr).z - (*itrNext).z); // Xinef: tree climbing, cut as much as we can if (zDiff > 2.0f || - (G3D::fuzzyNe(zDiff, 0.0f) && distDiff / zDiff < 2.15f)) // ~25Ëš + (G3D::fuzzyNe(zDiff, 0.0f) && distDiff / zDiff < 2.15f)) // ~25Ëš { _validPointsVector[_currentPoint].erase(randomIter); _preComputedPaths.erase(pathIdx); return; } - if (!map->isInLineOfSight((*itr).x, (*itr).y, (*itr).z+2.f, (*itrNext).x, (*itrNext).y, (*itrNext).z+2.f, creature->GetPhaseMask(), LINEOFSIGHT_ALL_CHECKS)) + if (!map->isInLineOfSight((*itr).x, (*itr).y, (*itr).z + 2.f, (*itrNext).x, (*itrNext).y, (*itrNext).z + 2.f, creature->GetPhaseMask(), LINEOFSIGHT_ALL_CHECKS)) { _validPointsVector[_currentPoint].erase(randomIter); _preComputedPaths.erase(pathIdx); @@ -171,7 +171,7 @@ void RandomMovementGenerator::_setRandomLocation(Creature* creature) } _currentPoint = newPoint; - G3D::Vector3& finalPoint = finalPath[finalPath.size()-1]; + G3D::Vector3& finalPoint = finalPath[finalPath.size() - 1]; _currDestPosition.Relocate(finalPoint.x, finalPoint.y, finalPoint.z); creature->AddUnitState(UNIT_STATE_ROAMING_MOVE); @@ -213,9 +213,9 @@ void RandomMovementGenerator::DoInitialize(Creature* creature) _destinationPoints.clear(); for (uint8 i = 0; i < RANDOM_POINTS_NUMBER; ++i) { - float angle = (M_PI*2.0f/(float)RANDOM_POINTS_NUMBER)*i; - float factor = 0.5f + rand_norm()*0.5f; - _destinationPoints.push_back(G3D::Vector3(_initialPosition.GetPositionX() + _wanderDistance*cos(angle)*factor, _initialPosition.GetPositionY() + _wanderDistance*sin(angle)*factor, _initialPosition.GetPositionZ())); + float angle = (M_PI * 2.0f / (float)RANDOM_POINTS_NUMBER) * i; + float factor = 0.5f + rand_norm() * 0.5f; + _destinationPoints.push_back(G3D::Vector3(_initialPosition.GetPositionX() + _wanderDistance * cos(angle)*factor, _initialPosition.GetPositionY() + _wanderDistance * sin(angle)*factor, _initialPosition.GetPositionZ())); } } @@ -233,7 +233,7 @@ void RandomMovementGenerator::DoReset(Creature* creature) template<> void RandomMovementGenerator::DoFinalize(Creature* creature) { - creature->ClearUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + creature->ClearUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); creature->SetWalk(false); } diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h index 03d60e0b2..8428ab208 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h @@ -17,41 +17,41 @@ template class RandomMovementGenerator : public MovementGeneratorMedium< T, RandomMovementGenerator > { - public: - RandomMovementGenerator(float wanderDistance = 0.0f) : _nextMoveTime(0), _moveCount(0), _wanderDistance(wanderDistance), _pathGenerator(nullptr), _currentPoint(RANDOM_POINTS_NUMBER) +public: + RandomMovementGenerator(float wanderDistance = 0.0f) : _nextMoveTime(0), _moveCount(0), _wanderDistance(wanderDistance), _pathGenerator(nullptr), _currentPoint(RANDOM_POINTS_NUMBER) + { + _initialPosition.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + _destinationPoints.reserve(RANDOM_POINTS_NUMBER); + + for (uint8 i = 0; i < RANDOM_POINTS_NUMBER; ++i) { - _initialPosition.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - _destinationPoints.reserve(RANDOM_POINTS_NUMBER); - - for (uint8 i = 0; i < RANDOM_POINTS_NUMBER; ++i) - { - _validPointsVector[i].reserve(RANDOM_LINKS_COUNT); - for (uint8 j = 0; j < RANDOM_LINKS_COUNT; ++j) - _validPointsVector[i].push_back((i + j + RANDOM_POINTS_NUMBER/2 - RANDOM_LINKS_COUNT/2) % RANDOM_POINTS_NUMBER); - } - - _validPointsVector[RANDOM_POINTS_NUMBER].reserve(RANDOM_POINTS_NUMBER); - for (uint8 i = 0; i < RANDOM_POINTS_NUMBER; ++i) - _validPointsVector[RANDOM_POINTS_NUMBER].push_back(i); + _validPointsVector[i].reserve(RANDOM_LINKS_COUNT); + for (uint8 j = 0; j < RANDOM_LINKS_COUNT; ++j) + _validPointsVector[i].push_back((i + j + RANDOM_POINTS_NUMBER / 2 - RANDOM_LINKS_COUNT / 2) % RANDOM_POINTS_NUMBER); } - void _setRandomLocation(T*); - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - bool DoUpdate(T*, const uint32); - bool GetResetPosition(float& x, float& y, float& z); - MovementGeneratorType GetMovementGeneratorType() { return RANDOM_MOTION_TYPE; } + _validPointsVector[RANDOM_POINTS_NUMBER].reserve(RANDOM_POINTS_NUMBER); + for (uint8 i = 0; i < RANDOM_POINTS_NUMBER; ++i) + _validPointsVector[RANDOM_POINTS_NUMBER].push_back(i); + } - private: - TimeTrackerSmall _nextMoveTime; - uint8 _moveCount; - float _wanderDistance; - PathGenerator* _pathGenerator; - std::vector _destinationPoints; - std::vector _validPointsVector[RANDOM_POINTS_NUMBER+1]; - uint8 _currentPoint; - std::map _preComputedPaths; - Position _initialPosition, _currDestPosition; + void _setRandomLocation(T*); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + bool DoUpdate(T*, const uint32); + bool GetResetPosition(float& x, float& y, float& z); + MovementGeneratorType GetMovementGeneratorType() { return RANDOM_MOTION_TYPE; } + +private: + TimeTrackerSmall _nextMoveTime; + uint8 _moveCount; + float _wanderDistance; + PathGenerator* _pathGenerator; + std::vector _destinationPoints; + std::vector _validPointsVector[RANDOM_POINTS_NUMBER + 1]; + uint8 _currentPoint; + std::map _preComputedPaths; + Position _initialPosition, _currDestPosition; }; #endif diff --git a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp index 2cd1496d3..2604c4a89 100644 --- a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp @@ -22,9 +22,9 @@ #include template -void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool initial) +void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool initial) { - if (!i_target.isValid() || !i_target->IsInWorld() || !owner->IsInMap(i_target.getTarget())) + if (!i_target.isValid() || !i_target->IsInWorld() || !owner->IsInMap(i_target.getTarget())) return; if (owner->HasUnitState(UNIT_STATE_NOT_MOVE)) @@ -41,7 +41,7 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini bool useMMaps = MMAP::MMapFactory::IsPathfindingEnabled(owner->FindMap()) && !sameTransport; bool forceDest = (owner->FindMap() && owner->FindMap()->IsDungeon() && !isPlayerPet) || // force in instances to prevent exploiting (owner->GetTypeId() == TYPEID_UNIT && ((owner->IsPet() && owner->HasUnitState(UNIT_STATE_FOLLOW)) || // allow pets following their master to cheat while generating paths - ((Creature*)owner)->isWorldBoss() || ((Creature*)owner)->IsDungeonBoss())) || // force for all bosses, even not in instances + ((Creature*)owner)->isWorldBoss() || ((Creature*)owner)->IsDungeonBoss())) || // force for all bosses, even not in instances (owner->GetMapId() == 572 && (owner->GetPositionX() < 1275.0f || i_target->GetPositionX() < 1275.0f)) || // pussywizard: Ruins of Lordaeron - special case (acid) sameTransport || // nothing to comment, can't find path on transports so allow it (i_target->GetTypeId() == TYPEID_PLAYER && i_target->ToPlayer()->IsGameMaster()); // for .npc follow @@ -63,10 +63,10 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini return; bool inRange = i_target->GetRandomContactPoint(owner, x, y, z, forcePoint); - if (useMMaps && !inRange && (!isPlayerPet || i_target->GetPositionZ()-z > 50.0f)) + if (useMMaps && !inRange && (!isPlayerPet || i_target->GetPositionZ() - z > 50.0f)) { //useMMaps = false; - owner->m_targetsNotAcceptable[i_target->GetGUID()] = MMapTargetData(sWorld->GetGameTime()+DISALLOW_TIME_AFTER_FAIL, owner, i_target.getTarget()); + owner->m_targetsNotAcceptable[i_target->GetGUID()] = MMapTargetData(sWorld->GetGameTime() + DISALLOW_TIME_AFTER_FAIL, owner, i_target.getTarget()); return; } @@ -115,7 +115,7 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini // Xinef: Fix follow angle for hostile units if (angle == 0.0f && owner->GetVictim() && owner->GetVictim()->GetGUID() == i_target->GetGUID()) - angle = MapManager::NormalizeOrientation(i_target->GetAngle(owner)-i_target->GetOrientation()); + angle = MapManager::NormalizeOrientation(i_target->GetAngle(owner) - i_target->GetOrientation()); // to at i_offset distance from target and i_angle from target facing bool inRange = i_target->GetClosePoint(x, y, z, size, dist, angle, owner, forcePoint); if (!inRange && (forceDest || !useMMaps) && owner->HasUnitState(UNIT_STATE_FOLLOW) && fabs(i_target->GetPositionZ() - z) > 25.0f) @@ -154,7 +154,7 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini else z = i_target->GetPositionZ(); - init.MoveTo(x,y,z); + init.MoveTo(x, y, z); if (i_angle == 0.f) init.SetFacing(i_target.getTarget()); init.SetWalk(((D*)this)->EnableWalking()); @@ -164,7 +164,7 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini if (pillar->GetGoState() == GO_STATE_ACTIVE || (pillar->GetGoState() == GO_STATE_READY && pillar->ToTransport()->GetPathProgress() > 0)) { Position pos; - owner->GetFirstCollisionPositionForTotem(pos, owner->GetExactDist2d(i_target.getTarget()), owner->GetAngle(i_target.getTarget())-owner->GetOrientation(), false); + owner->GetFirstCollisionPositionForTotem(pos, owner->GetExactDist2d(i_target.getTarget()), owner->GetAngle(i_target.getTarget()) - owner->GetOrientation(), false); x = pos.GetPositionX(); y = pos.GetPositionY(); z = 28.28f; @@ -184,10 +184,10 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini if (result) { float maxDist = MELEE_RANGE + owner->GetMeleeReach() + i_target->GetMeleeReach(); - if (!forceDest && (i_path->GetPathType() & PATHFIND_NOPATH || (!i_offset && !isPlayerPet && i_target->GetExactDistSq(i_path->GetActualEndPosition().x, i_path->GetActualEndPosition().y, i_path->GetActualEndPosition().z) > maxDist*maxDist))) + if (!forceDest && (i_path->GetPathType() & PATHFIND_NOPATH || (!i_offset && !isPlayerPet && i_target->GetExactDistSq(i_path->GetActualEndPosition().x, i_path->GetActualEndPosition().y, i_path->GetActualEndPosition().z) > maxDist * maxDist))) { lastPathingFailMSTime = World::GetGameTimeMS(); - owner->m_targetsNotAcceptable[i_target->GetGUID()] = MMapTargetData(sWorld->GetGameTime()+DISALLOW_TIME_AFTER_FAIL, owner, i_target.getTarget()); + owner->m_targetsNotAcceptable[i_target->GetGUID()] = MMapTargetData(sWorld->GetGameTime() + DISALLOW_TIME_AFTER_FAIL, owner, i_target.getTarget()); return; } else @@ -209,7 +209,7 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini owner->AddUnitState(UNIT_STATE_CHASE); - init.MoveTo(x,y,z); + init.MoveTo(x, y, z); // Using the same condition for facing target as the one that is used for SetInFront on movement end // - applies to ChaseMovementGenerator mostly if (i_angle == 0.f) @@ -220,7 +220,7 @@ void TargetedMovementGeneratorMedium::_setTargetLocation(T* owner, bool ini } template -bool TargetedMovementGeneratorMedium::DoUpdate(T* owner, uint32 time_diff) +bool TargetedMovementGeneratorMedium::DoUpdate(T* owner, uint32 time_diff) { if (!i_target.isValid() || !i_target->IsInWorld()) return false; @@ -288,10 +288,10 @@ bool TargetedMovementGeneratorMedium::DoUpdate(T* owner, uint32 time_diff) if (TransportBase* transport = owner->GetDirectTransport()) transport->CalculatePassengerPosition(dest.x, dest.y, dest.z); - float dist = (dest - G3D::Vector3(i_target->GetPositionX(),i_target->GetPositionY(),i_target->GetPositionZ())).squaredLength(); + float dist = (dest - G3D::Vector3(i_target->GetPositionX(), i_target->GetPositionY(), i_target->GetPositionZ())).squaredLength(); float targetMoveDistSq = i_target->GetExactDistSq(&lastTargetXYZ); - if (dist >= allowed_dist_sq || (!i_offset && targetMoveDistSq >= 1.5f*1.5f)) - if (targetMoveDistSq >= 0.1f*0.1f || owner->GetExactDistSq(&lastOwnerXYZ) >= 0.1f*0.1f) + if (dist >= allowed_dist_sq || (!i_offset && targetMoveDistSq >= 1.5f * 1.5f)) + if (targetMoveDistSq >= 0.1f * 0.1f || owner->GetExactDistSq(&lastOwnerXYZ) >= 0.1f * 0.1f) _setTargetLocation(owner, false); } @@ -332,7 +332,7 @@ template void ChaseMovementGenerator::_reachTarget(T* owner) { if (owner->IsWithinMeleeRange(this->i_target.getTarget())) - owner->Attack(this->i_target.getTarget(),true); + owner->Attack(this->i_target.getTarget(), true); } template<> @@ -450,14 +450,14 @@ void FollowMovementGenerator::MovementInform(Creature* unit) } //-----------------------------------------------// -template void TargetedMovementGeneratorMedium >::_setTargetLocation(Player*, bool initial); -template void TargetedMovementGeneratorMedium >::_setTargetLocation(Player*, bool initial); -template void TargetedMovementGeneratorMedium >::_setTargetLocation(Creature*, bool initial); -template void TargetedMovementGeneratorMedium >::_setTargetLocation(Creature*, bool initial); -template bool TargetedMovementGeneratorMedium >::DoUpdate(Player*, uint32); -template bool TargetedMovementGeneratorMedium >::DoUpdate(Player*, uint32); -template bool TargetedMovementGeneratorMedium >::DoUpdate(Creature*, uint32); -template bool TargetedMovementGeneratorMedium >::DoUpdate(Creature*, uint32); +template void TargetedMovementGeneratorMedium >::_setTargetLocation(Player*, bool initial); +template void TargetedMovementGeneratorMedium >::_setTargetLocation(Player*, bool initial); +template void TargetedMovementGeneratorMedium >::_setTargetLocation(Creature*, bool initial); +template void TargetedMovementGeneratorMedium >::_setTargetLocation(Creature*, bool initial); +template bool TargetedMovementGeneratorMedium >::DoUpdate(Player*, uint32); +template bool TargetedMovementGeneratorMedium >::DoUpdate(Player*, uint32); +template bool TargetedMovementGeneratorMedium >::DoUpdate(Creature*, uint32); +template bool TargetedMovementGeneratorMedium >::DoUpdate(Creature*, uint32); template void ChaseMovementGenerator::_reachTarget(Player*); template void ChaseMovementGenerator::_reachTarget(Creature*); diff --git a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h index 268287f6e..f7b0f8e0b 100644 --- a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h @@ -15,95 +15,95 @@ class TargetedMovementGeneratorBase { - public: - TargetedMovementGeneratorBase(Unit* target) { i_target.link(target, this); } - void stopFollowing() { } - protected: - FollowerReference i_target; - Position lastOwnerXYZ; - Position lastTargetXYZ; +public: + TargetedMovementGeneratorBase(Unit* target) { i_target.link(target, this); } + void stopFollowing() { } +protected: + FollowerReference i_target; + Position lastOwnerXYZ; + Position lastTargetXYZ; }; template class TargetedMovementGeneratorMedium : public MovementGeneratorMedium< T, D >, public TargetedMovementGeneratorBase { - protected: - TargetedMovementGeneratorMedium(Unit* target, float offset, float angle) : - TargetedMovementGeneratorBase(target), i_path(nullptr), lastPathingFailMSTime(0), - i_recheckDistance(0), i_recheckDistanceForced(2500), i_offset(offset), i_angle(angle), - i_recalculateTravel(false), i_targetReached(false) - { - } - ~TargetedMovementGeneratorMedium() { delete i_path; } +protected: + TargetedMovementGeneratorMedium(Unit* target, float offset, float angle) : + TargetedMovementGeneratorBase(target), i_path(nullptr), lastPathingFailMSTime(0), + i_recheckDistance(0), i_recheckDistanceForced(2500), i_offset(offset), i_angle(angle), + i_recalculateTravel(false), i_targetReached(false) + { + } + ~TargetedMovementGeneratorMedium() { delete i_path; } - public: - bool DoUpdate(T*, uint32); - Unit* GetTarget() const { return i_target.getTarget(); } +public: + bool DoUpdate(T*, uint32); + Unit* GetTarget() const { return i_target.getTarget(); } - void unitSpeedChanged() { i_recalculateTravel = true; } - bool IsReachable() const { return (i_path) ? (i_path->GetPathType() & PATHFIND_NORMAL) : true; } + void unitSpeedChanged() { i_recalculateTravel = true; } + bool IsReachable() const { return (i_path) ? (i_path->GetPathType() & PATHFIND_NORMAL) : true; } - protected: - void _setTargetLocation(T* owner, bool initial); +protected: + void _setTargetLocation(T* owner, bool initial); - PathGenerator* i_path; - uint32 lastPathingFailMSTime; - TimeTrackerSmall i_recheckDistance; - TimeTrackerSmall i_recheckDistanceForced; - float i_offset; - float i_angle; - bool i_recalculateTravel : 1; - bool i_targetReached : 1; + PathGenerator* i_path; + uint32 lastPathingFailMSTime; + TimeTrackerSmall i_recheckDistance; + TimeTrackerSmall i_recheckDistanceForced; + float i_offset; + float i_angle; + bool i_recalculateTravel : 1; + bool i_targetReached : 1; }; template class ChaseMovementGenerator : public TargetedMovementGeneratorMedium > { - public: - ChaseMovementGenerator(Unit* target) - : TargetedMovementGeneratorMedium >(target) {} - ChaseMovementGenerator(Unit* target, float offset, float angle) - : TargetedMovementGeneratorMedium >(target, offset, angle) {} - ~ChaseMovementGenerator() {} +public: + ChaseMovementGenerator(Unit* target) + : TargetedMovementGeneratorMedium >(target) {} + ChaseMovementGenerator(Unit* target, float offset, float angle) + : TargetedMovementGeneratorMedium >(target, offset, angle) {} + ~ChaseMovementGenerator() {} - MovementGeneratorType GetMovementGeneratorType() { return CHASE_MOTION_TYPE; } + MovementGeneratorType GetMovementGeneratorType() { return CHASE_MOTION_TYPE; } - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - void MovementInform(T*); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + void MovementInform(T*); - static void _clearUnitStateMove(T* u) { u->ClearUnitState(UNIT_STATE_CHASE_MOVE); } - static void _addUnitStateMove(T* u) { u->AddUnitState(UNIT_STATE_CHASE_MOVE); } - bool EnableWalking() const { return false;} - bool _lostTarget(T* u) const { return u->GetVictim() != this->GetTarget(); } - void _reachTarget(T*); + static void _clearUnitStateMove(T* u) { u->ClearUnitState(UNIT_STATE_CHASE_MOVE); } + static void _addUnitStateMove(T* u) { u->AddUnitState(UNIT_STATE_CHASE_MOVE); } + bool EnableWalking() const { return false;} + bool _lostTarget(T* u) const { return u->GetVictim() != this->GetTarget(); } + void _reachTarget(T*); }; template class FollowMovementGenerator : public TargetedMovementGeneratorMedium > { - public: - FollowMovementGenerator(Unit* target) - : TargetedMovementGeneratorMedium >(target){} - FollowMovementGenerator(Unit* target, float offset, float angle) - : TargetedMovementGeneratorMedium >(target, offset, angle) {} - ~FollowMovementGenerator() {} +public: + FollowMovementGenerator(Unit* target) + : TargetedMovementGeneratorMedium >(target) {} + FollowMovementGenerator(Unit* target, float offset, float angle) + : TargetedMovementGeneratorMedium >(target, offset, angle) {} + ~FollowMovementGenerator() {} - MovementGeneratorType GetMovementGeneratorType() { return FOLLOW_MOTION_TYPE; } + MovementGeneratorType GetMovementGeneratorType() { return FOLLOW_MOTION_TYPE; } - void DoInitialize(T*); - void DoFinalize(T*); - void DoReset(T*); - void MovementInform(T*); + void DoInitialize(T*); + void DoFinalize(T*); + void DoReset(T*); + void MovementInform(T*); - static void _clearUnitStateMove(T* u) { u->ClearUnitState(UNIT_STATE_FOLLOW_MOVE); } - static void _addUnitStateMove(T* u) { u->AddUnitState(UNIT_STATE_FOLLOW_MOVE); } - bool EnableWalking() const; - bool _lostTarget(T*) const { return false; } - void _reachTarget(T*) {} - private: - void _updateSpeed(T* owner); + static void _clearUnitStateMove(T* u) { u->ClearUnitState(UNIT_STATE_FOLLOW_MOVE); } + static void _addUnitStateMove(T* u) { u->AddUnitState(UNIT_STATE_FOLLOW_MOVE); } + bool EnableWalking() const; + bool _lostTarget(T*) const { return false; } + void _reachTarget(T*) {} +private: + void _updateSpeed(T* owner); }; #endif diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp index 895ddaf59..500ec9ead 100644 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp @@ -41,18 +41,18 @@ void WaypointMovementGenerator::LoadPath(Creature* creature) void WaypointMovementGenerator::DoInitialize(Creature* creature) { LoadPath(creature); - creature->AddUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + creature->AddUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); } void WaypointMovementGenerator::DoFinalize(Creature* creature) { - creature->ClearUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + creature->ClearUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); creature->SetWalk(false); } void WaypointMovementGenerator::DoReset(Creature* creature) { - creature->AddUnitState(UNIT_STATE_ROAMING|UNIT_STATE_ROAMING_MOVE); + creature->AddUnitState(UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE); StartMoveNow(creature); } @@ -134,7 +134,7 @@ bool WaypointMovementGenerator::StartMove(Creature* creature) return false; } - i_currentNode = (i_currentNode+1) % i_path->size(); + i_currentNode = (i_currentNode + 1) % i_path->size(); } // xinef: do not initialize motion if we got stunned in movementinform @@ -240,7 +240,7 @@ bool WaypointMovementGenerator::DoUpdate(Creature* creature, uint32 di // xinef: do not start pre-empetive movement if current node has delay or we are ending waypoint movement bool finished = creature->movespline->Finalized(); if (!finished && !i_path->at(i_currentNode)->delay && ((i_currentNode != i_path->size() - 1) || repeating)) - finished = (creature->movespline->_Spline().length(creature->movespline->_currentSplineIdx()+1) - creature->movespline->timePassed()) < 200; + finished = (creature->movespline->_Spline().length(creature->movespline->_currentSplineIdx() + 1) - creature->movespline->timePassed()) < 200; if (finished) { @@ -249,8 +249,8 @@ bool WaypointMovementGenerator::DoUpdate(Creature* creature, uint32 di } } } - return true; - } + return true; +} void WaypointMovementGenerator::MovementInform(Creature* creature) { @@ -277,7 +277,7 @@ void FlightPathMovementGenerator::LoadPath(Player* player) { _pointsForPathSwitch.clear(); std::vector const& taxi = player->m_taxi.GetPath(); - for (uint32 src = player->m_taxi.GetTaxiSegment(), dst = player->m_taxi.GetTaxiSegment()+1; dst < taxi.size(); src = dst++) + for (uint32 src = player->m_taxi.GetTaxiSegment(), dst = player->m_taxi.GetTaxiSegment() + 1; dst < taxi.size(); src = dst++) { uint32 path, cost; sObjectMgr->GetTaxiPath(taxi[src], taxi[dst], path, cost); @@ -397,7 +397,7 @@ bool FlightPathMovementGenerator::DoUpdate(Player* player, uint32 /*diff*/) departureEvent = !departureEvent; // xinef: map should be switched, do not rely on client packets QQ - if (i_currentNode + 1 < i_path.size() && i_path[i_currentNode+1]->mapid != player->GetMapId()) + if (i_currentNode + 1 < i_path.size() && i_path[i_currentNode + 1]->mapid != player->GetMapId()) { ++i_currentNode; _mapSwitch = true; @@ -415,8 +415,7 @@ bool FlightPathMovementGenerator::DoUpdate(Player* player, uint32 /*diff*/) return false; } - } - while (true); + } while (true); } return i_currentNode < (i_path.size() - 1); @@ -481,11 +480,12 @@ void FlightPathMovementGenerator::PreloadEndGrid() if (endMap) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDetail("Preloading rid (%f, %f) for map %u at node index %u/%u", _endGridX, _endGridY, _endMapId, _preloadTargetNode, (uint32)(i_path.size()-1)); + sLog->outDetail("Preloading rid (%f, %f) for map %u at node index %u/%u", _endGridX, _endGridY, _endMapId, _preloadTargetNode, (uint32)(i_path.size() - 1)); #endif endMap->LoadGrid(_endGridX, _endGridY); } - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("Unable to determine map to preload flightmaster grid"); #endif diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h index b2db09262..d8d4f51d1 100644 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h @@ -24,16 +24,16 @@ template class PathMovementBase { - public: - PathMovementBase() : i_path(), i_currentNode(0) {} - PathMovementBase(P path) : i_path(path), i_currentNode(0) {} - virtual ~PathMovementBase() {}; +public: + PathMovementBase() : i_path(), i_currentNode(0) {} + PathMovementBase(P path) : i_path(path), i_currentNode(0) {} + virtual ~PathMovementBase() {}; - uint32 GetCurrentNode() const { return i_currentNode; } + uint32 GetCurrentNode() const { return i_currentNode; } - protected: - P i_path; - uint32 i_currentNode; +protected: + P i_path; + uint32 i_currentNode; }; template @@ -43,47 +43,47 @@ template<> class WaypointMovementGenerator : public MovementGeneratorMedium< Creature, WaypointMovementGenerator >, public PathMovementBase { - public: - WaypointMovementGenerator(uint32 _path_id = 0, bool _repeating = true) - : PathMovementBase((WaypointPath const*)NULL), i_nextMoveTime(0), m_isArrivalDone(false), path_id(_path_id), repeating(_repeating) {} - ~WaypointMovementGenerator() { i_path = nullptr; } - void DoInitialize(Creature*); - void DoFinalize(Creature*); - void DoReset(Creature*); - bool DoUpdate(Creature*, uint32 diff); +public: + WaypointMovementGenerator(uint32 _path_id = 0, bool _repeating = true) + : PathMovementBase((WaypointPath const*)NULL), i_nextMoveTime(0), m_isArrivalDone(false), path_id(_path_id), repeating(_repeating) {} + ~WaypointMovementGenerator() { i_path = nullptr; } + void DoInitialize(Creature*); + void DoFinalize(Creature*); + void DoReset(Creature*); + bool DoUpdate(Creature*, uint32 diff); - void MovementInform(Creature*); + void MovementInform(Creature*); - MovementGeneratorType GetMovementGeneratorType() { return WAYPOINT_MOTION_TYPE; } + MovementGeneratorType GetMovementGeneratorType() { return WAYPOINT_MOTION_TYPE; } - // now path movement implmementation - void LoadPath(Creature*); + // now path movement implmementation + void LoadPath(Creature*); - private: +private: - void Stop(int32 time) { i_nextMoveTime.Reset(time);} + void Stop(int32 time) { i_nextMoveTime.Reset(time);} - bool Stopped() { return !i_nextMoveTime.Passed();} + bool Stopped() { return !i_nextMoveTime.Passed();} - bool CanMove(int32 diff) - { - i_nextMoveTime.Update(diff); - return i_nextMoveTime.Passed(); - } + bool CanMove(int32 diff) + { + i_nextMoveTime.Update(diff); + return i_nextMoveTime.Passed(); + } - void OnArrived(Creature*); - bool StartMove(Creature*); + void OnArrived(Creature*); + bool StartMove(Creature*); - void StartMoveNow(Creature* creature) - { - i_nextMoveTime.Reset(0); - StartMove(creature); - } + void StartMoveNow(Creature* creature) + { + i_nextMoveTime.Reset(0); + StartMove(creature); + } - TimeTrackerSmall i_nextMoveTime; - bool m_isArrivalDone; - uint32 path_id; - bool repeating; + TimeTrackerSmall i_nextMoveTime; + bool m_isArrivalDone; + uint32 path_id; + bool repeating; }; /** FlightPathMovementGenerator generates movement of the player for the paths @@ -92,40 +92,40 @@ class WaypointMovementGenerator : public MovementGeneratorMedium< Crea class FlightPathMovementGenerator : public MovementGeneratorMedium< Player, FlightPathMovementGenerator >, public PathMovementBase { - public: - explicit FlightPathMovementGenerator(uint32 startNode = 0) - { - i_currentNode = startNode; - _endGridX = 0.0f; - _endGridY = 0.0f; - _endMapId = 0; - _preloadTargetNode = 0; - _mapSwitch = false; - } - void LoadPath(Player* player); - void DoInitialize(Player*); - void DoReset(Player*); - void DoFinalize(Player*); - bool DoUpdate(Player*, uint32); - MovementGeneratorType GetMovementGeneratorType() { return FLIGHT_MOTION_TYPE; } +public: + explicit FlightPathMovementGenerator(uint32 startNode = 0) + { + i_currentNode = startNode; + _endGridX = 0.0f; + _endGridY = 0.0f; + _endMapId = 0; + _preloadTargetNode = 0; + _mapSwitch = false; + } + void LoadPath(Player* player); + void DoInitialize(Player*); + void DoReset(Player*); + void DoFinalize(Player*); + bool DoUpdate(Player*, uint32); + MovementGeneratorType GetMovementGeneratorType() { return FLIGHT_MOTION_TYPE; } - TaxiPathNodeList const& GetPath() { return i_path; } - uint32 GetPathAtMapEnd() const; - bool HasArrived() const { return (i_currentNode >= i_path.size()); } - void SetCurrentNodeAfterTeleport(); - void SkipCurrentNode() { ++i_currentNode; } - void DoEventIfAny(Player* player, TaxiPathNodeEntry const* node, bool departure); + TaxiPathNodeList const& GetPath() { return i_path; } + uint32 GetPathAtMapEnd() const; + bool HasArrived() const { return (i_currentNode >= i_path.size()); } + void SetCurrentNodeAfterTeleport(); + void SkipCurrentNode() { ++i_currentNode; } + void DoEventIfAny(Player* player, TaxiPathNodeEntry const* node, bool departure); - void InitEndGridInfo(); - void PreloadEndGrid(); + void InitEndGridInfo(); + void PreloadEndGrid(); - private: - float _endGridX; //! X coord of last node location - float _endGridY; //! Y coord of last node location - uint32 _endMapId; //! map Id of last node location - uint32 _preloadTargetNode; //! node index where preloading starts - bool _mapSwitch; +private: + float _endGridX; //! X coord of last node location + float _endGridY; //! Y coord of last node location + uint32 _endMapId; //! map Id of last node location + uint32 _preloadTargetNode; //! node index where preloading starts + bool _mapSwitch; - std::deque _pointsForPathSwitch; //! node indexes and costs where TaxiPath changes + std::deque _pointsForPathSwitch; //! node indexes and costs where TaxiPath changes }; #endif diff --git a/src/server/game/Movement/Spline/MoveSpline.cpp b/src/server/game/Movement/Spline/MoveSpline.cpp index cf3847401..96835faad 100644 --- a/src/server/game/Movement/Spline/MoveSpline.cpp +++ b/src/server/game/Movement/Spline/MoveSpline.cpp @@ -9,301 +9,304 @@ #include "Log.h" #include "Creature.h" -namespace Movement{ - -Location MoveSpline::ComputePosition() const +namespace Movement { - ASSERT(Initialized()); - float u = 1.f; - int32 seg_time = spline.length(point_Idx, point_Idx+1); - if (seg_time > 0) - u = (time_passed - spline.length(point_Idx)) / (float)seg_time; - Location c; - c.orientation = initialOrientation; - spline.evaluate_percent(point_Idx, u, c); - - if (splineflags.animation) - ;// MoveSplineFlag::Animation disables falling or parabolic movement - else if (splineflags.parabolic) - computeParabolicElevation(c.z); - else if (splineflags.falling) - computeFallElevation(c.z); - - if (splineflags.done && splineflags.isFacing()) + Location MoveSpline::ComputePosition() const { - if (splineflags.final_angle) - c.orientation = facing.angle; - else if (splineflags.final_point) - c.orientation = atan2(facing.f.y - c.y, facing.f.x - c.x); - //nothing to do for MoveSplineFlag::Final_Target flag - } - else - { - if (!splineflags.hasFlag(MoveSplineFlag::OrientationFixed | MoveSplineFlag::Falling)) + ASSERT(Initialized()); + + float u = 1.f; + int32 seg_time = spline.length(point_Idx, point_Idx + 1); + if (seg_time > 0) + u = (time_passed - spline.length(point_Idx)) / (float)seg_time; + Location c; + c.orientation = initialOrientation; + spline.evaluate_percent(point_Idx, u, c); + + if (splineflags.animation) + ;// MoveSplineFlag::Animation disables falling or parabolic movement + else if (splineflags.parabolic) + computeParabolicElevation(c.z); + else if (splineflags.falling) + computeFallElevation(c.z); + + if (splineflags.done && splineflags.isFacing()) { - Vector3 hermite; - spline.evaluate_derivative(point_Idx, u, hermite); - c.orientation = atan2(hermite.y, hermite.x); + if (splineflags.final_angle) + c.orientation = facing.angle; + else if (splineflags.final_point) + c.orientation = atan2(facing.f.y - c.y, facing.f.x - c.x); + //nothing to do for MoveSplineFlag::Final_Target flag } - - if (splineflags.orientationInversed) - c.orientation = -c.orientation; - } - return c; -} - -void MoveSpline::computeParabolicElevation(float& el) const -{ - if (time_passed > effect_start_time) - { - float t_passedf = MSToSec(time_passed - effect_start_time); - float t_durationf = MSToSec(Duration() - effect_start_time); //client use not modified duration here - - // -a*x*x + bx + c: - //(dur * v3->z_acceleration * dt)/2 - (v3->z_acceleration * dt * dt)/2 + Z; - el += (t_durationf - t_passedf) * 0.5f * vertical_acceleration * t_passedf; - } -} - -void MoveSpline::computeFallElevation(float& el) const -{ - float z_now = spline.getPoint(spline.first(), false).z - Movement::computeFallElevation(MSToSec(time_passed), false); - float final_z = FinalDestination().z; - el = std::max(z_now, final_z); -} - -inline uint32 computeDuration(float length, float velocity) -{ - return SecToMS(length / velocity); -} - -struct FallInitializer -{ - FallInitializer(float _start_elevation) : start_elevation(_start_elevation) {} - float start_elevation; - inline int32 operator()(Spline& s, int32 i) - { - return Movement::computeFallTime(start_elevation - s.getPoint(i+1, false).z, false) * 1000.f; - } -}; - -enum{ - minimal_duration = 1 -}; - -struct CommonInitializer -{ - CommonInitializer(float _velocity) : velocityInv(1000.f/_velocity), time(minimal_duration) {} - float velocityInv; - int32 time; - inline int32 operator()(Spline& s, int32 i) - { - time += (s.SegLength(i) * velocityInv); - return time; - } -}; - -void MoveSpline::init_spline(const MoveSplineInitArgs& args) -{ - const SplineBase::EvaluationMode modes[2] = {SplineBase::ModeLinear, SplineBase::ModeCatmullrom}; - if (args.flags.cyclic) - { - uint32 cyclic_point = 0; - // MoveSplineFlag::Enter_Cycle support dropped - //if (splineflags & SPLINEFLAG_ENTER_CYCLE) - //cyclic_point = 1; // shouldn't be modified, came from client - spline.init_cyclic_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()], cyclic_point); - } - else - { - spline.init_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()]); - } - - // init spline timestamps - if (splineflags.falling) - { - FallInitializer init(spline.getPoint(spline.first(), false).z); - spline.initLengths(init); - } - else - { - CommonInitializer init(args.velocity); - spline.initLengths(init); - } - - // TODO: what to do in such cases? problem is in input data (all points are at same coords) - if (spline.length() < minimal_duration) - { - //sLog->outError("MoveSpline::init_spline: zero length spline, wrong input data?"); // ZOMG! temp comment to avoid console spam from transports - spline.set_length(spline.last(), spline.isCyclic() ? 1000 : 1); - } - point_Idx = spline.first(); -} - -void MoveSpline::Initialize(MoveSplineInitArgs const& args) -{ - splineflags = args.flags; - facing = args.facing; - m_Id = args.splineId; - point_Idx_offset = args.path_Idx_offset; - initialOrientation = args.initialOrientation; - - time_passed = 0; - vertical_acceleration = 0.f; - effect_start_time = 0; - - // Check if its a stop spline - if (args.flags.done) - { - spline.clear(); - return; - } - - init_spline(args); - - // init parabolic / animation - // spline initialized, duration known and i able to compute parabolic acceleration - if (args.flags & (MoveSplineFlag::Parabolic | MoveSplineFlag::Animation)) - { - effect_start_time = Duration() * args.time_perc; - if (args.flags.parabolic && effect_start_time < Duration()) + else { - float f_duration = MSToSec(Duration() - effect_start_time); - vertical_acceleration = args.parabolic_amplitude * 8.f / (f_duration * f_duration); + if (!splineflags.hasFlag(MoveSplineFlag::OrientationFixed | MoveSplineFlag::Falling)) + { + Vector3 hermite; + spline.evaluate_derivative(point_Idx, u, hermite); + c.orientation = atan2(hermite.y, hermite.x); + } + + if (splineflags.orientationInversed) + c.orientation = -c.orientation; + } + return c; + } + + void MoveSpline::computeParabolicElevation(float& el) const + { + if (time_passed > effect_start_time) + { + float t_passedf = MSToSec(time_passed - effect_start_time); + float t_durationf = MSToSec(Duration() - effect_start_time); //client use not modified duration here + + // -a*x*x + bx + c: + //(dur * v3->z_acceleration * dt)/2 - (v3->z_acceleration * dt * dt)/2 + Z; + el += (t_durationf - t_passedf) * 0.5f * vertical_acceleration * t_passedf; } } -} -MoveSpline::MoveSpline() : m_Id(0), time_passed(0), - vertical_acceleration(0.f), initialOrientation(0.f), effect_start_time(0), point_Idx(0), point_Idx_offset(0), - onTransport(false) -{ - splineflags.done = true; -} + void MoveSpline::computeFallElevation(float& el) const + { + float z_now = spline.getPoint(spline.first(), false).z - Movement::computeFallElevation(MSToSec(time_passed), false); + float final_z = FinalDestination().z; + el = std::max(z_now, final_z); + } -/// ============================================================================================ + inline uint32 computeDuration(float length, float velocity) + { + return SecToMS(length / velocity); + } -bool MoveSplineInitArgs::Validate(Unit* unit) const -{ + struct FallInitializer + { + FallInitializer(float _start_elevation) : start_elevation(_start_elevation) {} + float start_elevation; + inline int32 operator()(Spline& s, int32 i) + { + return Movement::computeFallTime(start_elevation - s.getPoint(i + 1, false).z, false) * 1000.f; + } + }; + + enum + { + minimal_duration = 1 + }; + + struct CommonInitializer + { + CommonInitializer(float _velocity) : velocityInv(1000.f / _velocity), time(minimal_duration) {} + float velocityInv; + int32 time; + inline int32 operator()(Spline& s, int32 i) + { + time += (s.SegLength(i) * velocityInv); + return time; + } + }; + + void MoveSpline::init_spline(const MoveSplineInitArgs& args) + { + const SplineBase::EvaluationMode modes[2] = {SplineBase::ModeLinear, SplineBase::ModeCatmullrom}; + if (args.flags.cyclic) + { + uint32 cyclic_point = 0; + // MoveSplineFlag::Enter_Cycle support dropped + //if (splineflags & SPLINEFLAG_ENTER_CYCLE) + //cyclic_point = 1; // shouldn't be modified, came from client + spline.init_cyclic_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()], cyclic_point); + } + else + { + spline.init_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()]); + } + + // init spline timestamps + if (splineflags.falling) + { + FallInitializer init(spline.getPoint(spline.first(), false).z); + spline.initLengths(init); + } + else + { + CommonInitializer init(args.velocity); + spline.initLengths(init); + } + + // TODO: what to do in such cases? problem is in input data (all points are at same coords) + if (spline.length() < minimal_duration) + { + //sLog->outError("MoveSpline::init_spline: zero length spline, wrong input data?"); // ZOMG! temp comment to avoid console spam from transports + spline.set_length(spline.last(), spline.isCyclic() ? 1000 : 1); + } + point_Idx = spline.first(); + } + + void MoveSpline::Initialize(MoveSplineInitArgs const& args) + { + splineflags = args.flags; + facing = args.facing; + m_Id = args.splineId; + point_Idx_offset = args.path_Idx_offset; + initialOrientation = args.initialOrientation; + + time_passed = 0; + vertical_acceleration = 0.f; + effect_start_time = 0; + + // Check if its a stop spline + if (args.flags.done) + { + spline.clear(); + return; + } + + init_spline(args); + + // init parabolic / animation + // spline initialized, duration known and i able to compute parabolic acceleration + if (args.flags & (MoveSplineFlag::Parabolic | MoveSplineFlag::Animation)) + { + effect_start_time = Duration() * args.time_perc; + if (args.flags.parabolic && effect_start_time < Duration()) + { + float f_duration = MSToSec(Duration() - effect_start_time); + vertical_acceleration = args.parabolic_amplitude * 8.f / (f_duration * f_duration); + } + } + } + + MoveSpline::MoveSpline() : m_Id(0), time_passed(0), + vertical_acceleration(0.f), initialOrientation(0.f), effect_start_time(0), point_Idx(0), point_Idx_offset(0), + onTransport(false) + { + splineflags.done = true; + } + + /// ============================================================================================ + + bool MoveSplineInitArgs::Validate(Unit* unit) const + { #define CHECK(exp) \ if (!(exp))\ {\ sLog->outError("MoveSplineInitArgs::Validate: expression '%s' failed for GUID: %u Entry: %u", #exp, unit->GetTypeId() == TYPEID_PLAYER ? unit->GetGUIDLow() : unit->ToCreature()->GetDBTableGUIDLow(), unit->GetEntry());\ return false;\ } - CHECK(path.size() > 1); - CHECK(velocity > 0.01f); - CHECK(time_perc >= 0.f && time_perc <= 1.f); - //CHECK(_checkPathBounds()); - return true; + CHECK(path.size() > 1); + CHECK(velocity > 0.01f); + CHECK(time_perc >= 0.f && time_perc <= 1.f); + //CHECK(_checkPathBounds()); + return true; #undef CHECK -} + } -// MONSTER_MOVE packet format limitation for not CatmullRom movement: -// each vertex offset packed into 11 bytes -bool MoveSplineInitArgs::_checkPathBounds() const -{ - if (!(flags & MoveSplineFlag::Mask_CatmullRom) && path.size() > 2) + // MONSTER_MOVE packet format limitation for not CatmullRom movement: + // each vertex offset packed into 11 bytes + bool MoveSplineInitArgs::_checkPathBounds() const { - enum{ - MAX_OFFSET = (1 << 11) / 2 - }; - Vector3 middle = (path.front()+path.back()) / 2; - Vector3 offset; - for (uint32 i = 1; i < path.size()-1; ++i) + if (!(flags & MoveSplineFlag::Mask_CatmullRom) && path.size() > 2) { - offset = path[i] - middle; - if (fabs(offset.x) >= MAX_OFFSET || fabs(offset.y) >= MAX_OFFSET || fabs(offset.z) >= MAX_OFFSET) + enum { - sLog->outError("MoveSplineInitArgs::_checkPathBounds check failed"); - return false; + MAX_OFFSET = (1 << 11) / 2 + }; + Vector3 middle = (path.front() + path.back()) / 2; + Vector3 offset; + for (uint32 i = 1; i < path.size() - 1; ++i) + { + offset = path[i] - middle; + if (fabs(offset.x) >= MAX_OFFSET || fabs(offset.y) >= MAX_OFFSET || fabs(offset.z) >= MAX_OFFSET) + { + sLog->outError("MoveSplineInitArgs::_checkPathBounds check failed"); + return false; + } } } - } - return true; -} - -/// ============================================================================================ - -MoveSpline::UpdateResult MoveSpline::_updateState(int32& ms_time_diff) -{ - if (Finalized()) - { - ms_time_diff = 0; - return Result_Arrived; + return true; } - UpdateResult result = Result_None; + /// ============================================================================================ - int32 minimal_diff = std::min(ms_time_diff, segment_time_elapsed()); - if (minimal_diff < 0) - minimal_diff = 0; - - ASSERT(minimal_diff >= 0); - time_passed += minimal_diff; - ms_time_diff -= minimal_diff; - - if (time_passed >= next_timestamp()) + MoveSpline::UpdateResult MoveSpline::_updateState(int32& ms_time_diff) { - ++point_Idx; - if (point_Idx < spline.last()) + if (Finalized()) { - result = Result_NextSegment; + ms_time_diff = 0; + return Result_Arrived; } - else + + UpdateResult result = Result_None; + + int32 minimal_diff = std::min(ms_time_diff, segment_time_elapsed()); + if (minimal_diff < 0) + minimal_diff = 0; + + ASSERT(minimal_diff >= 0); + time_passed += minimal_diff; + ms_time_diff -= minimal_diff; + + if (time_passed >= next_timestamp()) { - if (spline.isCyclic()) + ++point_Idx; + if (point_Idx < spline.last()) { - point_Idx = spline.first(); - time_passed = time_passed % Duration(); - result = Movement::MoveSpline::UpdateResult(Result_NextCycle | Result_JustArrived); + result = Result_NextSegment; } else { - _Finalize(); - ms_time_diff = 0; - result = Movement::MoveSpline::UpdateResult(Result_Arrived | Result_JustArrived); + if (spline.isCyclic()) + { + point_Idx = spline.first(); + time_passed = time_passed % Duration(); + result = Movement::MoveSpline::UpdateResult(Result_NextCycle | Result_JustArrived); + } + else + { + _Finalize(); + ms_time_diff = 0; + result = Movement::MoveSpline::UpdateResult(Result_Arrived | Result_JustArrived); + } } } + + return result; } - return result; -} + std::string MoveSpline::ToString() const + { + std::stringstream str; + str << "MoveSpline" << std::endl; + str << "spline Id: " << GetId() << std::endl; + str << "flags: " << splineflags.ToString() << std::endl; + if (splineflags.final_angle) + str << "facing angle: " << facing.angle; + else if (splineflags.final_target) + str << "facing target: " << facing.target; + else if (splineflags.final_point) + str << "facing point: " << facing.f.x << " " << facing.f.y << " " << facing.f.z; + str << std::endl; + str << "time passed: " << time_passed << std::endl; + str << "total time: " << Duration() << std::endl; + str << "spline point Id: " << point_Idx << std::endl; + str << "path point Id: " << currentPathIdx() << std::endl; + str << spline.ToString(); + return str.str(); + } -std::string MoveSpline::ToString() const -{ - std::stringstream str; - str << "MoveSpline" << std::endl; - str << "spline Id: " << GetId() << std::endl; - str << "flags: " << splineflags.ToString() << std::endl; - if (splineflags.final_angle) - str << "facing angle: " << facing.angle; - else if (splineflags.final_target) - str << "facing target: " << facing.target; - else if (splineflags.final_point) - str << "facing point: " << facing.f.x << " " << facing.f.y << " " << facing.f.z; - str << std::endl; - str << "time passed: " << time_passed << std::endl; - str << "total time: " << Duration() << std::endl; - str << "spline point Id: " << point_Idx << std::endl; - str << "path point Id: " << currentPathIdx() << std::endl; - str << spline.ToString(); - return str.str(); -} + void MoveSpline::_Finalize() + { + splineflags.done = true; + point_Idx = spline.last() - 1; + time_passed = Duration(); + } -void MoveSpline::_Finalize() -{ - splineflags.done = true; - point_Idx = spline.last() - 1; - time_passed = Duration(); -} - -int32 MoveSpline::currentPathIdx() const -{ - int32 point = point_Idx_offset + point_Idx - spline.first() + (int)Finalized(); - if (isCyclic()) - point = point % (spline.last()-spline.first()); - return point; -} + int32 MoveSpline::currentPathIdx() const + { + int32 point = point_Idx_offset + point_Idx - spline.first() + (int)Finalized(); + if (isCyclic()) + point = point % (spline.last() - spline.first()); + return point; + } } diff --git a/src/server/game/Movement/Spline/MoveSplineFlag.h b/src/server/game/Movement/Spline/MoveSplineFlag.h index 6740da968..45f8a109e 100644 --- a/src/server/game/Movement/Spline/MoveSplineFlag.h +++ b/src/server/game/Movement/Spline/MoveSplineFlag.h @@ -24,7 +24,7 @@ namespace Movement enum eFlags { None = 0x00000000, - // x00-xFF(first byte) used as animation Ids storage in pair with Animation flag + // x00-xFF(first byte) used as animation Ids storage in pair with Animation flag Done = 0x00000100, Falling = 0x00000200, // Affects elevation computation, can't be combined with Parabolic flag No_Spline = 0x00000400, @@ -59,21 +59,21 @@ namespace Movement // CatmullRom interpolation mode used Mask_CatmullRom = Flying | Catmullrom, // Unused, not suported flags - Mask_Unused = No_Spline|Enter_Cycle|Frozen|Unknown7|Unknown8|Unknown10|Unknown11|Unknown12|Unknown13 + Mask_Unused = No_Spline | Enter_Cycle | Frozen | Unknown7 | Unknown8 | Unknown10 | Unknown11 | Unknown12 | Unknown13 }; - inline uint32& raw() { return (uint32&)*this; } - inline const uint32& raw() const { return (const uint32&)*this; } + inline uint32& raw() { return (uint32&) * this; } + inline const uint32& raw() const { return (const uint32&) * this; } MoveSplineFlag() { raw() = 0; } MoveSplineFlag(uint32 f) { raw() = f; } MoveSplineFlag(const MoveSplineFlag& f) { raw() = f.raw(); } /* requried as of C++ 11 */ - #if __cplusplus >= 201103L +#if __cplusplus >= 201103L MoveSplineFlag(MoveSplineFlag&&) = default; MoveSplineFlag& operator=(const MoveSplineFlag&) = default; MoveSplineFlag& operator=(MoveSplineFlag&&) = default; - #endif +#endif // Constant interface diff --git a/src/server/game/Movement/Spline/MoveSplineInit.cpp b/src/server/game/Movement/Spline/MoveSplineInit.cpp index 581027ea7..f6fbe7111 100644 --- a/src/server/game/Movement/Spline/MoveSplineInit.cpp +++ b/src/server/game/Movement/Spline/MoveSplineInit.cpp @@ -79,7 +79,7 @@ namespace Movement move_spline.onTransport = transport; uint32 moveFlags = unit->m_movementInfo.GetMovementFlags(); - moveFlags |= (MOVEMENTFLAG_SPLINE_ENABLED|MOVEMENTFLAG_FORWARD); + moveFlags |= (MOVEMENTFLAG_SPLINE_ENABLED | MOVEMENTFLAG_FORWARD); if (moveFlags & MOVEMENTFLAG_ROOT) moveFlags &= ~MOVEMENTFLAG_MASK_MOVING; @@ -121,7 +121,7 @@ namespace Movement std::copy(move_spline._Spline().getPoints(false).begin(), move_spline._Spline().getPoints(false).end(), visualPoints->begin()); PacketBuilder::WriteMonsterMove(move_spline, data); - unit->SendMessageToSet(&data,true); + unit->SendMessageToSet(&data, true); return move_spline.Duration(); } diff --git a/src/server/game/Movement/Spline/MoveSplineInitArgs.h b/src/server/game/Movement/Spline/MoveSplineInitArgs.h index 3454930b7..3c38fbb1a 100644 --- a/src/server/game/Movement/Spline/MoveSplineInitArgs.h +++ b/src/server/game/Movement/Spline/MoveSplineInitArgs.h @@ -18,7 +18,8 @@ namespace Movement union FacingInfo { - struct { + struct + { float x, y, z; } f; uint64 target; diff --git a/src/server/game/Movement/Spline/MovementPacketBuilder.cpp b/src/server/game/Movement/Spline/MovementPacketBuilder.cpp index 9743e0347..667ecb14e 100644 --- a/src/server/game/Movement/Spline/MovementPacketBuilder.cpp +++ b/src/server/game/Movement/Spline/MovementPacketBuilder.cpp @@ -88,7 +88,7 @@ namespace Movement void WriteLinearPath(const Spline& spline, ByteBuffer& data) { uint32 last_idx = spline.getPointCount() - 3; - const Vector3 * real_path = &spline.getPoint(1, true); + const Vector3* real_path = &spline.getPoint(1, true); data << last_idx; data << real_path[last_idx]; // destination @@ -115,7 +115,7 @@ namespace Movement void WriteCatmullRomCyclicPath(const Spline& spline, ByteBuffer& data, bool flying) { uint32 count = spline.getPointCount() - 3; - data << uint32(count+1); + data << uint32(count + 1); if (flying) { data << spline.getPoint(1, true); // fake point, client will erase it from the spline after first cycle done diff --git a/src/server/game/Movement/Spline/MovementPacketBuilder.h b/src/server/game/Movement/Spline/MovementPacketBuilder.h index 008f8cce3..04717de13 100644 --- a/src/server/game/Movement/Spline/MovementPacketBuilder.h +++ b/src/server/game/Movement/Spline/MovementPacketBuilder.h @@ -3,7 +3,7 @@ * Copyright (C) 2008-2016 TrinityCore * Copyright (C) 2005-2009 MaNGOS */ - + #ifndef TRINITYSERVER_PACKET_BUILDER_H #define TRINITYSERVER_PACKET_BUILDER_H diff --git a/src/server/game/Movement/Spline/MovementUtil.cpp b/src/server/game/Movement/Spline/MovementUtil.cpp index cfd31cf29..7a20204c8 100644 --- a/src/server/game/Movement/Spline/MovementUtil.cpp +++ b/src/server/game/Movement/Spline/MovementUtil.cpp @@ -17,8 +17,8 @@ namespace Movement float terminalVelocity = 60.148003f; float terminalSafefallVelocity = 7.0f; - const float terminal_length = float(terminalVelocity * terminalVelocity) / (2.0f * gravity); - const float terminal_safeFall_length = (terminalSafefallVelocity * terminalSafefallVelocity) / (2.0f * gravity); + const float terminal_length = float(terminalVelocity* terminalVelocity) / (2.0f * gravity); + const float terminal_safeFall_length = (terminalSafefallVelocity* terminalSafefallVelocity) / (2.0f * gravity); const float terminal_fallTime = float(terminalVelocity / gravity); // the time that needed to reach terminalVelocity const float terminal_safeFall_fallTime = float(terminalSafefallVelocity / gravity); // the time that needed to reach terminalVelocity with safefall @@ -64,8 +64,8 @@ namespace Movement if (t_passed > terminal_time) { result = termVel * (t_passed - terminal_time) + - start_velocity * terminal_time + - gravity * terminal_time * terminal_time*0.5f; + start_velocity * terminal_time + + gravity * terminal_time * terminal_time * 0.5f; } else result = t_passed * (start_velocity + t_passed * gravity * 0.5f); @@ -73,7 +73,7 @@ namespace Movement return result; } - #define STR(x) #x +#define STR(x) #x char const* g_MovementFlag_names[] = { @@ -165,7 +165,7 @@ namespace Movement }; template - void print_flags(Flags t, char const* (&names)[N], std::string& str) + void print_flags(Flags t, char const * (&names)[N], std::string& str) { for (int i = 0; i < N; ++i) { diff --git a/src/server/game/Movement/Spline/Spline.cpp b/src/server/game/Movement/Spline/Spline.cpp index 9bac1c549..d8750632b 100644 --- a/src/server/game/Movement/Spline/Spline.cpp +++ b/src/server/game/Movement/Spline/Spline.cpp @@ -8,287 +8,288 @@ #include #include -namespace Movement{ - -SplineBase::EvaluationMethtod SplineBase::evaluators[SplineBase::ModesEnd] = +namespace Movement { - &SplineBase::EvaluateLinear, - &SplineBase::EvaluateCatmullRom, - &SplineBase::EvaluateBezier3, - &SplineBase::UninitializedSplineEvaluationMethod, -}; -SplineBase::EvaluationMethtod SplineBase::derivative_evaluators[SplineBase::ModesEnd] = -{ - &SplineBase::EvaluateDerivativeLinear, - &SplineBase::EvaluateDerivativeCatmullRom, - &SplineBase::EvaluateDerivativeBezier3, - &SplineBase::UninitializedSplineEvaluationMethod, -}; - -SplineBase::SegLenghtMethtod SplineBase::seglengths[SplineBase::ModesEnd] = -{ - &SplineBase::SegLengthLinear, - &SplineBase::SegLengthCatmullRom, - &SplineBase::SegLengthBezier3, - &SplineBase::UninitializedSplineSegLenghtMethod, -}; - -SplineBase::InitMethtod SplineBase::initializers[SplineBase::ModesEnd] = -{ - //&SplineBase::InitLinear, - &SplineBase::InitCatmullRom, // we should use catmullrom initializer even for linear mode! (client's internal structure limitation) - &SplineBase::InitCatmullRom, - &SplineBase::InitBezier3, - &SplineBase::UninitializedSplineInitMethod, -}; - -/////////// - -using G3D::Matrix4; -static const Matrix4 s_catmullRomCoeffs( - -0.5f, 1.5f, -1.5f, 0.5f, - 1.f, -2.5f, 2.f, -0.5f, - -0.5f, 0.f, 0.5f, 0.f, - 0.f, 1.f, 0.f, 0.f); - -static const Matrix4 s_Bezier3Coeffs( - -1.f, 3.f, -3.f, 1.f, - 3.f, -6.f, 3.f, 0.f, - -3.f, 3.f, 0.f, 0.f, - 1.f, 0.f, 0.f, 0.f); - -/* classic view: -inline void C_Evaluate(const Vector3 *vertice, float t, const float (&matrix)[4][4], Vector3 &position) -{ - Vector3 tvec(t*t*t, t*t, t); - int i = 0; - double c; - double x = 0, y = 0, z = 0; - while ( i < 4 ) + SplineBase::EvaluationMethtod SplineBase::evaluators[SplineBase::ModesEnd] = { - c = matrix[0][i]*tvec.x + matrix[1][i]*tvec.y + matrix[2][i]*tvec.z + matrix[3][i]; + &SplineBase::EvaluateLinear, + &SplineBase::EvaluateCatmullRom, + &SplineBase::EvaluateBezier3, + &SplineBase::UninitializedSplineEvaluationMethod, + }; - x += c * vertice->x; - y += c * vertice->y; - z += c * vertice->z; + SplineBase::EvaluationMethtod SplineBase::derivative_evaluators[SplineBase::ModesEnd] = + { + &SplineBase::EvaluateDerivativeLinear, + &SplineBase::EvaluateDerivativeCatmullRom, + &SplineBase::EvaluateDerivativeBezier3, + &SplineBase::UninitializedSplineEvaluationMethod, + }; - ++i; - ++vertice; + SplineBase::SegLenghtMethtod SplineBase::seglengths[SplineBase::ModesEnd] = + { + &SplineBase::SegLengthLinear, + &SplineBase::SegLengthCatmullRom, + &SplineBase::SegLengthBezier3, + &SplineBase::UninitializedSplineSegLenghtMethod, + }; + + SplineBase::InitMethtod SplineBase::initializers[SplineBase::ModesEnd] = + { + //&SplineBase::InitLinear, + &SplineBase::InitCatmullRom, // we should use catmullrom initializer even for linear mode! (client's internal structure limitation) + &SplineBase::InitCatmullRom, + &SplineBase::InitBezier3, + &SplineBase::UninitializedSplineInitMethod, + }; + + /////////// + + using G3D::Matrix4; + static const Matrix4 s_catmullRomCoeffs( + -0.5f, 1.5f, -1.5f, 0.5f, + 1.f, -2.5f, 2.f, -0.5f, + -0.5f, 0.f, 0.5f, 0.f, + 0.f, 1.f, 0.f, 0.f); + + static const Matrix4 s_Bezier3Coeffs( + -1.f, 3.f, -3.f, 1.f, + 3.f, -6.f, 3.f, 0.f, + -3.f, 3.f, 0.f, 0.f, + 1.f, 0.f, 0.f, 0.f); + + /* classic view: + inline void C_Evaluate(const Vector3 *vertice, float t, const float (&matrix)[4][4], Vector3 &position) + { + Vector3 tvec(t*t*t, t*t, t); + int i = 0; + double c; + double x = 0, y = 0, z = 0; + while ( i < 4 ) + { + c = matrix[0][i]*tvec.x + matrix[1][i]*tvec.y + matrix[2][i]*tvec.z + matrix[3][i]; + + x += c * vertice->x; + y += c * vertice->y; + z += c * vertice->z; + + ++i; + ++vertice; + } + + position.x = x; + position.y = y; + position.z = z; + }*/ + + inline void C_Evaluate(const Vector3* vertice, float t, const Matrix4& matr, Vector3& result) + { + Vector4 tvec(t * t * t, t * t, t, 1.f); + Vector4 weights(tvec * matr); + + result = vertice[0] * weights[0] + vertice[1] * weights[1] + + vertice[2] * weights[2] + vertice[3] * weights[3]; } - position.x = x; - position.y = y; - position.z = z; -}*/ - -inline void C_Evaluate(const Vector3 *vertice, float t, const Matrix4& matr, Vector3 &result) -{ - Vector4 tvec(t*t*t, t*t, t, 1.f); - Vector4 weights(tvec * matr); - - result = vertice[0] * weights[0] + vertice[1] * weights[1] - + vertice[2] * weights[2] + vertice[3] * weights[3]; -} - -inline void C_Evaluate_Derivative(const Vector3 *vertice, float t, const Matrix4& matr, Vector3 &result) -{ - Vector4 tvec(3.f*t*t, 2.f*t, 1.f, 0.f); - Vector4 weights(tvec * matr); - - result = vertice[0] * weights[0] + vertice[1] * weights[1] - + vertice[2] * weights[2] + vertice[3] * weights[3]; -} - -void SplineBase::EvaluateLinear(index_type index, float u, Vector3& result) const -{ - ASSERT(index >= index_lo && index < index_hi); - result = points[index] + (points[index+1] - points[index]) * u; -} - -void SplineBase::EvaluateCatmullRom( index_type index, float t, Vector3& result) const -{ - ASSERT(index >= index_lo && index < index_hi); - C_Evaluate(&points[index - 1], t, s_catmullRomCoeffs, result); -} - -void SplineBase::EvaluateBezier3(index_type index, float t, Vector3& result) const -{ - index *= 3u; - ASSERT(index >= index_lo && index < index_hi); - C_Evaluate(&points[index], t, s_Bezier3Coeffs, result); -} - -void SplineBase::EvaluateDerivativeLinear(index_type index, float, Vector3& result) const -{ - ASSERT(index >= index_lo && index < index_hi); - result = points[index+1] - points[index]; -} - -void SplineBase::EvaluateDerivativeCatmullRom(index_type index, float t, Vector3& result) const -{ - ASSERT(index >= index_lo && index < index_hi); - C_Evaluate_Derivative(&points[index - 1], t, s_catmullRomCoeffs, result); -} - -void SplineBase::EvaluateDerivativeBezier3(index_type index, float t, Vector3& result) const -{ - index *= 3u; - ASSERT(index >= index_lo && index < index_hi); - C_Evaluate_Derivative(&points[index], t, s_Bezier3Coeffs, result); -} - -float SplineBase::SegLengthLinear(index_type index) const -{ - ASSERT(index >= index_lo && index < index_hi); - return (points[index] - points[index+1]).length(); -} - -float SplineBase::SegLengthCatmullRom(index_type index) const -{ - ASSERT(index >= index_lo && index < index_hi); - - Vector3 curPos, nextPos; - const Vector3 * p = &points[index - 1]; - curPos = nextPos = p[1]; - - index_type i = 1; - double length = 0; - while (i <= STEPS_PER_SEGMENT) + inline void C_Evaluate_Derivative(const Vector3* vertice, float t, const Matrix4& matr, Vector3& result) { - C_Evaluate(p, float(i) / float(STEPS_PER_SEGMENT), s_catmullRomCoeffs, nextPos); - length += (nextPos - curPos).length(); + Vector4 tvec(3.f * t * t, 2.f * t, 1.f, 0.f); + Vector4 weights(tvec * matr); + + result = vertice[0] * weights[0] + vertice[1] * weights[1] + + vertice[2] * weights[2] + vertice[3] * weights[3]; + } + + void SplineBase::EvaluateLinear(index_type index, float u, Vector3& result) const + { + ASSERT(index >= index_lo && index < index_hi); + result = points[index] + (points[index + 1] - points[index]) * u; + } + + void SplineBase::EvaluateCatmullRom( index_type index, float t, Vector3& result) const + { + ASSERT(index >= index_lo && index < index_hi); + C_Evaluate(&points[index - 1], t, s_catmullRomCoeffs, result); + } + + void SplineBase::EvaluateBezier3(index_type index, float t, Vector3& result) const + { + index *= 3u; + ASSERT(index >= index_lo && index < index_hi); + C_Evaluate(&points[index], t, s_Bezier3Coeffs, result); + } + + void SplineBase::EvaluateDerivativeLinear(index_type index, float, Vector3& result) const + { + ASSERT(index >= index_lo && index < index_hi); + result = points[index + 1] - points[index]; + } + + void SplineBase::EvaluateDerivativeCatmullRom(index_type index, float t, Vector3& result) const + { + ASSERT(index >= index_lo && index < index_hi); + C_Evaluate_Derivative(&points[index - 1], t, s_catmullRomCoeffs, result); + } + + void SplineBase::EvaluateDerivativeBezier3(index_type index, float t, Vector3& result) const + { + index *= 3u; + ASSERT(index >= index_lo && index < index_hi); + C_Evaluate_Derivative(&points[index], t, s_Bezier3Coeffs, result); + } + + float SplineBase::SegLengthLinear(index_type index) const + { + ASSERT(index >= index_lo && index < index_hi); + return (points[index] - points[index + 1]).length(); + } + + float SplineBase::SegLengthCatmullRom(index_type index) const + { + ASSERT(index >= index_lo && index < index_hi); + + Vector3 curPos, nextPos; + const Vector3* p = &points[index - 1]; + curPos = nextPos = p[1]; + + index_type i = 1; + double length = 0; + while (i <= STEPS_PER_SEGMENT) + { + C_Evaluate(p, float(i) / float(STEPS_PER_SEGMENT), s_catmullRomCoeffs, nextPos); + length += (nextPos - curPos).length(); + curPos = nextPos; + ++i; + } + return length; + } + + float SplineBase::SegLengthBezier3(index_type index) const + { + index *= 3u; + ASSERT(index >= index_lo && index < index_hi); + + Vector3 curPos, nextPos; + const Vector3* p = &points[index]; + + C_Evaluate(p, 0.f, s_Bezier3Coeffs, nextPos); curPos = nextPos; - ++i; + + index_type i = 1; + double length = 0; + while (i <= STEPS_PER_SEGMENT) + { + C_Evaluate(p, float(i) / float(STEPS_PER_SEGMENT), s_Bezier3Coeffs, nextPos); + length += (nextPos - curPos).length(); + curPos = nextPos; + ++i; + } + return length; } - return length; -} -float SplineBase::SegLengthBezier3(index_type index) const -{ - index *= 3u; - ASSERT(index >= index_lo && index < index_hi); - - Vector3 curPos, nextPos; - const Vector3 * p = &points[index]; - - C_Evaluate(p, 0.f, s_Bezier3Coeffs, nextPos); - curPos = nextPos; - - index_type i = 1; - double length = 0; - while (i <= STEPS_PER_SEGMENT) + void SplineBase::init_spline(const Vector3* controls, index_type count, EvaluationMode m) { - C_Evaluate(p, float(i) / float(STEPS_PER_SEGMENT), s_Bezier3Coeffs, nextPos); - length += (nextPos - curPos).length(); - curPos = nextPos; - ++i; + m_mode = m; + cyclic = false; + + (this->*initializers[m_mode])(controls, count, cyclic, 0); } - return length; -} -void SplineBase::init_spline(const Vector3 * controls, index_type count, EvaluationMode m) -{ - m_mode = m; - cyclic = false; - - (this->*initializers[m_mode])(controls, count, cyclic, 0); -} - -void SplineBase::init_cyclic_spline(const Vector3 * controls, index_type count, EvaluationMode m, index_type cyclic_point) -{ - m_mode = m; - cyclic = true; - - (this->*initializers[m_mode])(controls, count, cyclic, cyclic_point); -} - -void SplineBase::InitLinear(const Vector3* controls, index_type count, bool cyclic, index_type cyclic_point) -{ - ASSERT(count >= 2); - const int real_size = count + 1; - - points.resize(real_size); - - memcpy(&points[0], controls, sizeof(Vector3) * count); - - // first and last two indexes are space for special 'virtual points' - // these points are required for proper C_Evaluate and C_Evaluate_Derivative methtod work - if (cyclic) - points[count] = controls[cyclic_point]; - else - points[count] = controls[count-1]; - - index_lo = 0; - index_hi = cyclic ? count : (count - 1); -} - -void SplineBase::InitCatmullRom(const Vector3* controls, index_type count, bool cyclic, index_type cyclic_point) -{ - const int real_size = count + (cyclic ? (1+2) : (1+1)); - - points.resize(real_size); - - int lo_index = 1; - int high_index = lo_index + count - 1; - - memcpy(&points[lo_index], controls, sizeof(Vector3) * count); - - // first and last two indexes are space for special 'virtual points' - // these points are required for proper C_Evaluate and C_Evaluate_Derivative methtod work - if (cyclic) + void SplineBase::init_cyclic_spline(const Vector3* controls, index_type count, EvaluationMode m, index_type cyclic_point) { - if (cyclic_point == 0) - points[0] = controls[count-1]; + m_mode = m; + cyclic = true; + + (this->*initializers[m_mode])(controls, count, cyclic, cyclic_point); + } + + void SplineBase::InitLinear(const Vector3* controls, index_type count, bool cyclic, index_type cyclic_point) + { + ASSERT(count >= 2); + const int real_size = count + 1; + + points.resize(real_size); + + memcpy(&points[0], controls, sizeof(Vector3) * count); + + // first and last two indexes are space for special 'virtual points' + // these points are required for proper C_Evaluate and C_Evaluate_Derivative methtod work + if (cyclic) + points[count] = controls[cyclic_point]; else - points[0] = controls[0].lerp(controls[1], -1); + points[count] = controls[count - 1]; - points[high_index+1] = controls[cyclic_point]; - points[high_index+2] = controls[cyclic_point+1]; + index_lo = 0; + index_hi = cyclic ? count : (count - 1); } - else + + void SplineBase::InitCatmullRom(const Vector3* controls, index_type count, bool cyclic, index_type cyclic_point) { - points[0] = controls[0].lerp(controls[1], -1); - points[high_index+1] = controls[count-1]; + const int real_size = count + (cyclic ? (1 + 2) : (1 + 1)); + + points.resize(real_size); + + int lo_index = 1; + int high_index = lo_index + count - 1; + + memcpy(&points[lo_index], controls, sizeof(Vector3) * count); + + // first and last two indexes are space for special 'virtual points' + // these points are required for proper C_Evaluate and C_Evaluate_Derivative methtod work + if (cyclic) + { + if (cyclic_point == 0) + points[0] = controls[count - 1]; + else + points[0] = controls[0].lerp(controls[1], -1); + + points[high_index + 1] = controls[cyclic_point]; + points[high_index + 2] = controls[cyclic_point + 1]; + } + else + { + points[0] = controls[0].lerp(controls[1], -1); + points[high_index + 1] = controls[count - 1]; + } + + index_lo = lo_index; + index_hi = high_index + (cyclic ? 1 : 0); } - index_lo = lo_index; - index_hi = high_index + (cyclic ? 1 : 0); -} + void SplineBase::InitBezier3(const Vector3* controls, index_type count, bool /*cyclic*/, index_type /*cyclic_point*/) + { + index_type c = count / 3u * 3u; + index_type t = c / 3u; -void SplineBase::InitBezier3(const Vector3* controls, index_type count, bool /*cyclic*/, index_type /*cyclic_point*/) -{ - index_type c = count / 3u * 3u; - index_type t = c / 3u; + points.resize(c); + memcpy(&points[0], controls, sizeof(Vector3) * c); - points.resize(c); - memcpy(&points[0], controls, sizeof(Vector3) * c); + index_lo = 0; + index_hi = t - 1; + //mov_assert(points.size() % 3 == 0); + } - index_lo = 0; - index_hi = t-1; - //mov_assert(points.size() % 3 == 0); -} + void SplineBase::clear() + { + index_lo = 0; + index_hi = 0; + points.clear(); + pointsVisual.clear(); + } -void SplineBase::clear() -{ - index_lo = 0; - index_hi = 0; - points.clear(); - pointsVisual.clear(); -} + std::string SplineBase::ToString() const + { + std::stringstream str; + const char* mode_str[ModesEnd] = {"Linear", "CatmullRom", "Bezier3", "Uninitialized"}; -std::string SplineBase::ToString() const -{ - std::stringstream str; - const char * mode_str[ModesEnd] = {"Linear", "CatmullRom", "Bezier3", "Uninitialized"}; + index_type count = this->points.size(); + str << "mode: " << mode_str[mode()] << std::endl; + str << "points count: " << count << std::endl; + for (index_type i = 0; i < count; ++i) + str << "point " << i << " : " << points[i].toString() << std::endl; - index_type count = this->points.size(); - str << "mode: " << mode_str[mode()] << std::endl; - str << "points count: " << count << std::endl; - for (index_type i = 0; i < count; ++i) - str << "point " << i << " : " << points[i].toString() << std::endl; - - return str.str(); -} + return str.str(); + } } diff --git a/src/server/game/Movement/Spline/Spline.h b/src/server/game/Movement/Spline/Spline.h index d11e04128..421931571 100644 --- a/src/server/game/Movement/Spline/Spline.h +++ b/src/server/game/Movement/Spline/Spline.h @@ -11,192 +11,194 @@ #include #include -namespace Movement { - -class SplineBase +namespace Movement { -public: - typedef int index_type; - typedef std::vector ControlArray; - enum EvaluationMode + class SplineBase { - ModeLinear, - ModeCatmullrom, - ModeBezier3_Unused, - UninitializedMode, - ModesEnd - }; + public: + typedef int index_type; + typedef std::vector ControlArray; -protected: - ControlArray points; - ControlArray pointsVisual; - - index_type index_lo; - index_type index_hi; - - uint8 m_mode; - bool cyclic; - - enum{ - // could be modified, affects segment length evaluation precision - // lesser value saves more performance in cost of lover precision - // minimal value is 1 - // client's value is 20, blizzs use 2-3 steps to compute length - STEPS_PER_SEGMENT = 3 - }; - static_assert(STEPS_PER_SEGMENT > 0, "shouldn't be lesser than 1"); - -protected: - void EvaluateLinear(index_type, float, Vector3&) const; - void EvaluateCatmullRom(index_type, float, Vector3&) const; - void EvaluateBezier3(index_type, float, Vector3&) const; - typedef void (SplineBase::*EvaluationMethtod)(index_type, float, Vector3&) const; - static EvaluationMethtod evaluators[ModesEnd]; - - void EvaluateDerivativeLinear(index_type, float, Vector3&) const; - void EvaluateDerivativeCatmullRom(index_type, float, Vector3&) const; - void EvaluateDerivativeBezier3(index_type, float, Vector3&) const; - static EvaluationMethtod derivative_evaluators[ModesEnd]; - - float SegLengthLinear(index_type) const; - float SegLengthCatmullRom(index_type) const; - float SegLengthBezier3(index_type) const; - typedef float (SplineBase::*SegLenghtMethtod)(index_type) const; - static SegLenghtMethtod seglengths[ModesEnd]; - - void InitLinear(const Vector3*, index_type, bool, index_type); - void InitCatmullRom(const Vector3*, index_type, bool, index_type); - void InitBezier3(const Vector3*, index_type, bool, index_type); - typedef void (SplineBase::*InitMethtod)(const Vector3*, index_type, bool, index_type); - static InitMethtod initializers[ModesEnd]; - - void UninitializedSplineEvaluationMethod(index_type, float, Vector3&) const { ABORT(); } - float UninitializedSplineSegLenghtMethod(index_type) const { ABORT(); } - void UninitializedSplineInitMethod(Vector3 const*, index_type, bool, index_type) { ABORT(); } - -public: - - explicit SplineBase() : index_lo(0), index_hi(0), m_mode(UninitializedMode), cyclic(false) {} - - /** Caclulates the position for given segment Idx, and percent of segment length t - @param t - percent of segment length, assumes that t in range [0, 1] - @param Idx - spline segment index, should be in range [first, last) - */ - void evaluate_percent(index_type Idx, float u, Vector3& c) const {(this->*evaluators[m_mode])(Idx, u,c);} - - /** Caclulates derivation in index Idx, and percent of segment length t - @param Idx - spline segment index, should be in range [first, last) - @param t - percent of spline segment length, assumes that t in range [0, 1] - */ - void evaluate_derivative(index_type Idx, float u, Vector3& hermite) const {(this->*derivative_evaluators[m_mode])(Idx, u,hermite);} - - /** Bounds for spline indexes. All indexes should be in range [first, last). */ - index_type first() const { return index_lo;} - index_type last() const { return index_hi;} - - bool empty() const { return index_lo == index_hi;} - EvaluationMode mode() const { return (EvaluationMode)m_mode;} - bool isCyclic() const { return cyclic;} - - // Xinef: DO NOT USE EXCEPT FOR SPLINE INITIALIZATION!!!!!! - const ControlArray* allocateVisualPoints() const { return &pointsVisual; } - const ControlArray& getPoints(bool visual) const { return visual ? pointsVisual : points;} - index_type getPointCount() const { return points.size();} - const Vector3& getPoint(index_type i, bool visual) const { return visual ? pointsVisual[i] : points[i];} - - /** Initializes spline. Don't call other methods while spline not initialized. */ - void init_spline(const Vector3 * controls, index_type count, EvaluationMode m); - void init_cyclic_spline(const Vector3 * controls, index_type count, EvaluationMode m, index_type cyclic_point); - - /** As i can see there are a lot of ways how spline can be initialized - would be no harm to have some custom initializers. */ - template inline void init_spline_custom(Init& initializer) - { - initializer(m_mode, cyclic, points, index_lo, index_hi); - } - - void clear(); - - /** Calculates distance between [i; i+1] points, assumes that index i is in bounds. */ - float SegLength(index_type i) const { return (this->*seglengths[m_mode])(i);} - - std::string ToString() const; -}; - -template -class Spline : public SplineBase -{ -public: - typedef length_type LengthType; - typedef std::vector LengthArray; -protected: - - LengthArray lengths; - - index_type computeIndexInBounds(length_type length) const; -public: - - explicit Spline(){} - - /** Calculates the position for given t - @param t - percent of spline's length, assumes that t in range [0, 1]. */ - void evaluate_percent(float t, Vector3 & c) const; - - /** Calculates derivation for given t - @param t - percent of spline's length, assumes that t in range [0, 1]. */ - void evaluate_derivative(float t, Vector3& hermite) const; - - /** Calculates the position for given segment Idx, and percent of segment length t - @param t = partial_segment_length / whole_segment_length - @param Idx - spline segment index, should be in range [first, last). */ - void evaluate_percent(index_type Idx, float u, Vector3& c) const { SplineBase::evaluate_percent(Idx, u,c);} - - /** Caclulates derivation for index Idx, and percent of segment length t - @param Idx - spline segment index, should be in range [first, last) - @param t - percent of spline segment length, assumes that t in range [0, 1]. */ - void evaluate_derivative(index_type Idx, float u, Vector3& c) const { SplineBase::evaluate_derivative(Idx, u,c);} - - // Assumes that t in range [0, 1] - index_type computeIndexInBounds(float t) const; - void computeIndex(float t, index_type& out_idx, float& out_u) const; - - /** Initializes spline. Don't call other methods while spline not initialized. */ - void init_spline(const Vector3 * controls, index_type count, EvaluationMode m) { SplineBase::init_spline(controls, count, m);} - void init_cyclic_spline(const Vector3 * controls, index_type count, EvaluationMode m, index_type cyclic_point) { SplineBase::init_cyclic_spline(controls, count, m,cyclic_point);} - - /** Initializes lengths with SplineBase::SegLength method. */ - void initLengths(); - - /** Initializes lengths in some custom way - Note that value returned by cacher must be greater or equal to previous value. */ - template inline void initLengths(T& cacher) - { - index_type i = index_lo; - lengths.resize(index_hi+1); - length_type prev_length = 0, new_length = 0; - while (i < index_hi) + enum EvaluationMode { - new_length = cacher(*this, i); - // length overflowed, assign to max positive value - if (new_length < 0) - new_length = std::numeric_limits::max(); - lengths[++i] = new_length; + ModeLinear, + ModeCatmullrom, + ModeBezier3_Unused, + UninitializedMode, + ModesEnd + }; - ASSERT(prev_length <= new_length); - prev_length = new_length; + protected: + ControlArray points; + ControlArray pointsVisual; + + index_type index_lo; + index_type index_hi; + + uint8 m_mode; + bool cyclic; + + enum + { + // could be modified, affects segment length evaluation precision + // lesser value saves more performance in cost of lover precision + // minimal value is 1 + // client's value is 20, blizzs use 2-3 steps to compute length + STEPS_PER_SEGMENT = 3 + }; + static_assert(STEPS_PER_SEGMENT > 0, "shouldn't be lesser than 1"); + + protected: + void EvaluateLinear(index_type, float, Vector3&) const; + void EvaluateCatmullRom(index_type, float, Vector3&) const; + void EvaluateBezier3(index_type, float, Vector3&) const; + typedef void (SplineBase::*EvaluationMethtod)(index_type, float, Vector3&) const; + static EvaluationMethtod evaluators[ModesEnd]; + + void EvaluateDerivativeLinear(index_type, float, Vector3&) const; + void EvaluateDerivativeCatmullRom(index_type, float, Vector3&) const; + void EvaluateDerivativeBezier3(index_type, float, Vector3&) const; + static EvaluationMethtod derivative_evaluators[ModesEnd]; + + float SegLengthLinear(index_type) const; + float SegLengthCatmullRom(index_type) const; + float SegLengthBezier3(index_type) const; + typedef float (SplineBase::*SegLenghtMethtod)(index_type) const; + static SegLenghtMethtod seglengths[ModesEnd]; + + void InitLinear(const Vector3*, index_type, bool, index_type); + void InitCatmullRom(const Vector3*, index_type, bool, index_type); + void InitBezier3(const Vector3*, index_type, bool, index_type); + typedef void (SplineBase::*InitMethtod)(const Vector3*, index_type, bool, index_type); + static InitMethtod initializers[ModesEnd]; + + void UninitializedSplineEvaluationMethod(index_type, float, Vector3&) const { ABORT(); } + float UninitializedSplineSegLenghtMethod(index_type) const { ABORT(); } + void UninitializedSplineInitMethod(Vector3 const*, index_type, bool, index_type) { ABORT(); } + + public: + + explicit SplineBase() : index_lo(0), index_hi(0), m_mode(UninitializedMode), cyclic(false) {} + + /** Caclulates the position for given segment Idx, and percent of segment length t + @param t - percent of segment length, assumes that t in range [0, 1] + @param Idx - spline segment index, should be in range [first, last) + */ + void evaluate_percent(index_type Idx, float u, Vector3& c) const {(this->*evaluators[m_mode])(Idx, u, c);} + + /** Caclulates derivation in index Idx, and percent of segment length t + @param Idx - spline segment index, should be in range [first, last) + @param t - percent of spline segment length, assumes that t in range [0, 1] + */ + void evaluate_derivative(index_type Idx, float u, Vector3& hermite) const {(this->*derivative_evaluators[m_mode])(Idx, u, hermite);} + + /** Bounds for spline indexes. All indexes should be in range [first, last). */ + index_type first() const { return index_lo;} + index_type last() const { return index_hi;} + + bool empty() const { return index_lo == index_hi;} + EvaluationMode mode() const { return (EvaluationMode)m_mode;} + bool isCyclic() const { return cyclic;} + + // Xinef: DO NOT USE EXCEPT FOR SPLINE INITIALIZATION!!!!!! + const ControlArray* allocateVisualPoints() const { return &pointsVisual; } + const ControlArray& getPoints(bool visual) const { return visual ? pointsVisual : points;} + index_type getPointCount() const { return points.size();} + const Vector3& getPoint(index_type i, bool visual) const { return visual ? pointsVisual[i] : points[i];} + + /** Initializes spline. Don't call other methods while spline not initialized. */ + void init_spline(const Vector3* controls, index_type count, EvaluationMode m); + void init_cyclic_spline(const Vector3* controls, index_type count, EvaluationMode m, index_type cyclic_point); + + /** As i can see there are a lot of ways how spline can be initialized + would be no harm to have some custom initializers. */ + template inline void init_spline_custom(Init& initializer) + { + initializer(m_mode, cyclic, points, index_lo, index_hi); } - } - /** Returns length of the whole spline. */ - length_type length() const { return lengths[index_hi];} - /** Returns length between given nodes. */ - length_type length(index_type first, index_type last) const { return lengths[last]-lengths[first];} - length_type length(index_type Idx) const { return lengths[Idx];} + void clear(); - void set_length(index_type i, length_type length) { lengths[i] = length;} - void clear(); -}; + /** Calculates distance between [i; i+1] points, assumes that index i is in bounds. */ + float SegLength(index_type i) const { return (this->*seglengths[m_mode])(i);} + + std::string ToString() const; + }; + + template + class Spline : public SplineBase + { + public: + typedef length_type LengthType; + typedef std::vector LengthArray; + protected: + + LengthArray lengths; + + index_type computeIndexInBounds(length_type length) const; + public: + + explicit Spline() {} + + /** Calculates the position for given t + @param t - percent of spline's length, assumes that t in range [0, 1]. */ + void evaluate_percent(float t, Vector3& c) const; + + /** Calculates derivation for given t + @param t - percent of spline's length, assumes that t in range [0, 1]. */ + void evaluate_derivative(float t, Vector3& hermite) const; + + /** Calculates the position for given segment Idx, and percent of segment length t + @param t = partial_segment_length / whole_segment_length + @param Idx - spline segment index, should be in range [first, last). */ + void evaluate_percent(index_type Idx, float u, Vector3& c) const { SplineBase::evaluate_percent(Idx, u, c);} + + /** Caclulates derivation for index Idx, and percent of segment length t + @param Idx - spline segment index, should be in range [first, last) + @param t - percent of spline segment length, assumes that t in range [0, 1]. */ + void evaluate_derivative(index_type Idx, float u, Vector3& c) const { SplineBase::evaluate_derivative(Idx, u, c);} + + // Assumes that t in range [0, 1] + index_type computeIndexInBounds(float t) const; + void computeIndex(float t, index_type& out_idx, float& out_u) const; + + /** Initializes spline. Don't call other methods while spline not initialized. */ + void init_spline(const Vector3* controls, index_type count, EvaluationMode m) { SplineBase::init_spline(controls, count, m);} + void init_cyclic_spline(const Vector3* controls, index_type count, EvaluationMode m, index_type cyclic_point) { SplineBase::init_cyclic_spline(controls, count, m, cyclic_point);} + + /** Initializes lengths with SplineBase::SegLength method. */ + void initLengths(); + + /** Initializes lengths in some custom way + Note that value returned by cacher must be greater or equal to previous value. */ + template inline void initLengths(T& cacher) + { + index_type i = index_lo; + lengths.resize(index_hi + 1); + length_type prev_length = 0, new_length = 0; + while (i < index_hi) + { + new_length = cacher(*this, i); + // length overflowed, assign to max positive value + if (new_length < 0) + new_length = std::numeric_limits::max(); + lengths[++i] = new_length; + + ASSERT(prev_length <= new_length); + prev_length = new_length; + } + } + + /** Returns length of the whole spline. */ + length_type length() const { return lengths[index_hi];} + /** Returns length between given nodes. */ + length_type length(index_type first, index_type last) const { return lengths[last] - lengths[first];} + length_type length(index_type Idx) const { return lengths[Idx];} + + void set_length(index_type i, length_type length) { lengths[i] = length;} + void clear(); + }; } diff --git a/src/server/game/Movement/Spline/SplineImpl.h b/src/server/game/Movement/Spline/SplineImpl.h index 1fd3b6ab4..1c1f46222 100644 --- a/src/server/game/Movement/Spline/SplineImpl.h +++ b/src/server/game/Movement/Spline/SplineImpl.h @@ -6,80 +6,80 @@ namespace Movement { -template void Spline::evaluate_percent( float t, Vector3 & c ) const -{ - index_type Index; - float u; - computeIndex(t, Index, u); - evaluate_percent(Index, u, c); -} - -template void Spline::evaluate_derivative(float t, Vector3& hermite) const -{ - index_type Index; - float u; - computeIndex(t, Index, u); - evaluate_derivative(Index, u, hermite); -} - -template SplineBase::index_type Spline::computeIndexInBounds(length_type length_) const -{ -// Temporary disabled: causes infinite loop with t = 1.f -/* - index_type hi = index_hi; - index_type lo = index_lo; - - index_type i = lo + (float)(hi - lo) * t; - - while ((lengths[i] > length) || (lengths[i + 1] <= length)) + template void Spline::evaluate_percent( float t, Vector3& c ) const { - if (lengths[i] > length) - hi = i - 1; // too big - else if (lengths[i + 1] <= length) - lo = i + 1; // too small - - i = (hi + lo) / 2; - }*/ - - index_type i = index_lo; - index_type N = index_hi; - while (i+1 < N && lengths[i+1] < length_) - ++i; - - return i; -} - -template void Spline::computeIndex(float t, index_type& index, float& u) const -{ - ASSERT(t >= 0.f && t <= 1.f); - length_type length_ = t * length(); - index = computeIndexInBounds(length_); - ASSERT(index < index_hi); - u = (length_ - length(index)) / (float)length(index, index+1); -} - -template SplineBase::index_type Spline::computeIndexInBounds( float t ) const -{ - ASSERT(t >= 0.f && t <= 1.f); - return computeIndexInBounds(t * length()); -} - -template void Spline::initLengths() -{ - index_type i = index_lo; - length_type length = 0; - lengths.resize(index_hi+1); - while (i < index_hi) - { - length += SegLength(i); - lengths[++i] = length; + index_type Index; + float u; + computeIndex(t, Index, u); + evaluate_percent(Index, u, c); } -} -template void Spline::clear() -{ - SplineBase::clear(); - lengths.clear(); -} + template void Spline::evaluate_derivative(float t, Vector3& hermite) const + { + index_type Index; + float u; + computeIndex(t, Index, u); + evaluate_derivative(Index, u, hermite); + } + + template SplineBase::index_type Spline::computeIndexInBounds(length_type length_) const + { + // Temporary disabled: causes infinite loop with t = 1.f + /* + index_type hi = index_hi; + index_type lo = index_lo; + + index_type i = lo + (float)(hi - lo) * t; + + while ((lengths[i] > length) || (lengths[i + 1] <= length)) + { + if (lengths[i] > length) + hi = i - 1; // too big + else if (lengths[i + 1] <= length) + lo = i + 1; // too small + + i = (hi + lo) / 2; + }*/ + + index_type i = index_lo; + index_type N = index_hi; + while (i + 1 < N && lengths[i + 1] < length_) + ++i; + + return i; + } + + template void Spline::computeIndex(float t, index_type& index, float& u) const + { + ASSERT(t >= 0.f && t <= 1.f); + length_type length_ = t * length(); + index = computeIndexInBounds(length_); + ASSERT(index < index_hi); + u = (length_ - length(index)) / (float)length(index, index + 1); + } + + template SplineBase::index_type Spline::computeIndexInBounds( float t ) const + { + ASSERT(t >= 0.f && t <= 1.f); + return computeIndexInBounds(t * length()); + } + + template void Spline::initLengths() + { + index_type i = index_lo; + length_type length = 0; + lengths.resize(index_hi + 1); + while (i < index_hi) + { + length += SegLength(i); + lengths[++i] = length; + } + } + + template void Spline::clear() + { + SplineBase::clear(); + lengths.clear(); + } } diff --git a/src/server/game/Movement/Waypoints/WaypointManager.cpp b/src/server/game/Movement/Waypoints/WaypointManager.cpp index 20397158c..e64d88788 100644 --- a/src/server/game/Movement/Waypoints/WaypointManager.cpp +++ b/src/server/game/Movement/Waypoints/WaypointManager.cpp @@ -85,8 +85,7 @@ void WaypointMgr::Load() path.push_back(wp); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u waypoints in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -133,20 +132,19 @@ void WaypointMgr::ReloadPath(uint32 id) wp->z = z; wp->orientation = o; wp->move_type = fields[5].GetUInt32(); - + if (wp->move_type >= WAYPOINT_MOVE_TYPE_MAX) { //TC_LOG_ERROR("sql.sql", "Waypoint %u in waypoint_data has invalid move_type, ignoring", wp->id); delete wp; continue; } - + wp->delay = fields[6].GetUInt32(); wp->event_id = fields[7].GetUInt32(); wp->event_chance = fields[8].GetUInt8(); path.push_back(wp); - } - while (result->NextRow()); + } while (result->NextRow()); } diff --git a/src/server/game/Movement/Waypoints/WaypointManager.h b/src/server/game/Movement/Waypoints/WaypointManager.h index d5c74f5eb..9b13d221b 100644 --- a/src/server/game/Movement/Waypoints/WaypointManager.h +++ b/src/server/game/Movement/Waypoints/WaypointManager.h @@ -36,30 +36,30 @@ typedef std::unordered_map WaypointPathContainer; class WaypointMgr { - public: - static WaypointMgr* instance(); +public: + static WaypointMgr* instance(); - // Attempts to reload a single path from database - void ReloadPath(uint32 id); + // Attempts to reload a single path from database + void ReloadPath(uint32 id); - // Loads all paths from database, should only run on startup - void Load(); + // Loads all paths from database, should only run on startup + void Load(); - // Returns the path from a given id - WaypointPath const* GetPath(uint32 id) const - { - WaypointPathContainer::const_iterator itr = _waypointStore.find(id); - if (itr != _waypointStore.end()) - return &itr->second; + // Returns the path from a given id + WaypointPath const* GetPath(uint32 id) const + { + WaypointPathContainer::const_iterator itr = _waypointStore.find(id); + if (itr != _waypointStore.end()) + return &itr->second; - return nullptr; - } + return nullptr; + } - private: - WaypointMgr(); - ~WaypointMgr(); +private: + WaypointMgr(); + ~WaypointMgr(); - WaypointPathContainer _waypointStore; + WaypointPathContainer _waypointStore; }; #define sWaypointMgr WaypointMgr::instance() diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index 373b0fee0..f95705e25 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -394,7 +394,7 @@ void OutdoorPvP::SendUpdateWorldState(uint32 field, uint32 value) if (m_sendUpdate) for (int i = 0; i < 2; ++i) for (PlayerSet::iterator itr = m_players[i].begin(); itr != m_players[i].end(); ++itr) - if (Player * const player = ObjectAccessor::FindPlayer(*itr)) + if (Player* const player = ObjectAccessor::FindPlayer(*itr)) player->SendUpdateWorldState(field, value); } @@ -404,7 +404,7 @@ void OPvPCapturePoint::SendUpdateWorldState(uint32 field, uint32 value) { // send to all players present in the area for (PlayerSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr) - if (Player * const player = ObjectAccessor::FindPlayer(*itr)) + if (Player* const player = ObjectAccessor::FindPlayer(*itr)) player->SendUpdateWorldState(field, value); } } @@ -414,19 +414,19 @@ void OPvPCapturePoint::SendObjectiveComplete(uint32 id, uint64 guid) uint32 team; switch (m_State) { - case OBJECTIVESTATE_ALLIANCE: - team = 0; - break; - case OBJECTIVESTATE_HORDE: - team = 1; - break; - default: - return; + case OBJECTIVESTATE_ALLIANCE: + team = 0; + break; + case OBJECTIVESTATE_HORDE: + team = 1; + break; + default: + return; } // send to all players present in the area for (PlayerSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr) - if (Player * const player = ObjectAccessor::FindPlayer(*itr)) + if (Player* const player = ObjectAccessor::FindPlayer(*itr)) player->KilledMonsterCredit(id, guid); } @@ -474,7 +474,7 @@ bool OutdoorPvP::IsInsideObjective(Player* player) const bool OPvPCapturePoint::IsInsideObjective(Player* player) const { - PlayerSet const &plSet = m_activePlayers[player->GetTeamId()]; + PlayerSet const& plSet = m_activePlayers[player->GetTeamId()]; return plSet.find(player->GetGUID()) != plSet.end(); } @@ -560,12 +560,12 @@ bool OutdoorPvP::HandleAreaTrigger(Player* /*player*/, uint32 /*trigger*/) return false; } -void OutdoorPvP::BroadcastPacket(WorldPacket &data) const +void OutdoorPvP::BroadcastPacket(WorldPacket& data) const { // This is faster than sWorld->SendZoneMessage for (uint32 team = 0; team < 2; ++team) for (PlayerSet::const_iterator itr = m_players[team].begin(); itr != m_players[team].end(); ++itr) - if (Player * const player = ObjectAccessor::FindPlayer(*itr)) + if (Player* const player = ObjectAccessor::FindPlayer(*itr)) player->GetSession()->SendPacket(&data); } @@ -576,7 +576,7 @@ void OutdoorPvP::RegisterZone(uint32 zoneId) bool OutdoorPvP::HasPlayer(Player const* player) const { - PlayerSet const &plSet = m_players[player->GetTeamId()]; + PlayerSet const& plSet = m_players[player->GetTeamId()]; return plSet.find(player->GetGUID()) != plSet.end(); } @@ -585,16 +585,16 @@ void OutdoorPvP::TeamCastSpell(TeamId team, int32 spellId, Player* sameMapPlr) if (spellId > 0) { for (PlayerSet::iterator itr = m_players[team].begin(); itr != m_players[team].end(); ++itr) - if (Player * const player = ObjectAccessor::FindPlayer(*itr)) + if (Player* const player = ObjectAccessor::FindPlayer(*itr)) if (!sameMapPlr || sameMapPlr->FindMap() == player->FindMap()) player->CastSpell(player, (uint32)spellId, true); } else { for (PlayerSet::iterator itr = m_players[team].begin(); itr != m_players[team].end(); ++itr) - if (Player * const player = ObjectAccessor::FindPlayer(*itr)) + if (Player* const player = ObjectAccessor::FindPlayer(*itr)) if (!sameMapPlr || sameMapPlr->FindMap() == player->FindMap()) - player->RemoveAura((uint32)-spellId); // by stack? + player->RemoveAura((uint32) - spellId); // by stack? } } @@ -609,7 +609,7 @@ void OutdoorPvP::OnGameObjectCreate(GameObject* go) if (go->GetGoType() != GAMEOBJECT_TYPE_CAPTURE_POINT) return; - if (OPvPCapturePoint *cp = GetCapturePoint(go->GetDBTableGUIDLow())) + if (OPvPCapturePoint* cp = GetCapturePoint(go->GetDBTableGUIDLow())) cp->m_capturePoint = go; } @@ -618,6 +618,6 @@ void OutdoorPvP::OnGameObjectRemove(GameObject* go) if (go->GetGoType() != GAMEOBJECT_TYPE_CAPTURE_POINT) return; - if (OPvPCapturePoint *cp = GetCapturePoint(go->GetDBTableGUIDLow())) + if (OPvPCapturePoint* cp = GetCapturePoint(go->GetDBTableGUIDLow())) cp->m_capturePoint = nullptr; } diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.h b/src/server/game/OutdoorPvP/OutdoorPvP.h index 10fdb839f..bfd6077dc 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.h +++ b/src/server/game/OutdoorPvP/OutdoorPvP.h @@ -76,102 +76,102 @@ typedef std::set PlayerSet; class OPvPCapturePoint { - public: +public: - OPvPCapturePoint(OutdoorPvP* pvp); + OPvPCapturePoint(OutdoorPvP* pvp); - virtual ~OPvPCapturePoint() {} + virtual ~OPvPCapturePoint() {} - virtual void FillInitialWorldStates(WorldPacket & /*data*/) {} + virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} - // send world state update to all players present - void SendUpdateWorldState(uint32 field, uint32 value); + // send world state update to all players present + void SendUpdateWorldState(uint32 field, uint32 value); - // send kill notify to players in the controlling faction - void SendObjectiveComplete(uint32 id, uint64 guid); + // send kill notify to players in the controlling faction + void SendObjectiveComplete(uint32 id, uint64 guid); - // used when player is activated/inactivated in the area - virtual bool HandlePlayerEnter(Player* player); - virtual void HandlePlayerLeave(Player* player); + // used when player is activated/inactivated in the area + virtual bool HandlePlayerEnter(Player* player); + virtual void HandlePlayerLeave(Player* player); - // checks if player is in range of a capture credit marker - bool IsInsideObjective(Player* player) const; + // checks if player is in range of a capture credit marker + bool IsInsideObjective(Player* player) const; - virtual bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); + virtual bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); - virtual int32 HandleOpenGo(Player* player, uint64 guid); + virtual int32 HandleOpenGo(Player* player, uint64 guid); - // returns true if the state of the objective has changed, in this case, the OutdoorPvP must send a world state ui update. - virtual bool Update(uint32 diff); + // returns true if the state of the objective has changed, in this case, the OutdoorPvP must send a world state ui update. + virtual bool Update(uint32 diff); - virtual void ChangeState() = 0; + virtual void ChangeState() = 0; - virtual void ChangeTeam(TeamId /*oldTeam*/) {} + virtual void ChangeTeam(TeamId /*oldTeam*/) {} - virtual void SendChangePhase(); + virtual void SendChangePhase(); - virtual bool HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); + virtual bool HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); - virtual bool CanTalkTo(Player* player, Creature* c, GossipMenuItems const& gso); + virtual bool CanTalkTo(Player* player, Creature* c, GossipMenuItems const& gso); - virtual bool HandleDropFlag(Player* player, uint32 spellId); + virtual bool HandleDropFlag(Player* player, uint32 spellId); - virtual void DeleteSpawns(); + virtual void DeleteSpawns(); - uint64 m_capturePointGUID; + uint64 m_capturePointGUID; - GameObject* m_capturePoint; + GameObject* m_capturePoint; - void AddGO(uint32 type, uint32 guid, uint32 entry = 0); - void AddCre(uint32 type, uint32 guid, uint32 entry = 0); + void AddGO(uint32 type, uint32 guid, uint32 entry = 0); + void AddCre(uint32 type, uint32 guid, uint32 entry = 0); - bool SetCapturePointData(uint32 entry, uint32 map, float x, float y, float z, float o = 0, - float rotation0 = 0, float rotation1 = 0, float rotation2 = 0, float rotation3 = 0); + bool SetCapturePointData(uint32 entry, uint32 map, float x, float y, float z, float o = 0, + float rotation0 = 0, float rotation1 = 0, float rotation2 = 0, float rotation3 = 0); - protected: +protected: - bool AddObject(uint32 type, uint32 entry, uint32 map, float x, float y, float z, float o, - float rotation0, float rotation1, float rotation2, float rotation3); - bool AddCreature(uint32 type, uint32 entry, uint32 map, float x, float y, float z, float o, uint32 spawntimedelay = 0); + bool AddObject(uint32 type, uint32 entry, uint32 map, float x, float y, float z, float o, + float rotation0, float rotation1, float rotation2, float rotation3); + bool AddCreature(uint32 type, uint32 entry, uint32 map, float x, float y, float z, float o, uint32 spawntimedelay = 0); - bool DelCreature(uint32 type); - bool DelObject(uint32 type); + bool DelCreature(uint32 type); + bool DelObject(uint32 type); - bool DelCapturePoint(); + bool DelCapturePoint(); - protected: +protected: - // active players in the area of the objective, 0 - alliance, 1 - horde - PlayerSet m_activePlayers[2]; + // active players in the area of the objective, 0 - alliance, 1 - horde + PlayerSet m_activePlayers[2]; - // total shift needed to capture the objective - float m_maxValue; - float m_minValue; + // total shift needed to capture the objective + float m_maxValue; + float m_minValue; - // maximum speed of capture - float m_maxSpeed; + // maximum speed of capture + float m_maxSpeed; - // the status of the objective - float m_value; + // the status of the objective + float m_value; - TeamId m_team; + TeamId m_team; - // objective states - ObjectiveStates m_OldState; - ObjectiveStates m_State; + // objective states + ObjectiveStates m_OldState; + ObjectiveStates m_State; - // neutral value on capture bar - uint32 m_neutralValuePct; + // neutral value on capture bar + uint32 m_neutralValuePct; - // pointer to the OutdoorPvP this objective belongs to - OutdoorPvP* m_PvP; + // pointer to the OutdoorPvP this objective belongs to + OutdoorPvP* m_PvP; - // map to store the various gameobjects and creatures spawned by the objective - // type, guid - std::map m_Objects; - std::map m_Creatures; - std::map m_ObjectTypes; - std::map m_CreatureTypes; + // map to store the various gameobjects and creatures spawned by the objective + // type, guid + std::map m_Objects; + std::map m_Creatures; + std::map m_ObjectTypes; + std::map m_CreatureTypes; }; // base class for specific outdoor pvp handlers @@ -179,102 +179,102 @@ class OutdoorPvP : public ZoneScript { friend class OutdoorPvPMgr; - public: +public: - // ctor - OutdoorPvP(); + // ctor + OutdoorPvP(); - // dtor - virtual ~OutdoorPvP(); + // dtor + virtual ~OutdoorPvP(); - // deletes all gos/creatures spawned by the pvp - void DeleteSpawns(); + // deletes all gos/creatures spawned by the pvp + void DeleteSpawns(); - typedef std::map OPvPCapturePointMap; + typedef std::map OPvPCapturePointMap; - virtual void FillInitialWorldStates(WorldPacket & /*data*/) {} + virtual void FillInitialWorldStates(WorldPacket& /*data*/) {} - // called when a player triggers an areatrigger - virtual bool HandleAreaTrigger(Player* player, uint32 trigger); + // called when a player triggers an areatrigger + virtual bool HandleAreaTrigger(Player* player, uint32 trigger); - // called on custom spell - virtual bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); + // called on custom spell + virtual bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); - // called on go use - virtual bool HandleOpenGo(Player* player, uint64 guid); + // called on go use + virtual bool HandleOpenGo(Player* player, uint64 guid); - // setup stuff - virtual bool SetupOutdoorPvP() {return true;} + // setup stuff + virtual bool SetupOutdoorPvP() {return true;} - void OnGameObjectCreate(GameObject* go); - void OnGameObjectRemove(GameObject* go); - void OnCreatureCreate(Creature*) {} + void OnGameObjectCreate(GameObject* go); + void OnGameObjectRemove(GameObject* go); + void OnCreatureCreate(Creature*) {} - // send world state update to all players present - void SendUpdateWorldState(uint32 field, uint32 value); + // send world state update to all players present + void SendUpdateWorldState(uint32 field, uint32 value); - // called by OutdoorPvPMgr, updates the objectives and if needed, sends new worldstateui information - virtual bool Update(uint32 diff); + // called by OutdoorPvPMgr, updates the objectives and if needed, sends new worldstateui information + virtual bool Update(uint32 diff); - // handle npc/player kill - virtual void HandleKill(Player* killer, Unit* killed); - virtual void HandleKillImpl(Player* /*killer*/, Unit* /*killed*/) {} + // handle npc/player kill + virtual void HandleKill(Player* killer, Unit* killed); + virtual void HandleKillImpl(Player* /*killer*/, Unit* /*killed*/) {} - // checks if player is in range of a capture credit marker - bool IsInsideObjective(Player* player) const; + // checks if player is in range of a capture credit marker + bool IsInsideObjective(Player* player) const; - // awards rewards for player kill - virtual void AwardKillBonus(Player* /*player*/) {} + // awards rewards for player kill + virtual void AwardKillBonus(Player* /*player*/) {} - uint32 GetTypeId() {return m_TypeId;} + uint32 GetTypeId() {return m_TypeId;} - virtual bool HandleDropFlag(Player* player, uint32 spellId); + virtual bool HandleDropFlag(Player* player, uint32 spellId); - virtual bool HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); + virtual bool HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); - virtual bool CanTalkTo(Player* player, Creature* c, GossipMenuItems const& gso); + virtual bool CanTalkTo(Player* player, Creature* c, GossipMenuItems const& gso); - void TeamApplyBuff(TeamId teamId, uint32 spellId, uint32 spellId2 = 0, Player* sameMapPlr = nullptr); + void TeamApplyBuff(TeamId teamId, uint32 spellId, uint32 spellId2 = 0, Player* sameMapPlr = nullptr); - protected: +protected: - // the map of the objectives belonging to this outdoorpvp - OPvPCapturePointMap m_capturePoints; + // the map of the objectives belonging to this outdoorpvp + OPvPCapturePointMap m_capturePoints; - PlayerSet m_players[2]; + PlayerSet m_players[2]; - uint32 m_TypeId; + uint32 m_TypeId; - bool m_sendUpdate; + bool m_sendUpdate; - // world state stuff - virtual void SendRemoveWorldStates(Player* /*player*/) {} + // world state stuff + virtual void SendRemoveWorldStates(Player* /*player*/) {} - void BroadcastPacket(WorldPacket & data) const; + void BroadcastPacket(WorldPacket& data) const; - virtual void HandlePlayerEnterZone(Player* player, uint32 zone); - virtual void HandlePlayerLeaveZone(Player* player, uint32 zone); + virtual void HandlePlayerEnterZone(Player* player, uint32 zone); + virtual void HandlePlayerLeaveZone(Player* player, uint32 zone); - virtual void HandlePlayerResurrects(Player* player, uint32 zone); + virtual void HandlePlayerResurrects(Player* player, uint32 zone); - void AddCapturePoint(OPvPCapturePoint* cp) - { - m_capturePoints[GUID_LOPART(cp->m_capturePointGUID)] = cp; - } + void AddCapturePoint(OPvPCapturePoint* cp) + { + m_capturePoints[GUID_LOPART(cp->m_capturePointGUID)] = cp; + } - OPvPCapturePoint * GetCapturePoint(uint32 lowguid) const - { - OutdoorPvP::OPvPCapturePointMap::const_iterator itr = m_capturePoints.find(lowguid); - if (itr != m_capturePoints.end()) - return itr->second; - return nullptr; - } + OPvPCapturePoint* GetCapturePoint(uint32 lowguid) const + { + OutdoorPvP::OPvPCapturePointMap::const_iterator itr = m_capturePoints.find(lowguid); + if (itr != m_capturePoints.end()) + return itr->second; + return nullptr; + } - void RegisterZone(uint32 zoneid); + void RegisterZone(uint32 zoneid); - bool HasPlayer(Player const* player) const; + bool HasPlayer(Player const* player) const; - void TeamCastSpell(TeamId team, int32 spellId, Player* sameMapPlr = nullptr); + void TeamCastSpell(TeamId team, int32 spellId, Player* sameMapPlr = nullptr); }; #endif /*OUTDOOR_PVP_H_*/ diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp index 0ac25ca96..67391fba1 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp @@ -71,8 +71,7 @@ void OutdoorPvPMgr::InitOutdoorPvP() m_OutdoorPvPDatas[realTypeId] = data; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); OutdoorPvP* pvp; for (uint8 i = 1; i < MAX_OUTDOORPVP_TYPES; ++i) diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h index a8b43dd78..5aecdc70c 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h @@ -26,70 +26,70 @@ struct OutdoorPvPData // class to handle player enter / leave / areatrigger / GO use events class OutdoorPvPMgr { - private: - OutdoorPvPMgr(); - ~OutdoorPvPMgr() {}; +private: + OutdoorPvPMgr(); + ~OutdoorPvPMgr() {}; - public: - static OutdoorPvPMgr* instance(); +public: + static OutdoorPvPMgr* instance(); - // create outdoor pvp events - void InitOutdoorPvP(); + // create outdoor pvp events + void InitOutdoorPvP(); - // cleanup - void Die(); + // cleanup + void Die(); - // called when a player enters an outdoor pvp area - void HandlePlayerEnterZone(Player* player, uint32 areaflag); + // called when a player enters an outdoor pvp area + void HandlePlayerEnterZone(Player* player, uint32 areaflag); - // called when player leaves an outdoor pvp area - void HandlePlayerLeaveZone(Player* player, uint32 areaflag); + // called when player leaves an outdoor pvp area + void HandlePlayerLeaveZone(Player* player, uint32 areaflag); - // called when player resurrects - void HandlePlayerResurrects(Player* player, uint32 areaflag); + // called when player resurrects + void HandlePlayerResurrects(Player* player, uint32 areaflag); - // return assigned outdoor pvp - OutdoorPvP* GetOutdoorPvPToZoneId(uint32 zoneid); + // return assigned outdoor pvp + OutdoorPvP* GetOutdoorPvPToZoneId(uint32 zoneid); - // handle custom (non-exist in dbc) spell if registered - bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); + // handle custom (non-exist in dbc) spell if registered + bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); - // handle custom go if registered - bool HandleOpenGo(Player* player, uint64 guid); + // handle custom go if registered + bool HandleOpenGo(Player* player, uint64 guid); - ZoneScript* GetZoneScript(uint32 zoneId); + ZoneScript* GetZoneScript(uint32 zoneId); - void AddZone(uint32 zoneid, OutdoorPvP* handle); + void AddZone(uint32 zoneid, OutdoorPvP* handle); - void Update(uint32 diff); + void Update(uint32 diff); - void HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); + void HandleGossipOption(Player* player, uint64 guid, uint32 gossipid); - bool CanTalkTo(Player* player, Creature* creature, GossipMenuItems const& gso); + bool CanTalkTo(Player* player, Creature* creature, GossipMenuItems const& gso); - void HandleDropFlag(Player* player, uint32 spellId); + void HandleDropFlag(Player* player, uint32 spellId); - // pussywizard: lock required because different functions affect m_players - ACE_Thread_Mutex _lock; + // pussywizard: lock required because different functions affect m_players + ACE_Thread_Mutex _lock; - private: - typedef std::vector OutdoorPvPSet; - typedef std::map OutdoorPvPMap; - typedef std::map OutdoorPvPDataMap; +private: + typedef std::vector OutdoorPvPSet; + typedef std::map OutdoorPvPMap; + typedef std::map OutdoorPvPDataMap; - // contains all initiated outdoor pvp events - // used when initing / cleaning up - OutdoorPvPSet m_OutdoorPvPSet; + // contains all initiated outdoor pvp events + // used when initing / cleaning up + OutdoorPvPSet m_OutdoorPvPSet; - // maps the zone ids to an outdoor pvp event - // used in player event handling - OutdoorPvPMap m_OutdoorPvPMap; + // maps the zone ids to an outdoor pvp event + // used in player event handling + OutdoorPvPMap m_OutdoorPvPMap; - // Holds the outdoor PvP templates - OutdoorPvPDataMap m_OutdoorPvPDatas; + // Holds the outdoor PvP templates + OutdoorPvPDataMap m_OutdoorPvPDatas; - // update interval - uint32 m_UpdateTimer; + // update interval + uint32 m_UpdateTimer; }; #define sOutdoorPvPMgr OutdoorPvPMgr::instance() diff --git a/src/server/game/Petitions/PetitionMgr.h b/src/server/game/Petitions/PetitionMgr.h index f9acf454c..1401ea735 100644 --- a/src/server/game/Petitions/PetitionMgr.h +++ b/src/server/game/Petitions/PetitionMgr.h @@ -29,34 +29,34 @@ typedef std::map PetitionContainer; class PetitionMgr { - private: - PetitionMgr(); - ~PetitionMgr(); +private: + PetitionMgr(); + ~PetitionMgr(); - public: - static PetitionMgr* instance(); +public: + static PetitionMgr* instance(); - void LoadPetitions(); - void LoadSignatures(); - - // Petitions - void AddPetition(uint32 petitionId, uint32 ownerGuid, std::string const& name, uint8 type); - void RemovePetition(uint32 petitionId); - void RemovePetitionByOwnerAndType(uint32 ownerGuid, uint8 type); - Petition const* GetPetition(uint32 petitionId) const; - Petition const* GetPetitionByOwnerWithType(uint32 ownerGuid, uint8 type) const; - PetitionContainer* GetPetitionStore() { return &PetitionStore; } + void LoadPetitions(); + void LoadSignatures(); - // Signatures - void AddSignature(uint32 petitionId, uint32 accountId, uint32 playerGuid); - void RemoveSignaturesByPlayer(uint32 playerGuid); - void RemoveSignaturesByPlayerAndType(uint32 playerGuid, uint8 type); - Signatures const* GetSignature(uint32 petitionId) const; - SignatureContainer* GetSignatureStore() { return &SignatureStore; } + // Petitions + void AddPetition(uint32 petitionId, uint32 ownerGuid, std::string const& name, uint8 type); + void RemovePetition(uint32 petitionId); + void RemovePetitionByOwnerAndType(uint32 ownerGuid, uint8 type); + Petition const* GetPetition(uint32 petitionId) const; + Petition const* GetPetitionByOwnerWithType(uint32 ownerGuid, uint8 type) const; + PetitionContainer* GetPetitionStore() { return &PetitionStore; } - protected: - PetitionContainer PetitionStore; - SignatureContainer SignatureStore; + // Signatures + void AddSignature(uint32 petitionId, uint32 accountId, uint32 playerGuid); + void RemoveSignaturesByPlayer(uint32 playerGuid); + void RemoveSignaturesByPlayerAndType(uint32 playerGuid, uint8 type); + Signatures const* GetSignature(uint32 petitionId) const; + SignatureContainer* GetSignatureStore() { return &SignatureStore; } + +protected: + PetitionContainer PetitionStore; + SignatureContainer SignatureStore; }; #define sPetitionMgr PetitionMgr::instance() diff --git a/src/server/game/Pools/PoolMgr.cpp b/src/server/game/Pools/PoolMgr.cpp index 4ec41073a..fc07442f6 100644 --- a/src/server/game/Pools/PoolMgr.cpp +++ b/src/server/game/Pools/PoolMgr.cpp @@ -154,16 +154,16 @@ PoolObject* PoolGroup::RollOne(ActivePoolData& spawns, uint32 triggerFrom) // Triggering object is marked as spawned at this time and can be also rolled (respawn case) // so this need explicit check for this case if (roll < 0 && (ExplicitlyChanced[i].guid == triggerFrom || !spawns.IsActiveObject(ExplicitlyChanced[i].guid))) - return &ExplicitlyChanced[i]; + return &ExplicitlyChanced[i]; } } if (!EqualChanced.empty()) { - int32 index = irand(0, EqualChanced.size()-1); + int32 index = irand(0, EqualChanced.size() - 1); // Triggering object is marked as spawned at this time and can be also rolled (respawn case) // so this need explicit check for this case if (EqualChanced[index].guid == triggerFrom || !spawns.IsActiveObject(EqualChanced[index].guid)) - return &EqualChanced[index]; + return &EqualChanced[index]; } return nullptr; @@ -175,7 +175,7 @@ PoolObject* PoolGroup::RollOne(ActivePoolData& spawns, uint32 triggerFrom) template void PoolGroup::DespawnObject(ActivePoolData& spawns, uint32 guid) { - for (size_t i=0; i < EqualChanced.size(); ++i) + for (size_t i = 0; i < EqualChanced.size(); ++i) { // if spawned if (spawns.IsActiveObject(EqualChanced[i].guid)) @@ -576,8 +576,7 @@ void PoolMgr::LoadFromDB() pPoolTemplate.MaxLimit = fields[1].GetUInt32(); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u objects pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -634,8 +633,7 @@ void PoolMgr::LoadFromDB() mCreatureSearchMap.insert(p); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u creatures in pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -676,8 +674,8 @@ void PoolMgr::LoadFromDB() GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(data->id); if (goinfo->type != GAMEOBJECT_TYPE_CHEST && - goinfo->type != GAMEOBJECT_TYPE_GOOBER && - goinfo->type != GAMEOBJECT_TYPE_FISHINGHOLE) + goinfo->type != GAMEOBJECT_TYPE_GOOBER && + goinfo->type != GAMEOBJECT_TYPE_FISHINGHOLE) { sLog->outErrorDb("`pool_gameobject` has a not lootable gameobject spawn (GUID: %u, type: %u) defined for pool id (%u), skipped.", guid, goinfo->type, pool_id); continue; @@ -705,8 +703,7 @@ void PoolMgr::LoadFromDB() mGameobjectSearchMap.insert(p); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u gameobject in pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -773,8 +770,7 @@ void PoolMgr::LoadFromDB() mPoolSearchMap.insert(p); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); // Now check for circular reference // All pool_ids are in pool_template @@ -787,11 +783,11 @@ void PoolMgr::LoadFromDB() if (checkedPools.find(poolItr->second) != checkedPools.end()) { std::ostringstream ss; - ss<< "The pool(s) "; - for (std::set::const_iterator itr=checkedPools.begin(); itr != checkedPools.end(); ++itr) + ss << "The pool(s) "; + for (std::set::const_iterator itr = checkedPools.begin(); itr != checkedPools.end(); ++itr) ss << *itr << ' '; ss << "create(s) a circular reference, which can cause the server to freeze.\nRemoving the last link between mother pool " - << poolItr->first << " and child pool " << poolItr->second; + << poolItr->first << " and child pool " << poolItr->second; sLog->outErrorDb("%s", ss.str().c_str()); mPoolPoolGroups[poolItr->second].RemoveOneRelation(poolItr->first); mPoolSearchMap.erase(poolItr); @@ -889,8 +885,7 @@ void PoolMgr::LoadFromDB() mQuestSearchMap.insert(p); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u quests in pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -903,8 +898,8 @@ void PoolMgr::LoadFromDB() uint32 oldMSTime = getMSTime(); QueryResult result = WorldDatabase.Query("SELECT DISTINCT pool_template.entry, pool_pool.pool_id, pool_pool.mother_pool FROM pool_template" - " LEFT JOIN game_event_pool ON pool_template.entry=game_event_pool.pool_entry" - " LEFT JOIN pool_pool ON pool_template.entry=pool_pool.pool_id WHERE game_event_pool.pool_entry IS NULL"); + " LEFT JOIN game_event_pool ON pool_template.entry=game_event_pool.pool_entry" + " LEFT JOIN pool_pool ON pool_template.entry=pool_pool.pool_id WHERE game_event_pool.pool_entry IS NULL"); if (!result) { @@ -937,8 +932,7 @@ void PoolMgr::LoadFromDB() SpawnPool(pool_entry); count++; } - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outBasic("Pool handling system initialized, %u pools spawned in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/Pools/PoolMgr.h b/src/server/game/Pools/PoolMgr.h index 9e0803fd8..11ea7f6d9 100644 --- a/src/server/game/Pools/PoolMgr.h +++ b/src/server/game/Pools/PoolMgr.h @@ -33,56 +33,56 @@ typedef std::map ActivePoolPools; class ActivePoolData { - public: - template - bool IsActiveObject(uint32 db_guid_or_pool_id) const; +public: + template + bool IsActiveObject(uint32 db_guid_or_pool_id) const; - uint32 GetActiveObjectCount(uint32 pool_id) const; + uint32 GetActiveObjectCount(uint32 pool_id) const; - template - void ActivateObject(uint32 db_guid_or_pool_id, uint32 pool_id); + template + void ActivateObject(uint32 db_guid_or_pool_id, uint32 pool_id); - template - void RemoveObject(uint32 db_guid_or_pool_id, uint32 pool_id); + template + void RemoveObject(uint32 db_guid_or_pool_id, uint32 pool_id); - ActivePoolObjects GetActiveQuests() const { return mActiveQuests; } // a copy of the set - private: - ActivePoolObjects mSpawnedCreatures; - ActivePoolObjects mSpawnedGameobjects; - ActivePoolObjects mActiveQuests; - ActivePoolPools mSpawnedPools; + ActivePoolObjects GetActiveQuests() const { return mActiveQuests; } // a copy of the set +private: + ActivePoolObjects mSpawnedCreatures; + ActivePoolObjects mSpawnedGameobjects; + ActivePoolObjects mActiveQuests; + ActivePoolPools mSpawnedPools; }; template class PoolGroup { typedef std::vector PoolObjectList; - public: - explicit PoolGroup() : poolId(0) { } - void SetPoolId(uint32 pool_id) { poolId = pool_id; } - ~PoolGroup() {}; - bool isEmpty() const { return ExplicitlyChanced.empty() && EqualChanced.empty(); } - void AddEntry(PoolObject& poolitem, uint32 maxentries); - bool CheckPool() const; - PoolObject* RollOne(ActivePoolData& spawns, uint32 triggerFrom); - void DespawnObject(ActivePoolData& spawns, uint32 guid=0); - void Despawn1Object(uint32 guid); - void SpawnObject(ActivePoolData& spawns, uint32 limit, uint32 triggerFrom); +public: + explicit PoolGroup() : poolId(0) { } + void SetPoolId(uint32 pool_id) { poolId = pool_id; } + ~PoolGroup() {}; + bool isEmpty() const { return ExplicitlyChanced.empty() && EqualChanced.empty(); } + void AddEntry(PoolObject& poolitem, uint32 maxentries); + bool CheckPool() const; + PoolObject* RollOne(ActivePoolData& spawns, uint32 triggerFrom); + void DespawnObject(ActivePoolData& spawns, uint32 guid = 0); + void Despawn1Object(uint32 guid); + void SpawnObject(ActivePoolData& spawns, uint32 limit, uint32 triggerFrom); - void Spawn1Object(PoolObject* obj); - void ReSpawn1Object(PoolObject* obj); - void RemoveOneRelation(uint32 child_pool_id); - uint32 GetFirstEqualChancedObjectId() - { - if (EqualChanced.empty()) - return 0; - return EqualChanced.front().guid; - } - uint32 GetPoolId() const { return poolId; } - private: - uint32 poolId; - PoolObjectList ExplicitlyChanced; - PoolObjectList EqualChanced; + void Spawn1Object(PoolObject* obj); + void ReSpawn1Object(PoolObject* obj); + void RemoveOneRelation(uint32 child_pool_id); + uint32 GetFirstEqualChancedObjectId() + { + if (EqualChanced.empty()) + return 0; + return EqualChanced.front().guid; + } + uint32 GetPoolId() const { return poolId; } +private: + uint32 poolId; + PoolObjectList ExplicitlyChanced; + PoolObjectList EqualChanced; }; typedef std::multimap PooledQuestRelation; @@ -91,63 +91,63 @@ typedef std::pair class PoolMgr { - private: - PoolMgr(); - ~PoolMgr() {}; +private: + PoolMgr(); + ~PoolMgr() {}; - public: - static PoolMgr* instance(); +public: + static PoolMgr* instance(); - void LoadFromDB(); - void LoadQuestPools(); - void SaveQuestsToDB(bool daily, bool weekly, bool other); + void LoadFromDB(); + void LoadQuestPools(); + void SaveQuestsToDB(bool daily, bool weekly, bool other); - void Initialize(); + void Initialize(); - template - uint32 IsPartOfAPool(uint32 db_guid_or_pool_id) const; + template + uint32 IsPartOfAPool(uint32 db_guid_or_pool_id) const; - template - bool IsSpawnedObject(uint32 db_guid_or_pool_id) const { return mSpawnedData.IsActiveObject(db_guid_or_pool_id); } + template + bool IsSpawnedObject(uint32 db_guid_or_pool_id) const { return mSpawnedData.IsActiveObject(db_guid_or_pool_id); } - bool CheckPool(uint32 pool_id) const; + bool CheckPool(uint32 pool_id) const; - void SpawnPool(uint32 pool_id); - void DespawnPool(uint32 pool_id); + void SpawnPool(uint32 pool_id); + void DespawnPool(uint32 pool_id); - template - void UpdatePool(uint32 pool_id, uint32 db_guid_or_pool_id); + template + void UpdatePool(uint32 pool_id, uint32 db_guid_or_pool_id); - void ChangeDailyQuests(); - void ChangeWeeklyQuests(); + void ChangeDailyQuests(); + void ChangeWeeklyQuests(); - PooledQuestRelation mQuestCreatureRelation; - PooledQuestRelation mQuestGORelation; + PooledQuestRelation mQuestCreatureRelation; + PooledQuestRelation mQuestGORelation; - private: - template - void SpawnPool(uint32 pool_id, uint32 db_guid_or_pool_id); +private: + template + void SpawnPool(uint32 pool_id, uint32 db_guid_or_pool_id); - typedef std::unordered_map PoolTemplateDataMap; - typedef std::unordered_map> PoolGroupCreatureMap; - typedef std::unordered_map> PoolGroupGameObjectMap; - typedef std::unordered_map> PoolGroupPoolMap; - typedef std::unordered_map> PoolGroupQuestMap; - typedef std::pair SearchPair; - typedef std::map SearchMap; + typedef std::unordered_map PoolTemplateDataMap; + typedef std::unordered_map> PoolGroupCreatureMap; + typedef std::unordered_map> PoolGroupGameObjectMap; + typedef std::unordered_map> PoolGroupPoolMap; + typedef std::unordered_map> PoolGroupQuestMap; + typedef std::pair SearchPair; + typedef std::map SearchMap; - PoolTemplateDataMap mPoolTemplate; - PoolGroupCreatureMap mPoolCreatureGroups; - PoolGroupGameObjectMap mPoolGameobjectGroups; - PoolGroupPoolMap mPoolPoolGroups; - PoolGroupQuestMap mPoolQuestGroups; - SearchMap mCreatureSearchMap; - SearchMap mGameobjectSearchMap; - SearchMap mPoolSearchMap; - SearchMap mQuestSearchMap; + PoolTemplateDataMap mPoolTemplate; + PoolGroupCreatureMap mPoolCreatureGroups; + PoolGroupGameObjectMap mPoolGameobjectGroups; + PoolGroupPoolMap mPoolPoolGroups; + PoolGroupQuestMap mPoolQuestGroups; + SearchMap mCreatureSearchMap; + SearchMap mGameobjectSearchMap; + SearchMap mPoolSearchMap; + SearchMap mQuestSearchMap; - // dynamic data - ActivePoolData mSpawnedData; + // dynamic data + ActivePoolData mSpawnedData; }; #define sPoolMgr PoolMgr::instance() diff --git a/src/server/game/Quests/QuestDef.cpp b/src/server/game/Quests/QuestDef.cpp index 1c2707118..113cb6af2 100644 --- a/src/server/game/Quests/QuestDef.cpp +++ b/src/server/game/Quests/QuestDef.cpp @@ -49,8 +49,8 @@ Quest::Quest(Field* questRecord) for (int i = 0; i < QUEST_REWARDS_COUNT; ++i) { - RewardItemId[i] = questRecord[27+i*2].GetUInt32(); - RewardItemIdCount[i] = questRecord[28+i*2].GetUInt16(); + RewardItemId[i] = questRecord[27 + i * 2].GetUInt32(); + RewardItemIdCount[i] = questRecord[28 + i * 2].GetUInt16(); if (RewardItemId[i]) ++_rewItemsCount; @@ -58,8 +58,8 @@ Quest::Quest(Field* questRecord) for (int i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i) { - RewardChoiceItemId[i] = questRecord[35+i*2].GetUInt32(); - RewardChoiceItemCount[i] = questRecord[36+i*2].GetUInt16(); + RewardChoiceItemId[i] = questRecord[35 + i * 2].GetUInt32(); + RewardChoiceItemCount[i] = questRecord[36 + i * 2].GetUInt16(); if (RewardChoiceItemId[i]) ++_rewChoiceItemsCount; @@ -67,9 +67,9 @@ Quest::Quest(Field* questRecord) for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) { - RewardFactionId[i] = questRecord[47+i*3].GetUInt16(); - RewardFactionValueId[i] = questRecord[48+i*3].GetInt32(); - RewardFactionValueIdOverride[i] = questRecord[49+i*3].GetInt32(); + RewardFactionId[i] = questRecord[47 + i * 3].GetUInt16(); + RewardFactionValueId[i] = questRecord[48 + i * 3].GetInt32(); + RewardFactionValueIdOverride[i] = questRecord[49 + i * 3].GetInt32(); } POIContinent = questRecord[62].GetUInt16(); @@ -84,8 +84,8 @@ Quest::Quest(Field* questRecord) for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) { - RequiredNpcOrGo[i] = questRecord[71+i].GetInt32(); - RequiredNpcOrGoCount[i] = questRecord[75+i].GetUInt16(); + RequiredNpcOrGo[i] = questRecord[71 + i].GetInt32(); + RequiredNpcOrGoCount[i] = questRecord[75 + i].GetUInt16(); ObjectiveText[i] = questRecord[100 + i].GetString(); if (RequiredNpcOrGo[i]) @@ -94,8 +94,8 @@ Quest::Quest(Field* questRecord) for (int i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) { - ItemDrop[i] = questRecord[79+i].GetUInt32(); - ItemDropQuantity[i] = questRecord[83+i].GetUInt16(); + ItemDrop[i] = questRecord[79 + i].GetUInt32(); + ItemDropQuantity[i] = questRecord[83 + i].GetUInt16(); } for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) @@ -117,17 +117,17 @@ Quest::Quest(Field* questRecord) OfferRewardEmote[i] = 0; OfferRewardEmoteDelay[i] = 0; } - + _eventIdForQuest = 0; } void Quest::LoadQuestDetails(Field* fields) { for (int i = 0; i < QUEST_EMOTE_COUNT; ++i) - DetailsEmote[i] = fields[1+i].GetUInt16(); + DetailsEmote[i] = fields[1 + i].GetUInt16(); for (int i = 0; i < QUEST_EMOTE_COUNT; ++i) - DetailsEmoteDelay[i] = fields[5+i].GetUInt32(); + DetailsEmoteDelay[i] = fields[5 + i].GetUInt32(); } void Quest::LoadQuestRequestItems(Field* fields) diff --git a/src/server/game/Quests/QuestDef.h b/src/server/game/Quests/QuestDef.h index 039141b27..7e29c7164 100644 --- a/src/server/game/Quests/QuestDef.h +++ b/src/server/game/Quests/QuestDef.h @@ -192,198 +192,198 @@ struct QuestOfferRewardLocale class Quest { friend class ObjectMgr; - public: - Quest(Field* questRecord); - void LoadQuestDetails(Field* fields); - void LoadQuestRequestItems(Field* fields); - void LoadQuestOfferReward(Field* fields); - void LoadQuestTemplateAddon(Field* fields); +public: + Quest(Field* questRecord); + void LoadQuestDetails(Field* fields); + void LoadQuestRequestItems(Field* fields); + void LoadQuestOfferReward(Field* fields); + void LoadQuestTemplateAddon(Field* fields); - uint32 XPValue(Player* player) const; + uint32 XPValue(Player* player) const; - bool HasFlag(uint32 flag) const { return (Flags & flag) != 0; } - void SetFlag(uint32 flag) { Flags |= flag; } + bool HasFlag(uint32 flag) const { return (Flags & flag) != 0; } + void SetFlag(uint32 flag) { Flags |= flag; } - bool HasSpecialFlag(uint32 flag) const { return (SpecialFlags & flag) != 0; } - void SetSpecialFlag(uint32 flag) { SpecialFlags |= flag; } + bool HasSpecialFlag(uint32 flag) const { return (SpecialFlags & flag) != 0; } + void SetSpecialFlag(uint32 flag) { SpecialFlags |= flag; } - // table data accessors: - uint32 GetQuestId() const { return Id; } - uint32 GetQuestMethod() const { return Method; } - int32 GetZoneOrSort() const { return ZoneOrSort; } - uint32 GetMinLevel() const { return MinLevel; } - uint32 GetMaxLevel() const { return MaxLevel; } - int32 GetQuestLevel() const { return Level; } - uint32 GetType() const { return Type; } - uint32 GetRequiredClasses() const { return RequiredClasses; } - uint32 GetAllowableRaces() const { return AllowableRaces; } - uint32 GetRequiredSkill() const { return RequiredSkillId; } - uint32 GetRequiredSkillValue() const { return RequiredSkillPoints; } - uint32 GetRepObjectiveFaction() const { return RequiredFactionId1; } - int32 GetRepObjectiveValue() const { return RequiredFactionValue1; } - uint32 GetRepObjectiveFaction2() const { return RequiredFactionId2; } - int32 GetRepObjectiveValue2() const { return RequiredFactionValue2; } - uint32 GetRequiredMinRepFaction() const { return RequiredMinRepFaction; } - int32 GetRequiredMinRepValue() const { return RequiredMinRepValue; } - uint32 GetRequiredMaxRepFaction() const { return RequiredMaxRepFaction; } - int32 GetRequiredMaxRepValue() const { return RequiredMaxRepValue; } - uint32 GetSuggestedPlayers() const { return SuggestedPlayers; } - uint32 GetTimeAllowed() const { return TimeAllowed; } - int32 GetPrevQuestId() const { return PrevQuestId; } - uint32 GetNextQuestId() const { return NextQuestId; } - int32 GetExclusiveGroup() const { return ExclusiveGroup; } - uint32 GetNextQuestInChain() const { return RewardNextQuest; } - uint32 GetCharTitleId() const { return RewardTitleId; } - uint32 GetPlayersSlain() const { return RequiredPlayerKills; } - uint32 GetBonusTalents() const { return RewardTalents; } - int32 GetRewArenaPoints() const {return RewardArenaPoints; } - uint32 GetXPId() const { return RewardXPDifficulty; } - uint32 GetSrcItemId() const { return StartItem; } - uint32 GetSrcItemCount() const { return StartItemCount; } - uint32 GetSrcSpell() const { return SourceSpellid; } - std::string const& GetTitle() const { return Title; } - std::string const& GetDetails() const { return Details; } - std::string const& GetObjectives() const { return Objectives; } - std::string const& GetOfferRewardText() const { return OfferRewardText; } - std::string const& GetRequestItemsText() const { return RequestItemsText; } - std::string const& GetAreaDescription() const { return AreaDescription; } - std::string const& GetCompletedText() const { return CompletedText; } - int32 GetRewOrReqMoney() const; - uint32 GetRewHonorAddition() const { return RewardHonor; } - float GetRewHonorMultiplier() const { return RewardKillHonor; } - uint32 GetRewMoneyMaxLevel() const; // use in XP calculation at client - uint32 GetRewSpell() const { return RewardDisplaySpell; } - int32 GetRewSpellCast() const { return RewardSpell; } - uint32 GetRewMailTemplateId() const { return RewardMailTemplateId; } - uint32 GetRewMailDelaySecs() const { return RewardMailDelay; } - uint32 GetRewMailSenderEntry() const { return RewardMailSenderEntry; } - uint32 GetPOIContinent() const { return POIContinent; } - float GetPOIx() const { return POIx; } - float GetPOIy() const { return POIy; } - uint32 GetPointOpt() const { return POIPriority; } - uint32 GetIncompleteEmote() const { return EmoteOnIncomplete; } - uint32 GetCompleteEmote() const { return EmoteOnComplete; } - bool IsRepeatable() const { return SpecialFlags & QUEST_SPECIAL_FLAGS_REPEATABLE; } - bool IsAutoAccept() const; - bool IsAutoComplete() const; - uint32 GetFlags() const { return Flags; } - bool IsDaily() const { return Flags & QUEST_FLAGS_DAILY; } - bool IsWeekly() const { return Flags & QUEST_FLAGS_WEEKLY; } - bool IsMonthly() const { return SpecialFlags & QUEST_SPECIAL_FLAGS_MONTHLY; } - bool IsSeasonal() const { return (ZoneOrSort == -QUEST_SORT_SEASONAL || ZoneOrSort == -QUEST_SORT_SPECIAL || ZoneOrSort == -QUEST_SORT_LUNAR_FESTIVAL || ZoneOrSort == -QUEST_SORT_MIDSUMMER || ZoneOrSort == -QUEST_SORT_BREWFEST || ZoneOrSort == -QUEST_SORT_LOVE_IS_IN_THE_AIR || ZoneOrSort == -QUEST_SORT_NOBLEGARDEN) && !IsRepeatable(); } - bool IsDailyOrWeekly() const { return Flags & (QUEST_FLAGS_DAILY | QUEST_FLAGS_WEEKLY); } - bool IsRaidQuest(Difficulty difficulty) const; - bool IsAllowedInRaid(Difficulty difficulty) const; - bool IsDFQuest() const { return SpecialFlags & QUEST_SPECIAL_FLAGS_DF_QUEST; } - bool IsPVPQuest() const { return Type == QUEST_TYPE_PVP; } - uint32 CalculateHonorGain(uint8 level) const; + // table data accessors: + uint32 GetQuestId() const { return Id; } + uint32 GetQuestMethod() const { return Method; } + int32 GetZoneOrSort() const { return ZoneOrSort; } + uint32 GetMinLevel() const { return MinLevel; } + uint32 GetMaxLevel() const { return MaxLevel; } + int32 GetQuestLevel() const { return Level; } + uint32 GetType() const { return Type; } + uint32 GetRequiredClasses() const { return RequiredClasses; } + uint32 GetAllowableRaces() const { return AllowableRaces; } + uint32 GetRequiredSkill() const { return RequiredSkillId; } + uint32 GetRequiredSkillValue() const { return RequiredSkillPoints; } + uint32 GetRepObjectiveFaction() const { return RequiredFactionId1; } + int32 GetRepObjectiveValue() const { return RequiredFactionValue1; } + uint32 GetRepObjectiveFaction2() const { return RequiredFactionId2; } + int32 GetRepObjectiveValue2() const { return RequiredFactionValue2; } + uint32 GetRequiredMinRepFaction() const { return RequiredMinRepFaction; } + int32 GetRequiredMinRepValue() const { return RequiredMinRepValue; } + uint32 GetRequiredMaxRepFaction() const { return RequiredMaxRepFaction; } + int32 GetRequiredMaxRepValue() const { return RequiredMaxRepValue; } + uint32 GetSuggestedPlayers() const { return SuggestedPlayers; } + uint32 GetTimeAllowed() const { return TimeAllowed; } + int32 GetPrevQuestId() const { return PrevQuestId; } + uint32 GetNextQuestId() const { return NextQuestId; } + int32 GetExclusiveGroup() const { return ExclusiveGroup; } + uint32 GetNextQuestInChain() const { return RewardNextQuest; } + uint32 GetCharTitleId() const { return RewardTitleId; } + uint32 GetPlayersSlain() const { return RequiredPlayerKills; } + uint32 GetBonusTalents() const { return RewardTalents; } + int32 GetRewArenaPoints() const {return RewardArenaPoints; } + uint32 GetXPId() const { return RewardXPDifficulty; } + uint32 GetSrcItemId() const { return StartItem; } + uint32 GetSrcItemCount() const { return StartItemCount; } + uint32 GetSrcSpell() const { return SourceSpellid; } + std::string const& GetTitle() const { return Title; } + std::string const& GetDetails() const { return Details; } + std::string const& GetObjectives() const { return Objectives; } + std::string const& GetOfferRewardText() const { return OfferRewardText; } + std::string const& GetRequestItemsText() const { return RequestItemsText; } + std::string const& GetAreaDescription() const { return AreaDescription; } + std::string const& GetCompletedText() const { return CompletedText; } + int32 GetRewOrReqMoney() const; + uint32 GetRewHonorAddition() const { return RewardHonor; } + float GetRewHonorMultiplier() const { return RewardKillHonor; } + uint32 GetRewMoneyMaxLevel() const; // use in XP calculation at client + uint32 GetRewSpell() const { return RewardDisplaySpell; } + int32 GetRewSpellCast() const { return RewardSpell; } + uint32 GetRewMailTemplateId() const { return RewardMailTemplateId; } + uint32 GetRewMailDelaySecs() const { return RewardMailDelay; } + uint32 GetRewMailSenderEntry() const { return RewardMailSenderEntry; } + uint32 GetPOIContinent() const { return POIContinent; } + float GetPOIx() const { return POIx; } + float GetPOIy() const { return POIy; } + uint32 GetPointOpt() const { return POIPriority; } + uint32 GetIncompleteEmote() const { return EmoteOnIncomplete; } + uint32 GetCompleteEmote() const { return EmoteOnComplete; } + bool IsRepeatable() const { return SpecialFlags & QUEST_SPECIAL_FLAGS_REPEATABLE; } + bool IsAutoAccept() const; + bool IsAutoComplete() const; + uint32 GetFlags() const { return Flags; } + bool IsDaily() const { return Flags & QUEST_FLAGS_DAILY; } + bool IsWeekly() const { return Flags & QUEST_FLAGS_WEEKLY; } + bool IsMonthly() const { return SpecialFlags & QUEST_SPECIAL_FLAGS_MONTHLY; } + bool IsSeasonal() const { return (ZoneOrSort == -QUEST_SORT_SEASONAL || ZoneOrSort == -QUEST_SORT_SPECIAL || ZoneOrSort == -QUEST_SORT_LUNAR_FESTIVAL || ZoneOrSort == -QUEST_SORT_MIDSUMMER || ZoneOrSort == -QUEST_SORT_BREWFEST || ZoneOrSort == -QUEST_SORT_LOVE_IS_IN_THE_AIR || ZoneOrSort == -QUEST_SORT_NOBLEGARDEN) && !IsRepeatable(); } + bool IsDailyOrWeekly() const { return Flags & (QUEST_FLAGS_DAILY | QUEST_FLAGS_WEEKLY); } + bool IsRaidQuest(Difficulty difficulty) const; + bool IsAllowedInRaid(Difficulty difficulty) const; + bool IsDFQuest() const { return SpecialFlags & QUEST_SPECIAL_FLAGS_DF_QUEST; } + bool IsPVPQuest() const { return Type == QUEST_TYPE_PVP; } + uint32 CalculateHonorGain(uint8 level) const; - // multiple values - std::string ObjectiveText[QUEST_OBJECTIVES_COUNT]; - uint32 RequiredItemId[QUEST_ITEM_OBJECTIVES_COUNT]; - uint32 RequiredItemCount[QUEST_ITEM_OBJECTIVES_COUNT]; - uint32 ItemDrop[QUEST_SOURCE_ITEM_IDS_COUNT]; - uint32 ItemDropQuantity[QUEST_SOURCE_ITEM_IDS_COUNT]; - int32 RequiredNpcOrGo[QUEST_OBJECTIVES_COUNT]; // >0 Creature <0 Gameobject - uint32 RequiredNpcOrGoCount[QUEST_OBJECTIVES_COUNT]; - uint32 RewardChoiceItemId[QUEST_REWARD_CHOICES_COUNT]; - uint32 RewardChoiceItemCount[QUEST_REWARD_CHOICES_COUNT]; - uint32 RewardItemId[QUEST_REWARDS_COUNT]; - uint32 RewardItemIdCount[QUEST_REWARDS_COUNT]; - uint32 RewardFactionId[QUEST_REPUTATIONS_COUNT]; - int32 RewardFactionValueId[QUEST_REPUTATIONS_COUNT]; - int32 RewardFactionValueIdOverride[QUEST_REPUTATIONS_COUNT]; - uint32 DetailsEmote[QUEST_EMOTE_COUNT]; - uint32 DetailsEmoteDelay[QUEST_EMOTE_COUNT]; - uint32 OfferRewardEmote[QUEST_EMOTE_COUNT]; - uint32 OfferRewardEmoteDelay[QUEST_EMOTE_COUNT]; + // multiple values + std::string ObjectiveText[QUEST_OBJECTIVES_COUNT]; + uint32 RequiredItemId[QUEST_ITEM_OBJECTIVES_COUNT]; + uint32 RequiredItemCount[QUEST_ITEM_OBJECTIVES_COUNT]; + uint32 ItemDrop[QUEST_SOURCE_ITEM_IDS_COUNT]; + uint32 ItemDropQuantity[QUEST_SOURCE_ITEM_IDS_COUNT]; + int32 RequiredNpcOrGo[QUEST_OBJECTIVES_COUNT]; // >0 Creature <0 Gameobject + uint32 RequiredNpcOrGoCount[QUEST_OBJECTIVES_COUNT]; + uint32 RewardChoiceItemId[QUEST_REWARD_CHOICES_COUNT]; + uint32 RewardChoiceItemCount[QUEST_REWARD_CHOICES_COUNT]; + uint32 RewardItemId[QUEST_REWARDS_COUNT]; + uint32 RewardItemIdCount[QUEST_REWARDS_COUNT]; + uint32 RewardFactionId[QUEST_REPUTATIONS_COUNT]; + int32 RewardFactionValueId[QUEST_REPUTATIONS_COUNT]; + int32 RewardFactionValueIdOverride[QUEST_REPUTATIONS_COUNT]; + uint32 DetailsEmote[QUEST_EMOTE_COUNT]; + uint32 DetailsEmoteDelay[QUEST_EMOTE_COUNT]; + uint32 OfferRewardEmote[QUEST_EMOTE_COUNT]; + uint32 OfferRewardEmoteDelay[QUEST_EMOTE_COUNT]; - uint32 GetReqItemsCount() const { return _reqItemsCount; } - uint32 GetReqCreatureOrGOcount() const { return _reqCreatureOrGOcount; } - uint32 GetRewChoiceItemsCount() const { return _rewChoiceItemsCount; } - uint32 GetRewItemsCount() const { return _rewItemsCount; } + uint32 GetReqItemsCount() const { return _reqItemsCount; } + uint32 GetReqCreatureOrGOcount() const { return _reqCreatureOrGOcount; } + uint32 GetRewChoiceItemsCount() const { return _rewChoiceItemsCount; } + uint32 GetRewItemsCount() const { return _rewItemsCount; } - typedef std::vector PrevQuests; - PrevQuests prevQuests; - typedef std::vector PrevChainQuests; - PrevChainQuests prevChainQuests; + typedef std::vector PrevQuests; + PrevQuests prevQuests; + typedef std::vector PrevChainQuests; + PrevChainQuests prevChainQuests; - WorldPacket queryData; // pussywizard - void InitializeQueryData(); // pussywizard + WorldPacket queryData; // pussywizard + void InitializeQueryData(); // pussywizard - void SetEventIdForQuest(uint16 eventId) { _eventIdForQuest = eventId; } - uint16 GetEventIdForQuest() const { return _eventIdForQuest; } + void SetEventIdForQuest(uint16 eventId) { _eventIdForQuest = eventId; } + uint16 GetEventIdForQuest() const { return _eventIdForQuest; } - // cached data - private: - uint32 _reqItemsCount; - uint32 _reqCreatureOrGOcount; - uint32 _rewChoiceItemsCount; - uint32 _rewItemsCount; + // cached data +private: + uint32 _reqItemsCount; + uint32 _reqCreatureOrGOcount; + uint32 _rewChoiceItemsCount; + uint32 _rewItemsCount; - uint16 _eventIdForQuest; // pussywizard + uint16 _eventIdForQuest; // pussywizard - // table data - protected: - uint32 Id; - uint32 Method; - int32 ZoneOrSort; - uint32 MinLevel; - int32 Level; - uint32 Type; - uint32 AllowableRaces; - uint32 RequiredFactionId1; - int32 RequiredFactionValue1; - uint32 RequiredFactionId2; - int32 RequiredFactionValue2; - uint32 SuggestedPlayers; - uint32 TimeAllowed; - uint32 Flags; - uint32 RewardTitleId; - uint32 RequiredPlayerKills; - uint32 RewardTalents; - int32 RewardArenaPoints; - uint32 RewardNextQuest; - uint32 RewardXPDifficulty; - uint32 StartItem; - std::string Title; - std::string Details; - std::string Objectives; - std::string OfferRewardText; - std::string RequestItemsText; - std::string AreaDescription; - std::string CompletedText; - uint32 RewardHonor; - float RewardKillHonor; - int32 RewardMoney; - uint32 RewardBonusMoney; - uint32 RewardDisplaySpell; - int32 RewardSpell; - uint32 POIContinent; - float POIx; - float POIy; - uint32 POIPriority; - uint32 EmoteOnIncomplete; - uint32 EmoteOnComplete; + // table data +protected: + uint32 Id; + uint32 Method; + int32 ZoneOrSort; + uint32 MinLevel; + int32 Level; + uint32 Type; + uint32 AllowableRaces; + uint32 RequiredFactionId1; + int32 RequiredFactionValue1; + uint32 RequiredFactionId2; + int32 RequiredFactionValue2; + uint32 SuggestedPlayers; + uint32 TimeAllowed; + uint32 Flags; + uint32 RewardTitleId; + uint32 RequiredPlayerKills; + uint32 RewardTalents; + int32 RewardArenaPoints; + uint32 RewardNextQuest; + uint32 RewardXPDifficulty; + uint32 StartItem; + std::string Title; + std::string Details; + std::string Objectives; + std::string OfferRewardText; + std::string RequestItemsText; + std::string AreaDescription; + std::string CompletedText; + uint32 RewardHonor; + float RewardKillHonor; + int32 RewardMoney; + uint32 RewardBonusMoney; + uint32 RewardDisplaySpell; + int32 RewardSpell; + uint32 POIContinent; + float POIx; + float POIy; + uint32 POIPriority; + uint32 EmoteOnIncomplete; + uint32 EmoteOnComplete; - // quest_template_addon table (custom data) - uint32 MaxLevel = 0; - uint32 RequiredClasses = 0; - uint32 SourceSpellid = 0; - int32 PrevQuestId = 0; - uint32 NextQuestId = 0; - int32 ExclusiveGroup = 0; - uint32 RewardMailTemplateId = 0; - uint32 RewardMailDelay = 0; - uint32 RequiredSkillId = 0; - uint32 RequiredSkillPoints = 0; - uint32 RequiredMinRepFaction = 0; - int32 RequiredMinRepValue = 0; - uint32 RequiredMaxRepFaction = 0; - int32 RequiredMaxRepValue = 0; - uint32 StartItemCount = 0; - uint32 RewardMailSenderEntry = 0; - uint32 SpecialFlags = 0; // custom flags, not sniffed/WDB + // quest_template_addon table (custom data) + uint32 MaxLevel = 0; + uint32 RequiredClasses = 0; + uint32 SourceSpellid = 0; + int32 PrevQuestId = 0; + uint32 NextQuestId = 0; + int32 ExclusiveGroup = 0; + uint32 RewardMailTemplateId = 0; + uint32 RewardMailDelay = 0; + uint32 RequiredSkillId = 0; + uint32 RequiredSkillPoints = 0; + uint32 RequiredMinRepFaction = 0; + int32 RequiredMinRepValue = 0; + uint32 RequiredMaxRepFaction = 0; + int32 RequiredMaxRepValue = 0; + uint32 StartItemCount = 0; + uint32 RewardMailSenderEntry = 0; + uint32 SpecialFlags = 0; // custom flags, not sniffed/WDB }; struct QuestStatusData diff --git a/src/server/game/Reputation/ReputationMgr.cpp b/src/server/game/Reputation/ReputationMgr.cpp index 88e384e94..a0168fbdf 100644 --- a/src/server/game/Reputation/ReputationMgr.cpp +++ b/src/server/game/Reputation/ReputationMgr.cpp @@ -19,7 +19,7 @@ const int32 ReputationMgr::PointsInRank[MAX_REPUTATION_RANK] = {36000, 3000, 300 ReputationRank ReputationMgr::ReputationToRank(int32 standing) { int32 limit = Reputation_Cap + 1; - for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i) + for (int i = MAX_REPUTATION_RANK - 1; i >= MIN_REPUTATION_RANK; --i) { limit -= PointsInRank[i]; if (standing >= limit) @@ -71,13 +71,13 @@ int32 ReputationMgr::GetBaseReputation(FactionEntry const* factionEntry) const uint32 raceMask = _player->getRaceMask(); uint32 classMask = _player->getClassMask(); - for (int i=0; i < 4; i++) + for (int i = 0; i < 4; i++) { if ((factionEntry->BaseRepRaceMask[i] & raceMask || - (factionEntry->BaseRepRaceMask[i] == 0 && - factionEntry->BaseRepClassMask[i] != 0)) && - (factionEntry->BaseRepClassMask[i] & classMask || - factionEntry->BaseRepClassMask[i] == 0)) + (factionEntry->BaseRepRaceMask[i] == 0 && + factionEntry->BaseRepClassMask[i] != 0)) && + (factionEntry->BaseRepClassMask[i] & classMask || + factionEntry->BaseRepClassMask[i] == 0)) return factionEntry->BaseRepValue[i]; } @@ -125,13 +125,13 @@ uint32 ReputationMgr::GetDefaultStateFlags(FactionEntry const* factionEntry) con uint32 raceMask = _player->getRaceMask(); uint32 classMask = _player->getClassMask(); - for (int i=0; i < 4; i++) + for (int i = 0; i < 4; i++) { if ((factionEntry->BaseRepRaceMask[i] & raceMask || - (factionEntry->BaseRepRaceMask[i] == 0 && - factionEntry->BaseRepClassMask[i] != 0)) && - (factionEntry->BaseRepClassMask[i] & classMask || - factionEntry->BaseRepClassMask[i] == 0)) + (factionEntry->BaseRepRaceMask[i] == 0 && + factionEntry->BaseRepClassMask[i] != 0)) && + (factionEntry->BaseRepClassMask[i] & classMask || + factionEntry->BaseRepClassMask[i] == 0)) return factionEntry->ReputationFlags[i]; } @@ -141,7 +141,7 @@ uint32 ReputationMgr::GetDefaultStateFlags(FactionEntry const* factionEntry) con void ReputationMgr::SendForceReactions() { WorldPacket data; - data.Initialize(SMSG_SET_FORCED_REACTIONS, 4+_forcedReactions.size()*(4+4)); + data.Initialize(SMSG_SET_FORCED_REACTIONS, 4 + _forcedReactions.size() * (4 + 4)); data << uint32(_forcedReactions.size()); for (ForcedReactions::const_iterator itr = _forcedReactions.begin(); itr != _forcedReactions.end(); ++itr) { @@ -186,7 +186,7 @@ void ReputationMgr::SendState(FactionState const* faction) void ReputationMgr::SendInitialReputations() { - WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5)); + WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4 + 128 * 5)); data << uint32 (0x00000080); RepListID a = 0; @@ -394,7 +394,7 @@ bool ReputationMgr::SetOneFactionReputation(FactionEntry const* factionEntry, in return false; } -void ReputationMgr::SetVisible(FactionTemplateEntry const*factionTemplateEntry) +void ReputationMgr::SetVisible(FactionTemplateEntry const* factionTemplateEntry) { if (!factionTemplateEntry->faction) return; @@ -421,7 +421,7 @@ void ReputationMgr::SetVisible(FactionState* faction) { // always invisible or hidden faction can't be make visible // except if faction has FACTION_FLAG_SPECIAL - if (faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN) && !(faction->Flags & FACTION_FLAG_SPECIAL)) + if (faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED | FACTION_FLAG_HIDDEN) && !(faction->Flags & FACTION_FLAG_SPECIAL)) return; // already set @@ -444,7 +444,7 @@ void ReputationMgr::SetAtWar(RepListID repListID, bool on) return; // always invisible or hidden faction can't change war state - if (itr->second.Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) + if (itr->second.Flags & (FACTION_FLAG_INVISIBLE_FORCED | FACTION_FLAG_HIDDEN)) return; SetAtWar(&itr->second, on); @@ -481,7 +481,7 @@ void ReputationMgr::SetInactive(RepListID repListID, bool on) void ReputationMgr::SetInactive(FactionState* faction, bool inactive) const { // always invisible or hidden faction can't be inactive - if (inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE))) + if (inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED | FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE))) return; // already set @@ -555,8 +555,7 @@ void ReputationMgr::LoadFromDB(PreparedQueryResult result) faction->needSave = false; } } - } - while (result->NextRow()); + } while (result->NextRow()); } } diff --git a/src/server/game/Reputation/ReputationMgr.h b/src/server/game/Reputation/ReputationMgr.h index 718b2669f..fd623bd37 100644 --- a/src/server/game/Reputation/ReputationMgr.h +++ b/src/server/game/Reputation/ReputationMgr.h @@ -51,102 +51,102 @@ class Player; class ReputationMgr { - public: // constructors and global modifiers - explicit ReputationMgr(Player* owner) : _player(owner), - _visibleFactionCount(0), _honoredFactionCount(0), _reveredFactionCount(0), _exaltedFactionCount(0), _sendFactionIncreased(false) {} - ~ReputationMgr() {} +public: // constructors and global modifiers + explicit ReputationMgr(Player* owner) : _player(owner), + _visibleFactionCount(0), _honoredFactionCount(0), _reveredFactionCount(0), _exaltedFactionCount(0), _sendFactionIncreased(false) {} + ~ReputationMgr() {} - void SaveToDB(SQLTransaction& trans); - void LoadFromDB(PreparedQueryResult result); - public: // statics - static const int32 PointsInRank[MAX_REPUTATION_RANK]; - static const int32 Reputation_Cap = 42999; - static const int32 Reputation_Bottom = -42000; + void SaveToDB(SQLTransaction& trans); + void LoadFromDB(PreparedQueryResult result); +public: // statics + static const int32 PointsInRank[MAX_REPUTATION_RANK]; + static const int32 Reputation_Cap = 42999; + static const int32 Reputation_Bottom = -42000; - static ReputationRank ReputationToRank(int32 standing); - public: // accessors - uint8 GetVisibleFactionCount() const { return _visibleFactionCount; } - uint8 GetHonoredFactionCount() const { return _honoredFactionCount; } - uint8 GetReveredFactionCount() const { return _reveredFactionCount; } - uint8 GetExaltedFactionCount() const { return _exaltedFactionCount; } + static ReputationRank ReputationToRank(int32 standing); +public: // accessors + uint8 GetVisibleFactionCount() const { return _visibleFactionCount; } + uint8 GetHonoredFactionCount() const { return _honoredFactionCount; } + uint8 GetReveredFactionCount() const { return _reveredFactionCount; } + uint8 GetExaltedFactionCount() const { return _exaltedFactionCount; } - FactionStateList const& GetStateList() const { return _factions; } + FactionStateList const& GetStateList() const { return _factions; } - FactionState const* GetState(FactionEntry const* factionEntry) const - { - return factionEntry->CanHaveReputation() ? GetState(factionEntry->reputationListID) : nullptr; - } + FactionState const* GetState(FactionEntry const* factionEntry) const + { + return factionEntry->CanHaveReputation() ? GetState(factionEntry->reputationListID) : nullptr; + } - FactionState const* GetState(RepListID id) const - { - FactionStateList::const_iterator repItr = _factions.find (id); - return repItr != _factions.end() ? &repItr->second : nullptr; - } + FactionState const* GetState(RepListID id) const + { + FactionStateList::const_iterator repItr = _factions.find (id); + return repItr != _factions.end() ? &repItr->second : nullptr; + } - bool IsAtWar(uint32 faction_id) const; - bool IsAtWar(FactionEntry const* factionEntry) const; + bool IsAtWar(uint32 faction_id) const; + bool IsAtWar(FactionEntry const* factionEntry) const; - int32 GetReputation(uint32 faction_id) const; - int32 GetReputation(FactionEntry const* factionEntry) const; - int32 GetBaseReputation(FactionEntry const* factionEntry) const; + int32 GetReputation(uint32 faction_id) const; + int32 GetReputation(FactionEntry const* factionEntry) const; + int32 GetBaseReputation(FactionEntry const* factionEntry) const; - ReputationRank GetRank(FactionEntry const* factionEntry) const; - ReputationRank GetBaseRank(FactionEntry const* factionEntry) const; - uint32 GetReputationRankStrIndex(FactionEntry const* factionEntry) const - { - return ReputationRankStrIndex[GetRank(factionEntry)]; - }; + ReputationRank GetRank(FactionEntry const* factionEntry) const; + ReputationRank GetBaseRank(FactionEntry const* factionEntry) const; + uint32 GetReputationRankStrIndex(FactionEntry const* factionEntry) const + { + return ReputationRankStrIndex[GetRank(factionEntry)]; + }; - ReputationRank const* GetForcedRankIfAny(FactionTemplateEntry const* factionTemplateEntry) const - { - ForcedReactions::const_iterator forceItr = _forcedReactions.find(factionTemplateEntry->faction); - return forceItr != _forcedReactions.end() ? &forceItr->second : nullptr; - } + ReputationRank const* GetForcedRankIfAny(FactionTemplateEntry const* factionTemplateEntry) const + { + ForcedReactions::const_iterator forceItr = _forcedReactions.find(factionTemplateEntry->faction); + return forceItr != _forcedReactions.end() ? &forceItr->second : nullptr; + } - public: // modifiers - bool SetReputation(FactionEntry const* factionEntry, int32 standing) - { - return SetReputation(factionEntry, standing, false, false); - } - bool ModifyReputation(FactionEntry const* factionEntry, int32 standing, bool spillOverOnly = false) - { - return SetReputation(factionEntry, standing, true, spillOverOnly); - } +public: // modifiers + bool SetReputation(FactionEntry const* factionEntry, int32 standing) + { + return SetReputation(factionEntry, standing, false, false); + } + bool ModifyReputation(FactionEntry const* factionEntry, int32 standing, bool spillOverOnly = false) + { + return SetReputation(factionEntry, standing, true, spillOverOnly); + } - void SetVisible(FactionTemplateEntry const* factionTemplateEntry); - void SetVisible(FactionEntry const* factionEntry); - void SetAtWar(RepListID repListID, bool on); - void SetInactive(RepListID repListID, bool on); + void SetVisible(FactionTemplateEntry const* factionTemplateEntry); + void SetVisible(FactionEntry const* factionEntry); + void SetAtWar(RepListID repListID, bool on); + void SetInactive(RepListID repListID, bool on); - void ApplyForceReaction(uint32 faction_id, ReputationRank rank, bool apply); + void ApplyForceReaction(uint32 faction_id, ReputationRank rank, bool apply); - //! Public for chat command needs - bool SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing, bool incremental); + //! Public for chat command needs + bool SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing, bool incremental); - public: // senders - void SendInitialReputations(); - void SendForceReactions(); - void SendState(FactionState const* faction); - void SendStates(); +public: // senders + void SendInitialReputations(); + void SendForceReactions(); + void SendState(FactionState const* faction); + void SendStates(); - private: // internal helper functions - void Initialize(); - uint32 GetDefaultStateFlags(FactionEntry const* factionEntry) const; - bool SetReputation(FactionEntry const* factionEntry, int32 standing, bool incremental, bool spillOverOnly); - void SetVisible(FactionState* faction); - void SetAtWar(FactionState* faction, bool atWar) const; - void SetInactive(FactionState* faction, bool inactive) const; - void SendVisible(FactionState const* faction) const; - void UpdateRankCounters(ReputationRank old_rank, ReputationRank new_rank); - private: - Player* _player; - FactionStateList _factions; - ForcedReactions _forcedReactions; - uint8 _visibleFactionCount :8; - uint8 _honoredFactionCount :8; - uint8 _reveredFactionCount :8; - uint8 _exaltedFactionCount :8; - bool _sendFactionIncreased; //! Play visual effect on next SMSG_SET_FACTION_STANDING sent +private: // internal helper functions + void Initialize(); + uint32 GetDefaultStateFlags(FactionEntry const* factionEntry) const; + bool SetReputation(FactionEntry const* factionEntry, int32 standing, bool incremental, bool spillOverOnly); + void SetVisible(FactionState* faction); + void SetAtWar(FactionState* faction, bool atWar) const; + void SetInactive(FactionState* faction, bool inactive) const; + void SendVisible(FactionState const* faction) const; + void UpdateRankCounters(ReputationRank old_rank, ReputationRank new_rank); +private: + Player* _player; + FactionStateList _factions; + ForcedReactions _forcedReactions; + uint8 _visibleFactionCount : 8; + uint8 _honoredFactionCount : 8; + uint8 _reveredFactionCount : 8; + uint8 _exaltedFactionCount : 8; + bool _sendFactionIncreased; //! Play visual effect on next SMSG_SET_FACTION_STANDING sent }; #endif diff --git a/src/server/game/Scripting/MapScripts.cpp b/src/server/game/Scripting/MapScripts.cpp index 25369c7a7..dcc0ede48 100644 --- a/src/server/game/Scripting/MapScripts.cpp +++ b/src/server/game/Scripting/MapScripts.cpp @@ -21,7 +21,7 @@ /// Put scripts in the execution queue void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target) -{ +{ ///- Find the script map ScriptMapMap::const_iterator s = scripts.find(id); if (s == scripts.end()) @@ -59,7 +59,7 @@ void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, O } void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target) -{ +{ // NOTE: script record _must_ exist until command executed // prepare static data @@ -88,7 +88,7 @@ void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* sou // Helpers for ScriptProcess method. inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const -{ +{ Player* player = nullptr; if (!source && !target) sLog->outError("%s source and target objects are NULL.", scriptInfo->GetDebugInfo().c_str()); @@ -102,15 +102,15 @@ inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* targe if (!player) sLog->outError("%s neither source nor target object is player (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.", - scriptInfo->GetDebugInfo().c_str(), - source ? source->GetTypeId() : 0, source ? source->GetEntry() : 0, source ? source->GetGUIDLow() : 0, - target ? target->GetTypeId() : 0, target ? target->GetEntry() : 0, target ? target->GetGUIDLow() : 0); + scriptInfo->GetDebugInfo().c_str(), + source ? source->GetTypeId() : 0, source ? source->GetEntry() : 0, source ? source->GetGUIDLow() : 0, + target ? target->GetTypeId() : 0, target ? target->GetEntry() : 0, target ? target->GetGUIDLow() : 0); } return player; } inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse) const -{ +{ Creature* creature = nullptr; if (!source && !target) sLog->outError("%s source and target objects are NULL.", scriptInfo->GetDebugInfo().c_str()); @@ -135,33 +135,33 @@ inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* t if (!creature) sLog->outError("%s neither source nor target are creatures (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.", - scriptInfo->GetDebugInfo().c_str(), - source ? source->GetTypeId() : 0, source ? source->GetEntry() : 0, source ? source->GetGUIDLow() : 0, - target ? target->GetTypeId() : 0, target ? target->GetEntry() : 0, target ? target->GetGUIDLow() : 0); + scriptInfo->GetDebugInfo().c_str(), + source ? source->GetTypeId() : 0, source ? source->GetEntry() : 0, source ? source->GetGUIDLow() : 0, + target ? target->GetTypeId() : 0, target ? target->GetEntry() : 0, target ? target->GetGUIDLow() : 0); } return creature; } inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const -{ +{ Unit* unit = nullptr; if (!obj) sLog->outError("%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else if (!obj->isType(TYPEMASK_UNIT)) sLog->outError("%s %s object is not unit (TypeId: %u, Entry: %u, GUID: %u), skipping.", - scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); + scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); else { unit = obj->ToUnit(); if (!unit) sLog->outError("%s %s object could not be casted to unit.", - scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); + scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); } return unit; } inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const -{ +{ Player* player = nullptr; if (!obj) sLog->outError("%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); @@ -170,13 +170,13 @@ inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, const ScriptInf player = obj->ToPlayer(); if (!player) sLog->outError("%s %s object is not a player (TypeId: %u, Entry: %u, GUID: %u).", - scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); + scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); } return player; } inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const -{ +{ Creature* creature = nullptr; if (!obj) sLog->outError("%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); @@ -185,36 +185,39 @@ inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, const Scrip creature = obj->ToCreature(); if (!creature) sLog->outError("%s %s object is not a creature (TypeId: %u, Entry: %u, GUID: %u).", scriptInfo->GetDebugInfo().c_str(), - isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); + isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); } return creature; } inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const -{ +{ WorldObject* pWorldObject = nullptr; if (!obj) sLog->outError("%s %s object is NULL.", - scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); + scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else { pWorldObject = dynamic_cast(obj); if (!pWorldObject) sLog->outError("%s %s object is not a world object (TypeId: %u, Entry: %u, GUID: %u).", - scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); + scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUIDLow()); } return pWorldObject; } inline void Map::_ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const -{ +{ bool bOpen = false; uint32 guid = scriptInfo->ToggleDoor.GOGuid; int32 nTimeToToggle = std::max(15, int32(scriptInfo->ToggleDoor.ResetDelay)); switch (scriptInfo->command) { - case SCRIPT_COMMAND_OPEN_DOOR: bOpen = true; break; - case SCRIPT_COMMAND_CLOSE_DOOR: break; + case SCRIPT_COMMAND_OPEN_DOOR: + bOpen = true; + break; + case SCRIPT_COMMAND_CLOSE_DOOR: + break; default: sLog->outError("%s unknown command for _ScriptProcessDoor.", scriptInfo->GetDebugInfo().c_str()); return; @@ -225,13 +228,13 @@ inline void Map::_ScriptProcessDoor(Object* source, Object* target, const Script sLog->outError("%s source object is NULL.", scriptInfo->GetDebugInfo().c_str()); else if (!source->isType(TYPEMASK_UNIT)) sLog->outError("%s source object is not unit (TypeId: %u, Entry: %u, GUID: %u), skipping.", scriptInfo->GetDebugInfo().c_str(), - source->GetTypeId(), source->GetEntry(), source->GetGUIDLow()); + source->GetTypeId(), source->GetEntry(), source->GetGUIDLow()); else { WorldObject* wSource = dynamic_cast (source); if (!wSource) sLog->outError("%s source object could not be casted to world object (TypeId: %u, Entry: %u, GUID: %u), skipping.", - scriptInfo->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow()); + scriptInfo->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow()); else { GameObject* pDoor = _FindGameObject(wSource, guid); @@ -239,7 +242,7 @@ inline void Map::_ScriptProcessDoor(Object* source, Object* target, const Script sLog->outError("%s gameobject was not found (guid: %u).", scriptInfo->GetDebugInfo().c_str(), guid); else if (pDoor->GetGoType() != GAMEOBJECT_TYPE_DOOR) sLog->outError("%s gameobject is not a door (GoType: %u, Entry: %u, GUID: %u).", - scriptInfo->GetDebugInfo().c_str(), pDoor->GetGoType(), pDoor->GetEntry(), pDoor->GetGUIDLow()); + scriptInfo->GetDebugInfo().c_str(), pDoor->GetGoType(), pDoor->GetEntry(), pDoor->GetGUIDLow()); else if (bOpen == (pDoor->GetGoState() == GO_STATE_READY)) { pDoor->UseDoorOrButton(nTimeToToggle); @@ -256,7 +259,7 @@ inline void Map::_ScriptProcessDoor(Object* source, Object* target, const Script } inline GameObject* Map::_FindGameObject(WorldObject* searchObject, uint32 guid) const -{ +{ GameObject* gameobject = nullptr; CellCoord p(acore::ComputeCellCoord(searchObject->GetPositionX(), searchObject->GetPositionY())); @@ -273,7 +276,7 @@ inline GameObject* Map::_FindGameObject(WorldObject* searchObject, uint32 guid) /// Process queued scripts void Map::ScriptsProcess() -{ +{ if (m_scriptSchedule.empty()) return; @@ -311,14 +314,14 @@ void Map::ScriptsProcess() source = GetCorpse(step.sourceGUID); break; case HIGHGUID_MO_TRANSPORT: - { - GameObject* go = GetGameObject(step.sourceGUID); - source = go ? go->ToTransport() : nullptr; - break; - } + { + GameObject* go = GetGameObject(step.sourceGUID); + source = go ? go->ToTransport() : nullptr; + break; + } default: sLog->outError("%s source with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).", - step.script->GetDebugInfo().c_str(), step.sourceGUID, GUID_HIPART(step.sourceGUID)); + step.script->GetDebugInfo().c_str(), step.sourceGUID, GUID_HIPART(step.sourceGUID)); break; } } @@ -346,14 +349,14 @@ void Map::ScriptsProcess() target = GetCorpse(step.targetGUID); break; case HIGHGUID_MO_TRANSPORT: - { - GameObject* go = GetGameObject(step.targetGUID); - target = go ? go->ToTransport() : nullptr; - break; - } + { + GameObject* go = GetGameObject(step.targetGUID); + target = go ? go->ToTransport() : nullptr; + break; + } default: sLog->outError("%s target with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).", - step.script->GetDebugInfo().c_str(), step.targetGUID, GUID_HIPART(step.targetGUID)); + step.script->GetDebugInfo().c_str(), step.targetGUID, GUID_HIPART(step.targetGUID)); break; } } @@ -388,14 +391,14 @@ void Map::ScriptsProcess() break; case CHAT_TYPE_WHISPER: case CHAT_MSG_RAID_BOSS_WHISPER: - { - uint64 targetGUID = target ? target->GetGUID() : 0; - if (!targetGUID || !IS_PLAYER_GUID(targetGUID)) - sLog->outError("%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str()); - else - player->Whisper(text, LANG_UNIVERSAL, targetGUID); - break; - } + { + uint64 targetGUID = target ? target->GetGUID() : 0; + if (!targetGUID || !IS_PLAYER_GUID(targetGUID)) + sLog->outError("%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str()); + else + player->Whisper(text, LANG_UNIVERSAL, targetGUID); + break; + } default: break; // must be already checked at load } @@ -458,8 +461,8 @@ void Map::ScriptsProcess() // Validate field number. if (step.script->FieldSet.FieldID <= OBJECT_FIELD_ENTRY || step.script->FieldSet.FieldID >= cSource->GetValuesCount()) sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.", - step.script->GetDebugInfo().c_str(), step.script->FieldSet.FieldID, - cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow()); + step.script->GetDebugInfo().c_str(), step.script->FieldSet.FieldID, + cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow()); else cSource->SetUInt32Value(step.script->FieldSet.FieldID, step.script->FieldSet.FieldValue); } @@ -469,7 +472,7 @@ void Map::ScriptsProcess() // Source or target must be Creature. if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script)) { - Unit * unit = (Unit*)cSource; + Unit* unit = (Unit*)cSource; if (step.script->MoveTo.TravelTime != 0) { float speed = unit->GetDistance(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ) / ((float)step.script->MoveTo.TravelTime * 0.001f); @@ -487,8 +490,8 @@ void Map::ScriptsProcess() // Validate field number. if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY || step.script->FlagToggle.FieldID >= cSource->GetValuesCount()) sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.", - step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID, - cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow()); + step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID, + cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow()); else cSource->SetFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue); } @@ -501,8 +504,8 @@ void Map::ScriptsProcess() // Validate field number. if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY || step.script->FlagToggle.FieldID >= cSource->GetValuesCount()) sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.", - step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID, - cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow()); + step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID, + cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow()); else cSource->RemoveFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue); } @@ -524,63 +527,63 @@ void Map::ScriptsProcess() break; case SCRIPT_COMMAND_QUEST_EXPLORED: - { - if (!source) { - sLog->outError("%s source object is NULL.", step.script->GetDebugInfo().c_str()); - break; - } - if (!target) - { - sLog->outError("%s target object is NULL.", step.script->GetDebugInfo().c_str()); - break; - } - - // when script called for item spell casting then target == (unit or GO) and source is player - WorldObject* worldObject; - Player* player = target->ToPlayer(); - if (player) - { - if (source->GetTypeId() != TYPEID_UNIT && source->GetTypeId() != TYPEID_GAMEOBJECT && source->GetTypeId() != TYPEID_PLAYER) + if (!source) { - sLog->outError("%s source is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.", - step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow()); + sLog->outError("%s source object is NULL.", step.script->GetDebugInfo().c_str()); break; } - worldObject = dynamic_cast(source); - } - else - { - player = source->ToPlayer(); + if (!target) + { + sLog->outError("%s target object is NULL.", step.script->GetDebugInfo().c_str()); + break; + } + + // when script called for item spell casting then target == (unit or GO) and source is player + WorldObject* worldObject; + Player* player = target->ToPlayer(); if (player) { - if (target->GetTypeId() != TYPEID_UNIT && target->GetTypeId() != TYPEID_GAMEOBJECT && target->GetTypeId() != TYPEID_PLAYER) + if (source->GetTypeId() != TYPEID_UNIT && source->GetTypeId() != TYPEID_GAMEOBJECT && source->GetTypeId() != TYPEID_PLAYER) { - sLog->outError("%s target is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.", - step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow()); + sLog->outError("%s source is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.", + step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow()); break; } - worldObject = dynamic_cast(target); + worldObject = dynamic_cast(source); } else { - sLog->outError("%s neither source nor target is player (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.", - step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow(), - target->GetTypeId(), target->GetEntry(), target->GetGUIDLow()); - break; + player = source->ToPlayer(); + if (player) + { + if (target->GetTypeId() != TYPEID_UNIT && target->GetTypeId() != TYPEID_GAMEOBJECT && target->GetTypeId() != TYPEID_PLAYER) + { + sLog->outError("%s target is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.", + step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow()); + break; + } + worldObject = dynamic_cast(target); + } + else + { + sLog->outError("%s neither source nor target is player (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.", + step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow(), + target->GetTypeId(), target->GetEntry(), target->GetGUIDLow()); + break; + } } + + // quest id and flags checked at script loading + if ((worldObject->GetTypeId() != TYPEID_UNIT || ((Unit*)worldObject)->IsAlive()) && + (step.script->QuestExplored.Distance == 0 || worldObject->IsWithinDistInMap(player, float(step.script->QuestExplored.Distance)))) + player->AreaExploredOrEventHappens(step.script->QuestExplored.QuestID); + else + player->FailQuest(step.script->QuestExplored.QuestID); + + break; } - // quest id and flags checked at script loading - if ((worldObject->GetTypeId() != TYPEID_UNIT || ((Unit*)worldObject)->IsAlive()) && - (step.script->QuestExplored.Distance == 0 || worldObject->IsWithinDistInMap(player, float(step.script->QuestExplored.Distance)))) - player->AreaExploredOrEventHappens(step.script->QuestExplored.QuestID); - else - player->FailQuest(step.script->QuestExplored.QuestID); - - break; - } - case SCRIPT_COMMAND_KILL_CREDIT: // Source or target must be Player. if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script)) @@ -610,12 +613,12 @@ void Map::ScriptsProcess() } if (pGO->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE || - pGO->GetGoType() == GAMEOBJECT_TYPE_DOOR || - pGO->GetGoType() == GAMEOBJECT_TYPE_BUTTON || - pGO->GetGoType() == GAMEOBJECT_TYPE_TRAP) + pGO->GetGoType() == GAMEOBJECT_TYPE_DOOR || + pGO->GetGoType() == GAMEOBJECT_TYPE_BUTTON || + pGO->GetGoType() == GAMEOBJECT_TYPE_TRAP) { sLog->outError("%s can not be used with gameobject of type %u (guid: %u).", - step.script->GetDebugInfo().c_str(), uint32(pGO->GetGoType()), step.script->RespawnGameobject.GOGuid); + step.script->GetDebugInfo().c_str(), uint32(pGO->GetGoType()), step.script->RespawnGameobject.GOGuid); break; } @@ -632,32 +635,32 @@ void Map::ScriptsProcess() break; case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE: - { - // Source must be WorldObject. - if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script)) { - if (!step.script->TempSummonCreature.CreatureEntry) - sLog->outError("%s creature entry (datalong) is not specified.", step.script->GetDebugInfo().c_str()); - else + // Source must be WorldObject. + if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script)) { - uint32 entry = step.script->TempSummonCreature.CreatureEntry; + if (!step.script->TempSummonCreature.CreatureEntry) + sLog->outError("%s creature entry (datalong) is not specified.", step.script->GetDebugInfo().c_str()); + else + { + uint32 entry = step.script->TempSummonCreature.CreatureEntry; - float x = step.script->TempSummonCreature.PosX; - float y = step.script->TempSummonCreature.PosY; - float z = step.script->TempSummonCreature.PosZ; - float o = step.script->TempSummonCreature.Orientation; + float x = step.script->TempSummonCreature.PosX; + float y = step.script->TempSummonCreature.PosY; + float z = step.script->TempSummonCreature.PosZ; + float o = step.script->TempSummonCreature.Orientation; - if (step.script->TempSummonCreature.CheckIfExists) - if (Unit* trigger = pSummoner->SummonTrigger(x, y, z, o, 1)) - if (trigger->FindNearestCreature(entry, 60.0f)) - break; + if (step.script->TempSummonCreature.CheckIfExists) + if (Unit* trigger = pSummoner->SummonTrigger(x, y, z, o, 1)) + if (trigger->FindNearestCreature(entry, 60.0f)) + break; - if (!pSummoner->SummonCreature(entry, x, y, z, o, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, step.script->TempSummonCreature.DespawnDelay)) - sLog->outError("%s creature was not spawned (entry: %u).", step.script->GetDebugInfo().c_str(), step.script->TempSummonCreature.CreatureEntry); + if (!pSummoner->SummonCreature(entry, x, y, z, o, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, step.script->TempSummonCreature.DespawnDelay)) + sLog->outError("%s creature was not spawned (entry: %u).", step.script->GetDebugInfo().c_str(), step.script->TempSummonCreature.CreatureEntry); + } } + break; } - break; - } case SCRIPT_COMMAND_OPEN_DOOR: case SCRIPT_COMMAND_CLOSE_DOOR: @@ -678,7 +681,7 @@ void Map::ScriptsProcess() if (target->GetTypeId() != TYPEID_GAMEOBJECT) { sLog->outError("%s target object is not gameobject (TypeId: %u, Entry: %u, GUID: %u), skipping.", - step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow()); + step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow()); break; } @@ -688,69 +691,69 @@ void Map::ScriptsProcess() break; case SCRIPT_COMMAND_REMOVE_AURA: - { - // Source (datalong2 != 0) or target (datalong2 == 0) must be Unit. - bool bReverse = step.script->RemoveAura.Flags & SF_REMOVEAURA_REVERSE; - if (Unit* unit = _GetScriptUnit(bReverse ? source : target, bReverse, step.script)) - unit->RemoveAurasDueToSpell(step.script->RemoveAura.SpellID); - break; - } + { + // Source (datalong2 != 0) or target (datalong2 == 0) must be Unit. + bool bReverse = step.script->RemoveAura.Flags & SF_REMOVEAURA_REVERSE; + if (Unit* unit = _GetScriptUnit(bReverse ? source : target, bReverse, step.script)) + unit->RemoveAurasDueToSpell(step.script->RemoveAura.SpellID); + break; + } case SCRIPT_COMMAND_CAST_SPELL: - { - // TODO: Allow gameobjects to be targets and casters - if (!source && !target) { - sLog->outError("%s source and target objects are NULL.", step.script->GetDebugInfo().c_str()); + // TODO: Allow gameobjects to be targets and casters + if (!source && !target) + { + sLog->outError("%s source and target objects are NULL.", step.script->GetDebugInfo().c_str()); + break; + } + + Unit* uSource = nullptr; + Unit* uTarget = nullptr; + // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s + switch (step.script->CastSpell.Flags) + { + case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target + uSource = source ? source->ToUnit() : nullptr; + uTarget = target ? target->ToUnit() : nullptr; + break; + case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source + uSource = source ? source->ToUnit() : nullptr; + uTarget = uSource; + break; + case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target + uSource = target ? target->ToUnit() : nullptr; + uTarget = uSource; + break; + case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source + uSource = target ? target->ToUnit() : nullptr; + uTarget = source ? source->ToUnit() : nullptr; + break; + case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry + uSource = source ? source->ToUnit() : nullptr; + uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : nullptr; + break; + } + + if (!uSource || !uSource->isType(TYPEMASK_UNIT)) + { + sLog->outError("%s no source unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID); + break; + } + + if (!uTarget || !uTarget->isType(TYPEMASK_UNIT)) + { + sLog->outError("%s no target unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID); + break; + } + + bool triggered = (step.script->CastSpell.Flags != 4) ? + step.script->CastSpell.CreatureEntry & SF_CASTSPELL_TRIGGERED : + step.script->CastSpell.CreatureEntry < 0; + uSource->CastSpell(uTarget, step.script->CastSpell.SpellID, triggered); break; } - Unit* uSource = nullptr; - Unit* uTarget = nullptr; - // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s - switch (step.script->CastSpell.Flags) - { - case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target - uSource = source ? source->ToUnit() : nullptr; - uTarget = target ? target->ToUnit() : nullptr; - break; - case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source - uSource = source ? source->ToUnit() : nullptr; - uTarget = uSource; - break; - case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target - uSource = target ? target->ToUnit() : nullptr; - uTarget = uSource; - break; - case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source - uSource = target ? target->ToUnit() : nullptr; - uTarget = source ? source->ToUnit() : nullptr; - break; - case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry - uSource = source ? source->ToUnit() : nullptr; - uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : nullptr; - break; - } - - if (!uSource || !uSource->isType(TYPEMASK_UNIT)) - { - sLog->outError("%s no source unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID); - break; - } - - if (!uTarget || !uTarget->isType(TYPEMASK_UNIT)) - { - sLog->outError("%s no target unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID); - break; - } - - bool triggered = (step.script->CastSpell.Flags != 4) ? - step.script->CastSpell.CreatureEntry & SF_CASTSPELL_TRIGGERED : - step.script->CastSpell.CreatureEntry < 0; - uSource->CastSpell(uTarget, step.script->CastSpell.SpellID, triggered); - break; - } - case SCRIPT_COMMAND_PLAY_SOUND: // Source must be WorldObject. if (WorldObject* object = _GetScriptWorldObject(source, true, step.script)) @@ -807,56 +810,56 @@ void Map::ScriptsProcess() break; case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT: - { - if (!step.script->CallScript.CreatureEntry) { - sLog->outError("%s creature entry is not specified, skipping.", step.script->GetDebugInfo().c_str()); + if (!step.script->CallScript.CreatureEntry) + { + sLog->outError("%s creature entry is not specified, skipping.", step.script->GetDebugInfo().c_str()); + break; + } + if (!step.script->CallScript.ScriptID) + { + sLog->outError("%s script id is not specified, skipping.", step.script->GetDebugInfo().c_str()); + break; + } + + Creature* cTarget = nullptr; + WorldObject* wSource = dynamic_cast (source); + if (wSource) //using grid searcher + { + CellCoord p(acore::ComputeCellCoord(wSource->GetPositionX(), wSource->GetPositionY())); + Cell cell(p); + + acore::CreatureWithDbGUIDCheck target_check(step.script->CallScript.CreatureEntry); + acore::CreatureSearcher checker(wSource, cTarget, target_check); + + TypeContainerVisitor, GridTypeMapContainer > unit_checker(checker); + cell.Visit(p, unit_checker, *wSource->GetMap(), *wSource, wSource->GetGridActivationRange()); + } + else //check hashmap holders + { + if (CreatureData const* data = sObjectMgr->GetCreatureData(step.script->CallScript.CreatureEntry)) + cTarget = ObjectAccessor::GetObjectInWorld(data->mapid, data->posX, data->posY, MAKE_NEW_GUID(step.script->CallScript.CreatureEntry, data->id, HIGHGUID_UNIT), cTarget); + } + + if (!cTarget) + { + sLog->outError("%s target was not found (entry: %u)", step.script->GetDebugInfo().c_str(), step.script->CallScript.CreatureEntry); + break; + } + + //Lets choose our ScriptMap map + ScriptMapMap* datamap = GetScriptsMapByType(ScriptsType(step.script->CallScript.ScriptType)); + //if no scriptmap present... + if (!datamap) + { + sLog->outError("%s unknown scriptmap (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->CallScript.ScriptType); + break; + } + + // Insert script into schedule but do not start it + ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, nullptr); break; } - if (!step.script->CallScript.ScriptID) - { - sLog->outError("%s script id is not specified, skipping.", step.script->GetDebugInfo().c_str()); - break; - } - - Creature* cTarget = nullptr; - WorldObject* wSource = dynamic_cast (source); - if (wSource) //using grid searcher - { - CellCoord p(acore::ComputeCellCoord(wSource->GetPositionX(), wSource->GetPositionY())); - Cell cell(p); - - acore::CreatureWithDbGUIDCheck target_check(step.script->CallScript.CreatureEntry); - acore::CreatureSearcher checker(wSource, cTarget, target_check); - - TypeContainerVisitor, GridTypeMapContainer > unit_checker(checker); - cell.Visit(p, unit_checker, *wSource->GetMap(), *wSource, wSource->GetGridActivationRange()); - } - else //check hashmap holders - { - if (CreatureData const* data = sObjectMgr->GetCreatureData(step.script->CallScript.CreatureEntry)) - cTarget = ObjectAccessor::GetObjectInWorld(data->mapid, data->posX, data->posY, MAKE_NEW_GUID(step.script->CallScript.CreatureEntry, data->id, HIGHGUID_UNIT), cTarget); - } - - if (!cTarget) - { - sLog->outError("%s target was not found (entry: %u)", step.script->GetDebugInfo().c_str(), step.script->CallScript.CreatureEntry); - break; - } - - //Lets choose our ScriptMap map - ScriptMapMap* datamap = GetScriptsMapByType(ScriptsType(step.script->CallScript.ScriptType)); - //if no scriptmap present... - if (!datamap) - { - sLog->outError("%s unknown scriptmap (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->CallScript.ScriptType); - break; - } - - // Insert script into schedule but do not start it - ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, nullptr); - break; - } case SCRIPT_COMMAND_KILL: // Source or target must be Creature. @@ -864,7 +867,7 @@ void Map::ScriptsProcess() { if (cSource->isDead()) sLog->outError("%s creature is already dead (Entry: %u, GUID: %u)", - step.script->GetDebugInfo().c_str(), cSource->GetEntry(), cSource->GetGUIDLow()); + step.script->GetDebugInfo().c_str(), cSource->GetEntry(), cSource->GetGUIDLow()); else { cSource->setDeathState(JUST_DIED); diff --git a/src/server/game/Scripting/ScriptMgr.cpp b/src/server/game/Scripting/ScriptMgr.cpp index 7ad8b2b5a..13d09d324 100644 --- a/src/server/game/Scripting/ScriptMgr.cpp +++ b/src/server/game/Scripting/ScriptMgr.cpp @@ -90,7 +90,7 @@ void ScriptMgr::Initialize() void ScriptMgr::Unload() { - #define SCR_CLEAR(T) \ +#define SCR_CLEAR(T) \ for (SCR_REG_ITR(T) itr = SCR_REG_LST(T).begin(); itr != SCR_REG_LST(T).end(); ++itr) \ delete itr->second; \ SCR_REG_LST(T).clear(); @@ -128,7 +128,7 @@ void ScriptMgr::Unload() SCR_CLEAR(GameEventScript); SCR_CLEAR(MailScript); - #undef SCR_CLEAR +#undef SCR_CLEAR } void ScriptMgr::LoadDatabase() @@ -165,7 +165,7 @@ struct TSpellSummary { uint8 Targets; // set of enum SelectTarget uint8 Effects; // set of enum SelectEffect -} *SpellSummary; +}* SpellSummary; void ScriptMgr::CheckIfScriptsInDatabaseExist() { @@ -174,31 +174,31 @@ void ScriptMgr::CheckIfScriptsInDatabaseExist() if (uint32 sid = sObjectMgr->GetScriptId((*itr).c_str())) { if (!ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid) && - !ScriptRegistry::GetScriptById(sid)) + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid) && + !ScriptRegistry::GetScriptById(sid)) sLog->outErrorDb("Script named '%s' is assigned in the database, but has no code!", (*itr).c_str()); } } @@ -223,67 +223,67 @@ void ScriptMgr::FillSpellSummary() { // Spell targets self. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SELF-1); + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SELF - 1); // Spell targets a single enemy. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_TARGET_ENEMY) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SINGLE_ENEMY-1); + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_TARGET_ENEMY) + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SINGLE_ENEMY - 1); // Spell targets AoE at enemy. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_AOE_ENEMY-1); + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_AOE_ENEMY - 1); // Spell targets an enemy. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_TARGET_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_ANY_ENEMY-1); + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_TARGET_ENEMY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_ANY_ENEMY - 1); // Spell targets a single friend (or self). if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ALLY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_PARTY) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SINGLE_FRIEND-1); + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ALLY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_PARTY) + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SINGLE_FRIEND - 1); // Spell targets AoE friends. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER_AREA_PARTY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_LASTTARGET_AREA_PARTY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_AOE_FRIEND-1); + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_LASTTARGET_AREA_PARTY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER) + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_AOE_FRIEND - 1); // Spell targets any friend (or self). if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ALLY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_PARTY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER_AREA_PARTY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_LASTTARGET_AREA_PARTY || - pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER) - SpellSummary[i].Targets |= 1 << (SELECT_TARGET_ANY_FRIEND-1); + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ALLY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_PARTY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER_AREA_PARTY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_LASTTARGET_AREA_PARTY || + pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER) + SpellSummary[i].Targets |= 1 << (SELECT_TARGET_ANY_FRIEND - 1); // Make sure that this spell includes a damage effect. if (pTempSpell->Effects[j].Effect == SPELL_EFFECT_SCHOOL_DAMAGE || - pTempSpell->Effects[j].Effect == SPELL_EFFECT_INSTAKILL || - pTempSpell->Effects[j].Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE || - pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH) - SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_DAMAGE-1); + pTempSpell->Effects[j].Effect == SPELL_EFFECT_INSTAKILL || + pTempSpell->Effects[j].Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE || + pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH) + SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_DAMAGE - 1); // Make sure that this spell includes a healing effect (or an apply aura with a periodic heal). if (pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL || - pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL_MAX_HEALTH || - pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL_MECHANICAL || - (pTempSpell->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && pTempSpell->Effects[j].ApplyAuraName == 8)) - SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_HEALING-1); + pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL_MAX_HEALTH || + pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL_MECHANICAL || + (pTempSpell->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && pTempSpell->Effects[j].ApplyAuraName == 8)) + SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_HEALING - 1); // Make sure that this spell applies an aura. if (pTempSpell->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA) - SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_AURA-1); + SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_AURA - 1); } } } @@ -513,15 +513,15 @@ void ScriptMgr::OnCreateMap(Map* map) #endif SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnCreate(map); + itr->second->OnCreate(map); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnCreate((InstanceMap*)map); + itr->second->OnCreate((InstanceMap*)map); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnCreate((BattlegroundMap*)map); + itr->second->OnCreate((BattlegroundMap*)map); SCR_MAP_END; } @@ -534,15 +534,15 @@ void ScriptMgr::OnDestroyMap(Map* map) #endif SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnDestroy(map); + itr->second->OnDestroy(map); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnDestroy((InstanceMap*)map); + itr->second->OnDestroy((InstanceMap*)map); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnDestroy((BattlegroundMap*)map); + itr->second->OnDestroy((BattlegroundMap*)map); SCR_MAP_END; } @@ -552,15 +552,15 @@ void ScriptMgr::OnLoadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy) ASSERT(gmap); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnLoadGridMap(map, gmap, gx, gy); + itr->second->OnLoadGridMap(map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnLoadGridMap((InstanceMap*)map, gmap, gx, gy); + itr->second->OnLoadGridMap((InstanceMap*)map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnLoadGridMap((BattlegroundMap*)map, gmap, gx, gy); + itr->second->OnLoadGridMap((BattlegroundMap*)map, gmap, gx, gy); SCR_MAP_END; } @@ -570,15 +570,15 @@ void ScriptMgr::OnUnloadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy) ASSERT(gmap); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnUnloadGridMap(map, gmap, gx, gy); + itr->second->OnUnloadGridMap(map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnUnloadGridMap((InstanceMap*)map, gmap, gx, gy); + itr->second->OnUnloadGridMap((InstanceMap*)map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnUnloadGridMap((BattlegroundMap*)map, gmap, gx, gy); + itr->second->OnUnloadGridMap((BattlegroundMap*)map, gmap, gx, gy); SCR_MAP_END; } @@ -597,15 +597,15 @@ void ScriptMgr::OnPlayerEnterMap(Map* map, Player* player) FOREACH_SCRIPT(PlayerScript)->OnMapChanged(player); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnPlayerEnter(map, player); + itr->second->OnPlayerEnter(map, player); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnPlayerEnter((InstanceMap*)map, player); + itr->second->OnPlayerEnter((InstanceMap*)map, player); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnPlayerEnter((BattlegroundMap*)map, player); + itr->second->OnPlayerEnter((BattlegroundMap*)map, player); SCR_MAP_END; } @@ -621,15 +621,15 @@ void ScriptMgr::OnPlayerLeaveMap(Map* map, Player* player) FOREACH_SCRIPT(AllMapScript)->OnPlayerLeaveAll(map, player); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnPlayerLeave(map, player); + itr->second->OnPlayerLeave(map, player); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnPlayerLeave((InstanceMap*)map, player); + itr->second->OnPlayerLeave((InstanceMap*)map, player); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnPlayerLeave((BattlegroundMap*)map, player); + itr->second->OnPlayerLeave((BattlegroundMap*)map, player); SCR_MAP_END; } @@ -642,15 +642,15 @@ void ScriptMgr::OnMapUpdate(Map* map, uint32 diff) #endif SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); - itr->second->OnUpdate(map, diff); + itr->second->OnUpdate(map, diff); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); - itr->second->OnUpdate((InstanceMap*)map, diff); + itr->second->OnUpdate((InstanceMap*)map, diff); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); - itr->second->OnUpdate((BattlegroundMap*)map, diff); + itr->second->OnUpdate((BattlegroundMap*)map, diff); SCR_MAP_END; } @@ -709,7 +709,7 @@ bool ScriptMgr::OnItemExpire(Player* player, ItemTemplate const* proto) return tmpscript->OnExpire(player, proto); } -bool ScriptMgr::OnItemRemove(Player * player, Item * item) +bool ScriptMgr::OnItemRemove(Player* player, Item* item) { ASSERT(player); ASSERT(item); @@ -1065,7 +1065,7 @@ std::vector ScriptMgr::GetChatCommands() } // Sort commands in alphabetical order - std::sort(table.begin(), table.end(), [](const ChatCommand& a, const ChatCommand&b) + std::sort(table.begin(), table.end(), [](const ChatCommand & a, const ChatCommand & b) { return strcmp(a.Name, b.Name) < 0; }); @@ -1266,7 +1266,7 @@ void ScriptMgr::OnDynamicObjectUpdate(DynamicObject* dynobj, uint32 diff) ASSERT(dynobj); FOR_SCRIPTS(DynamicObjectScript, itr, end) - itr->second->OnUpdate(dynobj, diff); + itr->second->OnUpdate(dynobj, diff); } void ScriptMgr::OnAddPassenger(Transport* transport, Player* player) @@ -1550,7 +1550,7 @@ void ScriptMgr::OnPlayerCreate(Player* player) FOREACH_SCRIPT(PlayerScript)->OnCreate(player); } -void ScriptMgr::OnPlayerSave(Player * player) +void ScriptMgr::OnPlayerSave(Player* player) { #ifdef ELUNA sEluna->OnSave(player); @@ -1592,12 +1592,12 @@ void ScriptMgr::OnPlayerUpdateArea(Player* player, uint32 oldArea, uint32 newAre FOREACH_SCRIPT(PlayerScript)->OnUpdateArea(player, oldArea, newArea); } -bool ScriptMgr::OnBeforePlayerTeleport(Player* player, uint32 mapid, float x, float y, float z, float orientation, uint32 options, Unit *target) +bool ScriptMgr::OnBeforePlayerTeleport(Player* player, uint32 mapid, float x, float y, float z, float orientation, uint32 options, Unit* target) { - bool ret=true; + bool ret = true; FOR_SCRIPTS_RET(PlayerScript, itr, end, ret) // return true by default if not scripts - if (!itr->second->OnBeforeTeleport(player, mapid, x, y, z, orientation, options, target)) - ret=false; // we change ret value only when scripts return false + if (!itr->second->OnBeforeTeleport(player, mapid, x, y, z, orientation, options, target)) + ret = false; // we change ret value only when scripts return false return ret; } @@ -1607,7 +1607,7 @@ void ScriptMgr::OnPlayerUpdateFaction(Player* player) FOREACH_SCRIPT(PlayerScript)->OnUpdateFaction(player); } -void ScriptMgr::OnPlayerAddToBattleground(Player* player, Battleground *bg) +void ScriptMgr::OnPlayerAddToBattleground(Player* player, Battleground* bg) { FOREACH_SCRIPT(PlayerScript)->OnAddToBattleground(player, bg); } @@ -1642,9 +1642,9 @@ void ScriptMgr::OnPlayerBeingCharmed(Player* player, Unit* charmer, uint32 oldFa FOREACH_SCRIPT(PlayerScript)->OnBeingCharmed(player, charmer, oldFactionId, newFactionId); } -void ScriptMgr::OnAfterPlayerSetVisibleItemSlot(Player* player, uint8 slot, Item *item) +void ScriptMgr::OnAfterPlayerSetVisibleItemSlot(Player* player, uint8 slot, Item* item) { - FOREACH_SCRIPT(PlayerScript)->OnAfterSetVisibleItemSlot(player, slot,item); + FOREACH_SCRIPT(PlayerScript)->OnAfterSetVisibleItemSlot(player, slot, item); } void ScriptMgr::OnAfterPlayerMoveItemFromInventory(Player* player, Item* it, uint8 bag, uint8 slot, bool update) @@ -1695,8 +1695,8 @@ bool ScriptMgr::CanJoinInBattlegroundQueue(Player* player, uint64 BattlemasterGu bool ret = true; FOR_SCRIPTS_RET(PlayerScript, itr, end, ret) // return true by default if not scripts - if (!itr->second->CanJoinInBattlegroundQueue(player, BattlemasterGuid, BGTypeID, joinAsGroup, err)) - ret = false; // we change ret value only when scripts return false + if (!itr->second->CanJoinInBattlegroundQueue(player, BattlemasterGuid, BGTypeID, joinAsGroup, err)) + ret = false; // we change ret value only when scripts return false return ret; } @@ -1801,7 +1801,7 @@ void ScriptMgr::OnGuildDisband(Guild* guild) FOREACH_SCRIPT(GuildScript)->OnDisband(guild); } -void ScriptMgr::OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32 &amount, bool isRepair) +void ScriptMgr::OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32& amount, bool isRepair) { #ifdef ELUNA sEluna->OnMemberWitdrawMoney(guild, player, amount, isRepair); @@ -1809,7 +1809,7 @@ void ScriptMgr::OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32 & FOREACH_SCRIPT(GuildScript)->OnMemberWitdrawMoney(guild, player, amount, isRepair); } -void ScriptMgr::OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32 &amount) +void ScriptMgr::OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32& amount) { #ifdef ELUNA sEluna->OnMemberDepositMoney(guild, player, amount); @@ -1818,7 +1818,7 @@ void ScriptMgr::OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32 & } void ScriptMgr::OnGuildItemMove(Guild* guild, Player* player, Item* pItem, bool isSrcBank, uint8 srcContainer, uint8 srcSlotId, - bool isDestBank, uint8 destContainer, uint8 destSlotId) + bool isDestBank, uint8 destContainer, uint8 destSlotId) { #ifdef ELUNA sEluna->OnItemMove(guild, player, pItem, isSrcBank, srcContainer, srcSlotId, isDestBank, destContainer, destSlotId); @@ -1847,7 +1847,7 @@ void ScriptMgr::OnGroupAddMember(Group* group, uint64 guid) { ASSERT(group); #ifdef ELUNA - sEluna->OnAddMember(group, guid); + sEluna->OnAddMember(group, guid); #endif FOREACH_SCRIPT(GroupScript)->OnAddMember(group, guid); } @@ -1894,20 +1894,20 @@ void ScriptMgr::OnGlobalItemDelFromDB(SQLTransaction& trans, uint32 itemGuid) ASSERT(trans); ASSERT(itemGuid); - FOREACH_SCRIPT(GlobalScript)->OnItemDelFromDB(trans,itemGuid); + FOREACH_SCRIPT(GlobalScript)->OnItemDelFromDB(trans, itemGuid); } -void ScriptMgr::OnGlobalMirrorImageDisplayItem(const Item *item, uint32 &display) +void ScriptMgr::OnGlobalMirrorImageDisplayItem(const Item* item, uint32& display) { - FOREACH_SCRIPT(GlobalScript)->OnMirrorImageDisplayItem(item,display); + FOREACH_SCRIPT(GlobalScript)->OnMirrorImageDisplayItem(item, display); } -void ScriptMgr::OnBeforeUpdateArenaPoints(ArenaTeam* at, std::map &ap) +void ScriptMgr::OnBeforeUpdateArenaPoints(ArenaTeam* at, std::map& ap) { - FOREACH_SCRIPT(GlobalScript)->OnBeforeUpdateArenaPoints(at,ap); + FOREACH_SCRIPT(GlobalScript)->OnBeforeUpdateArenaPoints(at, ap); } -void ScriptMgr::OnAfterRefCount(Player const* player, Loot& loot, bool canRate, uint16 lootMode, LootStoreItem* LootStoreItem, uint32 &maxcount, LootStore const& store) +void ScriptMgr::OnAfterRefCount(Player const* player, Loot& loot, bool canRate, uint16 lootMode, LootStoreItem* LootStoreItem, uint32& maxcount, LootStore const& store) { FOREACH_SCRIPT(GlobalScript)->OnAfterRefCount(player, LootStoreItem, loot, canRate, lootMode, maxcount, store); } @@ -1917,7 +1917,8 @@ void ScriptMgr::OnBeforeDropAddItem(Player const* player, Loot& loot, bool canRa FOREACH_SCRIPT(GlobalScript)->OnBeforeDropAddItem(player, loot, canRate, lootMode, LootStoreItem, store); } -void ScriptMgr::OnItemRoll(Player const* player, LootStoreItem const* LootStoreItem, float &chance, Loot& loot, LootStore const& store) { +void ScriptMgr::OnItemRoll(Player const* player, LootStoreItem const* LootStoreItem, float& chance, Loot& loot, LootStore const& store) +{ FOREACH_SCRIPT(GlobalScript)->OnItemRoll(player, LootStoreItem, chance, loot, store); } @@ -1942,13 +1943,13 @@ void ScriptMgr::OnBeforeWorldObjectSetPhaseMask(WorldObject const* worldObject, } // Unit -uint32 ScriptMgr::DealDamage(Unit* AttackerUnit, Unit *pVictim, uint32 damage, DamageEffectType damagetype) +uint32 ScriptMgr::DealDamage(Unit* AttackerUnit, Unit* pVictim, uint32 damage, DamageEffectType damagetype) { FOR_SCRIPTS_RET(UnitScript, itr, end, damage) - damage = itr->second->DealDamage(AttackerUnit, pVictim, damage, damagetype); + damage = itr->second->DealDamage(AttackerUnit, pVictim, damage, damagetype); return damage; } -void ScriptMgr::Creature_SelectLevel(const CreatureTemplate *cinfo, Creature* creature) +void ScriptMgr::Creature_SelectLevel(const CreatureTemplate* cinfo, Creature* creature) { FOREACH_SCRIPT(AllCreatureScript)->Creature_SelectLevel(cinfo, creature); } @@ -1982,7 +1983,7 @@ void ScriptMgr::ModifyHealRecieved(Unit* target, Unit* attacker, uint32& damage) FOREACH_SCRIPT(UnitScript)->ModifyHealRecieved(target, attacker, damage); } -void ScriptMgr::OnBeforeRollMeleeOutcomeAgainst(const Unit* attacker, const Unit* victim, WeaponAttackType attType, int32 &attackerMaxSkillValueForLevel, int32 &victimMaxSkillValueForLevel, int32 &attackerWeaponSkill, int32 &victimDefenseSkill, int32 &crit_chance, int32 &miss_chance, int32 &dodge_chance, int32 &parry_chance, int32 &block_chance) +void ScriptMgr::OnBeforeRollMeleeOutcomeAgainst(const Unit* attacker, const Unit* victim, WeaponAttackType attType, int32& attackerMaxSkillValueForLevel, int32& victimMaxSkillValueForLevel, int32& attackerWeaponSkill, int32& victimDefenseSkill, int32& crit_chance, int32& miss_chance, int32& dodge_chance, int32& parry_chance, int32& block_chance) { FOREACH_SCRIPT(UnitScript)->OnBeforeRollMeleeOutcomeAgainst(attacker, victim, attType, attackerMaxSkillValueForLevel, victimMaxSkillValueForLevel, attackerWeaponSkill, victimDefenseSkill, crit_chance, miss_chance, dodge_chance, parry_chance, block_chance); } @@ -1992,12 +1993,12 @@ void ScriptMgr::OnPlayerMove(Player* player, MovementInfo movementInfo, uint32 o FOREACH_SCRIPT(MovementHandlerScript)->OnPlayerMove(player, movementInfo, opcode); } -void ScriptMgr::OnBeforeBuyItemFromVendor(Player* player, uint64 vendorguid, uint32 vendorslot, uint32 &item, uint8 count, uint8 bag, uint8 slot) +void ScriptMgr::OnBeforeBuyItemFromVendor(Player* player, uint64 vendorguid, uint32 vendorslot, uint32& item, uint8 count, uint8 bag, uint8 slot) { FOREACH_SCRIPT(PlayerScript)->OnBeforeBuyItemFromVendor(player, vendorguid, vendorslot, item, count, bag, slot); } -void ScriptMgr::OnAfterStoreOrEquipNewItem(Player* player, uint32 vendorslot, uint32 &item, uint8 count, uint8 bag, uint8 slot, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore) +void ScriptMgr::OnAfterStoreOrEquipNewItem(Player* player, uint32 vendorslot, uint32& item, uint8 count, uint8 bag, uint8 slot, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore) { FOREACH_SCRIPT(PlayerScript)->OnAfterStoreOrEquipNewItem(player, vendorslot, item, count, bag, slot, pProto, pVendor, crItem, bStore); } @@ -2027,7 +2028,7 @@ void ScriptMgr::OnBeforeInitTalentForLevel(Player* player, uint8& level, uint32& FOREACH_SCRIPT(PlayerScript)->OnBeforeInitTalentForLevel(player, level, talentPointsForLevel); } -void ScriptMgr::OnAfterArenaRatingCalculation(Battleground *const bg, int32 &winnerMatchmakerChange, int32 &loserMatchmakerChange, int32 &winnerChange, int32 &loserChange) +void ScriptMgr::OnAfterArenaRatingCalculation(Battleground* const bg, int32& winnerMatchmakerChange, int32& loserMatchmakerChange, int32& winnerChange, int32& loserChange) { FOREACH_SCRIPT(FormulaScript)->OnAfterArenaRatingCalculation(bg, winnerMatchmakerChange, loserMatchmakerChange, winnerChange, loserChange); } @@ -2073,20 +2074,20 @@ bool ScriptMgr::CanFillPlayersToBG(BattlegroundQueue* queue, Battleground* bg, c bool ret = true; FOR_SCRIPTS_RET(BGScript, itr, end, ret) // return true by default if not scripts - if (!itr->second->CanFillPlayersToBG(queue, bg, aliFree, hordeFree, bracket_id)) - ret = false; // we change ret value only when scripts return false + if (!itr->second->CanFillPlayersToBG(queue, bg, aliFree, hordeFree, bracket_id)) + ret = false; // we change ret value only when scripts return false return ret; } bool ScriptMgr::CanFillPlayersToBGWithSpecific(BattlegroundQueue* queue, Battleground* bg, const int32 aliFree, const int32 hordeFree, - BattlegroundBracketId thisBracketId, BattlegroundQueue* specificQueue, BattlegroundBracketId specificBracketId) + BattlegroundBracketId thisBracketId, BattlegroundQueue* specificQueue, BattlegroundBracketId specificBracketId) { bool ret = true; FOR_SCRIPTS_RET(BGScript, itr, end, ret) // return true by default if not scripts - if (!itr->second->CanFillPlayersToBGWithSpecific(queue, bg, aliFree, hordeFree, thisBracketId, specificQueue, specificBracketId)) - ret = false; // we change ret value only when scripts return false + if (!itr->second->CanFillPlayersToBGWithSpecific(queue, bg, aliFree, hordeFree, thisBracketId, specificQueue, specificBracketId)) + ret = false; // we change ret value only when scripts return false return ret; } @@ -2101,8 +2102,8 @@ bool ScriptMgr::CanSendMessageQueue(BattlegroundQueue* queue, Player* leader, Ba bool ret = true; FOR_SCRIPTS_RET(BGScript, itr, end, ret) // return true by default if not scripts - if (!itr->second->CanSendMessageQueue(queue, leader, bg, bracketEntry)) - ret = false; // we change ret value only when scripts return false + if (!itr->second->CanSendMessageQueue(queue, leader, bg, bracketEntry)) + ret = false; // we change ret value only when scripts return false return ret; } diff --git a/src/server/game/Scripting/ScriptMgr.h b/src/server/game/Scripting/ScriptMgr.h index 9cf7c6bdf..4b557dfe5 100644 --- a/src/server/game/Scripting/ScriptMgr.h +++ b/src/server/game/Scripting/ScriptMgr.h @@ -147,162 +147,162 @@ class ScriptObject { friend class ScriptMgr; - public: +public: - // Do not override this in scripts; it should be overridden by the various script type classes. It indicates - // whether or not this script type must be assigned in the database. - virtual bool IsDatabaseBound() const { return false; } - virtual bool isAfterLoadScript() const { return IsDatabaseBound(); } - virtual void checkValidity() { } + // Do not override this in scripts; it should be overridden by the various script type classes. It indicates + // whether or not this script type must be assigned in the database. + virtual bool IsDatabaseBound() const { return false; } + virtual bool isAfterLoadScript() const { return IsDatabaseBound(); } + virtual void checkValidity() { } - const std::string& GetName() const { return _name; } + const std::string& GetName() const { return _name; } - protected: +protected: - ScriptObject(const char* name) - : _name(std::string(name)) - { - } + ScriptObject(const char* name) + : _name(std::string(name)) + { + } - virtual ~ScriptObject() - { - } + virtual ~ScriptObject() + { + } - private: +private: - const std::string _name; + const std::string _name; }; template class UpdatableScript { - protected: +protected: - UpdatableScript() - { - } + UpdatableScript() + { + } - public: +public: - virtual void OnUpdate(TObject* /*obj*/, uint32 /*diff*/) { } + virtual void OnUpdate(TObject* /*obj*/, uint32 /*diff*/) { } }; class SpellScriptLoader : public ScriptObject { - protected: +protected: - SpellScriptLoader(const char* name); + SpellScriptLoader(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Should return a fully valid SpellScript pointer. - virtual SpellScript* GetSpellScript() const { return nullptr; } + // Should return a fully valid SpellScript pointer. + virtual SpellScript* GetSpellScript() const { return nullptr; } - // Should return a fully valid AuraScript pointer. - virtual AuraScript* GetAuraScript() const { return nullptr; } + // Should return a fully valid AuraScript pointer. + virtual AuraScript* GetAuraScript() const { return nullptr; } }; class ServerScript : public ScriptObject { - protected: +protected: - ServerScript(const char* name); + ServerScript(const char* name); - public: +public: - // Called when reactive socket I/O is started (WorldSocketMgr). - virtual void OnNetworkStart() { } + // Called when reactive socket I/O is started (WorldSocketMgr). + virtual void OnNetworkStart() { } - // Called when reactive I/O is stopped. - virtual void OnNetworkStop() { } + // Called when reactive I/O is stopped. + virtual void OnNetworkStop() { } - // Called when a remote socket establishes a connection to the server. Do not store the socket object. - virtual void OnSocketOpen(WorldSocket* /*socket*/) { } + // Called when a remote socket establishes a connection to the server. Do not store the socket object. + virtual void OnSocketOpen(WorldSocket* /*socket*/) { } - // Called when a socket is closed. Do not store the socket object, and do not rely on the connection - // being open; it is not. - virtual void OnSocketClose(WorldSocket* /*socket*/, bool /*wasNew*/) { } + // Called when a socket is closed. Do not store the socket object, and do not rely on the connection + // being open; it is not. + virtual void OnSocketClose(WorldSocket* /*socket*/, bool /*wasNew*/) { } - // Called when a packet is sent to a client. The packet object is a copy of the original packet, so reading - // and modifying it is safe. - virtual void OnPacketSend(WorldSession* /*session*/, WorldPacket& /*packet*/) { } + // Called when a packet is sent to a client. The packet object is a copy of the original packet, so reading + // and modifying it is safe. + virtual void OnPacketSend(WorldSession* /*session*/, WorldPacket& /*packet*/) { } - // Called when a (valid) packet is received by a client. The packet object is a copy of the original packet, so - // reading and modifying it is safe. Make sure to check WorldSession pointer before usage, it might be null in case of auth packets - virtual void OnPacketReceive(WorldSession* /*session*/, WorldPacket& /*packet*/) { } + // Called when a (valid) packet is received by a client. The packet object is a copy of the original packet, so + // reading and modifying it is safe. Make sure to check WorldSession pointer before usage, it might be null in case of auth packets + virtual void OnPacketReceive(WorldSession* /*session*/, WorldPacket& /*packet*/) { } }; class WorldScript : public ScriptObject { - protected: +protected: - WorldScript(const char* name); + WorldScript(const char* name); - public: +public: - // Called when the open/closed state of the world changes. - virtual void OnOpenStateChange(bool /*open*/) { } + // Called when the open/closed state of the world changes. + virtual void OnOpenStateChange(bool /*open*/) { } - // Called after the world configuration is (re)loaded. - virtual void OnAfterConfigLoad(bool /*reload*/) { } + // Called after the world configuration is (re)loaded. + virtual void OnAfterConfigLoad(bool /*reload*/) { } - // Called when loading custom database tables - virtual void OnLoadCustomDatabaseTable() { } + // Called when loading custom database tables + virtual void OnLoadCustomDatabaseTable() { } - // Called before the world configuration is (re)loaded. - virtual void OnBeforeConfigLoad(bool /*reload*/) { } + // Called before the world configuration is (re)loaded. + virtual void OnBeforeConfigLoad(bool /*reload*/) { } - // Called before the message of the day is changed. - virtual void OnMotdChange(std::string& /*newMotd*/) { } + // Called before the message of the day is changed. + virtual void OnMotdChange(std::string& /*newMotd*/) { } - // Called when a world shutdown is initiated. - virtual void OnShutdownInitiate(ShutdownExitCode /*code*/, ShutdownMask /*mask*/) { } + // Called when a world shutdown is initiated. + virtual void OnShutdownInitiate(ShutdownExitCode /*code*/, ShutdownMask /*mask*/) { } - // Called when a world shutdown is cancelled. - virtual void OnShutdownCancel() { } + // Called when a world shutdown is cancelled. + virtual void OnShutdownCancel() { } - // Called on every world tick (don't execute too heavy code here). - virtual void OnUpdate(uint32 /*diff*/) { } + // Called on every world tick (don't execute too heavy code here). + virtual void OnUpdate(uint32 /*diff*/) { } - // Called when the world is started. - virtual void OnStartup() { } + // Called when the world is started. + virtual void OnStartup() { } - // Called when the world is actually shut down. - virtual void OnShutdown() { } + // Called when the world is actually shut down. + virtual void OnShutdown() { } }; class FormulaScript : public ScriptObject { - protected: +protected: - FormulaScript(const char* name); + FormulaScript(const char* name); - public: +public: - // Called after calculating honor. - virtual void OnHonorCalculation(float& /*honor*/, uint8 /*level*/, float /*multiplier*/) { } + // Called after calculating honor. + virtual void OnHonorCalculation(float& /*honor*/, uint8 /*level*/, float /*multiplier*/) { } - // Called after gray level calculation. - virtual void OnGrayLevelCalculation(uint8& /*grayLevel*/, uint8 /*playerLevel*/) { } + // Called after gray level calculation. + virtual void OnGrayLevelCalculation(uint8& /*grayLevel*/, uint8 /*playerLevel*/) { } - // Called after calculating experience color. - virtual void OnColorCodeCalculation(XPColorChar& /*color*/, uint8 /*playerLevel*/, uint8 /*mobLevel*/) { } + // Called after calculating experience color. + virtual void OnColorCodeCalculation(XPColorChar& /*color*/, uint8 /*playerLevel*/, uint8 /*mobLevel*/) { } - // Called after calculating zero difference. - virtual void OnZeroDifferenceCalculation(uint8& /*diff*/, uint8 /*playerLevel*/) { } + // Called after calculating zero difference. + virtual void OnZeroDifferenceCalculation(uint8& /*diff*/, uint8 /*playerLevel*/) { } - // Called after calculating base experience gain. - virtual void OnBaseGainCalculation(uint32& /*gain*/, uint8 /*playerLevel*/, uint8 /*mobLevel*/, ContentLevels /*content*/) { } + // Called after calculating base experience gain. + virtual void OnBaseGainCalculation(uint32& /*gain*/, uint8 /*playerLevel*/, uint8 /*mobLevel*/, ContentLevels /*content*/) { } - // Called after calculating experience gain. - virtual void OnGainCalculation(uint32& /*gain*/, Player* /*player*/, Unit* /*unit*/) { } + // Called after calculating experience gain. + virtual void OnGainCalculation(uint32& /*gain*/, Player* /*player*/, Unit* /*unit*/) { } - // Called when calculating the experience rate for group experience. - virtual void OnGroupRateCalculation(float& /*rate*/, uint32 /*count*/, bool /*isRaid*/) { } + // Called when calculating the experience rate for group experience. + virtual void OnGroupRateCalculation(float& /*rate*/, uint32 /*count*/, bool /*isRaid*/) { } - // Called after calculating arena rating changes - virtual void OnAfterArenaRatingCalculation(Battleground *const /*bg*/, int32& /*winnerMatchmakerChange*/, int32& /*loserMatchmakerChange*/, int32& /*winnerChange*/, int32& /*loserChange*/) { }; + // Called after calculating arena rating changes + virtual void OnAfterArenaRatingCalculation(Battleground* const /*bg*/, int32& /*winnerMatchmakerChange*/, int32& /*loserMatchmakerChange*/, int32& /*winnerChange*/, int32& /*loserChange*/) { }; }; template class MapScript : public UpdatableScript @@ -310,133 +310,137 @@ template class MapScript : public UpdatableScript MapEntry const* _mapEntry; uint32 _mapId; - protected: +protected: - MapScript(uint32 mapId) - : _mapId(mapId) - { - } + MapScript(uint32 mapId) + : _mapId(mapId) + { + } - public: - void checkMap() { - _mapEntry = sMapStore.LookupEntry(_mapId); +public: + void checkMap() + { + _mapEntry = sMapStore.LookupEntry(_mapId); - if (!_mapEntry) - sLog->outError("Invalid MapScript for %u; no such map ID.", _mapId); - } + if (!_mapEntry) + sLog->outError("Invalid MapScript for %u; no such map ID.", _mapId); + } - // Gets the MapEntry structure associated with this script. Can return NULL. - MapEntry const* GetEntry() { return _mapEntry; } + // Gets the MapEntry structure associated with this script. Can return NULL. + MapEntry const* GetEntry() { return _mapEntry; } - // Called when the map is created. - virtual void OnCreate(TMap* /*map*/) { } + // Called when the map is created. + virtual void OnCreate(TMap* /*map*/) { } - // Called just before the map is destroyed. - virtual void OnDestroy(TMap* /*map*/) { } + // Called just before the map is destroyed. + virtual void OnDestroy(TMap* /*map*/) { } - // Called when a grid map is loaded. - virtual void OnLoadGridMap(TMap* /*map*/, GridMap* /*gmap*/, uint32 /*gx*/, uint32 /*gy*/) { } + // Called when a grid map is loaded. + virtual void OnLoadGridMap(TMap* /*map*/, GridMap* /*gmap*/, uint32 /*gx*/, uint32 /*gy*/) { } - // Called when a grid map is unloaded. - virtual void OnUnloadGridMap(TMap* /*map*/, GridMap* /*gmap*/, uint32 /*gx*/, uint32 /*gy*/) { } + // Called when a grid map is unloaded. + virtual void OnUnloadGridMap(TMap* /*map*/, GridMap* /*gmap*/, uint32 /*gx*/, uint32 /*gy*/) { } - // Called when a player enters the map. - virtual void OnPlayerEnter(TMap* /*map*/, Player* /*player*/) { } + // Called when a player enters the map. + virtual void OnPlayerEnter(TMap* /*map*/, Player* /*player*/) { } - // Called when a player leaves the map. - virtual void OnPlayerLeave(TMap* /*map*/, Player* /*player*/) { } + // Called when a player leaves the map. + virtual void OnPlayerLeave(TMap* /*map*/, Player* /*player*/) { } - // Called on every map update tick. - virtual void OnUpdate(TMap* /*map*/, uint32 /*diff*/) { } + // Called on every map update tick. + virtual void OnUpdate(TMap* /*map*/, uint32 /*diff*/) { } }; class WorldMapScript : public ScriptObject, public MapScript { - protected: +protected: - WorldMapScript(const char* name, uint32 mapId); + WorldMapScript(const char* name, uint32 mapId); - public: +public: - bool isAfterLoadScript() const { return true; } + bool isAfterLoadScript() const { return true; } - void checkValidity() { - checkMap(); + void checkValidity() + { + checkMap(); - if (GetEntry() && !GetEntry()->IsWorldMap()) - sLog->outError("WorldMapScript for map %u is invalid.", GetEntry()->MapID); - } + if (GetEntry() && !GetEntry()->IsWorldMap()) + sLog->outError("WorldMapScript for map %u is invalid.", GetEntry()->MapID); + } }; class InstanceMapScript : public ScriptObject, public MapScript { - protected: +protected: - InstanceMapScript(const char* name, uint32 mapId); + InstanceMapScript(const char* name, uint32 mapId); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - void checkValidity() { - checkMap(); + void checkValidity() + { + checkMap(); - if (GetEntry() && !GetEntry()->IsDungeon()) - sLog->outError("InstanceMapScript for map %u is invalid.", GetEntry()->MapID); - } + if (GetEntry() && !GetEntry()->IsDungeon()) + sLog->outError("InstanceMapScript for map %u is invalid.", GetEntry()->MapID); + } - // Gets an InstanceScript object for this instance. - virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return nullptr; } + // Gets an InstanceScript object for this instance. + virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return nullptr; } }; class BattlegroundMapScript : public ScriptObject, public MapScript { - protected: +protected: - BattlegroundMapScript(const char* name, uint32 mapId); + BattlegroundMapScript(const char* name, uint32 mapId); - public: +public: - bool isAfterLoadScript() const { return true; } + bool isAfterLoadScript() const { return true; } - void checkValidity() { - checkMap(); + void checkValidity() + { + checkMap(); - if (GetEntry() && !GetEntry()->IsBattleground()) - sLog->outError("BattlegroundMapScript for map %u is invalid.", GetEntry()->MapID); - } + if (GetEntry() && !GetEntry()->IsBattleground()) + sLog->outError("BattlegroundMapScript for map %u is invalid.", GetEntry()->MapID); + } }; class ItemScript : public ScriptObject { - protected: +protected: - ItemScript(const char* name); + ItemScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when a player accepts a quest from the item. - virtual bool OnQuestAccept(Player* /*player*/, Item* /*item*/, Quest const* /*quest*/) { return false; } + // Called when a player accepts a quest from the item. + virtual bool OnQuestAccept(Player* /*player*/, Item* /*item*/, Quest const* /*quest*/) { return false; } - // Called when a player uses the item. - virtual bool OnUse(Player* /*player*/, Item* /*item*/, SpellCastTargets const& /*targets*/) { return false; } + // Called when a player uses the item. + virtual bool OnUse(Player* /*player*/, Item* /*item*/, SpellCastTargets const& /*targets*/) { return false; } - // Called when the item is destroyed. - virtual bool OnRemove(Player* /*player*/, Item* /*item*/) { return false; } + // Called when the item is destroyed. + virtual bool OnRemove(Player* /*player*/, Item* /*item*/) { return false; } - // Called before casting a combat spell from this item (chance on hit spells of item template, can be used to prevent cast if returning false) - virtual bool OnCastItemCombatSpell(Player* /*player*/, Unit* /*victim*/, SpellInfo const* /*spellInfo*/, Item* /*item*/) { return true; } + // Called before casting a combat spell from this item (chance on hit spells of item template, can be used to prevent cast if returning false) + virtual bool OnCastItemCombatSpell(Player* /*player*/, Unit* /*victim*/, SpellInfo const* /*spellInfo*/, Item* /*item*/) { return true; } - // Called when the item expires (is destroyed). - virtual bool OnExpire(Player* /*player*/, ItemTemplate const* /*proto*/) { return false; } + // Called when the item expires (is destroyed). + virtual bool OnExpire(Player* /*player*/, ItemTemplate const* /*proto*/) { return false; } - // Called when a player selects an option in an item gossip window - virtual void OnGossipSelect(Player* /*player*/, Item* /*item*/, uint32 /*sender*/, uint32 /*action*/) { } + // Called when a player selects an option in an item gossip window + virtual void OnGossipSelect(Player* /*player*/, Item* /*item*/, uint32 /*sender*/, uint32 /*action*/) { } - // Called when a player selects an option in an item gossip window - virtual void OnGossipSelectCode(Player* /*player*/, Item* /*item*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { } + // Called when a player selects an option in an item gossip window + virtual void OnGossipSelectCode(Player* /*player*/, Item* /*item*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { } }; class UnitScript : public ScriptObject @@ -468,7 +472,7 @@ public: //Called when Damage is Dealt virtual uint32 DealDamage(Unit* /*AttackerUnit*/, Unit* /*pVictim*/, uint32 damage, DamageEffectType /*damagetype*/) { return damage; } - virtual void OnBeforeRollMeleeOutcomeAgainst(const Unit* /*attacker*/, const Unit* /*victim*/, WeaponAttackType /*attType*/, int32 &/*attackerMaxSkillValueForLevel*/, int32 &/*victimMaxSkillValueForLevel*/, int32 &/*attackerWeaponSkill*/, int32 &/*victimDefenseSkill*/, int32& /*crit_chance*/, int32& /*miss_chance*/ , int32& /*dodge_chance*/ , int32& /*parry_chance*/ , int32& /*block_chance*/ ) { }; + virtual void OnBeforeRollMeleeOutcomeAgainst(const Unit* /*attacker*/, const Unit* /*victim*/, WeaponAttackType /*attType*/, int32& /*attackerMaxSkillValueForLevel*/, int32& /*victimMaxSkillValueForLevel*/, int32& /*attackerWeaponSkill*/, int32& /*victimDefenseSkill*/, int32& /*crit_chance*/, int32& /*miss_chance*/, int32& /*dodge_chance*/, int32& /*parry_chance*/, int32& /*block_chance*/ ) { }; }; class MovementHandlerScript : public ScriptObject @@ -515,618 +519,618 @@ public: class CreatureScript : public ScriptObject, public UpdatableScript { - protected: +protected: - CreatureScript(const char* name); + CreatureScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when a player opens a gossip dialog with the creature. - virtual bool OnGossipHello(Player* /*player*/, Creature* /*creature*/) { return false; } + // Called when a player opens a gossip dialog with the creature. + virtual bool OnGossipHello(Player* /*player*/, Creature* /*creature*/) { return false; } - // Called when a player selects a gossip item in the creature's gossip menu. - virtual bool OnGossipSelect(Player* /*player*/, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/) { return false; } + // Called when a player selects a gossip item in the creature's gossip menu. + virtual bool OnGossipSelect(Player* /*player*/, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/) { return false; } - // Called when a player selects a gossip with a code in the creature's gossip menu. - virtual bool OnGossipSelectCode(Player* /*player*/, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { return false; } + // Called when a player selects a gossip with a code in the creature's gossip menu. + virtual bool OnGossipSelectCode(Player* /*player*/, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { return false; } - // Called when a player accepts a quest from the creature. - virtual bool OnQuestAccept(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } + // Called when a player accepts a quest from the creature. + virtual bool OnQuestAccept(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } - // Called when a player selects a quest in the creature's quest menu. - virtual bool OnQuestSelect(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } + // Called when a player selects a quest in the creature's quest menu. + virtual bool OnQuestSelect(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } - // Called when a player completes a quest with the creature. - virtual bool OnQuestComplete(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } + // Called when a player completes a quest with the creature. + virtual bool OnQuestComplete(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } - // Called when a player selects a quest reward. - virtual bool OnQuestReward(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } + // Called when a player selects a quest reward. + virtual bool OnQuestReward(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } - // Called when the dialog status between a player and the creature is requested. - virtual uint32 GetDialogStatus(Player* /*player*/, Creature* /*creature*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } + // Called when the dialog status between a player and the creature is requested. + virtual uint32 GetDialogStatus(Player* /*player*/, Creature* /*creature*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } - // Called when a CreatureAI object is needed for the creature. - virtual CreatureAI* GetAI(Creature* /*creature*/) const { return nullptr; } + // Called when a CreatureAI object is needed for the creature. + virtual CreatureAI* GetAI(Creature* /*creature*/) const { return nullptr; } }; class GameObjectScript : public ScriptObject, public UpdatableScript { - protected: +protected: - GameObjectScript(const char* name); + GameObjectScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when a player opens a gossip dialog with the gameobject. - virtual bool OnGossipHello(Player* /*player*/, GameObject* /*go*/) { return false; } + // Called when a player opens a gossip dialog with the gameobject. + virtual bool OnGossipHello(Player* /*player*/, GameObject* /*go*/) { return false; } - // Called when a player selects a gossip item in the gameobject's gossip menu. - virtual bool OnGossipSelect(Player* /*player*/, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/) { return false; } + // Called when a player selects a gossip item in the gameobject's gossip menu. + virtual bool OnGossipSelect(Player* /*player*/, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/) { return false; } - // Called when a player selects a gossip with a code in the gameobject's gossip menu. - virtual bool OnGossipSelectCode(Player* /*player*/, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { return false; } + // Called when a player selects a gossip with a code in the gameobject's gossip menu. + virtual bool OnGossipSelectCode(Player* /*player*/, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { return false; } - // Called when a player accepts a quest from the gameobject. - virtual bool OnQuestAccept(Player* /*player*/, GameObject* /*go*/, Quest const* /*quest*/) { return false; } + // Called when a player accepts a quest from the gameobject. + virtual bool OnQuestAccept(Player* /*player*/, GameObject* /*go*/, Quest const* /*quest*/) { return false; } - // Called when a player selects a quest reward. - virtual bool OnQuestReward(Player* /*player*/, GameObject* /*go*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } + // Called when a player selects a quest reward. + virtual bool OnQuestReward(Player* /*player*/, GameObject* /*go*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } - // Called when the dialog status between a player and the gameobject is requested. - virtual uint32 GetDialogStatus(Player* /*player*/, GameObject* /*go*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } + // Called when the dialog status between a player and the gameobject is requested. + virtual uint32 GetDialogStatus(Player* /*player*/, GameObject* /*go*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } - // Called when the game object is destroyed (destructible buildings only). - virtual void OnDestroyed(GameObject* /*go*/, Player* /*player*/) { } + // Called when the game object is destroyed (destructible buildings only). + virtual void OnDestroyed(GameObject* /*go*/, Player* /*player*/) { } - // Called when the game object is damaged (destructible buildings only). - virtual void OnDamaged(GameObject* /*go*/, Player* /*player*/) { } + // Called when the game object is damaged (destructible buildings only). + virtual void OnDamaged(GameObject* /*go*/, Player* /*player*/) { } - // Called when the game object loot state is changed. - virtual void OnLootStateChanged(GameObject* /*go*/, uint32 /*state*/, Unit* /*unit*/) { } + // Called when the game object loot state is changed. + virtual void OnLootStateChanged(GameObject* /*go*/, uint32 /*state*/, Unit* /*unit*/) { } - // Called when the game object state is changed. - virtual void OnGameObjectStateChanged(GameObject* /*go*/, uint32 /*state*/) { } + // Called when the game object state is changed. + virtual void OnGameObjectStateChanged(GameObject* /*go*/, uint32 /*state*/) { } - // Called when a GameObjectAI object is needed for the gameobject. - virtual GameObjectAI* GetAI(GameObject* /*go*/) const { return nullptr; } + // Called when a GameObjectAI object is needed for the gameobject. + virtual GameObjectAI* GetAI(GameObject* /*go*/) const { return nullptr; } }; class AreaTriggerScript : public ScriptObject { - protected: +protected: - AreaTriggerScript(const char* name); + AreaTriggerScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when the area trigger is activated by a player. - virtual bool OnTrigger(Player* /*player*/, AreaTrigger const* /*trigger*/) { return false; } + // Called when the area trigger is activated by a player. + virtual bool OnTrigger(Player* /*player*/, AreaTrigger const* /*trigger*/) { return false; } }; class BattlegroundScript : public ScriptObject { - protected: +protected: - BattlegroundScript(const char* name); + BattlegroundScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Should return a fully valid Battleground object for the type ID. - virtual Battleground* GetBattleground() const = 0; + // Should return a fully valid Battleground object for the type ID. + virtual Battleground* GetBattleground() const = 0; }; class OutdoorPvPScript : public ScriptObject { - protected: +protected: - OutdoorPvPScript(const char* name); + OutdoorPvPScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Should return a fully valid OutdoorPvP object for the type ID. - virtual OutdoorPvP* GetOutdoorPvP() const = 0; + // Should return a fully valid OutdoorPvP object for the type ID. + virtual OutdoorPvP* GetOutdoorPvP() const = 0; }; class CommandScript : public ScriptObject { - protected: +protected: - CommandScript(const char* name); + CommandScript(const char* name); - public: +public: - // Should return a pointer to a valid command table (ChatCommand array) to be used by ChatHandler. - virtual std::vector GetCommands() const = 0; + // Should return a pointer to a valid command table (ChatCommand array) to be used by ChatHandler. + virtual std::vector GetCommands() const = 0; }; class WeatherScript : public ScriptObject, public UpdatableScript { - protected: +protected: - WeatherScript(const char* name); + WeatherScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when the weather changes in the zone this script is associated with. - virtual void OnChange(Weather* /*weather*/, WeatherState /*state*/, float /*grade*/) { } + // Called when the weather changes in the zone this script is associated with. + virtual void OnChange(Weather* /*weather*/, WeatherState /*state*/, float /*grade*/) { } }; class AuctionHouseScript : public ScriptObject { - protected: +protected: - AuctionHouseScript(const char* name); + AuctionHouseScript(const char* name); - public: +public: - // Called when an auction is added to an auction house. - virtual void OnAuctionAdd(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } + // Called when an auction is added to an auction house. + virtual void OnAuctionAdd(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } - // Called when an auction is removed from an auction house. - virtual void OnAuctionRemove(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } + // Called when an auction is removed from an auction house. + virtual void OnAuctionRemove(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } - // Called when an auction was succesfully completed. - virtual void OnAuctionSuccessful(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } + // Called when an auction was succesfully completed. + virtual void OnAuctionSuccessful(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } - // Called when an auction expires. - virtual void OnAuctionExpire(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } + // Called when an auction expires. + virtual void OnAuctionExpire(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } - // Called before sending the mail concerning a won auction - virtual void OnBeforeAuctionHouseMgrSendAuctionWonMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*bidder*/, uint32& /*bidder_accId*/, bool& /*sendNotification*/, bool& /*updateAchievementCriteria*/, bool& /*sendMail*/) { } + // Called before sending the mail concerning a won auction + virtual void OnBeforeAuctionHouseMgrSendAuctionWonMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*bidder*/, uint32& /*bidder_accId*/, bool& /*sendNotification*/, bool& /*updateAchievementCriteria*/, bool& /*sendMail*/) { } - // Called before sending the mail concerning a pending sale - virtual void OnBeforeAuctionHouseMgrSendAuctionSalePendingMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*owner*/, uint32& /*owner_accId*/, bool& /*sendMail*/) { } + // Called before sending the mail concerning a pending sale + virtual void OnBeforeAuctionHouseMgrSendAuctionSalePendingMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*owner*/, uint32& /*owner_accId*/, bool& /*sendMail*/) { } - // Called before sending the mail concerning a successful auction - virtual void OnBeforeAuctionHouseMgrSendAuctionSuccessfulMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*owner*/, uint32& /*owner_accId*/, uint32& /*profit*/, bool& /*sendNotification*/, bool& /*updateAchievementCriteria*/, bool& /*sendMail*/) { } + // Called before sending the mail concerning a successful auction + virtual void OnBeforeAuctionHouseMgrSendAuctionSuccessfulMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*owner*/, uint32& /*owner_accId*/, uint32& /*profit*/, bool& /*sendNotification*/, bool& /*updateAchievementCriteria*/, bool& /*sendMail*/) { } - // Called before sending the mail concerning an expired auction - virtual void OnBeforeAuctionHouseMgrSendAuctionExpiredMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*owner*/, uint32& /*owner_accId*/, bool& /*sendNotification*/, bool& /*sendMail*/) { } + // Called before sending the mail concerning an expired auction + virtual void OnBeforeAuctionHouseMgrSendAuctionExpiredMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*owner*/, uint32& /*owner_accId*/, bool& /*sendNotification*/, bool& /*sendMail*/) { } - // Called before sending the mail concerning an outbidded auction - virtual void OnBeforeAuctionHouseMgrSendAuctionOutbiddedMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*oldBidder*/, uint32& /*oldBidder_accId*/, Player* /*newBidder*/, uint32& /*newPrice*/, bool& /*sendNotification*/, bool& /*sendMail*/) { } + // Called before sending the mail concerning an outbidded auction + virtual void OnBeforeAuctionHouseMgrSendAuctionOutbiddedMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*oldBidder*/, uint32& /*oldBidder_accId*/, Player* /*newBidder*/, uint32& /*newPrice*/, bool& /*sendNotification*/, bool& /*sendMail*/) { } - // Called before sending the mail concerning an cancelled auction - virtual void OnBeforeAuctionHouseMgrSendAuctionCancelledToBidderMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*bidder*/, uint32& /*bidder_accId*/, bool& /*sendMail*/) { } + // Called before sending the mail concerning an cancelled auction + virtual void OnBeforeAuctionHouseMgrSendAuctionCancelledToBidderMail(AuctionHouseMgr* /*auctionHouseMgr*/, AuctionEntry* /*auction*/, Player* /*bidder*/, uint32& /*bidder_accId*/, bool& /*sendMail*/) { } - // Called before updating the auctions - virtual void OnBeforeAuctionHouseMgrUpdate() { } + // Called before updating the auctions + virtual void OnBeforeAuctionHouseMgrUpdate() { } }; class ConditionScript : public ScriptObject { - protected: +protected: - ConditionScript(const char* name); + ConditionScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when a single condition is checked for a player. - virtual bool OnConditionCheck(Condition* /*condition*/, ConditionSourceInfo& /*sourceInfo*/) { return true; } + // Called when a single condition is checked for a player. + virtual bool OnConditionCheck(Condition* /*condition*/, ConditionSourceInfo& /*sourceInfo*/) { return true; } }; class VehicleScript : public ScriptObject { - protected: +protected: - VehicleScript(const char* name); + VehicleScript(const char* name); - public: +public: - // Called after a vehicle is installed. - virtual void OnInstall(Vehicle* /*veh*/) { } + // Called after a vehicle is installed. + virtual void OnInstall(Vehicle* /*veh*/) { } - // Called after a vehicle is uninstalled. - virtual void OnUninstall(Vehicle* /*veh*/) { } + // Called after a vehicle is uninstalled. + virtual void OnUninstall(Vehicle* /*veh*/) { } - // Called when a vehicle resets. - virtual void OnReset(Vehicle* /*veh*/) { } + // Called when a vehicle resets. + virtual void OnReset(Vehicle* /*veh*/) { } - // Called after an accessory is installed in a vehicle. - virtual void OnInstallAccessory(Vehicle* /*veh*/, Creature* /*accessory*/) { } + // Called after an accessory is installed in a vehicle. + virtual void OnInstallAccessory(Vehicle* /*veh*/, Creature* /*accessory*/) { } - // Called after a passenger is added to a vehicle. - virtual void OnAddPassenger(Vehicle* /*veh*/, Unit* /*passenger*/, int8 /*seatId*/) { } + // Called after a passenger is added to a vehicle. + virtual void OnAddPassenger(Vehicle* /*veh*/, Unit* /*passenger*/, int8 /*seatId*/) { } - // Called after a passenger is removed from a vehicle. - virtual void OnRemovePassenger(Vehicle* /*veh*/, Unit* /*passenger*/) { } + // Called after a passenger is removed from a vehicle. + virtual void OnRemovePassenger(Vehicle* /*veh*/, Unit* /*passenger*/) { } }; class DynamicObjectScript : public ScriptObject, public UpdatableScript { - protected: +protected: - DynamicObjectScript(const char* name); + DynamicObjectScript(const char* name); }; class TransportScript : public ScriptObject, public UpdatableScript { - protected: +protected: - TransportScript(const char* name); + TransportScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // Called when a player boards the transport. - virtual void OnAddPassenger(Transport* /*transport*/, Player* /*player*/) { } + // Called when a player boards the transport. + virtual void OnAddPassenger(Transport* /*transport*/, Player* /*player*/) { } - // Called when a creature boards the transport. - virtual void OnAddCreaturePassenger(Transport* /*transport*/, Creature* /*creature*/) { } + // Called when a creature boards the transport. + virtual void OnAddCreaturePassenger(Transport* /*transport*/, Creature* /*creature*/) { } - // Called when a player exits the transport. - virtual void OnRemovePassenger(Transport* /*transport*/, Player* /*player*/) { } + // Called when a player exits the transport. + virtual void OnRemovePassenger(Transport* /*transport*/, Player* /*player*/) { } - // Called when a transport moves. - virtual void OnRelocate(Transport* /*transport*/, uint32 /*waypointId*/, uint32 /*mapId*/, float /*x*/, float /*y*/, float /*z*/) { } + // Called when a transport moves. + virtual void OnRelocate(Transport* /*transport*/, uint32 /*waypointId*/, uint32 /*mapId*/, float /*x*/, float /*y*/, float /*z*/) { } }; class AchievementCriteriaScript : public ScriptObject { - protected: +protected: - AchievementCriteriaScript(const char* name); + AchievementCriteriaScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return true; } + bool IsDatabaseBound() const { return true; } - // deprecated/legacy - virtual bool OnCheck(Player* /*source*/, Unit* /*target*/) { return true; }; + // deprecated/legacy + virtual bool OnCheck(Player* /*source*/, Unit* /*target*/) { return true; }; }; class PlayerScript : public ScriptObject { - protected: +protected: - PlayerScript(const char* name); + PlayerScript(const char* name); - public: - virtual void OnPlayerReleasedGhost(Player* /*player*/) { } +public: + virtual void OnPlayerReleasedGhost(Player* /*player*/) { } - // Called when a player completes a quest - virtual void OnPlayerCompleteQuest(Player* /*player*/, Quest const* /*quest_id*/) { } + // Called when a player completes a quest + virtual void OnPlayerCompleteQuest(Player* /*player*/, Quest const* /*quest_id*/) { } - // Called when a player kills another player - virtual void OnPVPKill(Player* /*killer*/, Player* /*killed*/) { } + // Called when a player kills another player + virtual void OnPVPKill(Player* /*killer*/, Player* /*killed*/) { } - // Called when a player kills a creature - virtual void OnCreatureKill(Player* /*killer*/, Creature* /*killed*/) { } + // Called when a player kills a creature + virtual void OnCreatureKill(Player* /*killer*/, Creature* /*killed*/) { } - // Called when a player's pet kills a creature - virtual void OnCreatureKilledByPet(Player* /*PetOwner*/, Creature* /*killed*/) { } + // Called when a player's pet kills a creature + virtual void OnCreatureKilledByPet(Player* /*PetOwner*/, Creature* /*killed*/) { } - // Called when a player is killed by a creature - virtual void OnPlayerKilledByCreature(Creature* /*killer*/, Player* /*killed*/) { } + // Called when a player is killed by a creature + virtual void OnPlayerKilledByCreature(Creature* /*killer*/, Player* /*killed*/) { } - // Called when a player's level changes (right after the level is applied) - virtual void OnLevelChanged(Player* /*player*/, uint8 /*oldlevel*/) { } + // Called when a player's level changes (right after the level is applied) + virtual void OnLevelChanged(Player* /*player*/, uint8 /*oldlevel*/) { } - // Called when a player's free talent points change (right before the change is applied) - virtual void OnFreeTalentPointsChanged(Player* /*player*/, uint32 /*points*/) { } + // Called when a player's free talent points change (right before the change is applied) + virtual void OnFreeTalentPointsChanged(Player* /*player*/, uint32 /*points*/) { } - // Called when a player's talent points are reset (right before the reset is done) - virtual void OnTalentsReset(Player* /*player*/, bool /*noCost*/) { } + // Called when a player's talent points are reset (right before the reset is done) + virtual void OnTalentsReset(Player* /*player*/, bool /*noCost*/) { } - // Called for player::update - virtual void OnBeforeUpdate(Player* /*player*/, uint32 /*p_time*/){ } + // Called for player::update + virtual void OnBeforeUpdate(Player* /*player*/, uint32 /*p_time*/) { } - // Called when a player's money is modified (before the modification is done) - virtual void OnMoneyChanged(Player* /*player*/, int32& /*amount*/) { } + // Called when a player's money is modified (before the modification is done) + virtual void OnMoneyChanged(Player* /*player*/, int32& /*amount*/) { } - // Called when a player gains XP (before anything is given) - virtual void OnGiveXP(Player* /*player*/, uint32& /*amount*/, Unit* /*victim*/) { } + // Called when a player gains XP (before anything is given) + virtual void OnGiveXP(Player* /*player*/, uint32& /*amount*/, Unit* /*victim*/) { } - // Called when a player's reputation changes (before it is actually changed) - virtual void OnReputationChange(Player* /*player*/, uint32 /*factionId*/, int32& /*standing*/, bool /*incremental*/) { } + // Called when a player's reputation changes (before it is actually changed) + virtual void OnReputationChange(Player* /*player*/, uint32 /*factionId*/, int32& /*standing*/, bool /*incremental*/) { } - // Called when a player's reputation rank changes (before it is actually changed) - virtual void OnReputationRankChange(Player* /*player*/, uint32 /*factionID*/, ReputationRank /*newRank*/, ReputationRank /*olRank*/, bool /*increased*/) { } + // Called when a player's reputation rank changes (before it is actually changed) + virtual void OnReputationRankChange(Player* /*player*/, uint32 /*factionID*/, ReputationRank /*newRank*/, ReputationRank /*olRank*/, bool /*increased*/) { } - // Called when a player learned new spell - virtual void OnLearnSpell(Player* /*player*/, uint32 /*spellID*/) {} + // Called when a player learned new spell + virtual void OnLearnSpell(Player* /*player*/, uint32 /*spellID*/) {} - // Called when a player forgot spell - virtual void OnForgotSpell(Player* /*player*/, uint32 /*spellID*/) {} + // Called when a player forgot spell + virtual void OnForgotSpell(Player* /*player*/, uint32 /*spellID*/) {} - // Called when a duel is requested - virtual void OnDuelRequest(Player* /*target*/, Player* /*challenger*/) { } + // Called when a duel is requested + virtual void OnDuelRequest(Player* /*target*/, Player* /*challenger*/) { } - // Called when a duel starts (after 3s countdown) - virtual void OnDuelStart(Player* /*player1*/, Player* /*player2*/) { } + // Called when a duel starts (after 3s countdown) + virtual void OnDuelStart(Player* /*player1*/, Player* /*player2*/) { } - // Called when a duel ends - virtual void OnDuelEnd(Player* /*winner*/, Player* /*loser*/, DuelCompleteType /*type*/) { } + // Called when a duel ends + virtual void OnDuelEnd(Player* /*winner*/, Player* /*loser*/, DuelCompleteType /*type*/) { } - // The following methods are called when a player sends a chat message. - virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/) { } + // The following methods are called when a player sends a chat message. + virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/) { } - virtual void OnBeforeSendChatMessage(Player* /*player*/, uint32& /*type*/, uint32& /*lang*/, std::string& /*msg*/) { } + virtual void OnBeforeSendChatMessage(Player* /*player*/, uint32& /*type*/, uint32& /*lang*/, std::string& /*msg*/) { } - virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Player* /*receiver*/) { } + virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Player* /*receiver*/) { } - virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Group* /*group*/) { } + virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Group* /*group*/) { } - virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Guild* /*guild*/) { } + virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Guild* /*guild*/) { } - virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Channel* /*channel*/) { } + virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string& /*msg*/, Channel* /*channel*/) { } - // Both of the below are called on emote opcodes. - virtual void OnEmote(Player* /*player*/, uint32 /*emote*/) { } + // Both of the below are called on emote opcodes. + virtual void OnEmote(Player* /*player*/, uint32 /*emote*/) { } - virtual void OnTextEmote(Player* /*player*/, uint32 /*textEmote*/, uint32 /*emoteNum*/, uint64 /*guid*/) { } + virtual void OnTextEmote(Player* /*player*/, uint32 /*textEmote*/, uint32 /*emoteNum*/, uint64 /*guid*/) { } - // Called in Spell::Cast. - virtual void OnSpellCast(Player* /*player*/, Spell* /*spell*/, bool /*skipCheck*/) { } + // Called in Spell::Cast. + virtual void OnSpellCast(Player* /*player*/, Spell* /*spell*/, bool /*skipCheck*/) { } - // Called during data loading - virtual void OnLoadFromDB(Player* /*player*/) { }; + // Called during data loading + virtual void OnLoadFromDB(Player* /*player*/) { }; - // Called when a player logs in. - virtual void OnLogin(Player* /*player*/) { } + // Called when a player logs in. + virtual void OnLogin(Player* /*player*/) { } - // Called when a player logs out. - virtual void OnLogout(Player* /*player*/) { } + // Called when a player logs out. + virtual void OnLogout(Player* /*player*/) { } - // Called when a player is created. - virtual void OnCreate(Player* /*player*/) { } + // Called when a player is created. + virtual void OnCreate(Player* /*player*/) { } - // Called when a player is deleted. - virtual void OnDelete(uint64 /*guid*/, uint32 /*accountId*/) { } + // Called when a player is deleted. + virtual void OnDelete(uint64 /*guid*/, uint32 /*accountId*/) { } - // Called when a player delete failed. - virtual void OnFailedDelete(uint64 /*guid*/, uint32 /*accountId*/) { } + // Called when a player delete failed. + virtual void OnFailedDelete(uint64 /*guid*/, uint32 /*accountId*/) { } - // Called when a player is about to be saved. - virtual void OnSave(Player* /*player*/) { } + // Called when a player is about to be saved. + virtual void OnSave(Player* /*player*/) { } - // Called when a player is bound to an instance - virtual void OnBindToInstance(Player* /*player*/, Difficulty /*difficulty*/, uint32 /*mapId*/, bool /*permanent*/) { } + // Called when a player is bound to an instance + virtual void OnBindToInstance(Player* /*player*/, Difficulty /*difficulty*/, uint32 /*mapId*/, bool /*permanent*/) { } - // Called when a player switches to a new zone - virtual void OnUpdateZone(Player* /*player*/, uint32 /*newZone*/, uint32 /*newArea*/) { } + // Called when a player switches to a new zone + virtual void OnUpdateZone(Player* /*player*/, uint32 /*newZone*/, uint32 /*newArea*/) { } - // Called when a player switches to a new area (more accurate than UpdateZone) - virtual void OnUpdateArea(Player* /*player*/, uint32 /*oldArea*/, uint32 /*newArea*/) { } + // Called when a player switches to a new area (more accurate than UpdateZone) + virtual void OnUpdateArea(Player* /*player*/, uint32 /*oldArea*/, uint32 /*newArea*/) { } - // Called when a player changes to a new map (after moving to new map) - virtual void OnMapChanged(Player* /*player*/) { } + // Called when a player changes to a new map (after moving to new map) + virtual void OnMapChanged(Player* /*player*/) { } - // Called before a player is being teleported to new coords - virtual bool OnBeforeTeleport(Player* /*player*/, uint32 /*mapid*/, float /*x*/, float /*y*/, float /*z*/, float /*orientation*/, uint32 /*options*/, Unit* /*target*/) { return true; } + // Called before a player is being teleported to new coords + virtual bool OnBeforeTeleport(Player* /*player*/, uint32 /*mapid*/, float /*x*/, float /*y*/, float /*z*/, float /*orientation*/, uint32 /*options*/, Unit* /*target*/) { return true; } - // Called when team/faction is set on player - virtual void OnUpdateFaction(Player* /*player*/) { } + // Called when team/faction is set on player + virtual void OnUpdateFaction(Player* /*player*/) { } - // Called when a player is added to battleground - virtual void OnAddToBattleground(Player* /*player*/, Battleground* /*bg*/) { } + // Called when a player is added to battleground + virtual void OnAddToBattleground(Player* /*player*/, Battleground* /*bg*/) { } - // Called when a player is removed from battleground - virtual void OnRemoveFromBattleground(Player* /*player*/, Battleground* /*bg*/) { } + // Called when a player is removed from battleground + virtual void OnRemoveFromBattleground(Player* /*player*/, Battleground* /*bg*/) { } - // Called when a player complete an achievement - virtual void OnAchiComplete(Player* /*player*/, AchievementEntry const* /*achievement*/) { } + // Called when a player complete an achievement + virtual void OnAchiComplete(Player* /*player*/, AchievementEntry const* /*achievement*/) { } - // Called when a player complete an achievement criteria - virtual void OnCriteriaProgress(Player* /*player*/, AchievementCriteriaEntry const* /*criteria*/) { } + // Called when a player complete an achievement criteria + virtual void OnCriteriaProgress(Player* /*player*/, AchievementCriteriaEntry const* /*criteria*/) { } - // Called when an Achievement is saved to DB - virtual void OnAchiSave(SQLTransaction& /*trans*/, Player* /*player*/, uint16 /*achId*/, CompletedAchievementData /*achiData*/) { } + // Called when an Achievement is saved to DB + virtual void OnAchiSave(SQLTransaction& /*trans*/, Player* /*player*/, uint16 /*achId*/, CompletedAchievementData /*achiData*/) { } - // Called when an Criteria is saved to DB - virtual void OnCriteriaSave(SQLTransaction& /*trans*/, Player* /*player*/, uint16 /*achId*/, CriteriaProgress /*criteriaData*/) { } + // Called when an Criteria is saved to DB + virtual void OnCriteriaSave(SQLTransaction& /*trans*/, Player* /*player*/, uint16 /*achId*/, CriteriaProgress /*criteriaData*/) { } - // Called when a player selects an option in a player gossip window - virtual void OnGossipSelect(Player* /*player*/, uint32 /*menu_id*/, uint32 /*sender*/, uint32 /*action*/) { } + // Called when a player selects an option in a player gossip window + virtual void OnGossipSelect(Player* /*player*/, uint32 /*menu_id*/, uint32 /*sender*/, uint32 /*action*/) { } - // Called when a player selects an option in a player gossip window - virtual void OnGossipSelectCode(Player* /*player*/, uint32 /*menu_id*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { } + // Called when a player selects an option in a player gossip window + virtual void OnGossipSelectCode(Player* /*player*/, uint32 /*menu_id*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { } - // On player getting charmed - virtual void OnBeingCharmed(Player* /*player*/, Unit* /*charmer*/, uint32 /*oldFactionId*/, uint32 /*newFactionId*/) { } + // On player getting charmed + virtual void OnBeingCharmed(Player* /*player*/, Unit* /*charmer*/, uint32 /*oldFactionId*/, uint32 /*newFactionId*/) { } - // To change behaviour of set visible item slot - virtual void OnAfterSetVisibleItemSlot(Player* /*player*/, uint8 /*slot*/, Item* /*item*/) { } + // To change behaviour of set visible item slot + virtual void OnAfterSetVisibleItemSlot(Player* /*player*/, uint8 /*slot*/, Item* /*item*/) { } - // After an item has been moved from inventory - virtual void OnAfterMoveItemFromInventory(Player* /*player*/, Item* /*it*/, uint8 /*bag*/, uint8 /*slot*/, bool /*update*/) { } + // After an item has been moved from inventory + virtual void OnAfterMoveItemFromInventory(Player* /*player*/, Item* /*it*/, uint8 /*bag*/, uint8 /*slot*/, bool /*update*/) { } - // After an item has been equipped - virtual void OnEquip(Player* /*player*/, Item* /*it*/, uint8 /*bag*/, uint8 /*slot*/, bool /*update*/) { } + // After an item has been equipped + virtual void OnEquip(Player* /*player*/, Item* /*it*/, uint8 /*bag*/, uint8 /*slot*/, bool /*update*/) { } - // After player enters queue for BG - virtual void OnPlayerJoinBG(Player* /*player*/) { } + // After player enters queue for BG + virtual void OnPlayerJoinBG(Player* /*player*/) { } - // After player enters queue for Arena - virtual void OnPlayerJoinArena(Player* /*player*/) { } + // After player enters queue for Arena + virtual void OnPlayerJoinArena(Player* /*player*/) { } - //After looting item - virtual void OnLootItem(Player* /*player*/, Item* /*item*/, uint32 /*count*/, uint64 /*lootguid*/) { } + //After looting item + virtual void OnLootItem(Player* /*player*/, Item* /*item*/, uint32 /*count*/, uint64 /*lootguid*/) { } - //After creating item (eg profession item creation) - virtual void OnCreateItem(Player* /*player*/, Item* /*item*/, uint32 /*count*/) { } + //After creating item (eg profession item creation) + virtual void OnCreateItem(Player* /*player*/, Item* /*item*/, uint32 /*count*/) { } - //After receiving item as a quest reward - virtual void OnQuestRewardItem(Player* /*player*/, Item* /*item*/, uint32 /*count*/) { } + //After receiving item as a quest reward + virtual void OnQuestRewardItem(Player* /*player*/, Item* /*item*/, uint32 /*count*/) { } - //Before buying something from any vendor - virtual void OnBeforeBuyItemFromVendor(Player* /*player*/, uint64 /*vendorguid*/, uint32 /*vendorslot*/, uint32 &/*item*/, uint8 /*count*/, uint8 /*bag*/, uint8 /*slot*/) { }; + //Before buying something from any vendor + virtual void OnBeforeBuyItemFromVendor(Player* /*player*/, uint64 /*vendorguid*/, uint32 /*vendorslot*/, uint32& /*item*/, uint8 /*count*/, uint8 /*bag*/, uint8 /*slot*/) { }; - //Before buying something from any vendor - virtual void OnAfterStoreOrEquipNewItem(Player* /*player*/, uint32 /*vendorslot*/, uint32& /*item*/, uint8 /*count*/, uint8 /*bag*/, uint8 /*slot*/, ItemTemplate const* /*pProto*/, Creature* /*pVendor*/, VendorItem const* /*crItem*/, bool /*bStore*/) { }; + //Before buying something from any vendor + virtual void OnAfterStoreOrEquipNewItem(Player* /*player*/, uint32 /*vendorslot*/, uint32& /*item*/, uint8 /*count*/, uint8 /*bag*/, uint8 /*slot*/, ItemTemplate const* /*pProto*/, Creature* /*pVendor*/, VendorItem const* /*crItem*/, bool /*bStore*/) { }; - virtual void OnAfterUpdateMaxPower(Player* /*player*/, Powers& /*power*/, float& /*value*/) { } + virtual void OnAfterUpdateMaxPower(Player* /*player*/, Powers& /*power*/, float& /*value*/) { } - virtual void OnAfterUpdateMaxHealth(Player* /*player*/, float& /*value*/) { } + virtual void OnAfterUpdateMaxHealth(Player* /*player*/, float& /*value*/) { } - virtual void OnBeforeUpdateAttackPowerAndDamage(Player* /*player*/, float& /*level*/, float& /*val2*/, bool /*ranged*/) { } - virtual void OnAfterUpdateAttackPowerAndDamage(Player* /*player*/, float& /*level*/, float& /*base_attPower*/, float& /*attPowerMod*/, float& /*attPowerMultiplier*/, bool /*ranged*/) { } + virtual void OnBeforeUpdateAttackPowerAndDamage(Player* /*player*/, float& /*level*/, float& /*val2*/, bool /*ranged*/) { } + virtual void OnAfterUpdateAttackPowerAndDamage(Player* /*player*/, float& /*level*/, float& /*base_attPower*/, float& /*attPowerMod*/, float& /*attPowerMultiplier*/, bool /*ranged*/) { } - virtual void OnBeforeInitTalentForLevel(Player* /*player*/, uint8& /*level*/, uint32& /*talentPointsForLevel*/) { } + virtual void OnBeforeInitTalentForLevel(Player* /*player*/, uint8& /*level*/, uint32& /*talentPointsForLevel*/) { } - virtual void OnFirstLogin(Player* /*player*/) { } + virtual void OnFirstLogin(Player* /*player*/) { } - virtual bool CanJoinInBattlegroundQueue(Player* /*player*/, uint64 /*BattlemasterGuid*/, BattlegroundTypeId /*BGTypeID*/, uint8 /*joinAsGroup*/, GroupJoinBattlegroundResult& /*err*/) { return true; } + virtual bool CanJoinInBattlegroundQueue(Player* /*player*/, uint64 /*BattlemasterGuid*/, BattlegroundTypeId /*BGTypeID*/, uint8 /*joinAsGroup*/, GroupJoinBattlegroundResult& /*err*/) { return true; } - // Called before the player's temporary summoned creature has initialized it's stats - virtual void OnBeforeTempSummonInitStats(Player* /*player*/, TempSummon* /*tempSummon*/, uint32& /*duration*/) { } + // Called before the player's temporary summoned creature has initialized it's stats + virtual void OnBeforeTempSummonInitStats(Player* /*player*/, TempSummon* /*tempSummon*/, uint32& /*duration*/) { } - // Called before the player's guardian / pet has initialized it's stats for the player's level - virtual void OnBeforeGuardianInitStatsForLevel(Player* /*player*/, Guardian* /*guardian*/, CreatureTemplate const* /*cinfo*/, PetType& /*petType*/) { } + // Called before the player's guardian / pet has initialized it's stats for the player's level + virtual void OnBeforeGuardianInitStatsForLevel(Player* /*player*/, Guardian* /*guardian*/, CreatureTemplate const* /*cinfo*/, PetType& /*petType*/) { } - // Called after the player's guardian / pet has initialized it's stats for the player's level - virtual void OnAfterGuardianInitStatsForLevel(Player* /*player*/, Guardian* /*guardian*/) { } + // Called after the player's guardian / pet has initialized it's stats for the player's level + virtual void OnAfterGuardianInitStatsForLevel(Player* /*player*/, Guardian* /*guardian*/) { } - // Called before loading a player's pet from the DB - virtual void OnBeforeLoadPetFromDB(Player* /*player*/, uint32& /*petentry*/, uint32& /*petnumber*/, bool& /*current*/, bool& /*forceLoadFromDB*/) { } + // Called before loading a player's pet from the DB + virtual void OnBeforeLoadPetFromDB(Player* /*player*/, uint32& /*petentry*/, uint32& /*petnumber*/, bool& /*current*/, bool& /*forceLoadFromDB*/) { } }; class AccountScript : public ScriptObject { - protected: +protected: - AccountScript(const char* name); + AccountScript(const char* name); - public: +public: - // Called when an account logged in successfully - virtual void OnAccountLogin(uint32 /*accountId*/) { } + // Called when an account logged in successfully + virtual void OnAccountLogin(uint32 /*accountId*/) { } - // Called when an account login failed - virtual void OnFailedAccountLogin(uint32 /*accountId*/) { } + // Called when an account login failed + virtual void OnFailedAccountLogin(uint32 /*accountId*/) { } - // Called when Email is successfully changed for Account - virtual void OnEmailChange(uint32 /*accountId*/) { } + // Called when Email is successfully changed for Account + virtual void OnEmailChange(uint32 /*accountId*/) { } - // Called when Email failed to change for Account - virtual void OnFailedEmailChange(uint32 /*accountId*/) { } + // Called when Email failed to change for Account + virtual void OnFailedEmailChange(uint32 /*accountId*/) { } - // Called when Password is successfully changed for Account - virtual void OnPasswordChange(uint32 /*accountId*/) { } + // Called when Password is successfully changed for Account + virtual void OnPasswordChange(uint32 /*accountId*/) { } - // Called when Password failed to change for Account - virtual void OnFailedPasswordChange(uint32 /*accountId*/) { } + // Called when Password failed to change for Account + virtual void OnFailedPasswordChange(uint32 /*accountId*/) { } }; class GuildScript : public ScriptObject { - protected: +protected: - GuildScript(const char* name); + GuildScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return false; } + bool IsDatabaseBound() const { return false; } - // Called when a member is added to the guild. - virtual void OnAddMember(Guild* /*guild*/, Player* /*player*/, uint8& /*plRank*/) { } + // Called when a member is added to the guild. + virtual void OnAddMember(Guild* /*guild*/, Player* /*player*/, uint8& /*plRank*/) { } - // Called when a member is removed from the guild. - virtual void OnRemoveMember(Guild* /*guild*/, Player* /*player*/, bool /*isDisbanding*/, bool /*isKicked*/) { } + // Called when a member is removed from the guild. + virtual void OnRemoveMember(Guild* /*guild*/, Player* /*player*/, bool /*isDisbanding*/, bool /*isKicked*/) { } - // Called when the guild MOTD (message of the day) changes. - virtual void OnMOTDChanged(Guild* /*guild*/, const std::string& /*newMotd*/) { } + // Called when the guild MOTD (message of the day) changes. + virtual void OnMOTDChanged(Guild* /*guild*/, const std::string& /*newMotd*/) { } - // Called when the guild info is altered. - virtual void OnInfoChanged(Guild* /*guild*/, const std::string& /*newInfo*/) { } + // Called when the guild info is altered. + virtual void OnInfoChanged(Guild* /*guild*/, const std::string& /*newInfo*/) { } - // Called when a guild is created. - virtual void OnCreate(Guild* /*guild*/, Player* /*leader*/, const std::string& /*name*/) { } + // Called when a guild is created. + virtual void OnCreate(Guild* /*guild*/, Player* /*leader*/, const std::string& /*name*/) { } - // Called when a guild is disbanded. - virtual void OnDisband(Guild* /*guild*/) { } + // Called when a guild is disbanded. + virtual void OnDisband(Guild* /*guild*/) { } - // Called when a guild member withdraws money from a guild bank. - virtual void OnMemberWitdrawMoney(Guild* /*guild*/, Player* /*player*/, uint32& /*amount*/, bool /*isRepair*/) { } + // Called when a guild member withdraws money from a guild bank. + virtual void OnMemberWitdrawMoney(Guild* /*guild*/, Player* /*player*/, uint32& /*amount*/, bool /*isRepair*/) { } - // Called when a guild member deposits money in a guild bank. - virtual void OnMemberDepositMoney(Guild* /*guild*/, Player* /*player*/, uint32& /*amount*/) { } + // Called when a guild member deposits money in a guild bank. + virtual void OnMemberDepositMoney(Guild* /*guild*/, Player* /*player*/, uint32& /*amount*/) { } - // Called when a guild member moves an item in a guild bank. - virtual void OnItemMove(Guild* /*guild*/, Player* /*player*/, Item* /*pItem*/, bool /*isSrcBank*/, uint8 /*srcContainer*/, uint8 /*srcSlotId*/, - bool /*isDestBank*/, uint8 /*destContainer*/, uint8 /*destSlotId*/) { } + // Called when a guild member moves an item in a guild bank. + virtual void OnItemMove(Guild* /*guild*/, Player* /*player*/, Item* /*pItem*/, bool /*isSrcBank*/, uint8 /*srcContainer*/, uint8 /*srcSlotId*/, + bool /*isDestBank*/, uint8 /*destContainer*/, uint8 /*destSlotId*/) { } - virtual void OnEvent(Guild* /*guild*/, uint8 /*eventType*/, uint32 /*playerGuid1*/, uint32 /*playerGuid2*/, uint8 /*newRank*/) { } + virtual void OnEvent(Guild* /*guild*/, uint8 /*eventType*/, uint32 /*playerGuid1*/, uint32 /*playerGuid2*/, uint8 /*newRank*/) { } - virtual void OnBankEvent(Guild* /*guild*/, uint8 /*eventType*/, uint8 /*tabId*/, uint32 /*playerGuid*/, uint32 /*itemOrMoney*/, uint16 /*itemStackCount*/, uint8 /*destTabId*/) { } + virtual void OnBankEvent(Guild* /*guild*/, uint8 /*eventType*/, uint8 /*tabId*/, uint32 /*playerGuid*/, uint32 /*itemOrMoney*/, uint16 /*itemStackCount*/, uint8 /*destTabId*/) { } }; class GroupScript : public ScriptObject { - protected: +protected: - GroupScript(const char* name); + GroupScript(const char* name); - public: +public: - bool IsDatabaseBound() const { return false; } + bool IsDatabaseBound() const { return false; } - // Called when a member is added to a group. - virtual void OnAddMember(Group* /*group*/, uint64 /*guid*/) { } + // Called when a member is added to a group. + virtual void OnAddMember(Group* /*group*/, uint64 /*guid*/) { } - // Called when a member is invited to join a group. - virtual void OnInviteMember(Group* /*group*/, uint64 /*guid*/) { } + // Called when a member is invited to join a group. + virtual void OnInviteMember(Group* /*group*/, uint64 /*guid*/) { } - // Called when a member is removed from a group. - virtual void OnRemoveMember(Group* /*group*/, uint64 /*guid*/, RemoveMethod /*method*/, uint64 /*kicker*/, const char* /*reason*/) { } + // Called when a member is removed from a group. + virtual void OnRemoveMember(Group* /*group*/, uint64 /*guid*/, RemoveMethod /*method*/, uint64 /*kicker*/, const char* /*reason*/) { } - // Called when the leader of a group is changed. - virtual void OnChangeLeader(Group* /*group*/, uint64 /*newLeaderGuid*/, uint64 /*oldLeaderGuid*/) { } + // Called when the leader of a group is changed. + virtual void OnChangeLeader(Group* /*group*/, uint64 /*newLeaderGuid*/, uint64 /*oldLeaderGuid*/) { } - // Called when a group is disbanded. - virtual void OnDisband(Group* /*group*/) { } + // Called when a group is disbanded. + virtual void OnDisband(Group* /*group*/) { } }; // following hooks can be used anywhere and are not db bounded class GlobalScript : public ScriptObject { - protected: +protected: - GlobalScript(const char* name); + GlobalScript(const char* name); - public: +public: - // items - virtual void OnItemDelFromDB(SQLTransaction& /*trans*/, uint32 /*itemGuid*/) { } - virtual void OnMirrorImageDisplayItem(const Item* /*item*/, uint32& /*display*/) { } + // items + virtual void OnItemDelFromDB(SQLTransaction& /*trans*/, uint32 /*itemGuid*/) { } + virtual void OnMirrorImageDisplayItem(const Item* /*item*/, uint32& /*display*/) { } - // loot - virtual void OnAfterRefCount(Player const* /*player*/, LootStoreItem* /*LootStoreItem*/, Loot& /*loot*/, bool /*canRate*/, uint16 /*lootMode*/, uint32& /*maxcount*/, LootStore const& /*store*/) { } - virtual void OnBeforeDropAddItem(Player const* /*player*/, Loot& /*loot*/, bool /*canRate*/, uint16 /*lootMode*/, LootStoreItem* /*LootStoreItem*/, LootStore const& /*store*/) { } - virtual void OnItemRoll(Player const* /*player*/, LootStoreItem const* /*LootStoreItem*/, float& /*chance*/, Loot& /*loot*/, LootStore const& /*store*/) { }; + // loot + virtual void OnAfterRefCount(Player const* /*player*/, LootStoreItem* /*LootStoreItem*/, Loot& /*loot*/, bool /*canRate*/, uint16 /*lootMode*/, uint32& /*maxcount*/, LootStore const& /*store*/) { } + virtual void OnBeforeDropAddItem(Player const* /*player*/, Loot& /*loot*/, bool /*canRate*/, uint16 /*lootMode*/, LootStoreItem* /*LootStoreItem*/, LootStore const& /*store*/) { } + virtual void OnItemRoll(Player const* /*player*/, LootStoreItem const* /*LootStoreItem*/, float& /*chance*/, Loot& /*loot*/, LootStore const& /*store*/) { }; - virtual void OnInitializeLockedDungeons(Player* /*player*/, uint8& /*level*/, uint32& /*lockData*/) { } - virtual void OnAfterInitializeLockedDungeons(Player* /*player*/) { } + virtual void OnInitializeLockedDungeons(Player* /*player*/, uint8& /*level*/, uint32& /*lockData*/) { } + virtual void OnAfterInitializeLockedDungeons(Player* /*player*/) { } - // On Before arena points distribution - virtual void OnBeforeUpdateArenaPoints(ArenaTeam* /*at*/, std::map & /*ap*/) { } + // On Before arena points distribution + virtual void OnBeforeUpdateArenaPoints(ArenaTeam* /*at*/, std::map& /*ap*/) { } - // Called when a dungeon encounter is updated. - virtual void OnAfterUpdateEncounterState(Map* /*map*/, EncounterCreditType /*type*/, uint32 /*creditEntry*/, Unit* /*source*/, Difficulty /*difficulty_fixed*/, DungeonEncounterList const* /*encounters*/, uint32 /*dungeonCompleted*/, bool /*updated*/) { } + // Called when a dungeon encounter is updated. + virtual void OnAfterUpdateEncounterState(Map* /*map*/, EncounterCreditType /*type*/, uint32 /*creditEntry*/, Unit* /*source*/, Difficulty /*difficulty_fixed*/, DungeonEncounterList const* /*encounters*/, uint32 /*dungeonCompleted*/, bool /*updated*/) { } - // Called before the phase for a WorldObject is set - virtual void OnBeforeWorldObjectSetPhaseMask(WorldObject const* /*worldObject*/, uint32& /*oldPhaseMask*/, uint32& /*newPhaseMask*/, bool& /*useCombinedPhases*/, bool& /*update*/) { } + // Called before the phase for a WorldObject is set + virtual void OnBeforeWorldObjectSetPhaseMask(WorldObject const* /*worldObject*/, uint32& /*oldPhaseMask*/, uint32& /*newPhaseMask*/, bool& /*useCombinedPhases*/, bool& /*update*/) { } }; class BGScript : public ScriptObject @@ -1162,7 +1166,7 @@ public: virtual bool CanFillPlayersToBG(BattlegroundQueue* /*queue*/, Battleground* /*bg*/, const int32 /*aliFree*/, const int32 /*hordeFree*/, BattlegroundBracketId /*bracket_id*/) { return true; } virtual bool CanFillPlayersToBGWithSpecific(BattlegroundQueue* /*queue*/, Battleground* /*bg*/, const int32 /*aliFree*/, const int32 /*hordeFree*/, - BattlegroundBracketId /*thisBracketId*/, BattlegroundQueue* /*specificQueue*/, BattlegroundBracketId /*specificBracketId*/) { return true; } + BattlegroundBracketId /*thisBracketId*/, BattlegroundQueue* /*specificQueue*/, BattlegroundBracketId /*specificBracketId*/) { return true; } virtual void OnCheckNormalMatch(BattlegroundQueue* /*queue*/, uint32& /*Coef*/, Battleground* /*bgTemplate*/, BattlegroundBracketId /*bracket_id*/, uint32& /*minPlayers*/, uint32& /*maxPlayers*/) { } @@ -1188,9 +1192,9 @@ public: // creating their own custom hooks inside module itself class ModuleScript : public ScriptObject { - protected: +protected: - ModuleScript(const char* name); + ModuleScript(const char* name); }; class GameEventScript : public ScriptObject @@ -1208,14 +1212,14 @@ public: class MailScript : public ScriptObject { - protected: +protected: - MailScript(const char* name); + MailScript(const char* name); - public: +public: - // Called before mail is sent - virtual void OnBeforeMailDraftSendMailTo(MailDraft* /*mailDraft*/, MailReceiver const& /*receiver*/, MailSender const& /*sender*/, MailCheckMask& /*checked*/, uint32& /*deliver_delay*/, uint32& /*custom_expiration*/, bool& /*deleteMailItemsFromDB*/, bool& /*sendMail*/) { } + // Called before mail is sent + virtual void OnBeforeMailDraftSendMailTo(MailDraft* /*mailDraft*/, MailReceiver const& /*receiver*/, MailSender const& /*sender*/, MailCheckMask& /*checked*/, uint32& /*deliver_delay*/, uint32& /*custom_expiration*/, bool& /*deleteMailItemsFromDB*/, bool& /*sendMail*/) { } }; // Manages registration, loading, and execution of scripts. @@ -1223,370 +1227,370 @@ class ScriptMgr { friend class ScriptObject; - private: +private: - ScriptMgr(); - virtual ~ScriptMgr(); + ScriptMgr(); + virtual ~ScriptMgr(); - public: /* Initialization */ +public: /* Initialization */ - static ScriptMgr* instance(); - void Initialize(); - void LoadDatabase(); - void FillSpellSummary(); - void CheckIfScriptsInDatabaseExist(); - - const char* ScriptsVersion() const { return "Integrated Trinity Scripts"; } - - void IncrementScriptCount() { ++_scriptCount; } - uint32 GetScriptCount() const { return _scriptCount; } + static ScriptMgr* instance(); + void Initialize(); + void LoadDatabase(); + void FillSpellSummary(); + void CheckIfScriptsInDatabaseExist(); + + const char* ScriptsVersion() const { return "Integrated Trinity Scripts"; } + + void IncrementScriptCount() { ++_scriptCount; } + uint32 GetScriptCount() const { return _scriptCount; } - public: /* Unloading */ +public: /* Unloading */ - void Unload(); + void Unload(); - public: /* SpellScriptLoader */ +public: /* SpellScriptLoader */ - void CreateSpellScripts(uint32 spellId, std::list& scriptVector); - void CreateAuraScripts(uint32 spellId, std::list& scriptVector); - void CreateSpellScriptLoaders(uint32 spellId, std::vector::iterator> >& scriptVector); + void CreateSpellScripts(uint32 spellId, std::list& scriptVector); + void CreateAuraScripts(uint32 spellId, std::list& scriptVector); + void CreateSpellScriptLoaders(uint32 spellId, std::vector::iterator> >& scriptVector); - public: /* ServerScript */ +public: /* ServerScript */ - void OnNetworkStart(); - void OnNetworkStop(); - void OnSocketOpen(WorldSocket* socket); - void OnSocketClose(WorldSocket* socket, bool wasNew); - void OnPacketReceive(WorldSession* session, WorldPacket const& packet); - void OnPacketSend(WorldSession* session, WorldPacket const& packet); + void OnNetworkStart(); + void OnNetworkStop(); + void OnSocketOpen(WorldSocket* socket); + void OnSocketClose(WorldSocket* socket, bool wasNew); + void OnPacketReceive(WorldSession* session, WorldPacket const& packet); + void OnPacketSend(WorldSession* session, WorldPacket const& packet); - public: /* WorldScript */ +public: /* WorldScript */ - void OnLoadCustomDatabaseTable(); - void OnOpenStateChange(bool open); - void OnBeforeConfigLoad(bool reload); - void OnAfterConfigLoad(bool reload); - void OnMotdChange(std::string& newMotd); - void OnShutdownInitiate(ShutdownExitCode code, ShutdownMask mask); - void OnShutdownCancel(); - void OnWorldUpdate(uint32 diff); - void OnStartup(); - void OnShutdown(); + void OnLoadCustomDatabaseTable(); + void OnOpenStateChange(bool open); + void OnBeforeConfigLoad(bool reload); + void OnAfterConfigLoad(bool reload); + void OnMotdChange(std::string& newMotd); + void OnShutdownInitiate(ShutdownExitCode code, ShutdownMask mask); + void OnShutdownCancel(); + void OnWorldUpdate(uint32 diff); + void OnStartup(); + void OnShutdown(); - public: /* FormulaScript */ +public: /* FormulaScript */ - void OnHonorCalculation(float& honor, uint8 level, float multiplier); - void OnGrayLevelCalculation(uint8& grayLevel, uint8 playerLevel); - void OnColorCodeCalculation(XPColorChar& color, uint8 playerLevel, uint8 mobLevel); - void OnZeroDifferenceCalculation(uint8& diff, uint8 playerLevel); - void OnBaseGainCalculation(uint32& gain, uint8 playerLevel, uint8 mobLevel, ContentLevels content); - void OnGainCalculation(uint32& gain, Player* player, Unit* unit); - void OnGroupRateCalculation(float& rate, uint32 count, bool isRaid); - void OnAfterArenaRatingCalculation(Battleground *const bg, int32 &winnerMatchmakerChange, int32 &loserMatchmakerChange, int32 &winnerChange, int32 &loserChange); + void OnHonorCalculation(float& honor, uint8 level, float multiplier); + void OnGrayLevelCalculation(uint8& grayLevel, uint8 playerLevel); + void OnColorCodeCalculation(XPColorChar& color, uint8 playerLevel, uint8 mobLevel); + void OnZeroDifferenceCalculation(uint8& diff, uint8 playerLevel); + void OnBaseGainCalculation(uint32& gain, uint8 playerLevel, uint8 mobLevel, ContentLevels content); + void OnGainCalculation(uint32& gain, Player* player, Unit* unit); + void OnGroupRateCalculation(float& rate, uint32 count, bool isRaid); + void OnAfterArenaRatingCalculation(Battleground* const bg, int32& winnerMatchmakerChange, int32& loserMatchmakerChange, int32& winnerChange, int32& loserChange); - public: /* MapScript */ +public: /* MapScript */ - void OnCreateMap(Map* map); - void OnDestroyMap(Map* map); - void OnLoadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy); - void OnUnloadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy); - void OnPlayerEnterMap(Map* map, Player* player); - void OnPlayerLeaveMap(Map* map, Player* player); - void OnMapUpdate(Map* map, uint32 diff); + void OnCreateMap(Map* map); + void OnDestroyMap(Map* map); + void OnLoadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy); + void OnUnloadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy); + void OnPlayerEnterMap(Map* map, Player* player); + void OnPlayerLeaveMap(Map* map, Player* player); + void OnMapUpdate(Map* map, uint32 diff); - public: /* InstanceMapScript */ +public: /* InstanceMapScript */ - InstanceScript* CreateInstanceScript(InstanceMap* map); + InstanceScript* CreateInstanceScript(InstanceMap* map); - public: /* ItemScript */ +public: /* ItemScript */ - bool OnQuestAccept(Player* player, Item* item, Quest const* quest); - bool OnItemUse(Player* player, Item* item, SpellCastTargets const& targets); - bool OnItemExpire(Player* player, ItemTemplate const* proto); - bool OnItemRemove(Player* player, Item* item); - bool OnCastItemCombatSpell(Player* player, Unit* victim, SpellInfo const* spellInfo, Item* item); - void OnGossipSelect(Player* player, Item* item, uint32 sender, uint32 action); - void OnGossipSelectCode(Player* player, Item* item, uint32 sender, uint32 action, const char* code); + bool OnQuestAccept(Player* player, Item* item, Quest const* quest); + bool OnItemUse(Player* player, Item* item, SpellCastTargets const& targets); + bool OnItemExpire(Player* player, ItemTemplate const* proto); + bool OnItemRemove(Player* player, Item* item); + bool OnCastItemCombatSpell(Player* player, Unit* victim, SpellInfo const* spellInfo, Item* item); + void OnGossipSelect(Player* player, Item* item, uint32 sender, uint32 action); + void OnGossipSelectCode(Player* player, Item* item, uint32 sender, uint32 action, const char* code); - public: /* CreatureScript */ +public: /* CreatureScript */ - bool OnGossipHello(Player* player, Creature* creature); - bool OnGossipSelect(Player* player, Creature* creature, uint32 sender, uint32 action); - bool OnGossipSelectCode(Player* player, Creature* creature, uint32 sender, uint32 action, const char* code); - bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest); - bool OnQuestSelect(Player* player, Creature* creature, Quest const* quest); - bool OnQuestComplete(Player* player, Creature* creature, Quest const* quest); - bool OnQuestReward(Player* player, Creature* creature, Quest const* quest, uint32 opt); - uint32 GetDialogStatus(Player* player, Creature* creature); - CreatureAI* GetCreatureAI(Creature* creature); - void OnCreatureUpdate(Creature* creature, uint32 diff); + bool OnGossipHello(Player* player, Creature* creature); + bool OnGossipSelect(Player* player, Creature* creature, uint32 sender, uint32 action); + bool OnGossipSelectCode(Player* player, Creature* creature, uint32 sender, uint32 action, const char* code); + bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest); + bool OnQuestSelect(Player* player, Creature* creature, Quest const* quest); + bool OnQuestComplete(Player* player, Creature* creature, Quest const* quest); + bool OnQuestReward(Player* player, Creature* creature, Quest const* quest, uint32 opt); + uint32 GetDialogStatus(Player* player, Creature* creature); + CreatureAI* GetCreatureAI(Creature* creature); + void OnCreatureUpdate(Creature* creature, uint32 diff); - public: /* GameObjectScript */ +public: /* GameObjectScript */ - bool OnGossipHello(Player* player, GameObject* go); - bool OnGossipSelect(Player* player, GameObject* go, uint32 sender, uint32 action); - bool OnGossipSelectCode(Player* player, GameObject* go, uint32 sender, uint32 action, const char* code); - bool OnQuestAccept(Player* player, GameObject* go, Quest const* quest); - bool OnQuestReward(Player* player, GameObject* go, Quest const* quest, uint32 opt); - uint32 GetDialogStatus(Player* player, GameObject* go); - void OnGameObjectDestroyed(GameObject* go, Player* player); - void OnGameObjectDamaged(GameObject* go, Player* player); - void OnGameObjectLootStateChanged(GameObject* go, uint32 state, Unit* unit); - void OnGameObjectStateChanged(GameObject* go, uint32 state); - void OnGameObjectUpdate(GameObject* go, uint32 diff); - GameObjectAI* GetGameObjectAI(GameObject* go); - - public: /* AreaTriggerScript */ - - bool OnAreaTrigger(Player* player, AreaTrigger const* trigger); - - public: /* BattlegroundScript */ - - Battleground* CreateBattleground(BattlegroundTypeId typeId); - - public: /* OutdoorPvPScript */ - - OutdoorPvP* CreateOutdoorPvP(OutdoorPvPData const* data); - - public: /* CommandScript */ - - std::vector GetChatCommands(); - - public: /* WeatherScript */ - - void OnWeatherChange(Weather* weather, WeatherState state, float grade); - void OnWeatherUpdate(Weather* weather, uint32 diff); - - public: /* AuctionHouseScript */ - - void OnAuctionAdd(AuctionHouseObject* ah, AuctionEntry* entry); - void OnAuctionRemove(AuctionHouseObject* ah, AuctionEntry* entry); - void OnAuctionSuccessful(AuctionHouseObject* ah, AuctionEntry* entry); - void OnAuctionExpire(AuctionHouseObject* ah, AuctionEntry* entry); - void OnBeforeAuctionHouseMgrSendAuctionWonMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* bidder, uint32& bidder_accId, bool& sendNotification, bool& updateAchievementCriteria, bool& sendMail); - void OnBeforeAuctionHouseMgrSendAuctionSalePendingMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* owner, uint32& owner_accId, bool& sendMail); - void OnBeforeAuctionHouseMgrSendAuctionSuccessfulMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* owner, uint32& owner_accId, uint32& profit, bool& sendNotification, bool& updateAchievementCriteria, bool& sendMail); - void OnBeforeAuctionHouseMgrSendAuctionExpiredMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* owner, uint32& owner_accId, bool& sendNotification, bool& sendMail); - void OnBeforeAuctionHouseMgrSendAuctionOutbiddedMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* oldBidder, uint32& oldBidder_accId, Player* newBidder, uint32& newPrice, bool& sendNotification, bool& sendMail); - void OnBeforeAuctionHouseMgrSendAuctionCancelledToBidderMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* bidder, uint32& bidder_accId, bool& sendMail); - void OnBeforeAuctionHouseMgrUpdate(); - - public: /* ConditionScript */ - - bool OnConditionCheck(Condition* condition, ConditionSourceInfo& sourceInfo); - - public: /* VehicleScript */ - - void OnInstall(Vehicle* veh); - void OnUninstall(Vehicle* veh); - void OnReset(Vehicle* veh); - void OnInstallAccessory(Vehicle* veh, Creature* accessory); - void OnAddPassenger(Vehicle* veh, Unit* passenger, int8 seatId); - void OnRemovePassenger(Vehicle* veh, Unit* passenger); - - public: /* DynamicObjectScript */ - - void OnDynamicObjectUpdate(DynamicObject* dynobj, uint32 diff); - - public: /* TransportScript */ - - void OnAddPassenger(Transport* transport, Player* player); - void OnAddCreaturePassenger(Transport* transport, Creature* creature); - void OnRemovePassenger(Transport* transport, Player* player); - void OnTransportUpdate(Transport* transport, uint32 diff); - void OnRelocate(Transport* transport, uint32 waypointId, uint32 mapId, float x, float y, float z); - - public: /* AchievementCriteriaScript */ - - bool OnCriteriaCheck(uint32 scriptId, Player* source, Unit* target); - - public: /* PlayerScript */ - - void OnBeforePlayerUpdate(Player* player, uint32 p_time); - void OnPlayerReleasedGhost(Player* player); - void OnPVPKill(Player* killer, Player* killed); - void OnCreatureKill(Player* killer, Creature* killed); - void OnCreatureKilledByPet(Player* petOwner, Creature* killed); - void OnPlayerKilledByCreature(Creature* killer, Player* killed); - void OnPlayerLevelChanged(Player* player, uint8 oldLevel); - void OnPlayerFreeTalentPointsChanged(Player* player, uint32 newPoints); - void OnPlayerTalentsReset(Player* player, bool noCost); - void OnPlayerMoneyChanged(Player* player, int32& amount); - void OnGivePlayerXP(Player* player, uint32& amount, Unit* victim); - void OnPlayerReputationChange(Player* player, uint32 factionID, int32& standing, bool incremental); - void OnPlayerReputationRankChange(Player* player, uint32 factionID, ReputationRank newRank, ReputationRank oldRank, bool increased); - void OnPlayerLearnSpell(Player* player, uint32 spellID); - void OnPlayerForgotSpell(Player* player, uint32 spellID); - void OnPlayerDuelRequest(Player* target, Player* challenger); - void OnPlayerDuelStart(Player* player1, Player* player2); - void OnPlayerDuelEnd(Player* winner, Player* loser, DuelCompleteType type); - void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg); - void OnBeforeSendChatMessage(Player* player, uint32& type, uint32& lang, std::string& msg); - void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Player* receiver); - void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Group* group); - void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Guild* guild); - void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Channel* channel); - void OnPlayerEmote(Player* player, uint32 emote); - void OnPlayerTextEmote(Player* player, uint32 textEmote, uint32 emoteNum, uint64 guid); - void OnPlayerSpellCast(Player* player, Spell* spell, bool skipCheck); - void OnPlayerLogin(Player* player); - void OnPlayerLoadFromDB(Player* player); - void OnPlayerLogout(Player* player); - void OnPlayerCreate(Player* player); - void OnPlayerSave(Player* player); - void OnPlayerDelete(uint64 guid, uint32 accountId); - void OnPlayerFailedDelete(uint64 guid, uint32 accountId); - void OnPlayerBindToInstance(Player* player, Difficulty difficulty, uint32 mapid, bool permanent); - void OnPlayerUpdateZone(Player* player, uint32 newZone, uint32 newArea); - void OnPlayerUpdateArea(Player* player, uint32 oldArea, uint32 newArea); - bool OnBeforePlayerTeleport(Player* player, uint32 mapid, float x, float y, float z, float orientation, uint32 options, Unit *target); - void OnPlayerUpdateFaction(Player* player); - void OnPlayerAddToBattleground(Player* player, Battleground* bg); - void OnPlayerRemoveFromBattleground(Player* player, Battleground* bg); - void OnAchievementComplete(Player *player, AchievementEntry const* achievement); - void OnCriteriaProgress(Player *player, AchievementCriteriaEntry const* criteria); - void OnAchievementSave(SQLTransaction& trans, Player* player, uint16 achiId, CompletedAchievementData achiData); - void OnCriteriaSave(SQLTransaction& trans, Player* player, uint16 critId, CriteriaProgress criteriaData); - void OnGossipSelect(Player* player, uint32 menu_id, uint32 sender, uint32 action); - void OnGossipSelectCode(Player* player, uint32 menu_id, uint32 sender, uint32 action, const char* code); - void OnPlayerBeingCharmed(Player* player, Unit* charmer, uint32 oldFactionId, uint32 newFactionId); - void OnAfterPlayerSetVisibleItemSlot(Player* player, uint8 slot, Item *item); - void OnAfterPlayerMoveItemFromInventory(Player* player, Item* it, uint8 bag, uint8 slot, bool update); - void OnEquip(Player* player, Item* it, uint8 bag, uint8 slot, bool update); - void OnPlayerJoinBG(Player* player); - void OnPlayerJoinArena(Player* player); - void OnLootItem(Player* player, Item* item, uint32 count, uint64 lootguid); - void OnCreateItem(Player* player, Item* item, uint32 count); - void OnQuestRewardItem(Player* player, Item* item, uint32 count); - void OnBeforeBuyItemFromVendor(Player * player, uint64 vendorguid, uint32 vendorslot, uint32 &item, uint8 count, uint8 bag, uint8 slot); - void OnAfterStoreOrEquipNewItem(Player* player, uint32 vendorslot, uint32 &item, uint8 count, uint8 bag, uint8 slot, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore); - void OnAfterUpdateMaxPower(Player* player, Powers& power, float& value); - void OnAfterUpdateMaxHealth(Player* player, float& value); - void OnBeforeUpdateAttackPowerAndDamage(Player* player, float& level, float& val2, bool ranged); - void OnAfterUpdateAttackPowerAndDamage(Player* player, float& level, float& base_attPower, float& attPowerMod, float& attPowerMultiplier, bool ranged); - void OnBeforeInitTalentForLevel(Player* player, uint8& level, uint32& talentPointsForLevel); - void OnFirstLogin(Player* player); - void OnPlayerCompleteQuest(Player* player, Quest const* quest); - bool CanJoinInBattlegroundQueue(Player* player, uint64 BattlemasterGuid, BattlegroundTypeId BGTypeID, uint8 joinAsGroup, GroupJoinBattlegroundResult& err); - void OnBeforeTempSummonInitStats(Player* player, TempSummon* tempSummon, uint32& duration); - void OnBeforeGuardianInitStatsForLevel(Player* player, Guardian* guardian, CreatureTemplate const* cinfo, PetType& petType); - void OnAfterGuardianInitStatsForLevel(Player* player, Guardian* guardian); - void OnBeforeLoadPetFromDB(Player* player, uint32& petentry, uint32& petnumber, bool& current, bool& forceLoadFromDB); - - public: /* AccountScript */ - - void OnAccountLogin(uint32 accountId); - void OnFailedAccountLogin(uint32 accountId); - void OnEmailChange(uint32 accountId); - void OnFailedEmailChange(uint32 accountId); - void OnPasswordChange(uint32 accountId); - void OnFailedPasswordChange(uint32 accountId); - - public: /* GuildScript */ - - void OnGuildAddMember(Guild* guild, Player* player, uint8& plRank); - void OnGuildRemoveMember(Guild* guild, Player* player, bool isDisbanding, bool isKicked); - void OnGuildMOTDChanged(Guild* guild, const std::string& newMotd); - void OnGuildInfoChanged(Guild* guild, const std::string& newInfo); - void OnGuildCreate(Guild* guild, Player* leader, const std::string& name); - void OnGuildDisband(Guild* guild); - void OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32 &amount, bool isRepair); - void OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32 &amount); - void OnGuildItemMove(Guild* guild, Player* player, Item* pItem, bool isSrcBank, uint8 srcContainer, uint8 srcSlotId, - bool isDestBank, uint8 destContainer, uint8 destSlotId); - void OnGuildEvent(Guild* guild, uint8 eventType, uint32 playerGuid1, uint32 playerGuid2, uint8 newRank); - void OnGuildBankEvent(Guild* guild, uint8 eventType, uint8 tabId, uint32 playerGuid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId); - - public: /* GroupScript */ - - void OnGroupAddMember(Group* group, uint64 guid); - void OnGroupInviteMember(Group* group, uint64 guid); - void OnGroupRemoveMember(Group* group, uint64 guid, RemoveMethod method, uint64 kicker, const char* reason); - void OnGroupChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid); - void OnGroupDisband(Group* group); - - public: /* GlobalScript */ - void OnGlobalItemDelFromDB(SQLTransaction& trans, uint32 itemGuid); - void OnGlobalMirrorImageDisplayItem(const Item *item, uint32 &display); - void OnBeforeUpdateArenaPoints(ArenaTeam* at, std::map &ap); - void OnAfterRefCount(Player const* player, Loot& loot, bool canRate, uint16 lootMode, LootStoreItem* LootStoreItem, uint32 &maxcount, LootStore const& store); - void OnBeforeDropAddItem(Player const* player, Loot& loot, bool canRate, uint16 lootMode, LootStoreItem* LootStoreItem, LootStore const& store); - void OnItemRoll(Player const* player, LootStoreItem const* LootStoreItem, float &chance, Loot& loot, LootStore const& store); - void OnInitializeLockedDungeons(Player* player, uint8& level, uint32& lockData); - void OnAfterInitializeLockedDungeons(Player* player); - void OnAfterUpdateEncounterState(Map* map, EncounterCreditType type, uint32 creditEntry, Unit* source, Difficulty difficulty_fixed, DungeonEncounterList const* encounters, uint32 dungeonCompleted, bool updated); - void OnBeforeWorldObjectSetPhaseMask(WorldObject const* worldObject, uint32& oldPhaseMask, uint32& newPhaseMask, bool& useCombinedPhases, bool& update); - - public: /* Scheduled scripts */ - - uint32 IncreaseScheduledScriptsCount() { return ++_scheduledScripts; } - uint32 DecreaseScheduledScriptCount() { return --_scheduledScripts; } - uint32 DecreaseScheduledScriptCount(size_t count) { return _scheduledScripts -= count; } - bool IsScriptScheduled() const { return _scheduledScripts > 0; } - - public: /* UnitScript */ - - void OnHeal(Unit* healer, Unit* reciever, uint32& gain); - void OnDamage(Unit* attacker, Unit* victim, uint32& damage); - void ModifyPeriodicDamageAurasTick(Unit* target, Unit* attacker, uint32& damage); - void ModifyMeleeDamage(Unit* target, Unit* attacker, uint32& damage); - void ModifySpellDamageTaken(Unit* target, Unit* attacker, int32& damage); - void ModifyHealRecieved(Unit* target, Unit* attacker, uint32& addHealth); - uint32 DealDamage(Unit* AttackerUnit, Unit *pVictim, uint32 damage, DamageEffectType damagetype); - void OnBeforeRollMeleeOutcomeAgainst(const Unit* attacker, const Unit* victim, WeaponAttackType attType, int32 &attackerMaxSkillValueForLevel, int32 &victimMaxSkillValueForLevel, int32 &attackerWeaponSkill, int32 &victimDefenseSkill, int32 &crit_chance, int32 &miss_chance, int32 &dodge_chance, int32 &parry_chance, int32 &block_chance); - - - public: /* MovementHandlerScript */ - - void OnPlayerMove(Player* player, MovementInfo movementInfo, uint32 opcode); - - public: /* AllCreatureScript */ - - //listener function (OnAllCreatureUpdate) is called by OnCreatureUpdate - //void OnAllCreatureUpdate(Creature* creature, uint32 diff); - void Creature_SelectLevel(const CreatureTemplate *cinfo, Creature* creature); - - public: /* AllMapScript */ - - //listener functions are called by OnPlayerEnterMap and OnPlayerLeaveMap - //void OnPlayerEnterAll(Map* map, Player* player); - //void OnPlayerLeaveAll(Map* map, Player* player); - - public: /* BGScript */ - - void OnBattlegroundStart(Battleground* bg); - void OnBattlegroundEndReward(Battleground* bg, Player* player, TeamId winnerTeamId); - void OnBattlegroundUpdate(Battleground* bg, uint32 diff); - void OnBattlegroundAddPlayer(Battleground* bg, Player* player); - void OnBattlegroundBeforeAddPlayer(Battleground* bg, Player* player); - void OnBattlegroundRemovePlayerAtLeave(Battleground* bg, Player* player); - void OnAddGroup(BattlegroundQueue* queue, GroupQueueInfo* ginfo, uint32& index, Player* leader, Group* grp, PvPDifficultyEntry const* bracketEntry, bool isPremade); - bool CanFillPlayersToBG(BattlegroundQueue* queue, Battleground* bg, const int32 aliFree, const int32 hordeFree, BattlegroundBracketId bracket_id); - bool CanFillPlayersToBGWithSpecific(BattlegroundQueue* queue, Battleground* bg, const int32 aliFree, const int32 hordeFree, - BattlegroundBracketId thisBracketId, BattlegroundQueue* specificQueue, BattlegroundBracketId specificBracketId); - void OnCheckNormalMatch(BattlegroundQueue* queue, uint32& Coef, Battleground* bgTemplate, BattlegroundBracketId bracket_id, uint32& minPlayers, uint32& maxPlayers); - bool CanSendMessageQueue(BattlegroundQueue* queue, Player* leader, Battleground* bg, PvPDifficultyEntry const* bracketEntry); - - public: /* SpellSC */ + bool OnGossipHello(Player* player, GameObject* go); + bool OnGossipSelect(Player* player, GameObject* go, uint32 sender, uint32 action); + bool OnGossipSelectCode(Player* player, GameObject* go, uint32 sender, uint32 action, const char* code); + bool OnQuestAccept(Player* player, GameObject* go, Quest const* quest); + bool OnQuestReward(Player* player, GameObject* go, Quest const* quest, uint32 opt); + uint32 GetDialogStatus(Player* player, GameObject* go); + void OnGameObjectDestroyed(GameObject* go, Player* player); + void OnGameObjectDamaged(GameObject* go, Player* player); + void OnGameObjectLootStateChanged(GameObject* go, uint32 state, Unit* unit); + void OnGameObjectStateChanged(GameObject* go, uint32 state); + void OnGameObjectUpdate(GameObject* go, uint32 diff); + GameObjectAI* GetGameObjectAI(GameObject* go); + +public: /* AreaTriggerScript */ + + bool OnAreaTrigger(Player* player, AreaTrigger const* trigger); + +public: /* BattlegroundScript */ + + Battleground* CreateBattleground(BattlegroundTypeId typeId); + +public: /* OutdoorPvPScript */ + + OutdoorPvP* CreateOutdoorPvP(OutdoorPvPData const* data); + +public: /* CommandScript */ + + std::vector GetChatCommands(); + +public: /* WeatherScript */ + + void OnWeatherChange(Weather* weather, WeatherState state, float grade); + void OnWeatherUpdate(Weather* weather, uint32 diff); + +public: /* AuctionHouseScript */ + + void OnAuctionAdd(AuctionHouseObject* ah, AuctionEntry* entry); + void OnAuctionRemove(AuctionHouseObject* ah, AuctionEntry* entry); + void OnAuctionSuccessful(AuctionHouseObject* ah, AuctionEntry* entry); + void OnAuctionExpire(AuctionHouseObject* ah, AuctionEntry* entry); + void OnBeforeAuctionHouseMgrSendAuctionWonMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* bidder, uint32& bidder_accId, bool& sendNotification, bool& updateAchievementCriteria, bool& sendMail); + void OnBeforeAuctionHouseMgrSendAuctionSalePendingMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* owner, uint32& owner_accId, bool& sendMail); + void OnBeforeAuctionHouseMgrSendAuctionSuccessfulMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* owner, uint32& owner_accId, uint32& profit, bool& sendNotification, bool& updateAchievementCriteria, bool& sendMail); + void OnBeforeAuctionHouseMgrSendAuctionExpiredMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* owner, uint32& owner_accId, bool& sendNotification, bool& sendMail); + void OnBeforeAuctionHouseMgrSendAuctionOutbiddedMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* oldBidder, uint32& oldBidder_accId, Player* newBidder, uint32& newPrice, bool& sendNotification, bool& sendMail); + void OnBeforeAuctionHouseMgrSendAuctionCancelledToBidderMail(AuctionHouseMgr* auctionHouseMgr, AuctionEntry* auction, Player* bidder, uint32& bidder_accId, bool& sendMail); + void OnBeforeAuctionHouseMgrUpdate(); + +public: /* ConditionScript */ + + bool OnConditionCheck(Condition* condition, ConditionSourceInfo& sourceInfo); + +public: /* VehicleScript */ + + void OnInstall(Vehicle* veh); + void OnUninstall(Vehicle* veh); + void OnReset(Vehicle* veh); + void OnInstallAccessory(Vehicle* veh, Creature* accessory); + void OnAddPassenger(Vehicle* veh, Unit* passenger, int8 seatId); + void OnRemovePassenger(Vehicle* veh, Unit* passenger); + +public: /* DynamicObjectScript */ + + void OnDynamicObjectUpdate(DynamicObject* dynobj, uint32 diff); + +public: /* TransportScript */ + + void OnAddPassenger(Transport* transport, Player* player); + void OnAddCreaturePassenger(Transport* transport, Creature* creature); + void OnRemovePassenger(Transport* transport, Player* player); + void OnTransportUpdate(Transport* transport, uint32 diff); + void OnRelocate(Transport* transport, uint32 waypointId, uint32 mapId, float x, float y, float z); + +public: /* AchievementCriteriaScript */ + + bool OnCriteriaCheck(uint32 scriptId, Player* source, Unit* target); + +public: /* PlayerScript */ + + void OnBeforePlayerUpdate(Player* player, uint32 p_time); + void OnPlayerReleasedGhost(Player* player); + void OnPVPKill(Player* killer, Player* killed); + void OnCreatureKill(Player* killer, Creature* killed); + void OnCreatureKilledByPet(Player* petOwner, Creature* killed); + void OnPlayerKilledByCreature(Creature* killer, Player* killed); + void OnPlayerLevelChanged(Player* player, uint8 oldLevel); + void OnPlayerFreeTalentPointsChanged(Player* player, uint32 newPoints); + void OnPlayerTalentsReset(Player* player, bool noCost); + void OnPlayerMoneyChanged(Player* player, int32& amount); + void OnGivePlayerXP(Player* player, uint32& amount, Unit* victim); + void OnPlayerReputationChange(Player* player, uint32 factionID, int32& standing, bool incremental); + void OnPlayerReputationRankChange(Player* player, uint32 factionID, ReputationRank newRank, ReputationRank oldRank, bool increased); + void OnPlayerLearnSpell(Player* player, uint32 spellID); + void OnPlayerForgotSpell(Player* player, uint32 spellID); + void OnPlayerDuelRequest(Player* target, Player* challenger); + void OnPlayerDuelStart(Player* player1, Player* player2); + void OnPlayerDuelEnd(Player* winner, Player* loser, DuelCompleteType type); + void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg); + void OnBeforeSendChatMessage(Player* player, uint32& type, uint32& lang, std::string& msg); + void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Player* receiver); + void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Group* group); + void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Guild* guild); + void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Channel* channel); + void OnPlayerEmote(Player* player, uint32 emote); + void OnPlayerTextEmote(Player* player, uint32 textEmote, uint32 emoteNum, uint64 guid); + void OnPlayerSpellCast(Player* player, Spell* spell, bool skipCheck); + void OnPlayerLogin(Player* player); + void OnPlayerLoadFromDB(Player* player); + void OnPlayerLogout(Player* player); + void OnPlayerCreate(Player* player); + void OnPlayerSave(Player* player); + void OnPlayerDelete(uint64 guid, uint32 accountId); + void OnPlayerFailedDelete(uint64 guid, uint32 accountId); + void OnPlayerBindToInstance(Player* player, Difficulty difficulty, uint32 mapid, bool permanent); + void OnPlayerUpdateZone(Player* player, uint32 newZone, uint32 newArea); + void OnPlayerUpdateArea(Player* player, uint32 oldArea, uint32 newArea); + bool OnBeforePlayerTeleport(Player* player, uint32 mapid, float x, float y, float z, float orientation, uint32 options, Unit* target); + void OnPlayerUpdateFaction(Player* player); + void OnPlayerAddToBattleground(Player* player, Battleground* bg); + void OnPlayerRemoveFromBattleground(Player* player, Battleground* bg); + void OnAchievementComplete(Player* player, AchievementEntry const* achievement); + void OnCriteriaProgress(Player* player, AchievementCriteriaEntry const* criteria); + void OnAchievementSave(SQLTransaction& trans, Player* player, uint16 achiId, CompletedAchievementData achiData); + void OnCriteriaSave(SQLTransaction& trans, Player* player, uint16 critId, CriteriaProgress criteriaData); + void OnGossipSelect(Player* player, uint32 menu_id, uint32 sender, uint32 action); + void OnGossipSelectCode(Player* player, uint32 menu_id, uint32 sender, uint32 action, const char* code); + void OnPlayerBeingCharmed(Player* player, Unit* charmer, uint32 oldFactionId, uint32 newFactionId); + void OnAfterPlayerSetVisibleItemSlot(Player* player, uint8 slot, Item* item); + void OnAfterPlayerMoveItemFromInventory(Player* player, Item* it, uint8 bag, uint8 slot, bool update); + void OnEquip(Player* player, Item* it, uint8 bag, uint8 slot, bool update); + void OnPlayerJoinBG(Player* player); + void OnPlayerJoinArena(Player* player); + void OnLootItem(Player* player, Item* item, uint32 count, uint64 lootguid); + void OnCreateItem(Player* player, Item* item, uint32 count); + void OnQuestRewardItem(Player* player, Item* item, uint32 count); + void OnBeforeBuyItemFromVendor(Player* player, uint64 vendorguid, uint32 vendorslot, uint32& item, uint8 count, uint8 bag, uint8 slot); + void OnAfterStoreOrEquipNewItem(Player* player, uint32 vendorslot, uint32& item, uint8 count, uint8 bag, uint8 slot, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore); + void OnAfterUpdateMaxPower(Player* player, Powers& power, float& value); + void OnAfterUpdateMaxHealth(Player* player, float& value); + void OnBeforeUpdateAttackPowerAndDamage(Player* player, float& level, float& val2, bool ranged); + void OnAfterUpdateAttackPowerAndDamage(Player* player, float& level, float& base_attPower, float& attPowerMod, float& attPowerMultiplier, bool ranged); + void OnBeforeInitTalentForLevel(Player* player, uint8& level, uint32& talentPointsForLevel); + void OnFirstLogin(Player* player); + void OnPlayerCompleteQuest(Player* player, Quest const* quest); + bool CanJoinInBattlegroundQueue(Player* player, uint64 BattlemasterGuid, BattlegroundTypeId BGTypeID, uint8 joinAsGroup, GroupJoinBattlegroundResult& err); + void OnBeforeTempSummonInitStats(Player* player, TempSummon* tempSummon, uint32& duration); + void OnBeforeGuardianInitStatsForLevel(Player* player, Guardian* guardian, CreatureTemplate const* cinfo, PetType& petType); + void OnAfterGuardianInitStatsForLevel(Player* player, Guardian* guardian); + void OnBeforeLoadPetFromDB(Player* player, uint32& petentry, uint32& petnumber, bool& current, bool& forceLoadFromDB); + +public: /* AccountScript */ + + void OnAccountLogin(uint32 accountId); + void OnFailedAccountLogin(uint32 accountId); + void OnEmailChange(uint32 accountId); + void OnFailedEmailChange(uint32 accountId); + void OnPasswordChange(uint32 accountId); + void OnFailedPasswordChange(uint32 accountId); + +public: /* GuildScript */ + + void OnGuildAddMember(Guild* guild, Player* player, uint8& plRank); + void OnGuildRemoveMember(Guild* guild, Player* player, bool isDisbanding, bool isKicked); + void OnGuildMOTDChanged(Guild* guild, const std::string& newMotd); + void OnGuildInfoChanged(Guild* guild, const std::string& newInfo); + void OnGuildCreate(Guild* guild, Player* leader, const std::string& name); + void OnGuildDisband(Guild* guild); + void OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32& amount, bool isRepair); + void OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32& amount); + void OnGuildItemMove(Guild* guild, Player* player, Item* pItem, bool isSrcBank, uint8 srcContainer, uint8 srcSlotId, + bool isDestBank, uint8 destContainer, uint8 destSlotId); + void OnGuildEvent(Guild* guild, uint8 eventType, uint32 playerGuid1, uint32 playerGuid2, uint8 newRank); + void OnGuildBankEvent(Guild* guild, uint8 eventType, uint8 tabId, uint32 playerGuid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId); + +public: /* GroupScript */ + + void OnGroupAddMember(Group* group, uint64 guid); + void OnGroupInviteMember(Group* group, uint64 guid); + void OnGroupRemoveMember(Group* group, uint64 guid, RemoveMethod method, uint64 kicker, const char* reason); + void OnGroupChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid); + void OnGroupDisband(Group* group); + +public: /* GlobalScript */ + void OnGlobalItemDelFromDB(SQLTransaction& trans, uint32 itemGuid); + void OnGlobalMirrorImageDisplayItem(const Item* item, uint32& display); + void OnBeforeUpdateArenaPoints(ArenaTeam* at, std::map& ap); + void OnAfterRefCount(Player const* player, Loot& loot, bool canRate, uint16 lootMode, LootStoreItem* LootStoreItem, uint32& maxcount, LootStore const& store); + void OnBeforeDropAddItem(Player const* player, Loot& loot, bool canRate, uint16 lootMode, LootStoreItem* LootStoreItem, LootStore const& store); + void OnItemRoll(Player const* player, LootStoreItem const* LootStoreItem, float& chance, Loot& loot, LootStore const& store); + void OnInitializeLockedDungeons(Player* player, uint8& level, uint32& lockData); + void OnAfterInitializeLockedDungeons(Player* player); + void OnAfterUpdateEncounterState(Map* map, EncounterCreditType type, uint32 creditEntry, Unit* source, Difficulty difficulty_fixed, DungeonEncounterList const* encounters, uint32 dungeonCompleted, bool updated); + void OnBeforeWorldObjectSetPhaseMask(WorldObject const* worldObject, uint32& oldPhaseMask, uint32& newPhaseMask, bool& useCombinedPhases, bool& update); + +public: /* Scheduled scripts */ + + uint32 IncreaseScheduledScriptsCount() { return ++_scheduledScripts; } + uint32 DecreaseScheduledScriptCount() { return --_scheduledScripts; } + uint32 DecreaseScheduledScriptCount(size_t count) { return _scheduledScripts -= count; } + bool IsScriptScheduled() const { return _scheduledScripts > 0; } + +public: /* UnitScript */ + + void OnHeal(Unit* healer, Unit* reciever, uint32& gain); + void OnDamage(Unit* attacker, Unit* victim, uint32& damage); + void ModifyPeriodicDamageAurasTick(Unit* target, Unit* attacker, uint32& damage); + void ModifyMeleeDamage(Unit* target, Unit* attacker, uint32& damage); + void ModifySpellDamageTaken(Unit* target, Unit* attacker, int32& damage); + void ModifyHealRecieved(Unit* target, Unit* attacker, uint32& addHealth); + uint32 DealDamage(Unit* AttackerUnit, Unit* pVictim, uint32 damage, DamageEffectType damagetype); + void OnBeforeRollMeleeOutcomeAgainst(const Unit* attacker, const Unit* victim, WeaponAttackType attType, int32& attackerMaxSkillValueForLevel, int32& victimMaxSkillValueForLevel, int32& attackerWeaponSkill, int32& victimDefenseSkill, int32& crit_chance, int32& miss_chance, int32& dodge_chance, int32& parry_chance, int32& block_chance); + + +public: /* MovementHandlerScript */ + + void OnPlayerMove(Player* player, MovementInfo movementInfo, uint32 opcode); + +public: /* AllCreatureScript */ + + //listener function (OnAllCreatureUpdate) is called by OnCreatureUpdate + //void OnAllCreatureUpdate(Creature* creature, uint32 diff); + void Creature_SelectLevel(const CreatureTemplate* cinfo, Creature* creature); + +public: /* AllMapScript */ + + //listener functions are called by OnPlayerEnterMap and OnPlayerLeaveMap + //void OnPlayerEnterAll(Map* map, Player* player); + //void OnPlayerLeaveAll(Map* map, Player* player); + +public: /* BGScript */ + + void OnBattlegroundStart(Battleground* bg); + void OnBattlegroundEndReward(Battleground* bg, Player* player, TeamId winnerTeamId); + void OnBattlegroundUpdate(Battleground* bg, uint32 diff); + void OnBattlegroundAddPlayer(Battleground* bg, Player* player); + void OnBattlegroundBeforeAddPlayer(Battleground* bg, Player* player); + void OnBattlegroundRemovePlayerAtLeave(Battleground* bg, Player* player); + void OnAddGroup(BattlegroundQueue* queue, GroupQueueInfo* ginfo, uint32& index, Player* leader, Group* grp, PvPDifficultyEntry const* bracketEntry, bool isPremade); + bool CanFillPlayersToBG(BattlegroundQueue* queue, Battleground* bg, const int32 aliFree, const int32 hordeFree, BattlegroundBracketId bracket_id); + bool CanFillPlayersToBGWithSpecific(BattlegroundQueue* queue, Battleground* bg, const int32 aliFree, const int32 hordeFree, + BattlegroundBracketId thisBracketId, BattlegroundQueue* specificQueue, BattlegroundBracketId specificBracketId); + void OnCheckNormalMatch(BattlegroundQueue* queue, uint32& Coef, Battleground* bgTemplate, BattlegroundBracketId bracket_id, uint32& minPlayers, uint32& maxPlayers); + bool CanSendMessageQueue(BattlegroundQueue* queue, Player* leader, Battleground* bg, PvPDifficultyEntry const* bracketEntry); + +public: /* SpellSC */ - void OnCalcMaxDuration(Aura const* aura, int32& maxDuration); + void OnCalcMaxDuration(Aura const* aura, int32& maxDuration); - public: /* GameEventScript */ +public: /* GameEventScript */ - void OnGameEventStart(uint16 EventID); - void OnGameEventStop(uint16 EventID); + void OnGameEventStart(uint16 EventID); + void OnGameEventStop(uint16 EventID); - public: /* MailScript */ +public: /* MailScript */ - void OnBeforeMailDraftSendMailTo(MailDraft* mailDraft, MailReceiver const& receiver, MailSender const& sender, MailCheckMask& checked, uint32& deliver_delay, uint32& custom_expiration, bool& deleteMailItemsFromDB, bool& sendMail); + void OnBeforeMailDraftSendMailTo(MailDraft* mailDraft, MailReceiver const& receiver, MailSender const& sender, MailCheckMask& checked, uint32& deliver_delay, uint32& custom_expiration, bool& deleteMailItemsFromDB, bool& sendMail); - private: +private: - uint32 _scriptCount; + uint32 _scriptCount; - //atomic op counter for active scripts amount - std::atomic _scheduledScripts; + //atomic op counter for active scripts amount + std::atomic _scheduledScripts; }; #define sScriptMgr ScriptMgr::instance() @@ -1594,132 +1598,138 @@ class ScriptMgr template class ScriptRegistry { - public: +public: - typedef std::map ScriptMap; - typedef typename ScriptMap::iterator ScriptMapIterator; + typedef std::map ScriptMap; + typedef typename ScriptMap::iterator ScriptMapIterator; - typedef std::vector ScriptVector; - typedef typename ScriptVector::iterator ScriptVectorIterator; + typedef std::vector ScriptVector; + typedef typename ScriptVector::iterator ScriptVectorIterator; - // The actual list of scripts. This will be accessed concurrently, so it must not be modified - // after server startup. - static ScriptMap ScriptPointerList; - // After database load scripts - static ScriptVector ALScripts; + // The actual list of scripts. This will be accessed concurrently, so it must not be modified + // after server startup. + static ScriptMap ScriptPointerList; + // After database load scripts + static ScriptVector ALScripts; - static void AddScript(TScript* const script) + static void AddScript(TScript* const script) + { + ASSERT(script); + + if (!_checkMemory(script)) + return; + + if (script->isAfterLoadScript()) { - ASSERT(script); + ALScripts.push_back(script); + } + else + { + script->checkValidity(); - if (!_checkMemory(script)) - return; + // We're dealing with a code-only script; just add it. + ScriptPointerList[_scriptIdCounter++] = script; + sScriptMgr->IncrementScriptCount(); + } + } - if (script->isAfterLoadScript()) + static void AddALScripts() + { + for(ScriptVectorIterator it = ALScripts.begin(); it != ALScripts.end(); ++it) + { + TScript* const script = *it; + + script->checkValidity(); + + if (script->IsDatabaseBound()) { - ALScripts.push_back(script); + + if (!_checkMemory(script)) + return; + + // Get an ID for the script. An ID only exists if it's a script that is assigned in the database + // through a script name (or similar). + uint32 id = sObjectMgr->GetScriptId(script->GetName().c_str()); + if (id) + { + // Try to find an existing script. + bool existing = false; + for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) + { + // If the script names match... + if (it->second->GetName() == script->GetName()) + { + // ... It exists. + existing = true; + break; + } + } + + // If the script isn't assigned -> assign it! + if (!existing) + { + ScriptPointerList[id] = script; + sScriptMgr->IncrementScriptCount(); + } + else + { + // If the script is already assigned -> delete it! + sLog->outError("Script named '%s' is already assigned (two or more scripts have the same name), so the script can't work, aborting...", + script->GetName().c_str()); + + ABORT(); // Error that should be fixed ASAP. + } + } + else + { + // The script uses a script name from database, but isn't assigned to anything. + if (script->GetName().find("Smart") == std::string::npos) + sLog->outErrorDb("Script named '%s' is not assigned in the database.", + script->GetName().c_str()); + } } else { - script->checkValidity(); - // We're dealing with a code-only script; just add it. ScriptPointerList[_scriptIdCounter++] = script; sScriptMgr->IncrementScriptCount(); } } + } - static void AddALScripts() { - for(ScriptVectorIterator it = ALScripts.begin(); it != ALScripts.end(); ++it) { - TScript* const script = *it; + // Gets a script by its ID (assigned by ObjectMgr). + static TScript* GetScriptById(uint32 id) + { + ScriptMapIterator it = ScriptPointerList.find(id); + if (it != ScriptPointerList.end()) + return it->second; - script->checkValidity(); + return nullptr; + } - if (script->IsDatabaseBound()) { - - if (!_checkMemory(script)) - return; - - // Get an ID for the script. An ID only exists if it's a script that is assigned in the database - // through a script name (or similar). - uint32 id = sObjectMgr->GetScriptId(script->GetName().c_str()); - if (id) - { - // Try to find an existing script. - bool existing = false; - for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) - { - // If the script names match... - if (it->second->GetName() == script->GetName()) - { - // ... It exists. - existing = true; - break; - } - } - - // If the script isn't assigned -> assign it! - if (!existing) - { - ScriptPointerList[id] = script; - sScriptMgr->IncrementScriptCount(); - } - else - { - // If the script is already assigned -> delete it! - sLog->outError("Script named '%s' is already assigned (two or more scripts have the same name), so the script can't work, aborting...", - script->GetName().c_str()); - - ABORT(); // Error that should be fixed ASAP. - } - } - else - { - // The script uses a script name from database, but isn't assigned to anything. - if (script->GetName().find("Smart") == std::string::npos) - sLog->outErrorDb("Script named '%s' is not assigned in the database.", - script->GetName().c_str()); - } - } else { - // We're dealing with a code-only script; just add it. - ScriptPointerList[_scriptIdCounter++] = script; - sScriptMgr->IncrementScriptCount(); - } - } - } - - // Gets a script by its ID (assigned by ObjectMgr). - static TScript* GetScriptById(uint32 id) - { - ScriptMapIterator it = ScriptPointerList.find(id); - if (it != ScriptPointerList.end()) - return it->second; - - return nullptr; - } - - private: +private: + // See if the script is using the same memory as another script. If this happens, it means that + // someone forgot to allocate new memory for a script. + static bool _checkMemory(TScript* const script) + { // See if the script is using the same memory as another script. If this happens, it means that // someone forgot to allocate new memory for a script. - static bool _checkMemory(TScript* const script) { - // See if the script is using the same memory as another script. If this happens, it means that - // someone forgot to allocate new memory for a script. - for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) + for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) + { + if (it->second == script) { - if (it->second == script) - { - sLog->outError("Script '%s' has same memory pointer as '%s'.", - script->GetName().c_str(), it->second->GetName().c_str()); + sLog->outError("Script '%s' has same memory pointer as '%s'.", + script->GetName().c_str(), it->second->GetName().c_str()); - return false; - } + return false; } - - return true; } - // Counter used for code-only scripts. - static uint32 _scriptIdCounter; + return true; + } + + // Counter used for code-only scripts. + static uint32 _scriptIdCounter; }; // Instantiate static members of ScriptRegistry. diff --git a/src/server/game/Scripting/ScriptSystem.cpp b/src/server/game/Scripting/ScriptSystem.cpp index 17eab65bb..1fb457a34 100644 --- a/src/server/game/Scripting/ScriptSystem.cpp +++ b/src/server/game/Scripting/ScriptSystem.cpp @@ -71,8 +71,7 @@ void SystemMgr::LoadScriptWaypoints() m_mPointMoveMap[uiEntry].push_back(temp); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u Script Waypoint nodes in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/Scripting/ScriptSystem.h b/src/server/game/Scripting/ScriptSystem.h index fafc6066d..ed4b9f327 100644 --- a/src/server/game/Scripting/ScriptSystem.h +++ b/src/server/game/Scripting/ScriptSystem.h @@ -48,32 +48,32 @@ typedef std::vector ScriptPointVector; class SystemMgr { - SystemMgr() {} - ~SystemMgr() {} + SystemMgr() {} + ~SystemMgr() {} - public: - static SystemMgr* instance(); +public: + static SystemMgr* instance(); - typedef std::unordered_map PointMoveMap; + typedef std::unordered_map PointMoveMap; - //Database - void LoadScriptWaypoints(); + //Database + void LoadScriptWaypoints(); - ScriptPointVector const& GetPointMoveList(uint32 creatureEntry) const - { - PointMoveMap::const_iterator itr = m_mPointMoveMap.find(creatureEntry); + ScriptPointVector const& GetPointMoveList(uint32 creatureEntry) const + { + PointMoveMap::const_iterator itr = m_mPointMoveMap.find(creatureEntry); - if (itr == m_mPointMoveMap.end()) - return _empty; + if (itr == m_mPointMoveMap.end()) + return _empty; - return itr->second; - } + return itr->second; + } - protected: - PointMoveMap m_mPointMoveMap; //coordinates for waypoints +protected: + PointMoveMap m_mPointMoveMap; //coordinates for waypoints - private: - static ScriptPointVector const _empty; +private: + static ScriptPointVector const _empty; }; #define sScriptSystemMgr SystemMgr::instance() diff --git a/src/server/game/Server/Protocol/Opcodes.h b/src/server/game/Server/Protocol/Opcodes.h index 078d5d8a4..9ef7b2c1c 100644 --- a/src/server/game/Server/Protocol/Opcodes.h +++ b/src/server/game/Server/Protocol/Opcodes.h @@ -846,9 +846,9 @@ enum Opcodes SMSG_INSTANCE_DIFFICULTY = 0x33B, MSG_GM_RESETINSTANCELIMIT = 0x33C, SMSG_MOTD = 0x33D, - SMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY= 0x33E, - SMSG_MOVE_UNSET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY= 0x33F, - CMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY_ACK= 0x340, + SMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY = 0x33E, + SMSG_MOVE_UNSET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY = 0x33F, + CMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY_ACK = 0x340, MSG_MOVE_START_SWIM_CHEAT = 0x341, MSG_MOVE_STOP_SWIM_CHEAT = 0x342, SMSG_MOVE_SET_CAN_FLY = 0x343, @@ -858,7 +858,7 @@ enum Opcodes CMSG_SOCKET_GEMS = 0x347, CMSG_ARENA_TEAM_CREATE = 0x348, SMSG_ARENA_TEAM_COMMAND_RESULT = 0x349, - MSG_MOVE_UPDATE_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY= 0x34A, + MSG_MOVE_UPDATE_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY = 0x34A, CMSG_ARENA_TEAM_QUERY = 0x34B, SMSG_ARENA_TEAM_QUERY_RESPONSE = 0x34C, CMSG_ARENA_TEAM_ROSTER = 0x34D, @@ -1274,7 +1274,7 @@ enum Opcodes CMSG_BATTLEFIELD_MGR_EXIT_REQUEST = 0x4E7, SMSG_BATTLEFIELD_MGR_STATE_CHANGE = 0x4E8, // uint32, uint32 CMSG_BATTLEFIELD_MANAGER_ADVANCE_STATE = 0x4E9, - CMSG_BATTLEFIELD_MANAGER_SET_NEXT_TRANSITION_TIME= 0x4EA, + CMSG_BATTLEFIELD_MANAGER_SET_NEXT_TRANSITION_TIME = 0x4EA, MSG_SET_RAID_DIFFICULTY = 0x4EB, CMSG_TOGGLE_XP_GAIN = 0x4EC, SMSG_TOGGLE_XP_GAIN = 0x4ED, // enable/disable XP gain console message diff --git a/src/server/game/Server/Protocol/PacketLog.cpp b/src/server/game/Server/Protocol/PacketLog.cpp index 7931df7d9..ac3f21f01 100644 --- a/src/server/game/Server/Protocol/PacketLog.cpp +++ b/src/server/game/Server/Protocol/PacketLog.cpp @@ -33,7 +33,7 @@ void PacketLog::Initialize() std::string logsDir = sConfigMgr->GetStringDefault("LogsDir", ""); if (!logsDir.empty()) - if ((logsDir.at(logsDir.length()-1) != '/') && (logsDir.at(logsDir.length()-1) != '\\')) + if ((logsDir.at(logsDir.length() - 1) != '/') && (logsDir.at(logsDir.length() - 1) != '\\')) logsDir.push_back('/'); std::string logname = sConfigMgr->GetStringDefault("PacketLogFile", ""); @@ -43,7 +43,7 @@ void PacketLog::Initialize() void PacketLog::LogPacket(WorldPacket const& packet, Direction direction) { - ByteBuffer data(4+4+4+1+packet.size()); + ByteBuffer data(4 + 4 + 4 + 1 + packet.size()); data << int32(packet.GetOpcode()); data << int32(packet.size()); data << uint32(time(nullptr)); diff --git a/src/server/game/Server/Protocol/PacketLog.h b/src/server/game/Server/Protocol/PacketLog.h index c3b3713ca..e90d75438 100644 --- a/src/server/game/Server/Protocol/PacketLog.h +++ b/src/server/game/Server/Protocol/PacketLog.h @@ -19,19 +19,19 @@ class WorldPacket; class PacketLog { - private: - PacketLog(); - ~PacketLog(); +private: + PacketLog(); + ~PacketLog(); - public: - static PacketLog* instance(); +public: + static PacketLog* instance(); - void Initialize(); - bool CanLogPacket() const { return (_file != nullptr); } - void LogPacket(WorldPacket const& packet, Direction direction); + void Initialize(); + bool CanLogPacket() const { return (_file != nullptr); } + void LogPacket(WorldPacket const& packet, Direction direction); - private: - FILE* _file; +private: + FILE* _file; }; #define sPacketLog PacketLog::instance() diff --git a/src/server/game/Server/WorldSession.cpp b/src/server/game/Server/WorldSession.cpp index f3a645703..04c7f7423 100644 --- a/src/server/game/Server/WorldSession.cpp +++ b/src/server/game/Server/WorldSession.cpp @@ -39,7 +39,8 @@ #include "LuaEngine.h" #endif -namespace { +namespace +{ std::string const DefaultPlayerName = ""; @@ -167,7 +168,7 @@ WorldSession::~WorldSession() LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId()); // One-time query } -std::string const & WorldSession::GetPlayerName() const +std::string const& WorldSession::GetPlayerName() const { return _player != NULL ? _player->GetName() : DefaultPlayerName; } @@ -177,8 +178,8 @@ std::string WorldSession::GetPlayerInfo() const std::ostringstream ss; ss << "[Player: " << GetPlayerName() - << " (Guid: " << (_player != NULL ? _player->GetGUID() : 0) - << ", Account: " << GetAccountId() << ")]"; + << " (Guid: " << (_player != NULL ? _player->GetGUID() : 0) + << ", Account: " << GetAccountId() << ")]"; return ss.str(); } @@ -279,7 +280,7 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) } else { - OpcodeHandler &opHandle = opcodeTable[packet->GetOpcode()]; + OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()]; try { switch (opHandle.status) @@ -312,10 +313,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) movementPacket = nullptr; } sScriptMgr->OnPacketReceive(this, *packet); - #ifdef ELUNA +#ifdef ELUNA if (!sEluna->OnPacketReceive(this, *packet)) break; - #endif +#endif (this->*opHandle.handler)(*packet); } break; @@ -328,10 +329,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) movementPacket = nullptr; } sScriptMgr->OnPacketReceive(this, *packet); - #ifdef ELUNA +#ifdef ELUNA if (!sEluna->OnPacketReceive(this, *packet)) break; - #endif +#endif (this->*opHandle.handler)(*packet); } break; @@ -342,10 +343,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) if (AntiDOS.EvaluateOpcode(*packet, currentTime)) { sScriptMgr->OnPacketReceive(this, *packet); - #ifdef ELUNA +#ifdef ELUNA if (!sEluna->OnPacketReceive(this, *packet)) break; - #endif +#endif (this->*opHandle.handler)(*packet); } break; @@ -568,7 +569,7 @@ void WorldSession::LogoutPlayer(bool save) _player->GetGroup()->SendUpdate(); _player->GetGroup()->ResetMaxEnchantingLevel(); - Map::PlayerList const &playerList = _player->GetMap()->GetPlayers(); + Map::PlayerList const& playerList = _player->GetMap()->GetPlayers(); if (_player->GetMap()->IsDungeon() || _player->GetMap()->IsRaidOrHeroicDungeon()) if (playerList.isEmpty()) @@ -627,7 +628,7 @@ void WorldSession::KickPlayer(std::string const& reason, bool setKicked) SetKicked(true); // pussywizard: the session won't be left ingame for 60 seconds and to also kick offline session } -void WorldSession::SendNotification(const char *format, ...) +void WorldSession::SendNotification(const char* format, ...) { if (format) { @@ -805,7 +806,7 @@ void WorldSession::SendTutorialsData() SendPacket(&data); } -void WorldSession::SaveTutorialsData(SQLTransaction &trans) +void WorldSession::SaveTutorialsData(SQLTransaction& trans) { if (!m_TutorialsChanged) return; @@ -824,7 +825,7 @@ void WorldSession::SaveTutorialsData(SQLTransaction &trans) m_TutorialsChanged = false; } -void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi) +void WorldSession::ReadMovementInfo(WorldPacket& data, MovementInfo* mi) { data >> mi->flags; data >> mi->flags2; @@ -879,46 +880,46 @@ void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi) #endif -/*! This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid - in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD. - It will freeze clients that receive this player's movement info. -*/ + /*! This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid + in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD. + It will freeze clients that receive this player's movement info. + */ REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT), - MOVEMENTFLAG_ROOT); + MOVEMENTFLAG_ROOT); //! Cannot hover without SPELL_AURA_HOVER REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_HOVER) && !GetPlayer()->HasAuraType(SPELL_AURA_HOVER), - MOVEMENTFLAG_HOVER); + MOVEMENTFLAG_HOVER); //! Cannot ascend and descend at the same time REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ASCENDING) && mi->HasMovementFlag(MOVEMENTFLAG_DESCENDING), - MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING); + MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING); //! Cannot move left and right at the same time REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_RIGHT), - MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT); + MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT); //! Cannot strafe left and right at the same time REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_RIGHT), - MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT); + MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT); //! Cannot pitch up and down at the same time REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_PITCH_UP) && mi->HasMovementFlag(MOVEMENTFLAG_PITCH_DOWN), - MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN); + MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN); //! Cannot move forwards and backwards at the same time REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FORWARD) && mi->HasMovementFlag(MOVEMENTFLAG_BACKWARD), - MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD); + MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD); //! Cannot walk on water without SPELL_AURA_WATER_WALK REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_WATERWALKING) && - !GetPlayer()->HasAuraType(SPELL_AURA_WATER_WALK) && - !GetPlayer()->HasAuraType(SPELL_AURA_GHOST), - MOVEMENTFLAG_WATERWALKING); + !GetPlayer()->HasAuraType(SPELL_AURA_WATER_WALK) && + !GetPlayer()->HasAuraType(SPELL_AURA_GHOST), + MOVEMENTFLAG_WATERWALKING); //! Cannot feather fall without SPELL_AURA_FEATHER_FALL REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FALLING_SLOW) && !GetPlayer()->HasAuraType(SPELL_AURA_FEATHER_FALL), - MOVEMENTFLAG_FALLING_SLOW); + MOVEMENTFLAG_FALLING_SLOW); /*! Cannot fly if no fly auras present. Exception is being a GM. Note that we check for account level instead of Player::IsGameMaster() because in some @@ -928,15 +929,15 @@ void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi) REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY) && GetSecurity() == SEC_PLAYER && !GetPlayer()->m_mover->HasAuraType(SPELL_AURA_FLY) && !GetPlayer()->m_mover->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED), - MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY); + MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY); //! Cannot fly and fall at the same time REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_DISABLE_GRAVITY) && mi->HasMovementFlag(MOVEMENTFLAG_FALLING), - MOVEMENTFLAG_FALLING); + MOVEMENTFLAG_FALLING); REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_SPLINE_ENABLED) && - (!GetPlayer()->movespline->Initialized() || GetPlayer()->movespline->Finalized()), MOVEMENTFLAG_SPLINE_ENABLED); + (!GetPlayer()->movespline->Initialized() || GetPlayer()->movespline->Finalized()), MOVEMENTFLAG_SPLINE_ENABLED); #undef REMOVE_VIOLATING_FLAGS } @@ -979,7 +980,7 @@ void WorldSession::WriteMovementInfo(WorldPacket* data, MovementInfo* mi) *data << mi->splineElevation; } -void WorldSession::ReadAddonsInfo(WorldPacket &data) +void WorldSession::ReadAddonsInfo(WorldPacket& data) { if (data.rpos() + 4 > data.size()) return; @@ -1357,39 +1358,39 @@ bool WorldSession::DosProtection::EvaluateOpcode(WorldPacket& p, time_t time) co return true; sLog->outString("AntiDOS: Account %u, IP: %s, Ping: %u, Character %s, flooding packet (opc: %s (0x%X), count: %u)", - Session->GetAccountId(), Session->GetRemoteAddress().c_str(), Session->GetLatency(), - Session->GetPlayerName().c_str(), opcodeTable[p.GetOpcode()].name, p.GetOpcode(), packetCounter.amountCounter); + Session->GetAccountId(), Session->GetRemoteAddress().c_str(), Session->GetLatency(), + Session->GetPlayerName().c_str(), opcodeTable[p.GetOpcode()].name, p.GetOpcode(), packetCounter.amountCounter); switch (_policy) { case POLICY_LOG: return true; case POLICY_KICK: - { - sLog->outString("AntiDOS: Player %s kicked!", Session->GetPlayerName().c_str()); - Session->KickPlayer(); - return false; - } - case POLICY_BAN: - { - uint32 bm = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANMODE); - uint32 duration = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANDURATION); // in seconds - std::string nameOrIp = ""; - switch (bm) { - case 0: // Ban account - (void)AccountMgr::GetName(Session->GetAccountId(), nameOrIp); - sBan->BanAccount(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS"); - break; - case 1: // Ban ip - nameOrIp = Session->GetRemoteAddress(); - sBan->BanIP(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS"); - break; + sLog->outString("AntiDOS: Player %s kicked!", Session->GetPlayerName().c_str()); + Session->KickPlayer(); + return false; } + case POLICY_BAN: + { + uint32 bm = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANMODE); + uint32 duration = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANDURATION); // in seconds + std::string nameOrIp = ""; + switch (bm) + { + case 0: // Ban account + (void)AccountMgr::GetName(Session->GetAccountId(), nameOrIp); + sBan->BanAccount(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS"); + break; + case 1: // Ban ip + nameOrIp = Session->GetRemoteAddress(); + sBan->BanIP(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS"); + break; + } - sLog->outString("AntiDOS: Player automatically banned for %u seconds.", duration); - return false; - } + sLog->outString("AntiDOS: Player automatically banned for %u seconds.", duration); + return false; + } default: // invalid policy return true; } @@ -1490,12 +1491,12 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: // not profiled case CMSG_FORCE_TURN_RATE_CHANGE_ACK: // not profiled case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: // not profiled - { - // "0" is a magic number meaning there's no limit for the opcode. - // All the opcodes above must cause little CPU usage and no sync/async database queries at all - maxPacketCounterAllowed = 0; - break; - } + { + // "0" is a magic number meaning there's no limit for the opcode. + // All the opcodes above must cause little CPU usage and no sync/async database queries at all + maxPacketCounterAllowed = 0; + break; + } case CMSG_QUESTGIVER_ACCEPT_QUEST: // 0 4 case CMSG_QUESTLOG_REMOVE_QUEST: // 0 4 @@ -1508,10 +1509,10 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co case CMSG_PLAYER_VEHICLE_ENTER: // 0 8 case CMSG_LEARN_PREVIEW_TALENTS_PET: // not profiled case MSG_MOVE_HEARTBEAT: - { - maxPacketCounterAllowed = 200; - break; - } + { + maxPacketCounterAllowed = 200; + break; + } case CMSG_GUILD_SET_PUBLIC_NOTE: // 1 2 1 async db query case CMSG_GUILD_SET_OFFICER_NOTE: // 1 2 1 async db query @@ -1522,25 +1523,25 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co case CMSG_GAMEOBJ_REPORT_USE: // not profiled case CMSG_GAMEOBJ_USE: // not profiled case MSG_PETITION_DECLINE: // not profiled - { - maxPacketCounterAllowed = 50; - break; - } + { + maxPacketCounterAllowed = 50; + break; + } case CMSG_QUEST_POI_QUERY: // 0 25 very high upload bandwidth usage - { - maxPacketCounterAllowed = MAX_QUEST_LOG_SIZE; - break; - } + { + maxPacketCounterAllowed = MAX_QUEST_LOG_SIZE; + break; + } case CMSG_GM_REPORT_LAG: // 1 3 1 async db query case CMSG_SPELLCLICK: // not profiled case CMSG_REMOVE_GLYPH: // not profiled case CMSG_DISMISS_CONTROLLED_VEHICLE: // not profiled - { - maxPacketCounterAllowed = 20; - break; - } + { + maxPacketCounterAllowed = 20; + break; + } case CMSG_PETITION_SIGN: // 9 4 2 sync 1 async db queries case CMSG_TURN_IN_PETITION: // 8 5.5 2 sync db query @@ -1569,10 +1570,10 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co case CMSG_SOCKET_GEMS: // not profiled case CMSG_WRAP_ITEM: // not profiled case CMSG_REPORT_PVP_AFK: // not profiled - { - maxPacketCounterAllowed = 10; - break; - } + { + maxPacketCounterAllowed = 10; + break; + } case CMSG_CHAR_CREATE: // 7 5 3 async db queries case CMSG_CHAR_ENUM: // 22 3 2 async db queries @@ -1620,22 +1621,22 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co case MSG_SET_RAID_DIFFICULTY: // not profiled case MSG_PARTY_ASSIGNMENT: // not profiled case MSG_RAID_READY_CHECK: // not profiled - { - maxPacketCounterAllowed = 3; - break; - } + { + maxPacketCounterAllowed = 3; + break; + } case CMSG_ITEM_REFUND_INFO: // not profiled - { - maxPacketCounterAllowed = PLAYER_SLOTS_COUNT; - break; - } + { + maxPacketCounterAllowed = PLAYER_SLOTS_COUNT; + break; + } default: - { - maxPacketCounterAllowed = 100; - break; - } + { + maxPacketCounterAllowed = 100; + break; + } } return maxPacketCounterAllowed; diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index bba6c7dde..bca6aa8ef 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -47,13 +47,13 @@ struct MovementInfo; namespace lfg { -struct LfgJoinResultData; -struct LfgPlayerBoot; -struct LfgProposal; -struct LfgQueueStatusData; -struct LfgPlayerRewardData; -struct LfgRoleCheck; -struct LfgUpdateData; + struct LfgJoinResultData; + struct LfgPlayerBoot; + struct LfgProposal; + struct LfgQueueStatusData; + struct LfgPlayerRewardData; + struct LfgRoleCheck; + struct LfgUpdateData; } enum AccountDataType @@ -158,30 +158,30 @@ class CharacterCreateInfo friend class WorldSession; friend class Player; - protected: - CharacterCreateInfo(std::string const& name, uint8 race, uint8 cclass, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId, - WorldPacket& data) : Name(name), Race(race), Class(cclass), Gender(gender), Skin(skin), Face(face), HairStyle(hairStyle), HairColor(hairColor), FacialHair(facialHair), +protected: + CharacterCreateInfo(std::string const& name, uint8 race, uint8 cclass, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId, + WorldPacket& data) : Name(name), Race(race), Class(cclass), Gender(gender), Skin(skin), Face(face), HairStyle(hairStyle), HairColor(hairColor), FacialHair(facialHair), OutfitId(outfitId), Data(data), CharCount(0) - {} + {} - /// User specified variables - std::string Name; - uint8 Race; - uint8 Class; - uint8 Gender; - uint8 Skin; - uint8 Face; - uint8 HairStyle; - uint8 HairColor; - uint8 FacialHair; - uint8 OutfitId; - WorldPacket Data; + /// User specified variables + std::string Name; + uint8 Race; + uint8 Class; + uint8 Gender; + uint8 Skin; + uint8 Face; + uint8 HairStyle; + uint8 HairColor; + uint8 FacialHair; + uint8 OutfitId; + WorldPacket Data; - /// Server side data - uint8 CharCount; + /// Server side data + uint8 CharCount; - private: - virtual ~CharacterCreateInfo(){}; +private: + virtual ~CharacterCreateInfo() {}; }; struct PacketCounter @@ -193,855 +193,855 @@ struct PacketCounter /// Player session in the World class WorldSession { - public: - WorldSession(uint32 id, WorldSocket* sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter, bool skipQueue, uint32 TotalTime); - ~WorldSession(); +public: + WorldSession(uint32 id, WorldSocket* sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter, bool skipQueue, uint32 TotalTime); + ~WorldSession(); - bool PlayerLoading() const { return m_playerLoading; } - bool PlayerLogout() const { return m_playerLogout; } - bool PlayerLogoutWithSave() const { return m_playerLogout && m_playerSave; } + bool PlayerLoading() const { return m_playerLoading; } + bool PlayerLogout() const { return m_playerLogout; } + bool PlayerLogoutWithSave() const { return m_playerLogout && m_playerSave; } - void ReadAddonsInfo(WorldPacket& data); - void SendAddonsInfo(); + void ReadAddonsInfo(WorldPacket& data); + void SendAddonsInfo(); - void ReadMovementInfo(WorldPacket& data, MovementInfo* mi); - void WriteMovementInfo(WorldPacket* data, MovementInfo* mi); + void ReadMovementInfo(WorldPacket& data, MovementInfo* mi); + void WriteMovementInfo(WorldPacket* data, MovementInfo* mi); - void SendPacket(WorldPacket const* packet); - void SendNotification(const char *format, ...) ATTR_PRINTF(2, 3); - void SendNotification(uint32 string_id, ...); - void SendPetNameInvalid(uint32 error, std::string const& name, DeclinedName *declinedName); - void SendPartyResult(PartyOperation operation, std::string const& member, PartyResult res, uint32 val = 0); - void SendAreaTriggerMessage(const char* Text, ...) ATTR_PRINTF(2, 3); - void SendSetPhaseShift(uint32 phaseShift); - void SendQueryTimeResponse(); + void SendPacket(WorldPacket const* packet); + void SendNotification(const char* format, ...) ATTR_PRINTF(2, 3); + void SendNotification(uint32 string_id, ...); + void SendPetNameInvalid(uint32 error, std::string const& name, DeclinedName* declinedName); + void SendPartyResult(PartyOperation operation, std::string const& member, PartyResult res, uint32 val = 0); + void SendAreaTriggerMessage(const char* Text, ...) ATTR_PRINTF(2, 3); + void SendSetPhaseShift(uint32 phaseShift); + void SendQueryTimeResponse(); - void SendAuthResponse(uint8 code, bool shortForm, uint32 queuePos = 0); - void SendClientCacheVersion(uint32 version); + void SendAuthResponse(uint8 code, bool shortForm, uint32 queuePos = 0); + void SendClientCacheVersion(uint32 version); - AccountTypes GetSecurity() const { return _security; } - bool CanSkipQueue() const { return _skipQueue; } - uint32 GetAccountId() const { return _accountId; } - Player* GetPlayer() const { return _player; } - std::string const& GetPlayerName() const; - std::string GetPlayerInfo() const; + AccountTypes GetSecurity() const { return _security; } + bool CanSkipQueue() const { return _skipQueue; } + uint32 GetAccountId() const { return _accountId; } + Player* GetPlayer() const { return _player; } + std::string const& GetPlayerName() const; + std::string GetPlayerInfo() const; - uint32 GetCurrentVendor() const { return m_currentVendorEntry; } - void SetCurrentVendor(uint32 vendorEntry) { m_currentVendorEntry = vendorEntry; } + uint32 GetCurrentVendor() const { return m_currentVendorEntry; } + void SetCurrentVendor(uint32 vendorEntry) { m_currentVendorEntry = vendorEntry; } - uint32 GetGuidLow() const; - void SetSecurity(AccountTypes security) { _security = security; } - std::string const& GetRemoteAddress() { return m_Address; } - void SetPlayer(Player* player); - uint8 Expansion() const { return m_expansion; } + uint32 GetGuidLow() const; + void SetSecurity(AccountTypes security) { _security = security; } + std::string const& GetRemoteAddress() { return m_Address; } + void SetPlayer(Player* player); + uint8 Expansion() const { return m_expansion; } - void SetTotalTime(uint32 TotalTime) { m_total_time = TotalTime; } - uint32 GetTotalTime() const { return m_total_time; } + void SetTotalTime(uint32 TotalTime) { m_total_time = TotalTime; } + uint32 GetTotalTime() const { return m_total_time; } - void InitWarden(BigNumber* k, std::string const& os); + void InitWarden(BigNumber* k, std::string const& os); - /// Session in auth.queue currently - void SetInQueue(bool state) { m_inQueue = state; } + /// Session in auth.queue currently + void SetInQueue(bool state) { m_inQueue = state; } - /// Is the user engaged in a log out process? - bool isLogingOut() const { return _logoutTime || m_playerLogout; } + /// Is the user engaged in a log out process? + bool isLogingOut() const { return _logoutTime || m_playerLogout; } - /// Engage the logout process for the user - void LogoutRequest(time_t requestTime) + /// Engage the logout process for the user + void LogoutRequest(time_t requestTime) + { + _logoutTime = requestTime; + } + + /// Is logout cooldown expired? + bool ShouldLogOut(time_t currTime) const + { + return (_logoutTime > 0 && currTime >= _logoutTime + 20); + } + + void LogoutPlayer(bool save); + void KickPlayer(bool setKicked = true) { return this->KickPlayer("Unknown reason", setKicked); } + void KickPlayer(std::string const& reason, bool setKicked = true); + + void QueuePacket(WorldPacket* new_packet); + bool Update(uint32 diff, PacketFilter& updater); + + /// Handle the authentication waiting queue (to be completed) + void SendAuthWaitQue(uint32 position); + + //void SendTestCreatureQueryOpcode(uint32 entry, uint64 guid, uint32 testvalue); + void SendNameQueryOpcode(uint64 guid); + + void SendTrainerList(uint64 guid); + void SendTrainerList(uint64 guid, std::string const& strTitle); + void SendListInventory(uint64 guid, uint32 vendorEntry = 0); + void SendShowBank(uint64 guid); + bool CanOpenMailBox(uint64 guid); + void SendShowMailBox(uint64 guid); + void SendTabardVendorActivate(uint64 guid); + void SendSpiritResurrect(); + void SendBindPoint(Creature* npc); + + void SendAttackStop(Unit const* enemy); + + void SendBattleGroundList(uint64 guid, BattlegroundTypeId bgTypeId = BATTLEGROUND_RB); + + void SendTradeStatus(TradeStatus status); + void SendUpdateTrade(bool trader_data = true); + void SendCancelTrade(); + + void SendPetitionQueryOpcode(uint64 petitionguid); + + // Spell + void HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlags, SpellCastTargets& targets); + + // Pet + void SendPetNameQuery(uint64 guid, uint32 petnumber); + void SendStablePet(uint64 guid); + void SendStablePetCallback(PreparedQueryResult result, uint64 guid); + void SendStableResult(uint8 guid); + bool CheckStableMaster(uint64 guid); + + // Account Data + AccountData* GetAccountData(AccountDataType type) { return &m_accountData[type]; } + void SetAccountData(AccountDataType type, time_t tm, std::string const& data); + void SendAccountDataTimes(uint32 mask); + void LoadGlobalAccountData(); + void LoadAccountData(PreparedQueryResult result, uint32 mask); + + void LoadTutorialsData(); + void SendTutorialsData(); + void SaveTutorialsData(SQLTransaction& trans); + uint32 GetTutorialInt(uint8 index) const { return m_Tutorials[index]; } + void SetTutorialInt(uint8 index, uint32 value) + { + if (m_Tutorials[index] != value) { - _logoutTime = requestTime; + m_Tutorials[index] = value; + m_TutorialsChanged = true; } - - /// Is logout cooldown expired? - bool ShouldLogOut(time_t currTime) const - { - return (_logoutTime > 0 && currTime >= _logoutTime + 20); - } - - void LogoutPlayer(bool save); - void KickPlayer(bool setKicked = true) { return this->KickPlayer("Unknown reason", setKicked); } - void KickPlayer(std::string const& reason, bool setKicked = true); - - void QueuePacket(WorldPacket* new_packet); - bool Update(uint32 diff, PacketFilter& updater); - - /// Handle the authentication waiting queue (to be completed) - void SendAuthWaitQue(uint32 position); - - //void SendTestCreatureQueryOpcode(uint32 entry, uint64 guid, uint32 testvalue); - void SendNameQueryOpcode(uint64 guid); - - void SendTrainerList(uint64 guid); - void SendTrainerList(uint64 guid, std::string const& strTitle); - void SendListInventory(uint64 guid, uint32 vendorEntry = 0); - void SendShowBank(uint64 guid); - bool CanOpenMailBox(uint64 guid); - void SendShowMailBox(uint64 guid); - void SendTabardVendorActivate(uint64 guid); - void SendSpiritResurrect(); - void SendBindPoint(Creature* npc); - - void SendAttackStop(Unit const* enemy); - - void SendBattleGroundList(uint64 guid, BattlegroundTypeId bgTypeId = BATTLEGROUND_RB); - - void SendTradeStatus(TradeStatus status); - void SendUpdateTrade(bool trader_data = true); - void SendCancelTrade(); - - void SendPetitionQueryOpcode(uint64 petitionguid); - - // Spell - void HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlags, SpellCastTargets & targets); - - // Pet - void SendPetNameQuery(uint64 guid, uint32 petnumber); - void SendStablePet(uint64 guid); - void SendStablePetCallback(PreparedQueryResult result, uint64 guid); - void SendStableResult(uint8 guid); - bool CheckStableMaster(uint64 guid); - - // Account Data - AccountData* GetAccountData(AccountDataType type) { return &m_accountData[type]; } - void SetAccountData(AccountDataType type, time_t tm, std::string const& data); - void SendAccountDataTimes(uint32 mask); - void LoadGlobalAccountData(); - void LoadAccountData(PreparedQueryResult result, uint32 mask); - - void LoadTutorialsData(); - void SendTutorialsData(); - void SaveTutorialsData(SQLTransaction& trans); - uint32 GetTutorialInt(uint8 index) const { return m_Tutorials[index]; } - void SetTutorialInt(uint8 index, uint32 value) - { - if (m_Tutorials[index] != value) - { - m_Tutorials[index] = value; - m_TutorialsChanged = true; - } - } - //auction - void SendAuctionHello(uint64 guid, Creature* unit); - void SendAuctionCommandResult(uint32 auctionId, uint32 Action, uint32 ErrorCode, uint32 bidError = 0); - void SendAuctionBidderNotification(uint32 location, uint32 auctionId, uint64 bidder, uint32 bidSum, uint32 diff, uint32 item_template); - void SendAuctionOwnerNotification(AuctionEntry* auction); - - //Item Enchantment - void SendEnchantmentLog(uint64 target, uint64 caster, uint32 itemId, uint32 enchantId); - void SendItemEnchantTimeUpdate(uint64 Playerguid, uint64 Itemguid, uint32 slot, uint32 Duration); - - //Taxi - void SendTaxiStatus(uint64 guid); - void SendTaxiMenu(Creature* unit); - void SendDoFlight(uint32 mountDisplayId, uint32 path, uint32 pathNode = 0); - bool SendLearnNewTaxiNode(Creature* unit); - void SendDiscoverNewTaxiNode(uint32 nodeid); - - // Guild/Arena Team - void SendArenaTeamCommandResult(uint32 team_action, std::string const& team, std::string const& player, uint32 error_id = 0); - void SendNotInArenaTeamPacket(uint8 type); - void SendPetitionShowList(uint64 guid); - - void BuildPartyMemberStatsChangedPacket(Player* player, WorldPacket* data); - - void DoLootRelease(uint64 lguid); - - // Account mute time - time_t m_muteTime; - - // Locales - LocaleConstant GetSessionDbcLocale() const { return m_sessionDbcLocale; } - LocaleConstant GetSessionDbLocaleIndex() const { return m_sessionDbLocaleIndex; } - char const* GetAcoreString(uint32 entry) const; - - uint32 GetLatency() const { return m_latency; } - void SetLatency(uint32 latency) { m_latency = latency; } - void ResetClientTimeDelay() { m_clientTimeDelay = 0; } - - std::atomic m_timeOutTime; - void UpdateTimeOutTime(uint32 diff) - { - if (time_t(diff) > m_timeOutTime) - m_timeOutTime = 0; - else - m_timeOutTime -= diff; - } - void ResetTimeOutTime(bool onlyActive) - { - if (GetPlayer()) - m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME_ACTIVE)); - else if (!onlyActive) - m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME)); - } - bool IsConnectionIdle() const - { - return (m_timeOutTime <= 0 && !m_inQueue); - } - - // Recruit-A-Friend Handling - uint32 GetRecruiterId() const { return recruiterId; } - bool IsARecruiter() const { return isRecruiter; } - - // Packets cooldown - time_t GetCalendarEventCreationCooldown() const { return _calendarEventCreationCooldown; } - void SetCalendarEventCreationCooldown(time_t cooldown) { _calendarEventCreationCooldown = cooldown; } - - public: // opcodes handlers - - void Handle_NULL(WorldPacket& recvPacket); // not used - void Handle_EarlyProccess(WorldPacket& recvPacket); // just mark packets processed in WorldSocket::OnRead - void Handle_ServerSide(WorldPacket& recvPacket); // sever side only, can't be accepted from client - void Handle_Deprecated(WorldPacket& recvPacket); // never used anymore by client - - void HandleCharEnumOpcode(WorldPacket& recvPacket); - void HandleCharDeleteOpcode(WorldPacket& recvPacket); - void HandleCharCreateOpcode(WorldPacket& recvPacket); - void HandleCharCreateCallback(PreparedQueryResult result, CharacterCreateInfo* createInfo); - void HandlePlayerLoginOpcode(WorldPacket& recvPacket); - void HandleCharEnum(PreparedQueryResult result); - void HandlePlayerLoginFromDB(LoginQueryHolder * holder); - void HandlePlayerLoginToCharInWorld(Player* pCurrChar); - void HandlePlayerLoginToCharOutOfWorld(Player* pCurrChar); - void HandleCharFactionOrRaceChange(WorldPacket& recvData); - - // played time - void HandlePlayedTime(WorldPacket& recvPacket); - - // new - void HandleMoveUnRootAck(WorldPacket& recvPacket); - void HandleMoveRootAck(WorldPacket& recvPacket); - - // new inspect - void HandleInspectOpcode(WorldPacket& recvPacket); - - // new party stats - void HandleInspectHonorStatsOpcode(WorldPacket& recvPacket); - - void HandleMoveWaterWalkAck(WorldPacket& recvPacket); - void HandleFeatherFallAck(WorldPacket& recvData); - - void HandleMoveHoverAck(WorldPacket& recvData); - - void HandleMountSpecialAnimOpcode(WorldPacket& recvdata); - - // character view - void HandleShowingHelmOpcode(WorldPacket& recvData); - void HandleShowingCloakOpcode(WorldPacket& recvData); - - // repair - void HandleRepairItemOpcode(WorldPacket& recvPacket); - - // Knockback - void HandleMoveKnockBackAck(WorldPacket& recvPacket); - - void HandleMoveTeleportAck(WorldPacket& recvPacket); - void HandleForceSpeedChangeAck(WorldPacket& recvData); - - void HandleRepopRequestOpcode(WorldPacket& recvPacket); - void HandleAutostoreLootItemOpcode(WorldPacket& recvPacket); - void HandleLootMoneyOpcode(WorldPacket& recvPacket); - void HandleLootOpcode(WorldPacket& recvPacket); - void HandleLootReleaseOpcode(WorldPacket& recvPacket); - void HandleLootMasterGiveOpcode(WorldPacket& recvPacket); - void HandleWhoOpcode(WorldPacket& recvPacket); - void HandleLogoutRequestOpcode(WorldPacket& recvPacket); - void HandlePlayerLogoutOpcode(WorldPacket& recvPacket); - void HandleLogoutCancelOpcode(WorldPacket& recvPacket); - - // GM Ticket opcodes - void HandleGMTicketCreateOpcode(WorldPacket& recvPacket); - void HandleGMTicketUpdateOpcode(WorldPacket& recvPacket); - void HandleGMTicketDeleteOpcode(WorldPacket& recvPacket); - void HandleGMTicketGetTicketOpcode(WorldPacket& recvPacket); - void HandleGMTicketSystemStatusOpcode(WorldPacket& recvPacket); - void HandleGMSurveySubmit(WorldPacket& recvPacket); - void HandleReportLag(WorldPacket& recvPacket); - void HandleGMResponseResolve(WorldPacket& recvPacket); - - void HandleTogglePvP(WorldPacket& recvPacket); - - void HandleZoneUpdateOpcode(WorldPacket& recvPacket); - void HandleSetSelectionOpcode(WorldPacket& recvPacket); - void HandleStandStateChangeOpcode(WorldPacket& recvPacket); - void HandleEmoteOpcode(WorldPacket& recvPacket); - void HandleContactListOpcode(WorldPacket& recvPacket); - void HandleAddFriendOpcode(WorldPacket& recvPacket); - void HandleDelFriendOpcode(WorldPacket& recvPacket); - void HandleAddIgnoreOpcode(WorldPacket& recvPacket); - void HandleDelIgnoreOpcode(WorldPacket& recvPacket); - void HandleSetContactNotesOpcode(WorldPacket& recvPacket); - void HandleBugOpcode(WorldPacket& recvPacket); - void HandleSetAmmoOpcode(WorldPacket& recvPacket); - void HandleItemNameQueryOpcode(WorldPacket& recvPacket); - - void HandleAreaTriggerOpcode(WorldPacket& recvPacket); - - void HandleSetFactionAtWar(WorldPacket& recvData); - void HandleSetFactionCheat(WorldPacket& recvData); - void HandleSetWatchedFactionOpcode(WorldPacket& recvData); - void HandleSetFactionInactiveOpcode(WorldPacket& recvData); - - void HandleUpdateAccountData(WorldPacket& recvPacket); - void HandleRequestAccountData(WorldPacket& recvPacket); - void HandleSetActionButtonOpcode(WorldPacket& recvPacket); - - void HandleGameObjectUseOpcode(WorldPacket& recPacket); - void HandleGameobjectReportUse(WorldPacket& recvPacket); - - void HandleNameQueryOpcode(WorldPacket& recvPacket); - - void HandleQueryTimeOpcode(WorldPacket& recvPacket); - - void HandleCreatureQueryOpcode(WorldPacket& recvPacket); - - void HandleGameObjectQueryOpcode(WorldPacket& recvPacket); - - void HandleMoveWorldportAckOpcode(WorldPacket& recvPacket); - void HandleMoveWorldportAckOpcode(); // for server-side calls - - void HandleMovementOpcodes(WorldPacket& recvPacket); - void HandleSetActiveMoverOpcode(WorldPacket& recvData); - void HandleMoveNotActiveMover(WorldPacket& recvData); - void HandleDismissControlledVehicle(WorldPacket& recvData); - void HandleRequestVehicleExit(WorldPacket& recvData); - void HandleChangeSeatsOnControlledVehicle(WorldPacket& recvData); - void HandleMoveTimeSkippedOpcode(WorldPacket& recvData); - - void HandleRequestRaidInfoOpcode(WorldPacket& recvData); - - void HandleBattlefieldStatusOpcode(WorldPacket& recvData); - - void HandleGroupInviteOpcode(WorldPacket& recvPacket); - void HandleGroupAcceptOpcode(WorldPacket& recvPacket); - void HandleGroupDeclineOpcode(WorldPacket& recvPacket); - void HandleGroupUninviteOpcode(WorldPacket& recvPacket); - void HandleGroupUninviteGuidOpcode(WorldPacket& recvPacket); - void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket); - void HandleGroupDisbandOpcode(WorldPacket& recvPacket); - void HandleOptOutOfLootOpcode(WorldPacket& recvData); - void HandleLootMethodOpcode(WorldPacket& recvPacket); - void HandleLootRoll(WorldPacket& recvData); - void HandleRequestPartyMemberStatsOpcode(WorldPacket& recvData); - void HandleRaidTargetUpdateOpcode(WorldPacket& recvData); - void HandleRaidReadyCheckOpcode(WorldPacket& recvData); - void HandleRaidReadyCheckFinishedOpcode(WorldPacket& recvData); - void HandleGroupRaidConvertOpcode(WorldPacket& recvData); - void HandleGroupChangeSubGroupOpcode(WorldPacket& recvData); - void HandleGroupAssistantLeaderOpcode(WorldPacket& recvData); - void HandlePartyAssignmentOpcode(WorldPacket& recvData); - - void HandlePetitionBuyOpcode(WorldPacket& recvData); - void HandlePetitionShowSignOpcode(WorldPacket& recvData); - void HandlePetitionQueryOpcode(WorldPacket& recvData); - void HandlePetitionRenameOpcode(WorldPacket& recvData); - void HandlePetitionSignOpcode(WorldPacket& recvData); - void HandlePetitionDeclineOpcode(WorldPacket& recvData); - void HandleOfferPetitionOpcode(WorldPacket& recvData); - void HandleTurnInPetitionOpcode(WorldPacket& recvData); - - void HandleGuildQueryOpcode(WorldPacket& recvPacket); - void HandleGuildCreateOpcode(WorldPacket& recvPacket); - void HandleGuildInviteOpcode(WorldPacket& recvPacket); - void HandleGuildRemoveOpcode(WorldPacket& recvPacket); - void HandleGuildAcceptOpcode(WorldPacket& recvPacket); - void HandleGuildDeclineOpcode(WorldPacket& recvPacket); - void HandleGuildInfoOpcode(WorldPacket& recvPacket); - void HandleGuildEventLogQueryOpcode(WorldPacket& recvPacket); - void HandleGuildRosterOpcode(WorldPacket& recvPacket); - void HandleGuildPromoteOpcode(WorldPacket& recvPacket); - void HandleGuildDemoteOpcode(WorldPacket& recvPacket); - void HandleGuildLeaveOpcode(WorldPacket& recvPacket); - void HandleGuildDisbandOpcode(WorldPacket& recvPacket); - void HandleGuildLeaderOpcode(WorldPacket& recvPacket); - void HandleGuildMOTDOpcode(WorldPacket& recvPacket); - void HandleGuildSetPublicNoteOpcode(WorldPacket& recvPacket); - void HandleGuildSetOfficerNoteOpcode(WorldPacket& recvPacket); - void HandleGuildRankOpcode(WorldPacket& recvPacket); - void HandleGuildAddRankOpcode(WorldPacket& recvPacket); - void HandleGuildDelRankOpcode(WorldPacket& recvPacket); - void HandleGuildChangeInfoTextOpcode(WorldPacket& recvPacket); - void HandleSaveGuildEmblemOpcode(WorldPacket& recvPacket); - - void HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvPacket); - void HandleTaxiQueryAvailableNodes(WorldPacket& recvPacket); - void HandleActivateTaxiOpcode(WorldPacket& recvPacket); - void HandleActivateTaxiExpressOpcode(WorldPacket& recvPacket); - void HandleMoveSplineDoneOpcode(WorldPacket& recvPacket); - void SendActivateTaxiReply(ActivateTaxiReply reply); - - void HandleTabardVendorActivateOpcode(WorldPacket& recvPacket); - void HandleBankerActivateOpcode(WorldPacket& recvPacket); - void HandleBuyBankSlotOpcode(WorldPacket& recvPacket); - void HandleTrainerListOpcode(WorldPacket& recvPacket); - void HandleTrainerBuySpellOpcode(WorldPacket& recvPacket); - void HandlePetitionShowListOpcode(WorldPacket& recvPacket); - void HandleGossipHelloOpcode(WorldPacket& recvPacket); - void HandleGossipSelectOptionOpcode(WorldPacket& recvPacket); - void HandleSpiritHealerActivateOpcode(WorldPacket& recvPacket); - void HandleNpcTextQueryOpcode(WorldPacket& recvPacket); - void HandleBinderActivateOpcode(WorldPacket& recvPacket); - void HandleListStabledPetsOpcode(WorldPacket& recvPacket); - void HandleStablePet(WorldPacket& recvPacket); - void HandleStablePetCallback(PreparedQueryResult result); - void HandleUnstablePet(WorldPacket& recvPacket); - void HandleUnstablePetCallback(PreparedQueryResult result, uint32 petId); - void HandleBuyStableSlot(WorldPacket& recvPacket); - void HandleStableRevivePet(WorldPacket& recvPacket); - void HandleStableSwapPet(WorldPacket& recvPacket); - void HandleStableSwapPetCallback(PreparedQueryResult result, uint32 petId); - void HandleOpenWrappedItemCallback(PreparedQueryResult result, uint8 bagIndex, uint8 slot, uint32 itemLowGUID); - void HandleLoadActionsSwitchSpec(PreparedQueryResult result); - void HandleCharacterAuraFrozen(PreparedQueryResult result); - uint8 HandleLoadPetFromDBFirstCallback(PreparedQueryResult result, uint8 asynchLoadType); - void HandleLoadPetFromDBSecondCallback(LoadPetFromDBQueryHolder * holder); - - void HandleDuelAcceptedOpcode(WorldPacket& recvPacket); - void HandleDuelCancelledOpcode(WorldPacket& recvPacket); - - void HandleAcceptTradeOpcode(WorldPacket& recvPacket); - void HandleBeginTradeOpcode(WorldPacket& recvPacket); - void HandleBusyTradeOpcode(WorldPacket& recvPacket); - void HandleCancelTradeOpcode(WorldPacket& recvPacket); - void HandleClearTradeItemOpcode(WorldPacket& recvPacket); - void HandleIgnoreTradeOpcode(WorldPacket& recvPacket); - void HandleInitiateTradeOpcode(WorldPacket& recvPacket); - void HandleSetTradeGoldOpcode(WorldPacket& recvPacket); - void HandleSetTradeItemOpcode(WorldPacket& recvPacket); - void HandleUnacceptTradeOpcode(WorldPacket& recvPacket); - - void HandleAuctionHelloOpcode(WorldPacket& recvPacket); - void HandleAuctionListItems(WorldPacket& recvData); - void HandleAuctionListBidderItems(WorldPacket& recvData); - void HandleAuctionSellItem(WorldPacket& recvData); - void HandleAuctionRemoveItem(WorldPacket& recvData); - void HandleAuctionListOwnerItems(WorldPacket& recvData); - void HandleAuctionListOwnerItemsEvent(uint64 creatureGuid); - void HandleAuctionPlaceBid(WorldPacket& recvData); - void HandleAuctionListPendingSales(WorldPacket& recvData); - - void HandleGetMailList(WorldPacket& recvData); - void HandleSendMail(WorldPacket& recvData); - void HandleMailTakeMoney(WorldPacket& recvData); - void HandleMailTakeItem(WorldPacket& recvData); - void HandleMailMarkAsRead(WorldPacket& recvData); - void HandleMailReturnToSender(WorldPacket& recvData); - void HandleMailDelete(WorldPacket& recvData); - void HandleItemTextQuery(WorldPacket& recvData); - void HandleMailCreateTextItem(WorldPacket& recvData); - void HandleQueryNextMailTime(WorldPacket& recvData); - void HandleCancelChanneling(WorldPacket& recvData); - - void HandleSplitItemOpcode(WorldPacket& recvPacket); - void HandleSwapInvItemOpcode(WorldPacket& recvPacket); - void HandleDestroyItemOpcode(WorldPacket& recvPacket); - void HandleAutoEquipItemOpcode(WorldPacket& recvPacket); - void HandleItemQuerySingleOpcode(WorldPacket& recvPacket); - void HandleSellItemOpcode(WorldPacket& recvPacket); - void HandleBuyItemInSlotOpcode(WorldPacket& recvPacket); - void HandleBuyItemOpcode(WorldPacket& recvPacket); - void HandleListInventoryOpcode(WorldPacket& recvPacket); - void HandleAutoStoreBagItemOpcode(WorldPacket& recvPacket); - void HandleReadItem(WorldPacket& recvPacket); - void HandleAutoEquipItemSlotOpcode(WorldPacket& recvPacket); - void HandleSwapItem(WorldPacket& recvPacket); - void HandleBuybackItem(WorldPacket& recvPacket); - void HandleAutoBankItemOpcode(WorldPacket& recvPacket); - void HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket); - void HandleWrapItemOpcode(WorldPacket& recvPacket); - - void HandleAttackSwingOpcode(WorldPacket& recvPacket); - void HandleAttackStopOpcode(WorldPacket& recvPacket); - void HandleSetSheathedOpcode(WorldPacket& recvPacket); - - void HandleUseItemOpcode(WorldPacket& recvPacket); - void HandleOpenItemOpcode(WorldPacket& recvPacket); - void HandleCastSpellOpcode(WorldPacket& recvPacket); - void HandleCancelCastOpcode(WorldPacket& recvPacket); - void HandleCancelAuraOpcode(WorldPacket& recvPacket); - void HandleCancelGrowthAuraOpcode(WorldPacket& recvPacket); - void HandleCancelAutoRepeatSpellOpcode(WorldPacket& recvPacket); - - void HandleLearnTalentOpcode(WorldPacket& recvPacket); - void HandleLearnPreviewTalents(WorldPacket& recvPacket); - void HandleTalentWipeConfirmOpcode(WorldPacket& recvPacket); - void HandleUnlearnSkillOpcode(WorldPacket& recvPacket); - - void HandleQuestgiverStatusQueryOpcode(WorldPacket& recvPacket); - void HandleQuestgiverStatusMultipleQuery(WorldPacket& recvPacket); - void HandleQuestgiverHelloOpcode(WorldPacket& recvPacket); - void HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvPacket); - void HandleQuestgiverQueryQuestOpcode(WorldPacket& recvPacket); - void HandleQuestgiverChooseRewardOpcode(WorldPacket& recvPacket); - void HandleQuestgiverRequestRewardOpcode(WorldPacket& recvPacket); - void HandleQuestQueryOpcode(WorldPacket& recvPacket); - void HandleQuestgiverCancel(WorldPacket& recvData); - void HandleQuestLogSwapQuest(WorldPacket& recvData); - void HandleQuestLogRemoveQuest(WorldPacket& recvData); - void HandleQuestConfirmAccept(WorldPacket& recvData); - void HandleQuestgiverCompleteQuest(WorldPacket& recvData); - void HandleQuestgiverQuestAutoLaunch(WorldPacket& recvPacket); - void HandlePushQuestToParty(WorldPacket& recvPacket); - void HandleQuestPushResult(WorldPacket& recvPacket); - - void HandleMessagechatOpcode(WorldPacket& recvPacket); - void SendPlayerNotFoundNotice(std::string const& name); - void SendPlayerAmbiguousNotice(std::string const& name); - void SendWrongFactionNotice(); - void SendChatRestrictedNotice(ChatRestrictionType restriction); - void HandleTextEmoteOpcode(WorldPacket& recvPacket); - void HandleChatIgnoredOpcode(WorldPacket& recvPacket); - - void HandleReclaimCorpseOpcode(WorldPacket& recvPacket); - void HandleCorpseQueryOpcode(WorldPacket& recvPacket); - void HandleCorpseMapPositionQuery(WorldPacket& recvPacket); - void HandleResurrectResponseOpcode(WorldPacket& recvPacket); - void HandleSummonResponseOpcode(WorldPacket& recvData); - - void HandleJoinChannel(WorldPacket& recvPacket); - void HandleLeaveChannel(WorldPacket& recvPacket); - void HandleChannelList(WorldPacket& recvPacket); - void HandleChannelPassword(WorldPacket& recvPacket); - void HandleChannelSetOwner(WorldPacket& recvPacket); - void HandleChannelOwner(WorldPacket& recvPacket); - void HandleChannelModerator(WorldPacket& recvPacket); - void HandleChannelUnmoderator(WorldPacket& recvPacket); - void HandleChannelMute(WorldPacket& recvPacket); - void HandleChannelUnmute(WorldPacket& recvPacket); - void HandleChannelInvite(WorldPacket& recvPacket); - void HandleChannelKick(WorldPacket& recvPacket); - void HandleChannelBan(WorldPacket& recvPacket); - void HandleChannelUnban(WorldPacket& recvPacket); - void HandleChannelAnnouncements(WorldPacket& recvPacket); - void HandleChannelDeclineInvite(WorldPacket& recvPacket); - void HandleChannelDisplayListQuery(WorldPacket& recvPacket); - void HandleGetChannelMemberCount(WorldPacket& recvPacket); - void HandleSetChannelWatch(WorldPacket& recvPacket); - void HandleClearChannelWatch(WorldPacket& recvPacket); - - void HandleCompleteCinematic(WorldPacket& recvPacket); - void HandleNextCinematicCamera(WorldPacket& recvPacket); - - void HandlePageTextQueryOpcode(WorldPacket& recvPacket); - - void HandleTutorialFlag (WorldPacket& recvData); - void HandleTutorialClear(WorldPacket& recvData); - void HandleTutorialReset(WorldPacket& recvData); - - //Pet - void HandlePetAction(WorldPacket& recvData); - void HandlePetStopAttack(WorldPacket& recvData); - void HandlePetActionHelper(Unit* pet, uint64 guid1, uint16 spellid, uint16 flag, uint64 guid2); - void HandlePetNameQuery(WorldPacket& recvData); - void HandlePetSetAction(WorldPacket& recvData); - void HandlePetAbandon(WorldPacket& recvData); - void HandlePetRename(WorldPacket& recvData); - void HandlePetCancelAuraOpcode(WorldPacket& recvPacket); - void HandlePetSpellAutocastOpcode(WorldPacket& recvPacket); - void HandlePetCastSpellOpcode(WorldPacket& recvPacket); - void HandlePetLearnTalent(WorldPacket& recvPacket); - void HandleLearnPreviewTalentsPet(WorldPacket& recvPacket); - - void HandleSetActionBarToggles(WorldPacket& recvData); - - void HandleCharRenameOpcode(WorldPacket& recvData); - void HandleChangePlayerNameOpcodeCallBack(PreparedQueryResult result, std::string const& newName); - void HandleSetPlayerDeclinedNames(WorldPacket& recvData); - - void HandleTotemDestroyed(WorldPacket& recvData); - void HandleDismissCritter(WorldPacket& recvData); - - //Battleground - void HandleBattlemasterHelloOpcode(WorldPacket& recvData); - void HandleBattlemasterJoinOpcode(WorldPacket& recvData); - void HandleBattlegroundPlayerPositionsOpcode(WorldPacket& recvData); - void HandlePVPLogDataOpcode(WorldPacket& recvData); - void HandleBattleFieldPortOpcode(WorldPacket& recvData); - void HandleBattlefieldListOpcode(WorldPacket& recvData); - void HandleBattlefieldLeaveOpcode(WorldPacket& recvData); - void HandleBattlemasterJoinArena(WorldPacket& recvData); - void HandleReportPvPAFK(WorldPacket& recvData); - - void HandleWardenDataOpcode(WorldPacket& recvData); - void HandleWorldTeleportOpcode(WorldPacket& recvData); - void HandleMinimapPingOpcode(WorldPacket& recvData); - void HandleRandomRollOpcode(WorldPacket& recvData); - void HandleFarSightOpcode(WorldPacket& recvData); - void HandleSetDungeonDifficultyOpcode(WorldPacket& recvData); - void HandleSetRaidDifficultyOpcode(WorldPacket& recvData); - void HandleMoveSetCanFlyAckOpcode(WorldPacket& recvData); - void HandleSetTitleOpcode(WorldPacket& recvData); - void HandleRealmSplitOpcode(WorldPacket& recvData); - void HandleTimeSyncResp(WorldPacket& recvData); - void HandleWhoisOpcode(WorldPacket& recvData); - void HandleResetInstancesOpcode(WorldPacket& recvData); - void HandleHearthAndResurrect(WorldPacket& recvData); - void HandleInstanceLockResponse(WorldPacket& recvPacket); - void HandleUpdateMissileTrajectory(WorldPacket& recvPacket); - - // Battlefield - void SendBfInvitePlayerToWar(uint32 battleId, uint32 zoneId, uint32 time); - void SendBfInvitePlayerToQueue(uint32 battleId); - void SendBfQueueInviteResponse(uint32 battleId, uint32 zoneId, bool canQueue = true, bool full = false); - void SendBfEntered(uint32 battleId); - void SendBfLeaveMessage(uint32 battleId, BFLeaveReason reason = BF_LEAVE_REASON_EXITED); - void HandleBfQueueInviteResponse(WorldPacket& recvData); - void HandleBfEntryInviteResponse(WorldPacket& recvData); - void HandleBfExitRequest(WorldPacket& recvData); - - // Looking for Dungeon/Raid - void HandleLfgSetCommentOpcode(WorldPacket& recvData); - void HandleLfgPlayerLockInfoRequestOpcode(WorldPacket& recvData); - void HandleLfgPartyLockInfoRequestOpcode(WorldPacket& recvData); - void HandleLfgJoinOpcode(WorldPacket& recvData); - void HandleLfgLeaveOpcode(WorldPacket& recvData); - void HandleLfgSetRolesOpcode(WorldPacket& recvData); - void HandleLfgProposalResultOpcode(WorldPacket& recvData); - void HandleLfgSetBootVoteOpcode(WorldPacket& recvData); - void HandleLfgTeleportOpcode(WorldPacket& recvData); - void HandleLfrSearchJoinOpcode(WorldPacket& recvData); - void HandleLfrSearchLeaveOpcode(WorldPacket& recvData); - void HandleLfgGetStatus(WorldPacket& recvData); - - void SendLfgUpdatePlayer(lfg::LfgUpdateData const& updateData); - void SendLfgUpdateParty(lfg::LfgUpdateData const& updateData); - void SendLfgRoleChosen(uint64 guid, uint8 roles); - void SendLfgRoleCheckUpdate(lfg::LfgRoleCheck const& pRoleCheck); - void SendLfgLfrList(bool update); - void SendLfgJoinResult(lfg::LfgJoinResultData const& joinData); - void SendLfgQueueStatus(lfg::LfgQueueStatusData const& queueData); - void SendLfgPlayerReward(lfg::LfgPlayerRewardData const& lfgPlayerRewardData); - void SendLfgBootProposalUpdate(lfg::LfgPlayerBoot const& boot); - void SendLfgUpdateProposal(lfg::LfgProposal const& proposal); - void SendLfgDisabled(); - void SendLfgOfferContinue(uint32 dungeonEntry); - void SendLfgTeleportError(uint8 err); - - // Arena Team - void HandleInspectArenaTeamsOpcode(WorldPacket& recvData); - void HandleArenaTeamQueryOpcode(WorldPacket& recvData); - void HandleArenaTeamRosterOpcode(WorldPacket& recvData); - void HandleArenaTeamInviteOpcode(WorldPacket& recvData); - void HandleArenaTeamAcceptOpcode(WorldPacket& recvData); - void HandleArenaTeamDeclineOpcode(WorldPacket& recvData); - void HandleArenaTeamLeaveOpcode(WorldPacket& recvData); - void HandleArenaTeamRemoveOpcode(WorldPacket& recvData); - void HandleArenaTeamDisbandOpcode(WorldPacket& recvData); - void HandleArenaTeamLeaderOpcode(WorldPacket& recvData); - - void HandleAreaSpiritHealerQueryOpcode(WorldPacket& recvData); - void HandleAreaSpiritHealerQueueOpcode(WorldPacket& recvData); - void HandleCancelMountAuraOpcode(WorldPacket& recvData); - void HandleSelfResOpcode(WorldPacket& recvData); - void HandleComplainOpcode(WorldPacket& recvData); - void HandleRequestPetInfoOpcode(WorldPacket& recvData); - - // Socket gem - void HandleSocketOpcode(WorldPacket& recvData); - - void HandleCancelTempEnchantmentOpcode(WorldPacket& recvData); - - void HandleItemRefundInfoRequest(WorldPacket& recvData); - void HandleItemRefund(WorldPacket& recvData); - - void HandleChannelVoiceOnOpcode(WorldPacket& recvData); - void HandleVoiceSessionEnableOpcode(WorldPacket& recvData); - void HandleSetActiveVoiceChannel(WorldPacket& recvData); - void HandleSetTaxiBenchmarkOpcode(WorldPacket& recvData); - - // Guild Bank - void HandleGuildPermissions(WorldPacket& recvData); - void HandleGuildBankMoneyWithdrawn(WorldPacket& recvData); - void HandleGuildBankerActivate(WorldPacket& recvData); - void HandleGuildBankQueryTab(WorldPacket& recvData); - void HandleGuildBankLogQuery(WorldPacket& recvData); - void HandleGuildBankDepositMoney(WorldPacket& recvData); - void HandleGuildBankWithdrawMoney(WorldPacket& recvData); - void HandleGuildBankSwapItems(WorldPacket& recvData); - - void HandleGuildBankUpdateTab(WorldPacket& recvData); - void HandleGuildBankBuyTab(WorldPacket& recvData); - void HandleQueryGuildBankTabText(WorldPacket& recvData); - void HandleSetGuildBankTabText(WorldPacket& recvData); - - // Refer-a-Friend - void HandleGrantLevel(WorldPacket& recvData); - void HandleAcceptGrantLevel(WorldPacket& recvData); - - // Calendar - void HandleCalendarGetCalendar(WorldPacket& recvData); - void HandleCalendarGetEvent(WorldPacket& recvData); - void HandleCalendarGuildFilter(WorldPacket& recvData); - void HandleCalendarArenaTeam(WorldPacket& recvData); - void HandleCalendarAddEvent(WorldPacket& recvData); - void HandleCalendarUpdateEvent(WorldPacket& recvData); - void HandleCalendarRemoveEvent(WorldPacket& recvData); - void HandleCalendarCopyEvent(WorldPacket& recvData); - void HandleCalendarEventInvite(WorldPacket& recvData); - void HandleCalendarEventRsvp(WorldPacket& recvData); - void HandleCalendarEventRemoveInvite(WorldPacket& recvData); - void HandleCalendarEventStatus(WorldPacket& recvData); - void HandleCalendarEventModeratorStatus(WorldPacket& recvData); - void HandleCalendarComplain(WorldPacket& recvData); - void HandleCalendarGetNumPending(WorldPacket& recvData); - void HandleCalendarEventSignup(WorldPacket& recvData); - - void SendCalendarRaidLockout(InstanceSave const* save, bool add); - void SendCalendarRaidLockoutUpdated(InstanceSave const* save, bool isExtended); - void HandleSetSavedInstanceExtend(WorldPacket& recvData); - - void HandleSpellClick(WorldPacket& recvData); - void HandleMirrorImageDataRequest(WorldPacket& recvData); - void HandleAlterAppearance(WorldPacket& recvData); - void HandleRemoveGlyph(WorldPacket& recvData); - void HandleCharCustomize(WorldPacket& recvData); - void HandleQueryInspectAchievements(WorldPacket& recvData); - void HandleEquipmentSetSave(WorldPacket& recvData); - void HandleEquipmentSetDelete(WorldPacket& recvData); - void HandleEquipmentSetUse(WorldPacket& recvData); - void HandleWorldStateUITimerUpdate(WorldPacket& recvData); - void HandleReadyForAccountDataTimes(WorldPacket& recvData); - void HandleQueryQuestsCompleted(WorldPacket& recvData); - void HandleQuestPOIQuery(WorldPacket& recvData); - void HandleEjectPassenger(WorldPacket& data); - void HandleEnterPlayerVehicle(WorldPacket& data); - void HandleUpdateProjectilePosition(WorldPacket& recvPacket); - - // _loadPetFromDBFirstCallback helpers - //QueryCallback GetLoadPetFromDBFirstCallback() { return _loadPetFromDBFirstCallback; } - - uint32 _lastAuctionListItemsMSTime; - uint32 _lastAuctionListOwnerItemsMSTime; - - void HandleTeleportTimeout(bool updateInSessions); - bool HandleSocketClosed(); - void SetOfflineTime(uint32 time) { _offlineTime = time; } - uint32 GetOfflineTime() const { return _offlineTime; } - bool IsKicked() const { return _kicked; } - void SetKicked(bool val) { _kicked = val; } - void SetShouldSetOfflineInDB(bool val) { _shouldSetOfflineInDB = val; } - bool GetShouldSetOfflineInDB() const { return _shouldSetOfflineInDB; } + } + //auction + void SendAuctionHello(uint64 guid, Creature* unit); + void SendAuctionCommandResult(uint32 auctionId, uint32 Action, uint32 ErrorCode, uint32 bidError = 0); + void SendAuctionBidderNotification(uint32 location, uint32 auctionId, uint64 bidder, uint32 bidSum, uint32 diff, uint32 item_template); + void SendAuctionOwnerNotification(AuctionEntry* auction); + + //Item Enchantment + void SendEnchantmentLog(uint64 target, uint64 caster, uint32 itemId, uint32 enchantId); + void SendItemEnchantTimeUpdate(uint64 Playerguid, uint64 Itemguid, uint32 slot, uint32 Duration); + + //Taxi + void SendTaxiStatus(uint64 guid); + void SendTaxiMenu(Creature* unit); + void SendDoFlight(uint32 mountDisplayId, uint32 path, uint32 pathNode = 0); + bool SendLearnNewTaxiNode(Creature* unit); + void SendDiscoverNewTaxiNode(uint32 nodeid); + + // Guild/Arena Team + void SendArenaTeamCommandResult(uint32 team_action, std::string const& team, std::string const& player, uint32 error_id = 0); + void SendNotInArenaTeamPacket(uint8 type); + void SendPetitionShowList(uint64 guid); + + void BuildPartyMemberStatsChangedPacket(Player* player, WorldPacket* data); + + void DoLootRelease(uint64 lguid); + + // Account mute time + time_t m_muteTime; + + // Locales + LocaleConstant GetSessionDbcLocale() const { return m_sessionDbcLocale; } + LocaleConstant GetSessionDbLocaleIndex() const { return m_sessionDbLocaleIndex; } + char const* GetAcoreString(uint32 entry) const; + + uint32 GetLatency() const { return m_latency; } + void SetLatency(uint32 latency) { m_latency = latency; } + void ResetClientTimeDelay() { m_clientTimeDelay = 0; } + + std::atomic m_timeOutTime; + void UpdateTimeOutTime(uint32 diff) + { + if (time_t(diff) > m_timeOutTime) + m_timeOutTime = 0; + else + m_timeOutTime -= diff; + } + void ResetTimeOutTime(bool onlyActive) + { + if (GetPlayer()) + m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME_ACTIVE)); + else if (!onlyActive) + m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME)); + } + bool IsConnectionIdle() const + { + return (m_timeOutTime <= 0 && !m_inQueue); + } + + // Recruit-A-Friend Handling + uint32 GetRecruiterId() const { return recruiterId; } + bool IsARecruiter() const { return isRecruiter; } + + // Packets cooldown + time_t GetCalendarEventCreationCooldown() const { return _calendarEventCreationCooldown; } + void SetCalendarEventCreationCooldown(time_t cooldown) { _calendarEventCreationCooldown = cooldown; } + +public: // opcodes handlers + + void Handle_NULL(WorldPacket& recvPacket); // not used + void Handle_EarlyProccess(WorldPacket& recvPacket); // just mark packets processed in WorldSocket::OnRead + void Handle_ServerSide(WorldPacket& recvPacket); // sever side only, can't be accepted from client + void Handle_Deprecated(WorldPacket& recvPacket); // never used anymore by client + + void HandleCharEnumOpcode(WorldPacket& recvPacket); + void HandleCharDeleteOpcode(WorldPacket& recvPacket); + void HandleCharCreateOpcode(WorldPacket& recvPacket); + void HandleCharCreateCallback(PreparedQueryResult result, CharacterCreateInfo* createInfo); + void HandlePlayerLoginOpcode(WorldPacket& recvPacket); + void HandleCharEnum(PreparedQueryResult result); + void HandlePlayerLoginFromDB(LoginQueryHolder* holder); + void HandlePlayerLoginToCharInWorld(Player* pCurrChar); + void HandlePlayerLoginToCharOutOfWorld(Player* pCurrChar); + void HandleCharFactionOrRaceChange(WorldPacket& recvData); + + // played time + void HandlePlayedTime(WorldPacket& recvPacket); + + // new + void HandleMoveUnRootAck(WorldPacket& recvPacket); + void HandleMoveRootAck(WorldPacket& recvPacket); + + // new inspect + void HandleInspectOpcode(WorldPacket& recvPacket); + + // new party stats + void HandleInspectHonorStatsOpcode(WorldPacket& recvPacket); + + void HandleMoveWaterWalkAck(WorldPacket& recvPacket); + void HandleFeatherFallAck(WorldPacket& recvData); + + void HandleMoveHoverAck(WorldPacket& recvData); + + void HandleMountSpecialAnimOpcode(WorldPacket& recvdata); + + // character view + void HandleShowingHelmOpcode(WorldPacket& recvData); + void HandleShowingCloakOpcode(WorldPacket& recvData); + + // repair + void HandleRepairItemOpcode(WorldPacket& recvPacket); + + // Knockback + void HandleMoveKnockBackAck(WorldPacket& recvPacket); + + void HandleMoveTeleportAck(WorldPacket& recvPacket); + void HandleForceSpeedChangeAck(WorldPacket& recvData); + + void HandleRepopRequestOpcode(WorldPacket& recvPacket); + void HandleAutostoreLootItemOpcode(WorldPacket& recvPacket); + void HandleLootMoneyOpcode(WorldPacket& recvPacket); + void HandleLootOpcode(WorldPacket& recvPacket); + void HandleLootReleaseOpcode(WorldPacket& recvPacket); + void HandleLootMasterGiveOpcode(WorldPacket& recvPacket); + void HandleWhoOpcode(WorldPacket& recvPacket); + void HandleLogoutRequestOpcode(WorldPacket& recvPacket); + void HandlePlayerLogoutOpcode(WorldPacket& recvPacket); + void HandleLogoutCancelOpcode(WorldPacket& recvPacket); + + // GM Ticket opcodes + void HandleGMTicketCreateOpcode(WorldPacket& recvPacket); + void HandleGMTicketUpdateOpcode(WorldPacket& recvPacket); + void HandleGMTicketDeleteOpcode(WorldPacket& recvPacket); + void HandleGMTicketGetTicketOpcode(WorldPacket& recvPacket); + void HandleGMTicketSystemStatusOpcode(WorldPacket& recvPacket); + void HandleGMSurveySubmit(WorldPacket& recvPacket); + void HandleReportLag(WorldPacket& recvPacket); + void HandleGMResponseResolve(WorldPacket& recvPacket); + + void HandleTogglePvP(WorldPacket& recvPacket); + + void HandleZoneUpdateOpcode(WorldPacket& recvPacket); + void HandleSetSelectionOpcode(WorldPacket& recvPacket); + void HandleStandStateChangeOpcode(WorldPacket& recvPacket); + void HandleEmoteOpcode(WorldPacket& recvPacket); + void HandleContactListOpcode(WorldPacket& recvPacket); + void HandleAddFriendOpcode(WorldPacket& recvPacket); + void HandleDelFriendOpcode(WorldPacket& recvPacket); + void HandleAddIgnoreOpcode(WorldPacket& recvPacket); + void HandleDelIgnoreOpcode(WorldPacket& recvPacket); + void HandleSetContactNotesOpcode(WorldPacket& recvPacket); + void HandleBugOpcode(WorldPacket& recvPacket); + void HandleSetAmmoOpcode(WorldPacket& recvPacket); + void HandleItemNameQueryOpcode(WorldPacket& recvPacket); + + void HandleAreaTriggerOpcode(WorldPacket& recvPacket); + + void HandleSetFactionAtWar(WorldPacket& recvData); + void HandleSetFactionCheat(WorldPacket& recvData); + void HandleSetWatchedFactionOpcode(WorldPacket& recvData); + void HandleSetFactionInactiveOpcode(WorldPacket& recvData); + + void HandleUpdateAccountData(WorldPacket& recvPacket); + void HandleRequestAccountData(WorldPacket& recvPacket); + void HandleSetActionButtonOpcode(WorldPacket& recvPacket); + + void HandleGameObjectUseOpcode(WorldPacket& recPacket); + void HandleGameobjectReportUse(WorldPacket& recvPacket); + + void HandleNameQueryOpcode(WorldPacket& recvPacket); + + void HandleQueryTimeOpcode(WorldPacket& recvPacket); + + void HandleCreatureQueryOpcode(WorldPacket& recvPacket); + + void HandleGameObjectQueryOpcode(WorldPacket& recvPacket); + + void HandleMoveWorldportAckOpcode(WorldPacket& recvPacket); + void HandleMoveWorldportAckOpcode(); // for server-side calls + + void HandleMovementOpcodes(WorldPacket& recvPacket); + void HandleSetActiveMoverOpcode(WorldPacket& recvData); + void HandleMoveNotActiveMover(WorldPacket& recvData); + void HandleDismissControlledVehicle(WorldPacket& recvData); + void HandleRequestVehicleExit(WorldPacket& recvData); + void HandleChangeSeatsOnControlledVehicle(WorldPacket& recvData); + void HandleMoveTimeSkippedOpcode(WorldPacket& recvData); + + void HandleRequestRaidInfoOpcode(WorldPacket& recvData); + + void HandleBattlefieldStatusOpcode(WorldPacket& recvData); + + void HandleGroupInviteOpcode(WorldPacket& recvPacket); + void HandleGroupAcceptOpcode(WorldPacket& recvPacket); + void HandleGroupDeclineOpcode(WorldPacket& recvPacket); + void HandleGroupUninviteOpcode(WorldPacket& recvPacket); + void HandleGroupUninviteGuidOpcode(WorldPacket& recvPacket); + void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket); + void HandleGroupDisbandOpcode(WorldPacket& recvPacket); + void HandleOptOutOfLootOpcode(WorldPacket& recvData); + void HandleLootMethodOpcode(WorldPacket& recvPacket); + void HandleLootRoll(WorldPacket& recvData); + void HandleRequestPartyMemberStatsOpcode(WorldPacket& recvData); + void HandleRaidTargetUpdateOpcode(WorldPacket& recvData); + void HandleRaidReadyCheckOpcode(WorldPacket& recvData); + void HandleRaidReadyCheckFinishedOpcode(WorldPacket& recvData); + void HandleGroupRaidConvertOpcode(WorldPacket& recvData); + void HandleGroupChangeSubGroupOpcode(WorldPacket& recvData); + void HandleGroupAssistantLeaderOpcode(WorldPacket& recvData); + void HandlePartyAssignmentOpcode(WorldPacket& recvData); + + void HandlePetitionBuyOpcode(WorldPacket& recvData); + void HandlePetitionShowSignOpcode(WorldPacket& recvData); + void HandlePetitionQueryOpcode(WorldPacket& recvData); + void HandlePetitionRenameOpcode(WorldPacket& recvData); + void HandlePetitionSignOpcode(WorldPacket& recvData); + void HandlePetitionDeclineOpcode(WorldPacket& recvData); + void HandleOfferPetitionOpcode(WorldPacket& recvData); + void HandleTurnInPetitionOpcode(WorldPacket& recvData); + + void HandleGuildQueryOpcode(WorldPacket& recvPacket); + void HandleGuildCreateOpcode(WorldPacket& recvPacket); + void HandleGuildInviteOpcode(WorldPacket& recvPacket); + void HandleGuildRemoveOpcode(WorldPacket& recvPacket); + void HandleGuildAcceptOpcode(WorldPacket& recvPacket); + void HandleGuildDeclineOpcode(WorldPacket& recvPacket); + void HandleGuildInfoOpcode(WorldPacket& recvPacket); + void HandleGuildEventLogQueryOpcode(WorldPacket& recvPacket); + void HandleGuildRosterOpcode(WorldPacket& recvPacket); + void HandleGuildPromoteOpcode(WorldPacket& recvPacket); + void HandleGuildDemoteOpcode(WorldPacket& recvPacket); + void HandleGuildLeaveOpcode(WorldPacket& recvPacket); + void HandleGuildDisbandOpcode(WorldPacket& recvPacket); + void HandleGuildLeaderOpcode(WorldPacket& recvPacket); + void HandleGuildMOTDOpcode(WorldPacket& recvPacket); + void HandleGuildSetPublicNoteOpcode(WorldPacket& recvPacket); + void HandleGuildSetOfficerNoteOpcode(WorldPacket& recvPacket); + void HandleGuildRankOpcode(WorldPacket& recvPacket); + void HandleGuildAddRankOpcode(WorldPacket& recvPacket); + void HandleGuildDelRankOpcode(WorldPacket& recvPacket); + void HandleGuildChangeInfoTextOpcode(WorldPacket& recvPacket); + void HandleSaveGuildEmblemOpcode(WorldPacket& recvPacket); + + void HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvPacket); + void HandleTaxiQueryAvailableNodes(WorldPacket& recvPacket); + void HandleActivateTaxiOpcode(WorldPacket& recvPacket); + void HandleActivateTaxiExpressOpcode(WorldPacket& recvPacket); + void HandleMoveSplineDoneOpcode(WorldPacket& recvPacket); + void SendActivateTaxiReply(ActivateTaxiReply reply); + + void HandleTabardVendorActivateOpcode(WorldPacket& recvPacket); + void HandleBankerActivateOpcode(WorldPacket& recvPacket); + void HandleBuyBankSlotOpcode(WorldPacket& recvPacket); + void HandleTrainerListOpcode(WorldPacket& recvPacket); + void HandleTrainerBuySpellOpcode(WorldPacket& recvPacket); + void HandlePetitionShowListOpcode(WorldPacket& recvPacket); + void HandleGossipHelloOpcode(WorldPacket& recvPacket); + void HandleGossipSelectOptionOpcode(WorldPacket& recvPacket); + void HandleSpiritHealerActivateOpcode(WorldPacket& recvPacket); + void HandleNpcTextQueryOpcode(WorldPacket& recvPacket); + void HandleBinderActivateOpcode(WorldPacket& recvPacket); + void HandleListStabledPetsOpcode(WorldPacket& recvPacket); + void HandleStablePet(WorldPacket& recvPacket); + void HandleStablePetCallback(PreparedQueryResult result); + void HandleUnstablePet(WorldPacket& recvPacket); + void HandleUnstablePetCallback(PreparedQueryResult result, uint32 petId); + void HandleBuyStableSlot(WorldPacket& recvPacket); + void HandleStableRevivePet(WorldPacket& recvPacket); + void HandleStableSwapPet(WorldPacket& recvPacket); + void HandleStableSwapPetCallback(PreparedQueryResult result, uint32 petId); + void HandleOpenWrappedItemCallback(PreparedQueryResult result, uint8 bagIndex, uint8 slot, uint32 itemLowGUID); + void HandleLoadActionsSwitchSpec(PreparedQueryResult result); + void HandleCharacterAuraFrozen(PreparedQueryResult result); + uint8 HandleLoadPetFromDBFirstCallback(PreparedQueryResult result, uint8 asynchLoadType); + void HandleLoadPetFromDBSecondCallback(LoadPetFromDBQueryHolder* holder); + + void HandleDuelAcceptedOpcode(WorldPacket& recvPacket); + void HandleDuelCancelledOpcode(WorldPacket& recvPacket); + + void HandleAcceptTradeOpcode(WorldPacket& recvPacket); + void HandleBeginTradeOpcode(WorldPacket& recvPacket); + void HandleBusyTradeOpcode(WorldPacket& recvPacket); + void HandleCancelTradeOpcode(WorldPacket& recvPacket); + void HandleClearTradeItemOpcode(WorldPacket& recvPacket); + void HandleIgnoreTradeOpcode(WorldPacket& recvPacket); + void HandleInitiateTradeOpcode(WorldPacket& recvPacket); + void HandleSetTradeGoldOpcode(WorldPacket& recvPacket); + void HandleSetTradeItemOpcode(WorldPacket& recvPacket); + void HandleUnacceptTradeOpcode(WorldPacket& recvPacket); + + void HandleAuctionHelloOpcode(WorldPacket& recvPacket); + void HandleAuctionListItems(WorldPacket& recvData); + void HandleAuctionListBidderItems(WorldPacket& recvData); + void HandleAuctionSellItem(WorldPacket& recvData); + void HandleAuctionRemoveItem(WorldPacket& recvData); + void HandleAuctionListOwnerItems(WorldPacket& recvData); + void HandleAuctionListOwnerItemsEvent(uint64 creatureGuid); + void HandleAuctionPlaceBid(WorldPacket& recvData); + void HandleAuctionListPendingSales(WorldPacket& recvData); + + void HandleGetMailList(WorldPacket& recvData); + void HandleSendMail(WorldPacket& recvData); + void HandleMailTakeMoney(WorldPacket& recvData); + void HandleMailTakeItem(WorldPacket& recvData); + void HandleMailMarkAsRead(WorldPacket& recvData); + void HandleMailReturnToSender(WorldPacket& recvData); + void HandleMailDelete(WorldPacket& recvData); + void HandleItemTextQuery(WorldPacket& recvData); + void HandleMailCreateTextItem(WorldPacket& recvData); + void HandleQueryNextMailTime(WorldPacket& recvData); + void HandleCancelChanneling(WorldPacket& recvData); + + void HandleSplitItemOpcode(WorldPacket& recvPacket); + void HandleSwapInvItemOpcode(WorldPacket& recvPacket); + void HandleDestroyItemOpcode(WorldPacket& recvPacket); + void HandleAutoEquipItemOpcode(WorldPacket& recvPacket); + void HandleItemQuerySingleOpcode(WorldPacket& recvPacket); + void HandleSellItemOpcode(WorldPacket& recvPacket); + void HandleBuyItemInSlotOpcode(WorldPacket& recvPacket); + void HandleBuyItemOpcode(WorldPacket& recvPacket); + void HandleListInventoryOpcode(WorldPacket& recvPacket); + void HandleAutoStoreBagItemOpcode(WorldPacket& recvPacket); + void HandleReadItem(WorldPacket& recvPacket); + void HandleAutoEquipItemSlotOpcode(WorldPacket& recvPacket); + void HandleSwapItem(WorldPacket& recvPacket); + void HandleBuybackItem(WorldPacket& recvPacket); + void HandleAutoBankItemOpcode(WorldPacket& recvPacket); + void HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket); + void HandleWrapItemOpcode(WorldPacket& recvPacket); + + void HandleAttackSwingOpcode(WorldPacket& recvPacket); + void HandleAttackStopOpcode(WorldPacket& recvPacket); + void HandleSetSheathedOpcode(WorldPacket& recvPacket); + + void HandleUseItemOpcode(WorldPacket& recvPacket); + void HandleOpenItemOpcode(WorldPacket& recvPacket); + void HandleCastSpellOpcode(WorldPacket& recvPacket); + void HandleCancelCastOpcode(WorldPacket& recvPacket); + void HandleCancelAuraOpcode(WorldPacket& recvPacket); + void HandleCancelGrowthAuraOpcode(WorldPacket& recvPacket); + void HandleCancelAutoRepeatSpellOpcode(WorldPacket& recvPacket); + + void HandleLearnTalentOpcode(WorldPacket& recvPacket); + void HandleLearnPreviewTalents(WorldPacket& recvPacket); + void HandleTalentWipeConfirmOpcode(WorldPacket& recvPacket); + void HandleUnlearnSkillOpcode(WorldPacket& recvPacket); + + void HandleQuestgiverStatusQueryOpcode(WorldPacket& recvPacket); + void HandleQuestgiverStatusMultipleQuery(WorldPacket& recvPacket); + void HandleQuestgiverHelloOpcode(WorldPacket& recvPacket); + void HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvPacket); + void HandleQuestgiverQueryQuestOpcode(WorldPacket& recvPacket); + void HandleQuestgiverChooseRewardOpcode(WorldPacket& recvPacket); + void HandleQuestgiverRequestRewardOpcode(WorldPacket& recvPacket); + void HandleQuestQueryOpcode(WorldPacket& recvPacket); + void HandleQuestgiverCancel(WorldPacket& recvData); + void HandleQuestLogSwapQuest(WorldPacket& recvData); + void HandleQuestLogRemoveQuest(WorldPacket& recvData); + void HandleQuestConfirmAccept(WorldPacket& recvData); + void HandleQuestgiverCompleteQuest(WorldPacket& recvData); + void HandleQuestgiverQuestAutoLaunch(WorldPacket& recvPacket); + void HandlePushQuestToParty(WorldPacket& recvPacket); + void HandleQuestPushResult(WorldPacket& recvPacket); + + void HandleMessagechatOpcode(WorldPacket& recvPacket); + void SendPlayerNotFoundNotice(std::string const& name); + void SendPlayerAmbiguousNotice(std::string const& name); + void SendWrongFactionNotice(); + void SendChatRestrictedNotice(ChatRestrictionType restriction); + void HandleTextEmoteOpcode(WorldPacket& recvPacket); + void HandleChatIgnoredOpcode(WorldPacket& recvPacket); + + void HandleReclaimCorpseOpcode(WorldPacket& recvPacket); + void HandleCorpseQueryOpcode(WorldPacket& recvPacket); + void HandleCorpseMapPositionQuery(WorldPacket& recvPacket); + void HandleResurrectResponseOpcode(WorldPacket& recvPacket); + void HandleSummonResponseOpcode(WorldPacket& recvData); + + void HandleJoinChannel(WorldPacket& recvPacket); + void HandleLeaveChannel(WorldPacket& recvPacket); + void HandleChannelList(WorldPacket& recvPacket); + void HandleChannelPassword(WorldPacket& recvPacket); + void HandleChannelSetOwner(WorldPacket& recvPacket); + void HandleChannelOwner(WorldPacket& recvPacket); + void HandleChannelModerator(WorldPacket& recvPacket); + void HandleChannelUnmoderator(WorldPacket& recvPacket); + void HandleChannelMute(WorldPacket& recvPacket); + void HandleChannelUnmute(WorldPacket& recvPacket); + void HandleChannelInvite(WorldPacket& recvPacket); + void HandleChannelKick(WorldPacket& recvPacket); + void HandleChannelBan(WorldPacket& recvPacket); + void HandleChannelUnban(WorldPacket& recvPacket); + void HandleChannelAnnouncements(WorldPacket& recvPacket); + void HandleChannelDeclineInvite(WorldPacket& recvPacket); + void HandleChannelDisplayListQuery(WorldPacket& recvPacket); + void HandleGetChannelMemberCount(WorldPacket& recvPacket); + void HandleSetChannelWatch(WorldPacket& recvPacket); + void HandleClearChannelWatch(WorldPacket& recvPacket); + + void HandleCompleteCinematic(WorldPacket& recvPacket); + void HandleNextCinematicCamera(WorldPacket& recvPacket); + + void HandlePageTextQueryOpcode(WorldPacket& recvPacket); + + void HandleTutorialFlag (WorldPacket& recvData); + void HandleTutorialClear(WorldPacket& recvData); + void HandleTutorialReset(WorldPacket& recvData); + + //Pet + void HandlePetAction(WorldPacket& recvData); + void HandlePetStopAttack(WorldPacket& recvData); + void HandlePetActionHelper(Unit* pet, uint64 guid1, uint16 spellid, uint16 flag, uint64 guid2); + void HandlePetNameQuery(WorldPacket& recvData); + void HandlePetSetAction(WorldPacket& recvData); + void HandlePetAbandon(WorldPacket& recvData); + void HandlePetRename(WorldPacket& recvData); + void HandlePetCancelAuraOpcode(WorldPacket& recvPacket); + void HandlePetSpellAutocastOpcode(WorldPacket& recvPacket); + void HandlePetCastSpellOpcode(WorldPacket& recvPacket); + void HandlePetLearnTalent(WorldPacket& recvPacket); + void HandleLearnPreviewTalentsPet(WorldPacket& recvPacket); + + void HandleSetActionBarToggles(WorldPacket& recvData); + + void HandleCharRenameOpcode(WorldPacket& recvData); + void HandleChangePlayerNameOpcodeCallBack(PreparedQueryResult result, std::string const& newName); + void HandleSetPlayerDeclinedNames(WorldPacket& recvData); + + void HandleTotemDestroyed(WorldPacket& recvData); + void HandleDismissCritter(WorldPacket& recvData); + + //Battleground + void HandleBattlemasterHelloOpcode(WorldPacket& recvData); + void HandleBattlemasterJoinOpcode(WorldPacket& recvData); + void HandleBattlegroundPlayerPositionsOpcode(WorldPacket& recvData); + void HandlePVPLogDataOpcode(WorldPacket& recvData); + void HandleBattleFieldPortOpcode(WorldPacket& recvData); + void HandleBattlefieldListOpcode(WorldPacket& recvData); + void HandleBattlefieldLeaveOpcode(WorldPacket& recvData); + void HandleBattlemasterJoinArena(WorldPacket& recvData); + void HandleReportPvPAFK(WorldPacket& recvData); + + void HandleWardenDataOpcode(WorldPacket& recvData); + void HandleWorldTeleportOpcode(WorldPacket& recvData); + void HandleMinimapPingOpcode(WorldPacket& recvData); + void HandleRandomRollOpcode(WorldPacket& recvData); + void HandleFarSightOpcode(WorldPacket& recvData); + void HandleSetDungeonDifficultyOpcode(WorldPacket& recvData); + void HandleSetRaidDifficultyOpcode(WorldPacket& recvData); + void HandleMoveSetCanFlyAckOpcode(WorldPacket& recvData); + void HandleSetTitleOpcode(WorldPacket& recvData); + void HandleRealmSplitOpcode(WorldPacket& recvData); + void HandleTimeSyncResp(WorldPacket& recvData); + void HandleWhoisOpcode(WorldPacket& recvData); + void HandleResetInstancesOpcode(WorldPacket& recvData); + void HandleHearthAndResurrect(WorldPacket& recvData); + void HandleInstanceLockResponse(WorldPacket& recvPacket); + void HandleUpdateMissileTrajectory(WorldPacket& recvPacket); + + // Battlefield + void SendBfInvitePlayerToWar(uint32 battleId, uint32 zoneId, uint32 time); + void SendBfInvitePlayerToQueue(uint32 battleId); + void SendBfQueueInviteResponse(uint32 battleId, uint32 zoneId, bool canQueue = true, bool full = false); + void SendBfEntered(uint32 battleId); + void SendBfLeaveMessage(uint32 battleId, BFLeaveReason reason = BF_LEAVE_REASON_EXITED); + void HandleBfQueueInviteResponse(WorldPacket& recvData); + void HandleBfEntryInviteResponse(WorldPacket& recvData); + void HandleBfExitRequest(WorldPacket& recvData); + + // Looking for Dungeon/Raid + void HandleLfgSetCommentOpcode(WorldPacket& recvData); + void HandleLfgPlayerLockInfoRequestOpcode(WorldPacket& recvData); + void HandleLfgPartyLockInfoRequestOpcode(WorldPacket& recvData); + void HandleLfgJoinOpcode(WorldPacket& recvData); + void HandleLfgLeaveOpcode(WorldPacket& recvData); + void HandleLfgSetRolesOpcode(WorldPacket& recvData); + void HandleLfgProposalResultOpcode(WorldPacket& recvData); + void HandleLfgSetBootVoteOpcode(WorldPacket& recvData); + void HandleLfgTeleportOpcode(WorldPacket& recvData); + void HandleLfrSearchJoinOpcode(WorldPacket& recvData); + void HandleLfrSearchLeaveOpcode(WorldPacket& recvData); + void HandleLfgGetStatus(WorldPacket& recvData); + + void SendLfgUpdatePlayer(lfg::LfgUpdateData const& updateData); + void SendLfgUpdateParty(lfg::LfgUpdateData const& updateData); + void SendLfgRoleChosen(uint64 guid, uint8 roles); + void SendLfgRoleCheckUpdate(lfg::LfgRoleCheck const& pRoleCheck); + void SendLfgLfrList(bool update); + void SendLfgJoinResult(lfg::LfgJoinResultData const& joinData); + void SendLfgQueueStatus(lfg::LfgQueueStatusData const& queueData); + void SendLfgPlayerReward(lfg::LfgPlayerRewardData const& lfgPlayerRewardData); + void SendLfgBootProposalUpdate(lfg::LfgPlayerBoot const& boot); + void SendLfgUpdateProposal(lfg::LfgProposal const& proposal); + void SendLfgDisabled(); + void SendLfgOfferContinue(uint32 dungeonEntry); + void SendLfgTeleportError(uint8 err); + + // Arena Team + void HandleInspectArenaTeamsOpcode(WorldPacket& recvData); + void HandleArenaTeamQueryOpcode(WorldPacket& recvData); + void HandleArenaTeamRosterOpcode(WorldPacket& recvData); + void HandleArenaTeamInviteOpcode(WorldPacket& recvData); + void HandleArenaTeamAcceptOpcode(WorldPacket& recvData); + void HandleArenaTeamDeclineOpcode(WorldPacket& recvData); + void HandleArenaTeamLeaveOpcode(WorldPacket& recvData); + void HandleArenaTeamRemoveOpcode(WorldPacket& recvData); + void HandleArenaTeamDisbandOpcode(WorldPacket& recvData); + void HandleArenaTeamLeaderOpcode(WorldPacket& recvData); + + void HandleAreaSpiritHealerQueryOpcode(WorldPacket& recvData); + void HandleAreaSpiritHealerQueueOpcode(WorldPacket& recvData); + void HandleCancelMountAuraOpcode(WorldPacket& recvData); + void HandleSelfResOpcode(WorldPacket& recvData); + void HandleComplainOpcode(WorldPacket& recvData); + void HandleRequestPetInfoOpcode(WorldPacket& recvData); + + // Socket gem + void HandleSocketOpcode(WorldPacket& recvData); + + void HandleCancelTempEnchantmentOpcode(WorldPacket& recvData); + + void HandleItemRefundInfoRequest(WorldPacket& recvData); + void HandleItemRefund(WorldPacket& recvData); + + void HandleChannelVoiceOnOpcode(WorldPacket& recvData); + void HandleVoiceSessionEnableOpcode(WorldPacket& recvData); + void HandleSetActiveVoiceChannel(WorldPacket& recvData); + void HandleSetTaxiBenchmarkOpcode(WorldPacket& recvData); + + // Guild Bank + void HandleGuildPermissions(WorldPacket& recvData); + void HandleGuildBankMoneyWithdrawn(WorldPacket& recvData); + void HandleGuildBankerActivate(WorldPacket& recvData); + void HandleGuildBankQueryTab(WorldPacket& recvData); + void HandleGuildBankLogQuery(WorldPacket& recvData); + void HandleGuildBankDepositMoney(WorldPacket& recvData); + void HandleGuildBankWithdrawMoney(WorldPacket& recvData); + void HandleGuildBankSwapItems(WorldPacket& recvData); + + void HandleGuildBankUpdateTab(WorldPacket& recvData); + void HandleGuildBankBuyTab(WorldPacket& recvData); + void HandleQueryGuildBankTabText(WorldPacket& recvData); + void HandleSetGuildBankTabText(WorldPacket& recvData); + + // Refer-a-Friend + void HandleGrantLevel(WorldPacket& recvData); + void HandleAcceptGrantLevel(WorldPacket& recvData); + + // Calendar + void HandleCalendarGetCalendar(WorldPacket& recvData); + void HandleCalendarGetEvent(WorldPacket& recvData); + void HandleCalendarGuildFilter(WorldPacket& recvData); + void HandleCalendarArenaTeam(WorldPacket& recvData); + void HandleCalendarAddEvent(WorldPacket& recvData); + void HandleCalendarUpdateEvent(WorldPacket& recvData); + void HandleCalendarRemoveEvent(WorldPacket& recvData); + void HandleCalendarCopyEvent(WorldPacket& recvData); + void HandleCalendarEventInvite(WorldPacket& recvData); + void HandleCalendarEventRsvp(WorldPacket& recvData); + void HandleCalendarEventRemoveInvite(WorldPacket& recvData); + void HandleCalendarEventStatus(WorldPacket& recvData); + void HandleCalendarEventModeratorStatus(WorldPacket& recvData); + void HandleCalendarComplain(WorldPacket& recvData); + void HandleCalendarGetNumPending(WorldPacket& recvData); + void HandleCalendarEventSignup(WorldPacket& recvData); + + void SendCalendarRaidLockout(InstanceSave const* save, bool add); + void SendCalendarRaidLockoutUpdated(InstanceSave const* save, bool isExtended); + void HandleSetSavedInstanceExtend(WorldPacket& recvData); + + void HandleSpellClick(WorldPacket& recvData); + void HandleMirrorImageDataRequest(WorldPacket& recvData); + void HandleAlterAppearance(WorldPacket& recvData); + void HandleRemoveGlyph(WorldPacket& recvData); + void HandleCharCustomize(WorldPacket& recvData); + void HandleQueryInspectAchievements(WorldPacket& recvData); + void HandleEquipmentSetSave(WorldPacket& recvData); + void HandleEquipmentSetDelete(WorldPacket& recvData); + void HandleEquipmentSetUse(WorldPacket& recvData); + void HandleWorldStateUITimerUpdate(WorldPacket& recvData); + void HandleReadyForAccountDataTimes(WorldPacket& recvData); + void HandleQueryQuestsCompleted(WorldPacket& recvData); + void HandleQuestPOIQuery(WorldPacket& recvData); + void HandleEjectPassenger(WorldPacket& data); + void HandleEnterPlayerVehicle(WorldPacket& data); + void HandleUpdateProjectilePosition(WorldPacket& recvPacket); + + // _loadPetFromDBFirstCallback helpers + //QueryCallback GetLoadPetFromDBFirstCallback() { return _loadPetFromDBFirstCallback; } + + uint32 _lastAuctionListItemsMSTime; + uint32 _lastAuctionListOwnerItemsMSTime; + + void HandleTeleportTimeout(bool updateInSessions); + bool HandleSocketClosed(); + void SetOfflineTime(uint32 time) { _offlineTime = time; } + uint32 GetOfflineTime() const { return _offlineTime; } + bool IsKicked() const { return _kicked; } + void SetKicked(bool val) { _kicked = val; } + void SetShouldSetOfflineInDB(bool val) { _shouldSetOfflineInDB = val; } + bool GetShouldSetOfflineInDB() const { return _shouldSetOfflineInDB; } /*** CALLBACKS ***/ - private: - void InitializeQueryCallbackParameters(); - void ProcessQueryCallbacks(); - void ProcessQueryCallbackPlayer(); - void ProcessQueryCallbackPet(); - void ProcessQueryCallbackLogin(); +private: + void InitializeQueryCallbackParameters(); + void ProcessQueryCallbacks(); + void ProcessQueryCallbackPlayer(); + void ProcessQueryCallbackPet(); + void ProcessQueryCallbackLogin(); - PreparedQueryResultFuture _charEnumCallback; - PreparedQueryResultFuture _stablePetCallback; - QueryCallback _charRenameCallback; - QueryCallback _unstablePetCallback; - QueryCallback _stableSwapCallback; - QueryCallback _sendStabledPetCallback; - QueryCallback _charCreateCallback; + PreparedQueryResultFuture _charEnumCallback; + PreparedQueryResultFuture _stablePetCallback; + QueryCallback _charRenameCallback; + QueryCallback _unstablePetCallback; + QueryCallback _stableSwapCallback; + QueryCallback _sendStabledPetCallback; + QueryCallback _charCreateCallback; - QueryResultHolderFuture _charLoginCallback; + QueryResultHolderFuture _charLoginCallback; - QueryResultHolderFuture _loadPetFromDBSecondCallback; - QueryCallback_3 _openWrappedItemCallback; + QueryResultHolderFuture _loadPetFromDBSecondCallback; + QueryCallback_3 _openWrappedItemCallback; + friend class World; +protected: + class DosProtection + { friend class World; - protected: - class DosProtection - { - friend class World; - public: - DosProtection(WorldSession* s) : Session(s), _policy((Policy)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_POLICY)) { } - bool EvaluateOpcode(WorldPacket& p, time_t time) const; - protected: - enum Policy - { - POLICY_LOG, - POLICY_KICK, - POLICY_BAN - }; - - uint32 GetMaxPacketCounterAllowed(uint16 opcode) const; - - WorldSession* Session; - - private: - Policy _policy; - typedef std::unordered_map PacketThrottlingMap; - // mark this member as "mutable" so it can be modified even in const functions - mutable PacketThrottlingMap _PacketThrottlingMap; - - DosProtection(DosProtection const& right) = delete; - DosProtection& operator=(DosProtection const& right) = delete; - } AntiDOS; - public: - // xinef: those must be public, requires calls out of worldsession :( - QueryCallback_2 _loadPetFromDBFirstCallback; - PreparedQueryResultFuture _loadActionsSwitchSpecCallback; - PreparedQueryResultFuture _CharacterAuraFrozenCallback; + DosProtection(WorldSession* s) : Session(s), _policy((Policy)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_POLICY)) { } + bool EvaluateOpcode(WorldPacket& p, time_t time) const; + protected: + enum Policy + { + POLICY_LOG, + POLICY_KICK, + POLICY_BAN + }; + + uint32 GetMaxPacketCounterAllowed(uint16 opcode) const; + + WorldSession* Session; + + private: + Policy _policy; + typedef std::unordered_map PacketThrottlingMap; + // mark this member as "mutable" so it can be modified even in const functions + mutable PacketThrottlingMap _PacketThrottlingMap; + + DosProtection(DosProtection const& right) = delete; + DosProtection& operator=(DosProtection const& right) = delete; + } AntiDOS; + +public: + // xinef: those must be public, requires calls out of worldsession :( + QueryCallback_2 _loadPetFromDBFirstCallback; + PreparedQueryResultFuture _loadActionsSwitchSpecCallback; + PreparedQueryResultFuture _CharacterAuraFrozenCallback; /*** END OF CALLBACKS ***/ - private: - // private trade methods - void moveItems(Item* myItems[], Item* hisItems[]); +private: + // private trade methods + void moveItems(Item* myItems[], Item* hisItems[]); - bool CanUseBank(uint64 bankerGUID = 0) const; + bool CanUseBank(uint64 bankerGUID = 0) const; - bool recoveryItem(Item* pItem); + bool recoveryItem(Item* pItem); - // EnumData helpers - bool IsLegitCharacterForAccount(uint32 lowGUID) - { - return _legitCharacters.find(lowGUID) != _legitCharacters.end(); - } + // EnumData helpers + bool IsLegitCharacterForAccount(uint32 lowGUID) + { + return _legitCharacters.find(lowGUID) != _legitCharacters.end(); + } - // this stores the GUIDs of the characters who can login - // characters who failed on Player::BuildEnumData shouldn't login - std::set _legitCharacters; + // this stores the GUIDs of the characters who can login + // characters who failed on Player::BuildEnumData shouldn't login + std::set _legitCharacters; - uint32 m_GUIDLow; - Player* _player; - WorldSocket* m_Socket; - std::string m_Address; - // std::string m_LAddress; // Last Attempted Remote Adress - we can not set attempted ip for a non-existing session! + uint32 m_GUIDLow; + Player* _player; + WorldSocket* m_Socket; + std::string m_Address; + // std::string m_LAddress; // Last Attempted Remote Adress - we can not set attempted ip for a non-existing session! - AccountTypes _security; - bool _skipQueue; - uint32 _accountId; - uint8 m_expansion; - uint32 m_total_time; + AccountTypes _security; + bool _skipQueue; + uint32 _accountId; + uint8 m_expansion; + uint32 m_total_time; - typedef std::list AddonsList; + typedef std::list AddonsList; - // Warden - Warden* _warden; // Remains NULL if Warden system is not enabled by config + // Warden + Warden* _warden; // Remains NULL if Warden system is not enabled by config - time_t _logoutTime; - bool m_inQueue; // session wait in auth.queue - bool m_playerLoading; // code processed in LoginPlayer - bool m_playerLogout; // code processed in LogoutPlayer - bool m_playerSave; - LocaleConstant m_sessionDbcLocale; - LocaleConstant m_sessionDbLocaleIndex; - uint32 m_latency; - uint32 m_clientTimeDelay; - AccountData m_accountData[NUM_ACCOUNT_DATA_TYPES]; - uint32 m_Tutorials[MAX_ACCOUNT_TUTORIAL_VALUES]; - bool m_TutorialsChanged; - AddonsList m_addonsList; - uint32 recruiterId; - bool isRecruiter; - ACE_Based::LockedQueue _recvQueue; - uint32 m_currentVendorEntry; - uint64 m_currentBankerGUID; - time_t timeWhoCommandAllowed; - uint32 _offlineTime; - bool _kicked; - bool _shouldSetOfflineInDB; - // Packets cooldown - time_t _calendarEventCreationCooldown; + time_t _logoutTime; + bool m_inQueue; // session wait in auth.queue + bool m_playerLoading; // code processed in LoginPlayer + bool m_playerLogout; // code processed in LogoutPlayer + bool m_playerSave; + LocaleConstant m_sessionDbcLocale; + LocaleConstant m_sessionDbLocaleIndex; + uint32 m_latency; + uint32 m_clientTimeDelay; + AccountData m_accountData[NUM_ACCOUNT_DATA_TYPES]; + uint32 m_Tutorials[MAX_ACCOUNT_TUTORIAL_VALUES]; + bool m_TutorialsChanged; + AddonsList m_addonsList; + uint32 recruiterId; + bool isRecruiter; + ACE_Based::LockedQueue _recvQueue; + uint32 m_currentVendorEntry; + uint64 m_currentBankerGUID; + time_t timeWhoCommandAllowed; + uint32 _offlineTime; + bool _kicked; + bool _shouldSetOfflineInDB; + // Packets cooldown + time_t _calendarEventCreationCooldown; }; #endif /// @} diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index bd9eb2296..7557f7a97 100644 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -51,23 +51,23 @@ struct ServerPktHeader */ ServerPktHeader(uint32 size, uint16 cmd) : size(size) { - uint8 headerIndex=0; + uint8 headerIndex = 0; if (isLargePacket()) { sLog->outDebug(LOG_FILTER_NETWORKIO, "initializing large server to client packet. Size: %u, cmd: %u", size, cmd); - header[headerIndex++] = 0x80|(0xFF &(size>>16)); + header[headerIndex++] = 0x80 | (0xFF & (size >> 16)); } - header[headerIndex++] = 0xFF &(size>>8); - header[headerIndex++] = 0xFF &size; + header[headerIndex++] = 0xFF & (size >> 8); + header[headerIndex++] = 0xFF & size; header[headerIndex++] = 0xFF & cmd; - header[headerIndex++] = 0xFF & (cmd>>8); + header[headerIndex++] = 0xFF & (cmd >> 8); } uint8 getHeaderLength() { // cmd = 2 bytes, size= 2||3bytes - return 2+(isLargePacket()?3:2); + return 2 + (isLargePacket() ? 3 : 2); } bool isLargePacket() const @@ -92,15 +92,15 @@ struct ClientPktHeader #endif WorldSocket::WorldSocket(void): WorldHandler(), -m_LastPingTime(SystemTimePoint::min()), m_OverSpeedPings(0), m_Session(0), -m_RecvWPct(0), m_RecvPct(), m_Header(sizeof (ClientPktHeader)), -m_OutBuffer(0), m_OutBufferSize(65536), m_OutActive(false), -m_Seed(static_cast (rand32())) + m_LastPingTime(SystemTimePoint::min()), m_OverSpeedPings(0), m_Session(0), + m_RecvWPct(0), m_RecvPct(), m_Header(sizeof (ClientPktHeader)), + m_OutBuffer(0), m_OutBufferSize(65536), m_OutActive(false), + m_Seed(static_cast (rand32())) { reference_counting_policy().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED); - msg_queue()->high_water_mark(8*1024*1024); - msg_queue()->low_water_mark(8*1024*1024); + msg_queue()->high_water_mark(8 * 1024 * 1024); + msg_queue()->low_water_mark(8 * 1024 * 1024); } WorldSocket::~WorldSocket(void) @@ -158,7 +158,7 @@ int WorldSocket::SendPacket(WorldPacket const& pct) if (sPacketLog->CanLogPacket()) sPacketLog->LogPacket(pct, SERVER_TO_CLIENT); - ServerPktHeader header(pct.size()+2, pct.GetOpcode()); + ServerPktHeader header(pct.size() + 2, pct.GetOpcode()); m_Crypt.EncryptSend ((uint8*)header.header, header.getHeaderLength()); if (m_OutBuffer->space() >= pct.size() + header.getHeaderLength() && msg_queue()->is_empty()) @@ -204,7 +204,7 @@ long WorldSocket::RemoveReference(void) return static_cast (remove_reference()); } -int WorldSocket::open(void *a) +int WorldSocket::open(void* a) { ACE_UNUSED_ARG (a); @@ -282,29 +282,29 @@ int WorldSocket::handle_input(ACE_HANDLE) switch (handle_input_missing_data()) { case -1 : - { - if ((errno == EWOULDBLOCK) || - (errno == EAGAIN)) { - return Update(); // interesting line, isn't it ? + if ((errno == EWOULDBLOCK) || + (errno == EAGAIN)) + { + return Update(); // interesting line, isn't it ? + } + +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outStaticDebug("WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno)); +#endif + + errno = ECONNRESET; + return -1; } - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug("WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno)); -#endif - - errno = ECONNRESET; - return -1; - } case 0: - { + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug("WorldSocket::handle_input: Peer has closed connection"); + sLog->outStaticDebug("WorldSocket::handle_input: Peer has closed connection"); #endif - errno = ECONNRESET; - return -1; - } + errno = ECONNRESET; + return -1; + } case 1: return 1; default: @@ -533,12 +533,12 @@ int WorldSocket::handle_input_missing_data(void) char buf [4096]; ACE_Data_Block db (sizeof (buf), - ACE_Message_Block::MB_DATA, - buf, - 0, - 0, - ACE_Message_Block::DONT_DELETE, - 0); + ACE_Message_Block::MB_DATA, + buf, + 0, + 0, + ACE_Message_Block::DONT_DELETE, + 0); ACE_Message_Block message_block(&db, ACE_Message_Block::DONT_DELETE, @@ -547,7 +547,7 @@ int WorldSocket::handle_input_missing_data(void) const size_t recv_size = message_block.space(); const ssize_t n = peer().recv (message_block.wr_ptr(), - recv_size); + recv_size); if (n <= 0) return int(n); @@ -627,7 +627,7 @@ int WorldSocket::cancel_wakeup_output(GuardType& g) g.release(); if (reactor()->cancel_wakeup - (this, ACE_Event_Handler::WRITE_MASK) == -1) + (this, ACE_Event_Handler::WRITE_MASK) == -1) { // would be good to store errno from reactor with errno guard sLog->outError("WorldSocket::cancel_wakeup_output"); @@ -647,7 +647,7 @@ int WorldSocket::schedule_wakeup_output(GuardType& g) g.release(); if (reactor()->schedule_wakeup - (this, ACE_Event_Handler::WRITE_MASK) == -1) + (this, ACE_Event_Handler::WRITE_MASK) == -1) { sLog->outError("WorldSocket::schedule_wakeup_output"); return -1; @@ -677,15 +677,15 @@ int WorldSocket::ProcessIncoming(WorldPacket* new_pct) switch (opcode) { case CMSG_PING: - { - try { - return HandlePing(*new_pct); + try + { + return HandlePing(*new_pct); + } + catch (ByteBufferPositionException const&) {} + sLog->outError("WorldSocket::ReadDataHandler(): client sent malformed CMSG_PING"); + return -1; } - catch (ByteBufferPositionException const&) {} - sLog->outError("WorldSocket::ReadDataHandler(): client sent malformed CMSG_PING"); - return -1; - } case CMSG_AUTH_SESSION: if (m_Session) { @@ -693,36 +693,36 @@ int WorldSocket::ProcessIncoming(WorldPacket* new_pct) return -1; } return HandleAuthSession (*new_pct); - case CMSG_KEEP_ALIVE: + case CMSG_KEEP_ALIVE: if (m_Session) m_Session->ResetTimeOutTime(true); return 0; default: - { - ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1); - - if (m_Session != nullptr) { - // Our Idle timer will reset on any non PING opcodes. - // Catches people idling on the login screen and any lingering ingame connections. - m_Session->ResetTimeOutTime(false); + ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1); - // OK, give the packet to WorldSession - aptr.release(); - m_Session->QueuePacket (new_pct); - return 0; + if (m_Session != nullptr) + { + // Our Idle timer will reset on any non PING opcodes. + // Catches people idling on the login screen and any lingering ingame connections. + m_Session->ResetTimeOutTime(false); + + // OK, give the packet to WorldSession + aptr.release(); + m_Session->QueuePacket (new_pct); + return 0; + } + else + { + sLog->outError("WorldSocket::ProcessIncoming: Client not authed opcode = %u", uint32(opcode)); + return -1; + } } - else - { - sLog->outError("WorldSocket::ProcessIncoming: Client not authed opcode = %u", uint32(opcode)); - return -1; - } - } } } catch (ByteBufferException const&) { - sLog->outError("WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet (opcode: %u) from client %s, accountid=%i. Disconnected client.", opcode, GetRemoteAddress().c_str(), m_Session?m_Session->GetAccountId():-1); + sLog->outError("WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet (opcode: %u) from client %s, accountid=%i. Disconnected client.", opcode, GetRemoteAddress().c_str(), m_Session ? m_Session->GetAccountId() : -1); if (sLog->IsOutDebug()) { sLog->outDebug(LOG_FILTER_NETWORKIO, "Dumping error causing packet:"); @@ -940,9 +940,9 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket) uint32 seed = m_Seed; sha.UpdateData (account); - sha.UpdateData ((uint8 *) & t, 4); - sha.UpdateData ((uint8 *) & clientSeed, 4); - sha.UpdateData ((uint8 *) & seed, 4); + sha.UpdateData ((uint8*) & t, 4); + sha.UpdateData ((uint8*) & clientSeed, 4); + sha.UpdateData ((uint8*) & seed, 4); sha.UpdateBigNumbers (&k, nullptr); sha.Finalize(); @@ -959,8 +959,8 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outStaticDebug("WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.", - account.c_str(), - address.c_str()); + account.c_str(), + address.c_str()); #endif // Check if this user is by any chance a recruiter stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_RECRUITER); @@ -1005,7 +1005,7 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket) SendPacket(packet); sLog->outError("WorldSocket::HandleAuthSession: Client %s requested connecting with realm id %u but this realm has id %u set in config.", - address.c_str(), realm, realmID); + address.c_str(), realm, realmID); sScriptMgr->OnFailedAccountLogin(id); return -1; } @@ -1044,7 +1044,7 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket) else { auto now = std::chrono::system_clock::now(); - Seconds seconds = std::chrono::duration_cast(now - m_LastPingTime); + Seconds seconds = std::chrono::duration_cast(now - m_LastPingTime); m_LastPingTime = now; if (seconds.count() < 27) @@ -1061,10 +1061,10 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket) { Player* _player = m_Session->GetPlayer(); sLog->outError("WorldSocket::HandlePing: Player (account: %u, GUID: %u, name: %s) kicked for over-speed pings (address: %s)", - m_Session->GetAccountId(), - _player ? _player->GetGUIDLow() : 0, - _player ? _player->GetName().c_str() : "", - GetRemoteAddress().c_str()); + m_Session->GetAccountId(), + _player ? _player->GetGUIDLow() : 0, + _player ? _player->GetName().c_str() : "", + GetRemoteAddress().c_str()); return -1; } @@ -1086,10 +1086,10 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket) else { sLog->outError("WorldSocket::HandlePing: peer sent CMSG_PING, " - "but is not authenticated or got recently kicked, " - " address = %s", - GetRemoteAddress().c_str()); - return -1; + "but is not authenticated or got recently kicked, " + " address = %s", + GetRemoteAddress().c_str()); + return -1; } } diff --git a/src/server/game/Server/WorldSocket.h b/src/server/game/Server/WorldSocket.h index 5dfc0c099..368e8d99a 100644 --- a/src/server/game/Server/WorldSocket.h +++ b/src/server/game/Server/WorldSocket.h @@ -74,124 +74,124 @@ typedef ACE_Svc_Handler WorldHandler; */ class WorldSocket : public WorldHandler { - public: - WorldSocket (void); - virtual ~WorldSocket (void); +public: + WorldSocket (void); + virtual ~WorldSocket (void); - friend class WorldSocketMgr; + friend class WorldSocketMgr; - /// Mutex type used for various synchronizations. - typedef ACE_Thread_Mutex LockType; - typedef ACE_Guard GuardType; + /// Mutex type used for various synchronizations. + typedef ACE_Thread_Mutex LockType; + typedef ACE_Guard GuardType; - /// Check if socket is closed. - bool IsClosed (void) const; + /// Check if socket is closed. + bool IsClosed (void) const; - /// Close the socket. - void CloseSocket(std::string const& reason); + /// Close the socket. + void CloseSocket(std::string const& reason); - /// Get address of connected peer. - const std::string& GetRemoteAddress (void) const; + /// Get address of connected peer. + const std::string& GetRemoteAddress (void) const; - /// Send A packet on the socket, this function is reentrant. - /// @param pct packet to send - /// @return -1 of failure - int SendPacket(const WorldPacket& pct); + /// Send A packet on the socket, this function is reentrant. + /// @param pct packet to send + /// @return -1 of failure + int SendPacket(const WorldPacket& pct); - /// Add reference to this object. - long AddReference (void); + /// Add reference to this object. + long AddReference (void); - /// Remove reference to this object. - long RemoveReference (void); + /// Remove reference to this object. + long RemoveReference (void); - /// things called by ACE framework. + /// things called by ACE framework. - /// Called on open, the void* is the acceptor. - virtual int open (void *); + /// Called on open, the void* is the acceptor. + virtual int open (void*); - /// Called on failures inside of the acceptor, don't call from your code. - virtual int close (u_long); + /// Called on failures inside of the acceptor, don't call from your code. + virtual int close (u_long); - /// Called when we can read from the socket. - virtual int handle_input (ACE_HANDLE = ACE_INVALID_HANDLE); + /// Called when we can read from the socket. + virtual int handle_input (ACE_HANDLE = ACE_INVALID_HANDLE); - /// Called when the socket can write. - virtual int handle_output (ACE_HANDLE = ACE_INVALID_HANDLE); + /// Called when the socket can write. + virtual int handle_output (ACE_HANDLE = ACE_INVALID_HANDLE); - /// Called when connection is closed or error happens. - virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, - ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); + /// Called when connection is closed or error happens. + virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE, + ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); - /// Called by WorldSocketMgr/ReactorRunnable. - int Update (void); + /// Called by WorldSocketMgr/ReactorRunnable. + int Update (void); - private: - /// Helper functions for processing incoming data. - int handle_input_header (void); - int handle_input_payload (void); - int handle_input_missing_data (void); +private: + /// Helper functions for processing incoming data. + int handle_input_header (void); + int handle_input_payload (void); + int handle_input_missing_data (void); - /// Help functions to mark/unmark the socket for output. - /// @param g the guard is for m_OutBufferLock, the function will release it - int cancel_wakeup_output (GuardType& g); - int schedule_wakeup_output (GuardType& g); + /// Help functions to mark/unmark the socket for output. + /// @param g the guard is for m_OutBufferLock, the function will release it + int cancel_wakeup_output (GuardType& g); + int schedule_wakeup_output (GuardType& g); - /// Drain the queue if its not empty. - int handle_output_queue (GuardType& g); + /// Drain the queue if its not empty. + int handle_output_queue (GuardType& g); - /// process one incoming packet. - /// @param new_pct received packet, note that you need to delete it. - int ProcessIncoming (WorldPacket* new_pct); + /// process one incoming packet. + /// @param new_pct received packet, note that you need to delete it. + int ProcessIncoming (WorldPacket* new_pct); - /// Called by ProcessIncoming() on CMSG_AUTH_SESSION. - int HandleAuthSession (WorldPacket& recvPacket); + /// Called by ProcessIncoming() on CMSG_AUTH_SESSION. + int HandleAuthSession (WorldPacket& recvPacket); - /// Called by ProcessIncoming() on CMSG_PING. - int HandlePing (WorldPacket& recvPacket); + /// Called by ProcessIncoming() on CMSG_PING. + int HandlePing (WorldPacket& recvPacket); - private: - /// Time in which the last ping was received - SystemTimePoint m_LastPingTime; +private: + /// Time in which the last ping was received + SystemTimePoint m_LastPingTime; - /// Keep track of over-speed pings, to prevent ping flood. - uint32 m_OverSpeedPings; + /// Keep track of over-speed pings, to prevent ping flood. + uint32 m_OverSpeedPings; - /// Address of the remote peer - std::string m_Address; + /// Address of the remote peer + std::string m_Address; - /// Class used for managing encryption of the headers - AuthCrypt m_Crypt; + /// Class used for managing encryption of the headers + AuthCrypt m_Crypt; - /// Mutex lock to protect m_Session - LockType m_SessionLock; + /// Mutex lock to protect m_Session + LockType m_SessionLock; - /// Session to which received packets are routed - WorldSession* m_Session; + /// Session to which received packets are routed + WorldSession* m_Session; - /// here are stored the fragments of the received data - WorldPacket* m_RecvWPct; + /// here are stored the fragments of the received data + WorldPacket* m_RecvWPct; - /// This block actually refers to m_RecvWPct contents, - /// which allows easy and safe writing to it. - /// It wont free memory when its deleted. m_RecvWPct takes care of freeing. - ACE_Message_Block m_RecvPct; + /// This block actually refers to m_RecvWPct contents, + /// which allows easy and safe writing to it. + /// It wont free memory when its deleted. m_RecvWPct takes care of freeing. + ACE_Message_Block m_RecvPct; - /// Fragment of the received header. - ACE_Message_Block m_Header; + /// Fragment of the received header. + ACE_Message_Block m_Header; - /// Mutex for protecting output related data. - LockType m_OutBufferLock; + /// Mutex for protecting output related data. + LockType m_OutBufferLock; - /// Buffer used for writing output. - ACE_Message_Block* m_OutBuffer; + /// Buffer used for writing output. + ACE_Message_Block* m_OutBuffer; - /// Size of the m_OutBuffer. - size_t m_OutBufferSize; + /// Size of the m_OutBuffer. + size_t m_OutBufferSize; - /// True if the socket is registered with the reactor for output - bool m_OutActive; + /// True if the socket is registered with the reactor for output + bool m_OutActive; - uint32 m_Seed; + uint32 m_Seed; }; diff --git a/src/server/game/Server/WorldSocketMgr.cpp b/src/server/game/Server/WorldSocketMgr.cpp index 54a5643cc..7a97a0a12 100644 --- a/src/server/game/Server/WorldSocketMgr.cpp +++ b/src/server/game/Server/WorldSocketMgr.cpp @@ -42,166 +42,166 @@ */ class ReactorRunnable : protected ACE_Task_Base { - public: +public: - ReactorRunnable() : - m_Reactor(0), - m_Connections(0), - m_ThreadId(-1) + ReactorRunnable() : + m_Reactor(0), + m_Connections(0), + m_ThreadId(-1) + { + ACE_Reactor_Impl* imp; + +#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) + + imp = new ACE_Dev_Poll_Reactor(); + + imp->max_notify_iterations (128); + imp->restart (1); + +#else + + imp = new ACE_TP_Reactor(); + imp->max_notify_iterations (128); + +#endif + + m_Reactor = new ACE_Reactor (imp, 1); + } + + virtual ~ReactorRunnable() + { + Stop(); + Wait(); + + delete m_Reactor; + } + + void Stop() + { + m_Reactor->end_reactor_event_loop(); + } + + int Start() + { + if (m_ThreadId != -1) + return -1; + + return (m_ThreadId = activate()); + } + + void Wait() { ACE_Task_Base::wait(); } + + long Connections() + { + return m_Connections; + } + + int AddSocket (WorldSocket* sock) + { + ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock); + + ++m_Connections; + sock->AddReference(); + sock->reactor (m_Reactor); + m_NewSockets.insert (sock); + + sScriptMgr->OnSocketOpen(sock); + + return 0; + } + + ACE_Reactor* GetReactor() + { + return m_Reactor; + } + +protected: + + void AddNewSockets() + { + ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock); + + if (m_NewSockets.empty()) + return; + + for (SocketSet::const_iterator i = m_NewSockets.begin(); i != m_NewSockets.end(); ++i) { - ACE_Reactor_Impl* imp; + WorldSocket* sock = (*i); - #if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) - - imp = new ACE_Dev_Poll_Reactor(); - - imp->max_notify_iterations (128); - imp->restart (1); - - #else - - imp = new ACE_TP_Reactor(); - imp->max_notify_iterations (128); - - #endif - - m_Reactor = new ACE_Reactor (imp, 1); - } - - virtual ~ReactorRunnable() - { - Stop(); - Wait(); - - delete m_Reactor; - } - - void Stop() - { - m_Reactor->end_reactor_event_loop(); - } - - int Start() - { - if (m_ThreadId != -1) - return -1; - - return (m_ThreadId = activate()); - } - - void Wait() { ACE_Task_Base::wait(); } - - long Connections() - { - return m_Connections; - } - - int AddSocket (WorldSocket* sock) - { - ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock); - - ++m_Connections; - sock->AddReference(); - sock->reactor (m_Reactor); - m_NewSockets.insert (sock); - - sScriptMgr->OnSocketOpen(sock); - - return 0; - } - - ACE_Reactor* GetReactor() - { - return m_Reactor; - } - - protected: - - void AddNewSockets() - { - ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock); - - if (m_NewSockets.empty()) - return; - - for (SocketSet::const_iterator i = m_NewSockets.begin(); i != m_NewSockets.end(); ++i) + if (sock->IsClosed()) { - WorldSocket* sock = (*i); + sScriptMgr->OnSocketClose(sock, true); - if (sock->IsClosed()) + sock->RemoveReference(); + --m_Connections; + } + else + m_Sockets.insert (sock); + } + + m_NewSockets.clear(); + } + + virtual int svc() + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outStaticDebug ("Network Thread Starting"); +#endif + + ACE_ASSERT (m_Reactor); + + SocketSet::iterator i, t; + + while (!m_Reactor->reactor_event_loop_done()) + { + // dont be too smart to move this outside the loop + // the run_reactor_event_loop will modify interval + ACE_Time_Value interval (0, 10000); + + if (m_Reactor->run_reactor_event_loop (interval) == -1) + break; + + AddNewSockets(); + + for (i = m_Sockets.begin(); i != m_Sockets.end();) + { + if ((*i)->Update() == -1) { - sScriptMgr->OnSocketClose(sock, true); + t = i; + ++i; - sock->RemoveReference(); + (*t)->CloseSocket("svc()"); + + sScriptMgr->OnSocketClose((*t), false); + + (*t)->RemoveReference(); --m_Connections; + m_Sockets.erase (t); } else - m_Sockets.insert (sock); + ++i; } - - m_NewSockets.clear(); } - virtual int svc() - { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("Network Thread Starting"); + sLog->outStaticDebug ("Network Thread exits"); #endif - ACE_ASSERT (m_Reactor); + return 0; + } - SocketSet::iterator i, t; +private: + typedef std::atomic AtomicInt; + typedef std::set SocketSet; - while (!m_Reactor->reactor_event_loop_done()) - { - // dont be too smart to move this outside the loop - // the run_reactor_event_loop will modify interval - ACE_Time_Value interval (0, 10000); + ACE_Reactor* m_Reactor; + AtomicInt m_Connections; + int m_ThreadId; - if (m_Reactor->run_reactor_event_loop (interval) == -1) - break; + SocketSet m_Sockets; - AddNewSockets(); - - for (i = m_Sockets.begin(); i != m_Sockets.end();) - { - if ((*i)->Update() == -1) - { - t = i; - ++i; - - (*t)->CloseSocket("svc()"); - - sScriptMgr->OnSocketClose((*t), false); - - (*t)->RemoveReference(); - --m_Connections; - m_Sockets.erase (t); - } - else - ++i; - } - } - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outStaticDebug ("Network Thread exits"); -#endif - - return 0; - } - - private: - typedef std::atomic AtomicInt; - typedef std::set SocketSet; - - ACE_Reactor* m_Reactor; - AtomicInt m_Connections; - int m_ThreadId; - - SocketSet m_Sockets; - - SocketSet m_NewSockets; - ACE_Thread_Mutex m_NewSockets_Lock; + SocketSet m_NewSockets; + ACE_Thread_Mutex m_NewSockets_Lock; }; WorldSocketMgr::WorldSocketMgr() : @@ -322,9 +322,9 @@ WorldSocketMgr::OnSocketOpen (WorldSocket* sock) if (m_SockOutKBuff >= 0) { if (sock->peer().set_option (SOL_SOCKET, - SO_SNDBUF, - (void*) & m_SockOutKBuff, - sizeof (int)) == -1 && errno != ENOTSUP) + SO_SNDBUF, + (void*) & m_SockOutKBuff, + sizeof (int)) == -1 && errno != ENOTSUP) { sLog->outError("WorldSocketMgr::OnSocketOpen set_option SO_SNDBUF"); return -1; @@ -337,9 +337,9 @@ WorldSocketMgr::OnSocketOpen (WorldSocket* sock) if (m_UseNoDelay) { if (sock->peer().set_option (ACE_IPPROTO_TCP, - TCP_NODELAY, - (void*)&ndoption, - sizeof (int)) == -1) + TCP_NODELAY, + (void*)&ndoption, + sizeof (int)) == -1) { sLog->outError("WorldSocketMgr::OnSocketOpen: peer().set_option TCP_NODELAY errno = %s", ACE_OS::strerror (errno)); return -1; diff --git a/src/server/game/Server/WorldSocketMgr.h b/src/server/game/Server/WorldSocketMgr.h index 7d0ef78dc..d12309dc6 100644 --- a/src/server/game/Server/WorldSocketMgr.h +++ b/src/server/game/Server/WorldSocketMgr.h @@ -28,7 +28,7 @@ public: friend class WorldSocket; static WorldSocketMgr* instance(); - + /// Start network, listen at address:port . int StartNetwork(uint16 port, const char* address); diff --git a/src/server/game/Skills/SkillDiscovery.cpp b/src/server/game/Skills/SkillDiscovery.cpp index be85e4d63..cc271fe22 100644 --- a/src/server/game/Skills/SkillDiscovery.cpp +++ b/src/server/game/Skills/SkillDiscovery.cpp @@ -65,7 +65,7 @@ void LoadSkillDiscoveryTable() if (chance <= 0) // chance { ssNonDiscoverableEntries << "spellId = " << spellId << " reqSkillOrSpell = " << reqSkillOrSpell - << " reqSkillValue = " << reqSkillValue << " chance = " << chance << "(chance problem)\n"; + << " reqSkillValue = " << reqSkillValue << " chance = " << chance << "(chance problem)\n"; continue; } @@ -85,14 +85,14 @@ void LoadSkillDiscoveryTable() // mechanic discovery if (reqSpellInfo->Mechanic != MECHANIC_DISCOVERY && - // explicit discovery ability - !reqSpellInfo->IsExplicitDiscovery()) + // explicit discovery ability + !reqSpellInfo->IsExplicitDiscovery()) { if (reportedReqSpells.find(absReqSkillOrSpell) == reportedReqSpells.end()) { sLog->outErrorDb("Spell (ID: %u) not have MECHANIC_DISCOVERY (28) value in Mechanic field in spell.dbc" - " and not 100%% chance random discovery ability but listed for spellId %u (and maybe more) in `skill_discovery_template` table", - absReqSkillOrSpell, spellId); + " and not 100%% chance random discovery ability but listed for spellId %u (and maybe more) in `skill_discovery_template` table", + absReqSkillOrSpell, spellId); reportedReqSpells.insert(absReqSkillOrSpell); } continue; @@ -120,8 +120,7 @@ void LoadSkillDiscoveryTable() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); if (!ssNonDiscoverableEntries.str().empty()) sLog->outErrorDb("Some items can't be successfully discovered: have in chance field value < 0.000001 in `skill_discovery_template` DB table . List:\n%s", ssNonDiscoverableEntries.str().c_str()); @@ -212,8 +211,8 @@ uint32 GetSkillDiscoverySpell(uint32 skillId, uint32 spellId, Player* player) for (SkillDiscoveryList::const_iterator item_iter = tab->second.begin(); item_iter != tab->second.end(); ++item_iter) { if (roll_chance_f(item_iter->chance * sWorld->getRate(RATE_SKILL_DISCOVERY)) && - item_iter->reqSkillValue <= skillvalue && - !player->HasSpell(item_iter->spellId)) + item_iter->reqSkillValue <= skillvalue && + !player->HasSpell(item_iter->spellId)) return item_iter->spellId; } @@ -230,8 +229,8 @@ uint32 GetSkillDiscoverySpell(uint32 skillId, uint32 spellId, Player* player) for (SkillDiscoveryList::const_iterator item_iter = tab->second.begin(); item_iter != tab->second.end(); ++item_iter) { if (roll_chance_f(item_iter->chance * sWorld->getRate(RATE_SKILL_DISCOVERY)) && - item_iter->reqSkillValue <= skillvalue && - !player->HasSpell(item_iter->spellId)) + item_iter->reqSkillValue <= skillvalue && + !player->HasSpell(item_iter->spellId)) return item_iter->spellId; } diff --git a/src/server/game/Skills/SkillExtraItems.cpp b/src/server/game/Skills/SkillExtraItems.cpp index c332c4d04..db8767028 100644 --- a/src/server/game/Skills/SkillExtraItems.cpp +++ b/src/server/game/Skills/SkillExtraItems.cpp @@ -181,14 +181,13 @@ void LoadSkillExtraItemTable() skillExtraItemEntry.newMaxOrEntry = newMaxOrEntry; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u spell specialization definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } -bool CanCreatePerfectItem(Player* player, uint32 spellId, float &perfectCreateChance, uint32 &perfectItemType) +bool CanCreatePerfectItem(Player* player, uint32 spellId, float& perfectCreateChance, uint32& perfectItemType) { SkillPerfectItemMap::const_iterator ret = SkillPerfectItemStore.find(spellId); // no entry in DB means no perfection proc possible @@ -212,7 +211,7 @@ bool CanCreatePerfectItem(Player* player, uint32 spellId, float &perfectCreateCh return true; } -bool canCreateExtraItems(Player* player, uint32 spellId, float &additionalChance, int32 &newMaxOrEntry) +bool canCreateExtraItems(Player* player, uint32 spellId, float& additionalChance, int32& newMaxOrEntry) { // get the info for the specified spell SkillExtraItemMap::const_iterator ret = SkillExtraItemStore.find(spellId); diff --git a/src/server/game/Skills/SkillExtraItems.h b/src/server/game/Skills/SkillExtraItems.h index 7820ce0e0..e1a073e07 100644 --- a/src/server/game/Skills/SkillExtraItems.h +++ b/src/server/game/Skills/SkillExtraItems.h @@ -12,11 +12,11 @@ // predef classes used in functions class Player; // returns true and sets the appropriate info if the player can create a perfect item with the given spellId -bool CanCreatePerfectItem(Player* player, uint32 spellId, float &perfectCreateChance, uint32 &perfectItemType); +bool CanCreatePerfectItem(Player* player, uint32 spellId, float& perfectCreateChance, uint32& perfectItemType); // load perfection proc info from DB void LoadSkillPerfectItemTable(); // returns true and sets the appropriate info if the player can create extra items with the given spellId -bool canCreateExtraItems(Player* player, uint32 spellId, float &additionalChance, int32 &newMaxOrEntry); +bool canCreateExtraItems(Player* player, uint32 spellId, float& additionalChance, int32& newMaxOrEntry); // function to load the extra item creation info from DB void LoadSkillExtraItemTable(); #endif diff --git a/src/server/game/Spells/Auras/SpellAuraDefines.h b/src/server/game/Spells/Auras/SpellAuraDefines.h index 40929f3ea..c322004b8 100644 --- a/src/server/game/Spells/Auras/SpellAuraDefines.h +++ b/src/server/game/Spells/Auras/SpellAuraDefines.h @@ -233,7 +233,7 @@ enum AuraType SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT = 182, SPELL_AURA_MOD_CRITICAL_THREAT = 183, SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE = 184, - SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE= 185, + SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE = 185, SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE = 186, SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE = 187, SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE = 188, diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index a6f936c2a..620107fa9 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -46,7 +46,7 @@ class Aura; // because for change amount operation packets will not be send // aura effect handlers shouldn't contain any AuraEffect or Aura object modifications -pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]= +pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS] = { &AuraEffect::HandleNULL, // 0 SPELL_AURA_NONE &AuraEffect::HandleBindSight, // 1 SPELL_AURA_BIND_SIGHT @@ -367,11 +367,11 @@ pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]= &AuraEffect::HandleNoImmediateEffect, //316 SPELL_AURA_PERIODIC_HASTE implemented in AuraEffect::CalculatePeriodic }; -AuraEffect::AuraEffect(Aura* base, uint8 effIndex, int32 *baseAmount, Unit* caster): -m_base(base), m_spellInfo(base->GetSpellInfo()), -m_baseAmount(baseAmount ? *baseAmount : m_spellInfo->Effects[effIndex].BasePoints), m_critChance(0), -m_oldAmount(0), m_isAuraEnabled(true), m_channelData(nullptr), m_spellmod(nullptr), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex), -m_canBeRecalculated(true), m_isPeriodic(false) +AuraEffect::AuraEffect(Aura* base, uint8 effIndex, int32* baseAmount, Unit* caster): + m_base(base), m_spellInfo(base->GetSpellInfo()), + m_baseAmount(baseAmount ? * baseAmount : m_spellInfo->Effects[effIndex].BasePoints), m_critChance(0), + m_oldAmount(0), m_isAuraEnabled(true), m_channelData(nullptr), m_spellmod(nullptr), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex), + m_canBeRecalculated(true), m_isPeriodic(false) { CalculatePeriodic(caster, true, false); CalculatePeriodicData(); @@ -395,9 +395,9 @@ AuraEffect::~AuraEffect() delete m_channelData; } -void AuraEffect::GetTargetList(std::list & targetList) const +void AuraEffect::GetTargetList(std::list& targetList) const { - Aura::ApplicationMap const & targetMap = GetBase()->GetApplicationMap(); + Aura::ApplicationMap const& targetMap = GetBase()->GetApplicationMap(); // remove all targets which were not added to new list - they no longer deserve area aura for (Aura::ApplicationMap::const_iterator appIter = targetMap.begin(); appIter != targetMap.end(); ++appIter) { @@ -406,9 +406,9 @@ void AuraEffect::GetTargetList(std::list & targetList) const } } -void AuraEffect::GetApplicationList(std::list & applicationList) const +void AuraEffect::GetApplicationList(std::list& applicationList) const { - Aura::ApplicationMap const & targetMap = GetBase()->GetApplicationMap(); + Aura::ApplicationMap const& targetMap = GetBase()->GetApplicationMap(); for (Aura::ApplicationMap::const_iterator appIter = targetMap.begin(); appIter != targetMap.end(); ++appIter) { if (appIter->second->HasEffect(GetEffIndex())) @@ -459,10 +459,10 @@ int32 AuraEffect::CalculateAmount(Unit* caster) { for (int t = 0; t < MAX_SPELL_ITEM_ENCHANTMENT_EFFECTS; t++) if (pEnchant->spellid[t] == m_spellInfo->Id) - { - amount = uint32((item_rand_suffix->prefix[k]*castItem->GetItemSuffixFactor()) / 10000); - break; - } + { + amount = uint32((item_rand_suffix->prefix[k] * castItem->GetItemSuffixFactor()) / 10000); + break; + } } if (amount) @@ -524,8 +524,8 @@ int32 AuraEffect::CalculateAmount(Unit* caster) break; if (GetId() == 49152 && caster->ToPlayer()) { - Item *item1 = caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK); - Item *item2 = caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK); + Item* item1 = caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK); + Item* item2 = caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK); if (item1 && item2 && (item1->GetTemplate()->InventoryType == INVTYPE_2HWEAPON || item2->GetTemplate()->InventoryType == INVTYPE_2HWEAPON)) amount = -10; @@ -538,7 +538,7 @@ int32 AuraEffect::CalculateAmount(Unit* caster) } // xinef: save base amount, before calculating sp etc. Used for Unit::CastDelayedSpellWithPeriodicAmount - SetOldAmount(amount*GetBase()->GetStackAmount()); + SetOldAmount(amount * GetBase()->GetStackAmount()); GetBase()->CallScriptEffectCalcAmountHandlers(this, amount, m_canBeRecalculated); // Xinef: Periodic auras @@ -587,7 +587,7 @@ void AuraEffect::CalculatePeriodic(Unit* caster, bool create, bool load) m_amplitude = m_spellInfo->Effects[m_effIndex].Amplitude; // prepare periodics - switch (GetAuraType()) + switch (GetAuraType()) { case SPELL_AURA_OBS_MOD_POWER: // 3 spells have no amplitude set @@ -651,7 +651,7 @@ void AuraEffect::CalculatePeriodic(Unit* caster, bool create, bool load) // possibly we should not reset periodic timers only when aura is triggered by proc // or maybe there's a spell attribute somewhere bool resetPeriodicTimer = create - || ((GetAuraType() != SPELL_AURA_PERIODIC_DAMAGE) && (GetAuraType() != SPELL_AURA_PERIODIC_DAMAGE_PERCENT)); + || ((GetAuraType() != SPELL_AURA_PERIODIC_DAMAGE) && (GetAuraType() != SPELL_AURA_PERIODIC_DAMAGE_PERCENT)); if (resetPeriodicTimer) { @@ -660,12 +660,12 @@ void AuraEffect::CalculatePeriodic(Unit* caster, bool create, bool load) if (m_amplitude) { if (!GetSpellInfo()->HasAttribute(SPELL_ATTR5_START_PERIODIC_AT_APPLY)) - m_periodicTimer += m_amplitude; + m_periodicTimer += m_amplitude; else if (caster && caster->IsTotem()) // for totems only ;d { m_periodicTimer = 100; // make it ALMOST instant if (!GetBase()->IsPassive()) - GetBase()->SetDuration(GetBase()->GetDuration()+100); + GetBase()->SetDuration(GetBase()->GetDuration() + 100); } } } @@ -729,16 +729,16 @@ void AuraEffect::ChangeAmount(int32 newAmount, bool mark, bool onStackOrReapply) HandleEffect(*apptItr, handleMask, true); } -void AuraEffect::HandleEffect(AuraApplication * aurApp, uint8 mode, bool apply) +void AuraEffect::HandleEffect(AuraApplication* aurApp, uint8 mode, bool apply) { // check if call is correct, we really don't want using bitmasks here (with 1 exception) ASSERT(mode == AURA_EFFECT_HANDLE_REAL - || mode == AURA_EFFECT_HANDLE_SEND_FOR_CLIENT - || mode == AURA_EFFECT_HANDLE_CHANGE_AMOUNT - || mode == AURA_EFFECT_HANDLE_STAT - || mode == AURA_EFFECT_HANDLE_SKILL - || mode == AURA_EFFECT_HANDLE_REAPPLY - || mode == (AURA_EFFECT_HANDLE_CHANGE_AMOUNT | AURA_EFFECT_HANDLE_REAPPLY)); + || mode == AURA_EFFECT_HANDLE_SEND_FOR_CLIENT + || mode == AURA_EFFECT_HANDLE_CHANGE_AMOUNT + || mode == AURA_EFFECT_HANDLE_STAT + || mode == AURA_EFFECT_HANDLE_SKILL + || mode == AURA_EFFECT_HANDLE_REAPPLY + || mode == (AURA_EFFECT_HANDLE_CHANGE_AMOUNT | AURA_EFFECT_HANDLE_REAPPLY)); // register/unregister effect in lists in case of real AuraEffect apply/remove // registration/unregistration is done always before real effect handling (some effect handlers code is depending on this) @@ -805,81 +805,81 @@ void AuraEffect::ApplySpellMod(Unit* target, bool apply) case SPELLMOD_EFFECT1: case SPELLMOD_EFFECT2: case SPELLMOD_EFFECT3: - { - uint64 guid = target->GetGUID(); - Unit::AuraApplicationMap & auras = target->GetAppliedAuras(); - for (Unit::AuraApplicationMap::iterator iter = auras.begin(); iter != auras.end(); ++iter) { - Aura* aura = iter->second->GetBase(); - // only passive and permament auras-active auras should have amount set on spellcast and not be affected - // if aura is casted by others, it will not be affected - if ((aura->IsPassive() || aura->IsPermanent()) && aura->GetCasterGUID() == guid && aura->GetSpellInfo()->IsAffectedBySpellMod(m_spellmod)) + uint64 guid = target->GetGUID(); + Unit::AuraApplicationMap& auras = target->GetAppliedAuras(); + for (Unit::AuraApplicationMap::iterator iter = auras.begin(); iter != auras.end(); ++iter) { - if (GetMiscValue() == SPELLMOD_ALL_EFFECTS) + Aura* aura = iter->second->GetBase(); + // only passive and permament auras-active auras should have amount set on spellcast and not be affected + // if aura is casted by others, it will not be affected + if ((aura->IsPassive() || aura->IsPermanent()) && aura->GetCasterGUID() == guid && aura->GetSpellInfo()->IsAffectedBySpellMod(m_spellmod)) { - for (uint8 i = 0; iGetEffect(i)) + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (AuraEffect* aurEff = aura->GetEffect(i)) + aurEff->RecalculateAmount(); + } + } + else if (GetMiscValue() == SPELLMOD_EFFECT1) + { + if (AuraEffect* aurEff = aura->GetEffect(0)) + aurEff->RecalculateAmount(); + } + else if (GetMiscValue() == SPELLMOD_EFFECT2) + { + if (AuraEffect* aurEff = aura->GetEffect(1)) + aurEff->RecalculateAmount(); + } + else //if (modOp == SPELLMOD_EFFECT3) + { + if (AuraEffect* aurEff = aura->GetEffect(2)) aurEff->RecalculateAmount(); } } - else if (GetMiscValue() == SPELLMOD_EFFECT1) - { - if (AuraEffect* aurEff = aura->GetEffect(0)) - aurEff->RecalculateAmount(); - } - else if (GetMiscValue() == SPELLMOD_EFFECT2) - { - if (AuraEffect* aurEff = aura->GetEffect(1)) - aurEff->RecalculateAmount(); - } - else //if (modOp == SPELLMOD_EFFECT3) - { - if (AuraEffect* aurEff = aura->GetEffect(2)) - aurEff->RecalculateAmount(); - } } - } - Pet* pet = target->ToPlayer()->GetPet(); - if (!pet) - break; + Pet* pet = target->ToPlayer()->GetPet(); + if (!pet) + break; - uint64 petguid = pet->GetGUID(); - Unit::AuraApplicationMap & petauras = pet->GetAppliedAuras(); - for (Unit::AuraApplicationMap::iterator iter = petauras.begin(); iter != petauras.end(); ++iter) - { - Aura* aura = iter->second->GetBase(); - // only passive auras-active auras should have amount set on spellcast and not be affected - // if aura is casted by others, it will not be affected - if ((aura->IsPassive() || aura->IsPermanent()) && aura->GetCasterGUID() == petguid && aura->GetSpellInfo()->IsAffectedBySpellMod(m_spellmod)) + uint64 petguid = pet->GetGUID(); + Unit::AuraApplicationMap& petauras = pet->GetAppliedAuras(); + for (Unit::AuraApplicationMap::iterator iter = petauras.begin(); iter != petauras.end(); ++iter) { - if (GetMiscValue() == SPELLMOD_ALL_EFFECTS) + Aura* aura = iter->second->GetBase(); + // only passive auras-active auras should have amount set on spellcast and not be affected + // if aura is casted by others, it will not be affected + if ((aura->IsPassive() || aura->IsPermanent()) && aura->GetCasterGUID() == petguid && aura->GetSpellInfo()->IsAffectedBySpellMod(m_spellmod)) { - for (uint8 i = 0; iGetEffect(i)) + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (AuraEffect* aurEff = aura->GetEffect(i)) + aurEff->RecalculateAmount(); + } + } + else if (GetMiscValue() == SPELLMOD_EFFECT1) + { + if (AuraEffect* aurEff = aura->GetEffect(0)) + aurEff->RecalculateAmount(); + } + else if (GetMiscValue() == SPELLMOD_EFFECT2) + { + if (AuraEffect* aurEff = aura->GetEffect(1)) + aurEff->RecalculateAmount(); + } + else //if (modOp == SPELLMOD_EFFECT3) + { + if (AuraEffect* aurEff = aura->GetEffect(2)) aurEff->RecalculateAmount(); } } - else if (GetMiscValue() == SPELLMOD_EFFECT1) - { - if (AuraEffect* aurEff = aura->GetEffect(0)) - aurEff->RecalculateAmount(); - } - else if (GetMiscValue() == SPELLMOD_EFFECT2) - { - if (AuraEffect* aurEff = aura->GetEffect(1)) - aurEff->RecalculateAmount(); - } - else //if (modOp == SPELLMOD_EFFECT3) - { - if (AuraEffect* aurEff = aura->GetEffect(2)) - aurEff->RecalculateAmount(); - } } } - } default: break; } @@ -887,7 +887,7 @@ void AuraEffect::ApplySpellMod(Unit* target, bool apply) void AuraEffect::Update(uint32 diff, Unit* caster) { - if (m_isPeriodic && (GetBase()->GetDuration() >=0 || GetBase()->IsPassive() || GetBase()->IsPermanent())) + if (m_isPeriodic && (GetBase()->GetDuration() >= 0 || GetBase()->IsPassive() || GetBase()->IsPermanent())) { m_periodicTimer -= int32(diff); while (m_periodicTimer <= 0) @@ -987,9 +987,12 @@ void AuraEffect::UpdatePeriodic(Unit* caster) break; case 58549: // Tenacity case 59911: // Tenacity (vehicle) - GetBase()->RefreshDuration(); - break; - case 66823: case 67618: case 67619: case 67620: // Paralytic Toxin + GetBase()->RefreshDuration(); + break; + case 66823: + case 67618: + case 67619: + case 67620: // Paralytic Toxin // Get 0 effect aura if (AuraEffect* slow = GetBase()->GetEffect(0)) { @@ -1001,7 +1004,7 @@ void AuraEffect::UpdatePeriodic(Unit* caster) break; case 66020: // Get 0 effect aura - if (AuraEffect *slow = GetBase()->GetEffect(0)) + if (AuraEffect* slow = GetBase()->GetEffect(0)) { int32 newAmount = slow->GetAmount() + GetAmount(); if (newAmount > 0) @@ -1015,9 +1018,9 @@ void AuraEffect::UpdatePeriodic(Unit* caster) break; default: break; - } - default: - break; + } + default: + break; } GetBase()->CallScriptEffectUpdatePeriodicHandlers(this); } @@ -1080,7 +1083,7 @@ void AuraEffect::SendTickImmune(Unit* target, Unit* caster) const caster->SendSpellDamageImmune(target, m_spellInfo->Id); } -void AuraEffect::PeriodicTick(AuraApplication * aurApp, Unit* caster) const +void AuraEffect::PeriodicTick(AuraApplication* aurApp, Unit* caster) const { bool prevented = GetBase()->CallScriptEffectPeriodicHandlers(this, aurApp); if (prevented) @@ -1293,7 +1296,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const if (!spellInfo || !spellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE | SPELL_ATTR0_HIDDEN_CLIENTSIDE))) continue; - if (spellInfo->Stances & (1<<(GetMiscValue()-1))) + if (spellInfo->Stances & (1 << (GetMiscValue() - 1))) target->CastSpell(target, itr->first, true, NULL, this, target->GetGUID()); } @@ -1312,7 +1315,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const if (!spellInfo || !spellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE | SPELL_ATTR0_HIDDEN_CLIENTSIDE)) || spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL)) continue; - if (spellInfo->Stances & (1<<(GetMiscValue()-1))) + if (spellInfo->Stances & (1 << (GetMiscValue() - 1))) target->CastSpell(target, itr->first, true, NULL, this, target->GetGUID()); } @@ -1326,8 +1329,8 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(glyph->SpellId); if (!spellInfo || !spellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE | SPELL_ATTR0_HIDDEN_CLIENTSIDE))) continue; - if (spellInfo->Stances & (1<<(GetMiscValue()-1))) - target->CastSpell(target, glyph->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK&~(TRIGGERED_IGNORE_SHAPESHIFT|TRIGGERED_IGNORE_CASTER_AURASTATE)), NULL, this, target->GetGUID()); + if (spellInfo->Stances & (1 << (GetMiscValue() - 1))) + target->CastSpell(target, glyph->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK & ~(TRIGGERED_IGNORE_SHAPESHIFT | TRIGGERED_IGNORE_CASTER_AURASTATE)), NULL, this, target->GetGUID()); } } } @@ -1336,7 +1339,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const if (player->HasTalent(17007, player->GetActiveSpec())) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(24932); - if (spellInfo && spellInfo->Stances & (1<<(GetMiscValue()-1))) + if (spellInfo && spellInfo->Stances & (1 << (GetMiscValue() - 1))) target->CastSpell(target, 24932, true, NULL, this, target->GetGUID()); } // Improved Barkskin - apply/remove armor bonus due to shapeshift @@ -1348,7 +1351,8 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const } // Heart of the Wild if (HotWSpellId) - { // hacky, but the only way as spell family is not SPELLFAMILY_DRUID + { + // hacky, but the only way as spell family is not SPELLFAMILY_DRUID Unit::AuraEffectList const& mModTotalStatPct = target->GetAuraEffectsByType(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE); for (Unit::AuraEffectList::const_iterator i = mModTotalStatPct.begin(); i != mModTotalStatPct.end(); ++i) { @@ -1389,7 +1393,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const int32 bp = aurEff->GetAmount(); target->CastCustomSpell(target, 48420, &bp, nullptr, nullptr, true); } - break; + break; case FORM_DIREBEAR: case FORM_BEAR: // Master Shapeshifter - Bear @@ -1404,7 +1408,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const int32 bp = aurEff->GetSpellInfo()->Effects[EFFECT_2].CalcValue(); target->CastCustomSpell(target, 62069, &bp, nullptr, nullptr, true, 0, this, target->GetGUID()); } - break; + break; case FORM_MOONKIN: // Master Shapeshifter - Moonkin if (AuraEffect const* aurEff = target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2851, 0)) @@ -1412,15 +1416,15 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const int32 bp = aurEff->GetAmount(); target->CastCustomSpell(target, 48421, &bp, nullptr, nullptr, true); } - break; - // Master Shapeshifter - Tree of Life + break; + // Master Shapeshifter - Tree of Life case FORM_TREE: if (AuraEffect const* aurEff = target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2851, 0)) { int32 bp = aurEff->GetAmount(); target->CastCustomSpell(target, 48422, &bp, nullptr, nullptr, true); } - break; + break; } } } @@ -1452,13 +1456,13 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const break; } } - + // Use the new aura to see on what stance the target will be - uint32 newStance = (1<<((newAura ? newAura->GetMiscValue() : 0)-1)); + uint32 newStance = (1 << ((newAura ? newAura->GetMiscValue() : 0) - 1)); Unit::AuraApplicationMap& tAuras = target->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator itr = tAuras.begin(); itr != tAuras.end();) - { + { // If the stances are not compatible with the spell, remove it // Xinef: Remove all passive auras, they will be added if needed if (itr->second->GetBase()->IsRemovedOnShapeLost(target) && (!(itr->second->GetBase()->GetSpellInfo()->Stances & newStance) || itr->second->GetBase()->IsPassive())) @@ -1861,17 +1865,17 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo case FORM_FLIGHT_EPIC: case FORM_FLIGHT: case FORM_MOONKIN: - { - // remove movement affects - target->RemoveAurasByShapeShift(); + { + // remove movement affects + target->RemoveAurasByShapeShift(); - // and polymorphic affects - if (target->IsPolymorphed()) - target->RemoveAurasDueToSpell(target->getTransForm()); - break; - } + // and polymorphic affects + if (target->IsPolymorphed()) + target->RemoveAurasDueToSpell(target->getTransForm()); + break; + } default: - break; + break; } // remove other shapeshift before applying a new one @@ -1895,35 +1899,35 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo case FORM_CAT: case FORM_BEAR: case FORM_DIREBEAR: - { - // get furor proc chance - uint32 FurorChance = 0; - if (AuraEffect const* dummy = target->GetDummyAuraEffect(SPELLFAMILY_DRUID, 238, 0)) - FurorChance = std::max(dummy->GetAmount(), 0); - - switch (GetMiscValue()) { - case FORM_CAT: + // get furor proc chance + uint32 FurorChance = 0; + if (AuraEffect const* dummy = target->GetDummyAuraEffect(SPELLFAMILY_DRUID, 238, 0)) + FurorChance = std::max(dummy->GetAmount(), 0); + + switch (GetMiscValue()) { - int32 basePoints = int32(std::min(oldPower, FurorChance)); - target->SetPower(POWER_ENERGY, 0); - target->CastCustomSpell(target, 17099, &basePoints, nullptr, nullptr, true, NULL, this); - break; - } - case FORM_BEAR: - case FORM_DIREBEAR: - if (urand(0, 99) < FurorChance) - target->CastSpell(target, 17057, true); - break; - default: - { - uint32 newEnergy = std::min(target->GetPower(POWER_ENERGY), FurorChance); - target->SetPower(POWER_ENERGY, newEnergy); - break; + case FORM_CAT: + { + int32 basePoints = int32(std::min(oldPower, FurorChance)); + target->SetPower(POWER_ENERGY, 0); + target->CastCustomSpell(target, 17099, &basePoints, nullptr, nullptr, true, NULL, this); + break; + } + case FORM_BEAR: + case FORM_DIREBEAR: + if (urand(0, 99) < FurorChance) + target->CastSpell(target, 17057, true); + break; + default: + { + uint32 newEnergy = std::min(target->GetPower(POWER_ENERGY), FurorChance); + target->SetPower(POWER_ENERGY, newEnergy); + break; + } } + break; } - break; - } default: break; } @@ -1981,45 +1985,45 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo case FORM_BATTLESTANCE: case FORM_DEFENSIVESTANCE: case FORM_BERSERKERSTANCE: - { - uint32 Rage_val = 0; - // Defensive Tactics - if (form == FORM_DEFENSIVESTANCE) { - if (AuraEffect const* aurEff = target->IsScriptOverriden(m_spellInfo, 831)) - Rage_val += aurEff->GetAmount() * 10; - } - // Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch) - if (target->GetTypeId() == TYPEID_PLAYER) - { - // Stance mastery - trainer spell - PlayerSpellMap const& sp_list = target->ToPlayer()->GetSpellMap(); - for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) + uint32 Rage_val = 0; + // Defensive Tactics + if (form == FORM_DEFENSIVESTANCE) { - if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(target->ToPlayer()->GetActiveSpec())) - continue; - - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); - if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139) - Rage_val += target->CalculateSpellDamage(target, spellInfo, 0) * 10; + if (AuraEffect const* aurEff = target->IsScriptOverriden(m_spellInfo, 831)) + Rage_val += aurEff->GetAmount() * 10; } - - // Tactical Mastery - talent - PlayerTalentMap const& tp_list = target->ToPlayer()->GetTalentMap(); - for (PlayerTalentMap::const_iterator itr = tp_list.begin(); itr != tp_list.end(); ++itr) + // Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch) + if (target->GetTypeId() == TYPEID_PLAYER) { - if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(target->ToPlayer()->GetActiveSpec())) - continue; + // Stance mastery - trainer spell + PlayerSpellMap const& sp_list = target->ToPlayer()->GetSpellMap(); + for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) + { + if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(target->ToPlayer()->GetActiveSpec())) + continue; - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); - if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139) - Rage_val += target->CalculateSpellDamage(target, spellInfo, 0) * 10; + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); + if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139) + Rage_val += target->CalculateSpellDamage(target, spellInfo, 0) * 10; + } + + // Tactical Mastery - talent + PlayerTalentMap const& tp_list = target->ToPlayer()->GetTalentMap(); + for (PlayerTalentMap::const_iterator itr = tp_list.begin(); itr != tp_list.end(); ++itr) + { + if (itr->second->State == PLAYERSPELL_REMOVED || !itr->second->IsInSpec(target->ToPlayer()->GetActiveSpec())) + continue; + + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); + if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139) + Rage_val += target->CalculateSpellDamage(target, spellInfo, 0) * 10; + } } + if (target->GetPower(POWER_RAGE) > Rage_val) + target->SetPower(POWER_RAGE, Rage_val); + break; } - if (target->GetPower(POWER_RAGE) > Rage_val) - target->SetPower(POWER_RAGE, Rage_val); - break; - } default: break; } @@ -2058,7 +2062,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo { SpellShapeshiftEntry const* shapeInfo = sSpellShapeshiftStore.LookupEntry(form); // Learn spells for shapeshift form - no need to send action bars or add spells to spellbook - for (uint8 i = 0; istanceSpell[i]) continue; @@ -2089,57 +2093,57 @@ void AuraEffect::HandleAuraTransform(AuraApplication const* aurApp, uint8 mode, { // Orb of Deception case 16739: - { - if (target->GetTypeId() != TYPEID_PLAYER) - return; - - switch (target->getRace()) { - // Blood Elf - case RACE_BLOODELF: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 17829 : 17830); - break; - // Orc - case RACE_ORC: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10139 : 10140); - break; - // Troll - case RACE_TROLL: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10135 : 10134); - break; - // Tauren - case RACE_TAUREN: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10136 : 10147); - break; - // Undead - case RACE_UNDEAD_PLAYER: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10146 : 10145); - break; - // Draenei - case RACE_DRAENEI: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 17827 : 17828); - break; - // Dwarf - case RACE_DWARF: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10141 : 10142); - break; - // Gnome - case RACE_GNOME: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10148 : 10149); - break; - // Human - case RACE_HUMAN: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10137 : 10138); - break; - // Night Elf - case RACE_NIGHTELF: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 10143 : 10144); - break; - default: - break; + if (target->GetTypeId() != TYPEID_PLAYER) + return; + + switch (target->getRace()) + { + // Blood Elf + case RACE_BLOODELF: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 17829 : 17830); + break; + // Orc + case RACE_ORC: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10139 : 10140); + break; + // Troll + case RACE_TROLL: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10135 : 10134); + break; + // Tauren + case RACE_TAUREN: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10136 : 10147); + break; + // Undead + case RACE_UNDEAD_PLAYER: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10146 : 10145); + break; + // Draenei + case RACE_DRAENEI: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 17827 : 17828); + break; + // Dwarf + case RACE_DWARF: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10141 : 10142); + break; + // Gnome + case RACE_GNOME: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10148 : 10149); + break; + // Human + case RACE_HUMAN: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10137 : 10138); + break; + // Night Elf + case RACE_NIGHTELF: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 10143 : 10144); + break; + default: + break; + } + break; } - break; - } // Murloc costume case 42365: target->SetDisplayId(21723); @@ -2148,57 +2152,57 @@ void AuraEffect::HandleAuraTransform(AuraApplication const* aurApp, uint8 mode, case 50517: // Corsair Costume case 51926: - { - if (target->GetTypeId() != TYPEID_PLAYER) - return; - - switch (target->getRace()) { - // Blood Elf - case RACE_BLOODELF: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043); - break; - // Orc - case RACE_ORC: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050); - break; - // Troll - case RACE_TROLL: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052); - break; - // Tauren - case RACE_TAUREN: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051); - break; - // Undead - case RACE_UNDEAD_PLAYER: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053); - break; - // Draenei - case RACE_DRAENEI: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044); - break; - // Dwarf - case RACE_DWARF: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045); - break; - // Gnome - case RACE_GNOME: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046); - break; - // Human - case RACE_HUMAN: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048); - break; - // Night Elf - case RACE_NIGHTELF: - target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049); - break; - default: - break; + if (target->GetTypeId() != TYPEID_PLAYER) + return; + + switch (target->getRace()) + { + // Blood Elf + case RACE_BLOODELF: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043); + break; + // Orc + case RACE_ORC: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050); + break; + // Troll + case RACE_TROLL: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052); + break; + // Tauren + case RACE_TAUREN: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051); + break; + // Undead + case RACE_UNDEAD_PLAYER: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053); + break; + // Draenei + case RACE_DRAENEI: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044); + break; + // Dwarf + case RACE_DWARF: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045); + break; + // Gnome + case RACE_GNOME: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046); + break; + // Human + case RACE_HUMAN: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048); + break; + // Night Elf + case RACE_NIGHTELF: + target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049); + break; + default: + break; + } + break; } - break; - } // Pygmy Oil case 53806: target->SetDisplayId(22512); @@ -2261,7 +2265,7 @@ void AuraEffect::HandleAuraTransform(AuraApplication const* aurApp, uint8 mode, // for players, start regeneration after 1s (in polymorph fast regeneration case) // only if caster is Player (after patch 2.4.2) if (IS_PLAYER_GUID(GetCasterGUID())) - target->ToPlayer()->setRegenTimerCount(1*IN_MILLISECONDS); + target->ToPlayer()->setRegenTimerCount(1 * IN_MILLISECONDS); //dismount polymorphed target (after patch 2.4.2) if (target->IsMounted()) @@ -2423,11 +2427,11 @@ void AuraEffect::HandleFeignDeath(AuraApplication const* aurApp, uint8 mode, boo // stop handling the effect if it was removed by linked event if (aurApp->GetRemoveMode()) return; - // blizz like 2.0.x + // blizz like 2.0.x target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); - // blizz like 2.0.x + // blizz like 2.0.x target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); - // blizz like 2.0.x + // blizz like 2.0.x target->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); target->AddUnitState(UNIT_STATE_DIED); @@ -2440,11 +2444,11 @@ void AuraEffect::HandleFeignDeath(AuraApplication const* aurApp, uint8 mode, boo data<SendMessageToSet(&data, true); */ - // blizz like 2.0.x + // blizz like 2.0.x target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); - // blizz like 2.0.x + // blizz like 2.0.x target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); - // blizz like 2.0.x + // blizz like 2.0.x target->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); target->ClearUnitState(UNIT_STATE_DIED); @@ -2752,7 +2756,7 @@ void AuraEffect::HandleAuraModSkill(AuraApplication const* aurApp, uint8 mode, b uint32 prot = GetMiscValue(); int32 points = GetAmount(); - target->ToPlayer()->ModifySkillBonus(prot, ((apply) ? points: -points), GetAuraType() == SPELL_AURA_MOD_SKILL_TALENT); + target->ToPlayer()->ModifySkillBonus(prot, ((apply) ? points : -points), GetAuraType() == SPELL_AURA_MOD_SKILL_TALENT); if (prot == SKILL_DEFENSE) target->ToPlayer()->UpdateDefenseBonusesMod(); } @@ -2794,7 +2798,7 @@ void AuraEffect::HandleAuraMounted(AuraApplication const* aurApp, uint8 mode, bo //some spell has one aura of mount and one of vehicle for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (GetSpellInfo()->Effects[i].Effect == SPELL_EFFECT_SUMMON - && GetSpellInfo()->Effects[i].MiscValue == GetMiscValue()) + && GetSpellInfo()->Effects[i].MiscValue == GetMiscValue()) displayID = 0; target->Mount(displayID, ci->VehicleId, GetMiscValue()); @@ -3286,202 +3290,202 @@ void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 { case 96: case 1615: - { - if (!GetAmount()) { - mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) - | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) - | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) - | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) - | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) - | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); + if (!GetAmount()) + { + mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) + | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) + | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) + | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) + | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) + | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_CHARM); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); - aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); - aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); - aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_CHARM); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); + aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); + aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + } + break; } - break; - } case 679: - { - if (GetId() == 57742) { - mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) - | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) - | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) - | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) - | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) - | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); + if (GetId() == 57742) + { + mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) + | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) + | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) + | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) + | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) + | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); - aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); - aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); - aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); + aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); + aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + } + break; } - break; - } case 1557: - { - if (GetId() == 64187) { - mechanic_immunity_list = (1 << MECHANIC_STUN); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - } - else - { - mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) - | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) - | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) - | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) - | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) - | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); + if (GetId() == 64187) + { + mechanic_immunity_list = (1 << MECHANIC_STUN); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + } + else + { + mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) + | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) + | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) + | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) + | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) + | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); - aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); - aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); - aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); + aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); + aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + } + break; } - break; - } case 1614: case 1694: - { - target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT); - break; - } - case 1630: - { - if (!GetAmount()) { target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, apply); aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT); + break; } - else + case 1630: { - mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) - | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) - | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) - | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) - | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) - | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); + if (!GetAmount()) + { + target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT); + } + else + { + mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) + | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) + | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) + | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) + | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) + | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); - aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); - aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); - aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); + aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); + aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + } + break; } - break; - } case 477: case 1733: case 1632: - { - if (!GetAmount()) { - mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) - | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) - | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) - | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) - | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) - | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN) | (1 << MECHANIC_BANISH); + if (!GetAmount()) + { + mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_ROOT) + | (1 << MECHANIC_FEAR) | (1 << MECHANIC_STUN) + | (1 << MECHANIC_SLEEP) | (1 << MECHANIC_CHARM) + | (1 << MECHANIC_SAPPED) | (1 << MECHANIC_HORROR) + | (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED) + | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_TURN) | (1 << MECHANIC_BANISH); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_BANISH, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK_DEST, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_ROOT, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FEAR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SLEEP, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_CHARM, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SAPPED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_HORROR, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_TURN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_BANISH, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK_DEST, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); - aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); - aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); - aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); + aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); + aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); + } + break; } - break; - } case 878: - { - if (GetAmount() == 1) { - mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_STUN) - | (1 << MECHANIC_DISORIENTED) | (1 << MECHANIC_FREEZE); + if (GetAmount() == 1) + { + mechanic_immunity_list = (1 << MECHANIC_SNARE) | (1 << MECHANIC_STUN) + | (1 << MECHANIC_DISORIENTED) | (1 << MECHANIC_FREEZE); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_STUN, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, apply); + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_FREEZE, apply); + aura_immunity_list.push_back(SPELL_AURA_MOD_STUN); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + } + break; } - break; - } default: break; } @@ -3489,7 +3493,7 @@ void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 if (aura_immunity_list.empty()) { // Roots, OK - if (GetMiscValue() & (1<<0)) + if (GetMiscValue() & (1 << 0)) { mechanic_immunity_list = (1 << MECHANIC_SNARE); @@ -3497,12 +3501,12 @@ void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 aura_immunity_list.push_back(SPELL_AURA_MOD_ROOT); } // Taunt, OK - if (GetMiscValue() & (1<<1)) + if (GetMiscValue() & (1 << 1)) { aura_immunity_list.push_back(SPELL_AURA_MOD_TAUNT); } // Crowd-Control auras? - if (GetMiscValue() & (1<<2)) + if (GetMiscValue() & (1 << 2)) { mechanic_immunity_list = (1 << MECHANIC_POLYMORPH) | (1 << MECHANIC_DISORIENTED); @@ -3511,34 +3515,34 @@ void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 aura_immunity_list.push_back(SPELL_AURA_MOD_CONFUSE); } // Interrupt, OK - if (GetMiscValue() & (1<<3)) + if (GetMiscValue() & (1 << 3)) { mechanic_immunity_list = (1 << MECHANIC_INTERRUPT); target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_INTERRUPT, apply); } // Transform? - if (GetMiscValue() & (1<<4)) + if (GetMiscValue() & (1 << 4)) { aura_immunity_list.push_back(SPELL_AURA_TRANSFORM); } // Stun auras breakable by damage (Incapacitate effects), OK - if (GetMiscValue() & (1<<5)) + if (GetMiscValue() & (1 << 5)) { mechanic_immunity_list = (1 << MECHANIC_KNOCKOUT); target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_KNOCKOUT, apply); } // // Slowing effects - if (GetMiscValue() & (1<<6)) + if (GetMiscValue() & (1 << 6)) { mechanic_immunity_list = (1 << MECHANIC_SNARE); target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_SNARE, apply); - aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); + aura_immunity_list.push_back(SPELL_AURA_MOD_DECREASE_SPEED); } // Charm auras?, 90% - if ((GetMiscValue() & (1<<7))) + if ((GetMiscValue() & (1 << 7))) { mechanic_immunity_list = (1 << MECHANIC_CHARM); @@ -3547,11 +3551,11 @@ void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 aura_immunity_list.push_back(SPELL_AURA_MOD_POSSESS); } // UNK - if ((GetMiscValue() & (1<<8))) + if ((GetMiscValue() & (1 << 8))) { } // Fear, OK - if (GetMiscValue() & (1<<9)) + if (GetMiscValue() & (1 << 9)) { mechanic_immunity_list = (1 << MECHANIC_FEAR); @@ -3559,7 +3563,7 @@ void AuraEffect::HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 aura_immunity_list.push_back(SPELL_AURA_MOD_FEAR); } // Stuns, OK - if (GetMiscValue() & (1<<10)) + if (GetMiscValue() & (1 << 10)) { mechanic_immunity_list = (1 << MECHANIC_STUN); @@ -3729,13 +3733,13 @@ void AuraEffect::HandleAuraModSchoolImmunity(AuraApplication const* aurApp, uint // remove all flag auras (they are positive, but they must be removed when you are immune) if (GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) - && GetSpellInfo()->HasAttribute(SPELL_ATTR2_DAMAGE_REDUCED_SHIELD)) + && GetSpellInfo()->HasAttribute(SPELL_ATTR2_DAMAGE_REDUCED_SHIELD)) target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); // TODO: optimalize this cycle - use RemoveAurasWithInterruptFlags call or something else if ((apply) - && GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) - && GetSpellInfo()->IsPositive()) //Only positive immunity removes auras + && GetSpellInfo()->HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) + && GetSpellInfo()->IsPositive()) //Only positive immunity removes auras { uint32 school_mask = GetMiscValue(); Unit::AuraApplicationMap& Auras = target->GetAppliedAuras(); @@ -3743,9 +3747,9 @@ void AuraEffect::HandleAuraModSchoolImmunity(AuraApplication const* aurApp, uint { SpellInfo const* spell = iter->second->GetBase()->GetSpellInfo(); if ((spell->GetSchoolMask() & school_mask)//Check for school mask - && GetSpellInfo()->CanDispelAura(spell) - && !iter->second->IsPositive() //Don't remove positive spells - && spell->Id != GetId()) //Don't remove self + && GetSpellInfo()->CanDispelAura(spell) + && !iter->second->IsPositive() //Don't remove positive spells + && spell->Id != GetId()) //Don't remove self { target->RemoveAura(iter); } @@ -3792,9 +3796,9 @@ void AuraEffect::HandleAuraModResistanceExclusive(AuraApplication const* aurApp, for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; x++) { - if (GetMiscValue() & int32(1<GetMaxPositiveAuraModifierByMiscMask(SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE, 1<GetMaxPositiveAuraModifierByMiscMask(SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE, 1 << x, this); if (amount < GetAmount()) { float value = float(GetAmount() - amount); @@ -3815,7 +3819,7 @@ void AuraEffect::HandleAuraModResistance(AuraApplication const* aurApp, uint8 mo for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; x++) { - if (GetMiscValue() & int32(1<HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), TOTAL_VALUE, float(GetAmount()), apply); if (target->GetTypeId() == TYPEID_PLAYER || target->IsPet()) @@ -3842,7 +3846,7 @@ void AuraEffect::HandleAuraModBaseResistancePCT(AuraApplication const* aurApp, u { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; x++) { - if (GetMiscValue() & int32(1<HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_PCT, float(GetAmount()), apply); } } @@ -3857,7 +3861,7 @@ void AuraEffect::HandleModResistancePercent(AuraApplication const* aurApp, uint8 for (int8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; i++) { - if (GetMiscValue() & int32(1<HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_PCT, float(GetAmount()), apply); if (target->GetTypeId() == TYPEID_PLAYER || target->IsPet()) @@ -3886,7 +3890,7 @@ void AuraEffect::HandleModBaseResistance(AuraApplication const* aurApp, uint8 mo else { for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; i++) - if (GetMiscValue() & (1<HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + i), TOTAL_VALUE, float(GetAmount()), apply); } } @@ -4306,7 +4310,7 @@ void AuraEffect::HandleAuraModParryPercent(AuraApplication const* aurApp, uint8 if (target->GetTypeId() != TYPEID_PLAYER) return; - + if (!target->ToPlayer()->CanParry()) target->ToPlayer()->SetCanParry(true); else @@ -4403,7 +4407,7 @@ void AuraEffect::HandleModSpellHitChance(AuraApplication const* aurApp, uint8 mo if (target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->UpdateSpellHitChances(); else - target->m_modSpellHitChance += (apply) ? GetAmount(): (-GetAmount()); + target->m_modSpellHitChance += (apply) ? GetAmount() : (-GetAmount()); } void AuraEffect::HandleModSpellCritChance(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -4416,7 +4420,7 @@ void AuraEffect::HandleModSpellCritChance(AuraApplication const* aurApp, uint8 m if (target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->UpdateAllSpellCritChances(); else - target->m_baseSpellCritChance += (apply) ? GetAmount():-GetAmount(); + target->m_baseSpellCritChance += (apply) ? GetAmount() : -GetAmount(); } void AuraEffect::HandleModSpellCritChanceShool(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const @@ -4430,7 +4434,7 @@ void AuraEffect::HandleModSpellCritChanceShool(AuraApplication const* aurApp, ui return; for (int school = SPELL_SCHOOL_NORMAL; school < MAX_SPELL_SCHOOL; ++school) - if (GetMiscValue() & (1<ToPlayer()->UpdateSpellCritChance(school); } @@ -4443,7 +4447,7 @@ void AuraEffect::HandleAuraModCritPct(AuraApplication const* aurApp, uint8 mode, if (target->GetTypeId() != TYPEID_PLAYER) { - target->m_baseSpellCritChance += (apply) ? GetAmount():-GetAmount(); + target->m_baseSpellCritChance += (apply) ? GetAmount() : -GetAmount(); return; } @@ -4732,16 +4736,16 @@ void AuraEffect::HandleModDamageDone(AuraApplication const* aurApp, uint8 mode, { for (uint32 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; i++) { - if ((GetMiscValue() & (1<ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, GetAmount(), apply); + if ((GetMiscValue() & (1 << i)) != 0) + target->ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, GetAmount(), apply); } } else { for (uint32 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; i++) { - if ((GetMiscValue() & (1<ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, GetAmount(), apply); + if ((GetMiscValue() & (1 << i)) != 0) + target->ApplyModInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, GetAmount(), apply); } } if (Guardian* pet = target->ToPlayer()->GetGuardianPet()) @@ -4830,8 +4834,8 @@ void AuraEffect::HandleModPowerCost(AuraApplication const* aurApp, uint8 mode, b Unit* target = aurApp->GetTarget(); for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) - if (GetMiscValue() & (1<ApplyModInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i, GetAmount(), apply); + if (GetMiscValue() & (1 << i)) + target->ApplyModInt32Value(UNIT_FIELD_POWER_COST_MODIFIER + i, GetAmount(), apply); } void AuraEffect::HandleArenaPreparation(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -4864,12 +4868,12 @@ void AuraEffect::HandleNoReagentUseAura(AuraApplication const* aurApp, uint8 mod flag96 mask; Unit::AuraEffectList const& noReagent = target->GetAuraEffectsByType(SPELL_AURA_NO_REAGENT_USE); - for (Unit::AuraEffectList::const_iterator i = noReagent.begin(); i != noReagent.end(); ++i) - mask |= (*i)->m_spellInfo->Effects[(*i)->m_effIndex].SpellClassMask; + for (Unit::AuraEffectList::const_iterator i = noReagent.begin(); i != noReagent.end(); ++i) + mask |= (*i)->m_spellInfo->Effects[(*i)->m_effIndex].SpellClassMask; - target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1 , mask[0]); - target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1+1, mask[1]); - target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1+2, mask[2]); + target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1, mask[0]); + target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + 1, mask[1]); + target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + 2, mask[2]); } void AuraEffect::HandleAuraRetainComboPoints(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -4932,53 +4936,53 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool caster->CastSpell(caster, 13138, true, NULL, this); break; case 34026: // kill command - { - Unit* pet = target->GetGuardianPet(); - if (!pet) + { + Unit* pet = target->GetGuardianPet(); + if (!pet) + break; + + target->CastSpell(target, 34027, true, NULL, this); + + // set 3 stacks and 3 charges (to make all auras not disappear at once) + Aura* owner_aura = target->GetAura(34027, GetCasterGUID()); + Aura* pet_aura = pet->GetAura(58914, GetCasterGUID()); + if (owner_aura) + { + owner_aura->SetCharges(0); + owner_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount); + if (pet_aura) + { + pet_aura->SetCharges(0); + pet_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount); + } + } break; - - target->CastSpell(target, 34027, true, NULL, this); - - // set 3 stacks and 3 charges (to make all auras not disappear at once) - Aura* owner_aura = target->GetAura(34027, GetCasterGUID()); - Aura* pet_aura = pet->GetAura(58914, GetCasterGUID()); - if (owner_aura) - { - owner_aura->SetCharges(0); - owner_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount); - if (pet_aura) - { - pet_aura->SetCharges(0); - pet_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount); - } } - break; - } case 37096: // Blood Elf Illusion - { - if (caster) { - switch (caster->getGender()) + if (caster) { - case GENDER_FEMALE: - caster->CastSpell(target, 37095, true, NULL, this); // Blood Elf Disguise - break; - case GENDER_MALE: - caster->CastSpell(target, 37093, true, NULL, this); - break; - default: - break; + switch (caster->getGender()) + { + case GENDER_FEMALE: + caster->CastSpell(target, 37095, true, NULL, this); // Blood Elf Disguise + break; + case GENDER_MALE: + caster->CastSpell(target, 37093, true, NULL, this); + break; + default: + break; + } } + break; } - break; - } case 55198: // Tidal Force - { - target->CastSpell(target, 55166, true); - if (Aura* owner_aura = target->GetAura(55166)) - owner_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount); - return; - } + { + target->CastSpell(target, 55166, true); + if (Aura* owner_aura = target->GetAura(55166)) + owner_aura->SetStackAmount(owner_aura->GetSpellInfo()->StackAmount); + return; + } case 39850: // Rocket Blast if (roll_chance_i(20)) // backfire stun target->CastSpell(target, 51581, true, NULL, this); @@ -5009,11 +5013,11 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool target->ToPlayer()->RemoveAmmo(); // not use ammo and not allow use break; case 71563: - { - if (Aura* newAura = target->AddAura(71564, target)) - newAura->SetStackAmount(newAura->GetSpellInfo()->StackAmount); - return; - } + { + if (Aura* newAura = target->AddAura(71564, target)) + newAura->SetStackAmount(newAura->GetSpellInfo()->StackAmount); + return; + } } } // AT REMOVE @@ -5024,24 +5028,60 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool uint32 finalSpelId = 0; switch (GetId()) { - case 19548: finalSpelId = 19597; break; - case 19674: finalSpelId = 19677; break; - case 19687: finalSpelId = 19676; break; - case 19688: finalSpelId = 19678; break; - case 19689: finalSpelId = 19679; break; - case 19692: finalSpelId = 19680; break; - case 19693: finalSpelId = 19684; break; - case 19694: finalSpelId = 19681; break; - case 19696: finalSpelId = 19682; break; - case 19697: finalSpelId = 19683; break; - case 19699: finalSpelId = 19685; break; - case 19700: finalSpelId = 19686; break; - case 30646: finalSpelId = 30647; break; - case 30653: finalSpelId = 30648; break; - case 30654: finalSpelId = 30652; break; - case 30099: finalSpelId = 30100; break; - case 30102: finalSpelId = 30103; break; - case 30105: finalSpelId = 30104; break; + case 19548: + finalSpelId = 19597; + break; + case 19674: + finalSpelId = 19677; + break; + case 19687: + finalSpelId = 19676; + break; + case 19688: + finalSpelId = 19678; + break; + case 19689: + finalSpelId = 19679; + break; + case 19692: + finalSpelId = 19680; + break; + case 19693: + finalSpelId = 19684; + break; + case 19694: + finalSpelId = 19681; + break; + case 19696: + finalSpelId = 19682; + break; + case 19697: + finalSpelId = 19683; + break; + case 19699: + finalSpelId = 19685; + break; + case 19700: + finalSpelId = 19686; + break; + case 30646: + finalSpelId = 30647; + break; + case 30653: + finalSpelId = 30648; + break; + case 30654: + finalSpelId = 30652; + break; + case 30099: + finalSpelId = 30100; + break; + case 30102: + finalSpelId = 30103; + break; + case 30105: + finalSpelId = 30104; + break; } if (finalSpelId) @@ -5064,14 +5104,14 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool } break; case 43681: // Inactive - { - if (target->GetTypeId() != TYPEID_PLAYER || aurApp->GetRemoveMode() != AURA_REMOVE_BY_EXPIRE) - return; + { + if (target->GetTypeId() != TYPEID_PLAYER || aurApp->GetRemoveMode() != AURA_REMOVE_BY_EXPIRE) + return; - if (target->GetMap()->IsBattleground()) - target->ToPlayer()->LeaveBattleground(); - break; - } + if (target->GetMap()->IsBattleground()) + target->ToPlayer()->LeaveBattleground(); + break; + } case 52172: // Coyote Spirit Despawn Aura case 60244: // Blood Parrot Despawn Aura target->CastSpell((Unit*)NULL, GetAmount(), true, NULL, this); @@ -5109,8 +5149,8 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool } } break; - default: - break; + default: + break; } } } @@ -5120,149 +5160,157 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - if (!(mode & AURA_EFFECT_HANDLE_REAL)) - break; - switch (GetId()) { - // Recently Bandaged - case 11196: - target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, GetMiscValue(), apply); + if (!(mode & AURA_EFFECT_HANDLE_REAL)) break; - // Unstable Power - case 24658: + switch (GetId()) { - uint32 spellId = 24659; - if (apply && caster) - { - SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellId); - - for (uint32 i = 0; i < spell->StackAmount; ++i) - caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); + // Recently Bandaged + case 11196: + target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, GetMiscValue(), apply); break; - } - target->RemoveAurasDueToSpell(spellId); - break; - } - // Restless Strength - case 24661: - { - uint32 spellId = 24662; - if (apply && caster) - { - SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellId); - for (uint32 i = 0; i < spell->StackAmount; ++i) - caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); - break; - } - target->RemoveAurasDueToSpell(spellId); - break; - } - // Tag Murloc - case 30877: - { - // Tag/untag Blacksilt Scout - target->SetEntry(apply ? 17654 : 17326); - break; - } - case 57819: // Argent Champion - case 57820: // Ebon Champion - case 57821: // Champion of the Kirin Tor - case 57822: // Wyrmrest Champion - { - if (!caster || caster->GetTypeId() != TYPEID_PLAYER) - break; - - uint32 FactionID = 0; - - if (apply) - { - switch (m_spellInfo->Id) + // Unstable Power + case 24658: { - case 57819: FactionID = 1106; break; // Argent Crusade - case 57820: FactionID = 1098; break; // Knights of the Ebon Blade - case 57821: FactionID = 1090; break; // Kirin Tor - case 57822: FactionID = 1091; break; // The Wyrmrest Accord + uint32 spellId = 24659; + if (apply && caster) + { + SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellId); + + for (uint32 i = 0; i < spell->StackAmount; ++i) + caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); + break; + } + target->RemoveAurasDueToSpell(spellId); + break; } - } - caster->ToPlayer()->SetChampioningFaction(FactionID); - break; - } - // LK Intro VO (1) - case 58204: - if (target->GetTypeId() == TYPEID_PLAYER) - { - // Play part 1 - if (apply) - target->PlayDirectSound(14970, target->ToPlayer()); - // continue in 58205 - else - target->CastSpell(target, 58205, true); - } - break; - // LK Intro VO (2) - case 58205: - if (target->GetTypeId() == TYPEID_PLAYER) - { - // Play part 2 - if (apply) - target->PlayDirectSound(14971, target->ToPlayer()); - // Play part 3 - else - target->PlayDirectSound(14972, target->ToPlayer()); - } - break; - case 62061: // Festive Holiday Mount - if (target->HasAuraType(SPELL_AURA_MOUNTED)) - { - uint32 creatureEntry = 0; - if (apply) + // Restless Strength + case 24661: { - if (target->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED)) - creatureEntry = 24906; + uint32 spellId = 24662; + if (apply && caster) + { + SpellInfo const* spell = sSpellMgr->GetSpellInfo(spellId); + for (uint32 i = 0; i < spell->StackAmount; ++i) + caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); + break; + } + target->RemoveAurasDueToSpell(spellId); + break; + } + // Tag Murloc + case 30877: + { + // Tag/untag Blacksilt Scout + target->SetEntry(apply ? 17654 : 17326); + break; + } + case 57819: // Argent Champion + case 57820: // Ebon Champion + case 57821: // Champion of the Kirin Tor + case 57822: // Wyrmrest Champion + { + if (!caster || caster->GetTypeId() != TYPEID_PLAYER) + break; + + uint32 FactionID = 0; + + if (apply) + { + switch (m_spellInfo->Id) + { + case 57819: + FactionID = 1106; + break; // Argent Crusade + case 57820: + FactionID = 1098; + break; // Knights of the Ebon Blade + case 57821: + FactionID = 1090; + break; // Kirin Tor + case 57822: + FactionID = 1091; + break; // The Wyrmrest Accord + } + } + caster->ToPlayer()->SetChampioningFaction(FactionID); + break; + } + // LK Intro VO (1) + case 58204: + if (target->GetTypeId() == TYPEID_PLAYER) + { + // Play part 1 + if (apply) + target->PlayDirectSound(14970, target->ToPlayer()); + // continue in 58205 else - creatureEntry = 15665; + target->CastSpell(target, 58205, true); } - else - creatureEntry = target->GetAuraEffectsByType(SPELL_AURA_MOUNTED).front()->GetMiscValue(); - - if (CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry)) + break; + // LK Intro VO (2) + case 58205: + if (target->GetTypeId() == TYPEID_PLAYER) { - uint32 displayID = ObjectMgr::ChooseDisplayId(creatureInfo); - sObjectMgr->GetCreatureModelRandomGender(&displayID); - - target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, displayID); + // Play part 2 + if (apply) + target->PlayDirectSound(14971, target->ToPlayer()); + // Play part 3 + else + target->PlayDirectSound(14972, target->ToPlayer()); } - } - break; - } + break; + case 62061: // Festive Holiday Mount + if (target->HasAuraType(SPELL_AURA_MOUNTED)) + { + uint32 creatureEntry = 0; + if (apply) + { + if (target->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED)) + creatureEntry = 24906; + else + creatureEntry = 15665; + } + else + creatureEntry = target->GetAuraEffectsByType(SPELL_AURA_MOUNTED).front()->GetMiscValue(); - break; - } + if (CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry)) + { + uint32 displayID = ObjectMgr::ChooseDisplayId(creatureInfo); + sObjectMgr->GetCreatureModelRandomGender(&displayID); + + target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, displayID); + } + } + break; + } + + break; + } case SPELLFAMILY_MAGE: - { - //if (!(mode & AURA_EFFECT_HANDLE_REAL)) + { + //if (!(mode & AURA_EFFECT_HANDLE_REAL)) //break; - break; - } + break; + } case SPELLFAMILY_PRIEST: - { - //if (!(mode & AURA_EFFECT_HANDLE_REAL)) + { + //if (!(mode & AURA_EFFECT_HANDLE_REAL)) //break; - break; - } + break; + } case SPELLFAMILY_DRUID: - { - //if (!(mode & AURA_EFFECT_HANDLE_REAL)) - // break; - break; - } + { + //if (!(mode & AURA_EFFECT_HANDLE_REAL)) + // break; + break; + } case SPELLFAMILY_SHAMAN: - { - //if (!(mode & AURA_EFFECT_HANDLE_REAL)) - // break; - break; - } + { + //if (!(mode & AURA_EFFECT_HANDLE_REAL)) + // break; + break; + } } } @@ -5294,7 +5342,7 @@ void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mod { // Soul Shard only from units that grant XP or honor if (!plCaster->isHonorOrXPTarget(target) || - (target->GetTypeId() == TYPEID_UNIT && !target->ToCreature()->isTappedBy(plCaster))) + (target->GetTypeId() == TYPEID_UNIT && !target->ToCreature()->isTappedBy(plCaster))) return; // If this is Drain Soul, check for Glyph of Drain Soul @@ -5315,7 +5363,7 @@ void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mod InventoryResult msg = plCaster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, GetSpellInfo()->Effects[m_effIndex].ItemType, count, &noSpaceForCount); if (msg != EQUIP_ERR_OK) { - count-=noSpaceForCount; + count -= noSpaceForCount; plCaster->SendEquipError(msg, nullptr, nullptr, GetSpellInfo()->Effects[m_effIndex].ItemType); if (count == 0) return; @@ -5510,7 +5558,7 @@ void AuraEffect::HandleAuraOpenStable(AuraApplication const* aurApp, uint8 mode, if (apply) target->ToPlayer()->GetSession()->SendStablePet(target->GetGUID()); - // client auto close stable dialog at !apply aura + // client auto close stable dialog at !apply aura } void AuraEffect::HandleAuraModFakeInebriation(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -5604,7 +5652,7 @@ void AuraEffect::HandleAuraSetVehicle(AuraApplication const* aurApp, uint8 mode, else if (target->GetVehicleKit()) target->RemoveVehicleKit(); - WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, target->GetPackGUID().size()+4); + WorldPacket data(SMSG_PLAYER_VEHICLE_DATA, target->GetPackGUID().size() + 4); data.appendPackGUID(target->GetGUID()); data << uint32(apply ? vehicleId : 0); target->SendMessageToSet(&data, true); @@ -5635,61 +5683,61 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const switch (GetSpellInfo()->SpellFamilyName) { case SPELLFAMILY_DRUID: - { - switch (GetSpellInfo()->Id) { - // Frenzied Regeneration - case 22842: + switch (GetSpellInfo()->Id) { - // Converts up to 10 rage per second into health for $d. Each point of rage is converted into ${$m2/10}.1% of max health. - // Should be manauser - if (target->getPowerType() != POWER_RAGE) - break; - uint32 rage = target->GetPower(POWER_RAGE); - // Nothing todo - if (rage == 0) - break; - int32 mod = (rage < 100) ? rage : 100; - int32 points = target->CalculateSpellDamage(target, GetSpellInfo(), 1); - int32 regen = target->GetMaxHealth() * (mod * points / 10) / 1000; - target->CastCustomSpell(target, 22845, ®en, 0, 0, true, 0, this); - target->SetPower(POWER_RAGE, rage-mod); - break; + // Frenzied Regeneration + case 22842: + { + // Converts up to 10 rage per second into health for $d. Each point of rage is converted into ${$m2/10}.1% of max health. + // Should be manauser + if (target->getPowerType() != POWER_RAGE) + break; + uint32 rage = target->GetPower(POWER_RAGE); + // Nothing todo + if (rage == 0) + break; + int32 mod = (rage < 100) ? rage : 100; + int32 points = target->CalculateSpellDamage(target, GetSpellInfo(), 1); + int32 regen = target->GetMaxHealth() * (mod * points / 10) / 1000; + target->CastCustomSpell(target, 22845, ®en, 0, 0, true, 0, this); + target->SetPower(POWER_RAGE, rage - mod); + break; + } } - } - break; - } - case SPELLFAMILY_HUNTER: - { - // Explosive Shot - if (GetSpellInfo()->SpellFamilyFlags[1] & 0x80000000) - { - if (caster) - caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, NULL, this); break; } - switch (GetSpellInfo()->Id) + case SPELLFAMILY_HUNTER: { - // Feeding Frenzy Rank 1 - case 53511: - if (target->GetVictim() && target->GetVictim()->HealthBelowPct(35)) - target->CastSpell(target, 60096, true, 0, this); - return; - // Feeding Frenzy Rank 2 - case 53512: - if (target->GetVictim() && target->GetVictim()->HealthBelowPct(35)) - target->CastSpell(target, 60097, true, 0, this); - return; - default: + // Explosive Shot + if (GetSpellInfo()->SpellFamilyFlags[1] & 0x80000000) + { + if (caster) + caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, NULL, this); break; + } + switch (GetSpellInfo()->Id) + { + // Feeding Frenzy Rank 1 + case 53511: + if (target->GetVictim() && target->GetVictim()->HealthBelowPct(35)) + target->CastSpell(target, 60096, true, 0, this); + return; + // Feeding Frenzy Rank 2 + case 53512: + if (target->GetVictim() && target->GetVictim()->HealthBelowPct(35)) + target->CastSpell(target, 60097, true, 0, this); + return; + default: + break; + } + break; } - break; - } case SPELLFAMILY_SHAMAN: if (GetId() == 52179) // Astral Shift { // Periodic need for remove visual on stun/fear/silence lost - if (!(target->GetUInt32Value(UNIT_FIELD_FLAGS)&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))) + if (!(target->GetUInt32Value(UNIT_FIELD_FLAGS) & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED))) target->RemoveAurasDueToSpell(52179); break; } @@ -5712,7 +5760,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const if (target->ToPlayer()->getClass() != CLASS_DEATH_KNIGHT) return; - // timer expired - remove death runes + // timer expired - remove death runes target->ToPlayer()->RemoveRunesByAuraEffect(this); } break; @@ -5736,164 +5784,164 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) switch (auraSpellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - switch (auraId) { - // Thaumaturgy Channel - case 9712: - triggerSpellId = 21029; - if (caster) - caster->CastSpell(caster, triggerSpellId, true); - return; - // Brood Affliction: Bronze - case 23170: - triggerSpellId = 23171; - break; - // Restoration - case 24379: - case 23493: + switch (auraId) { - if (caster) - { - int32 heal = caster->CountPctFromMaxHealth(10); - caster->HealBySpell(target, auraSpellInfo, heal); - - if (int32 mana = caster->GetMaxPower(POWER_MANA)) + // Thaumaturgy Channel + case 9712: + triggerSpellId = 21029; + if (caster) + caster->CastSpell(caster, triggerSpellId, true); + return; + // Brood Affliction: Bronze + case 23170: + triggerSpellId = 23171; + break; + // Restoration + case 24379: + case 23493: { - mana /= 10; - caster->EnergizeBySpell(caster, 23493, mana, POWER_MANA); - } - } - return; - } - // Nitrous Boost - case 27746: - if (caster && target->GetPower(POWER_MANA) >= 10) - { - target->ModifyPower(POWER_MANA, -10); - target->SendEnergizeSpellLog(caster, 27746, 10, POWER_MANA); - } - else - target->RemoveAurasDueToSpell(27746); - return; - // Frost Blast - case 27808: - if (caster) - { - caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, NULL, this); - if (GetTickNumber() == 1) - caster->CastSpell(target, 27808, true); - } - return; - // Inoculate Nestlewood Owlkin - case 29528: - if (target->GetTypeId() != TYPEID_UNIT) // prevent error reports in case ignored player target - return; - break; - // Feed Captured Animal - case 29917: - triggerSpellId = 29916; - break; - // Extract Gas - case 30427: - { - // move loot to player inventory and despawn target - if (caster && caster->GetTypeId() == TYPEID_PLAYER && - target->GetTypeId() == TYPEID_UNIT && - target->ToCreature()->GetCreatureTemplate()->type == CREATURE_TYPE_GAS_CLOUD) - { - Player* player = caster->ToPlayer(); - Creature* creature = target->ToCreature(); - // missing lootid has been reported on startup - just return - if (!creature->GetCreatureTemplate()->SkinLootId) + if (caster) + { + int32 heal = caster->CountPctFromMaxHealth(10); + caster->HealBySpell(target, auraSpellInfo, heal); + + if (int32 mana = caster->GetMaxPower(POWER_MANA)) + { + mana /= 10; + caster->EnergizeBySpell(caster, 23493, mana, POWER_MANA); + } + } return; - - player->AutoStoreLoot(creature->GetCreatureTemplate()->SkinLootId, LootTemplates_Skinning, true); - - creature->DespawnOrUnsummon(); - } - return; - } - // Quake - case 30576: - triggerSpellId = 30571; - break; - // Doom - // TODO: effect trigger spell may be independant on spell targets, and executed in spell finish phase - // so instakill will be naturally done before trigger spell - case 31347: - { - target->CastSpell(target, 31350, true, NULL, this); - Unit::Kill(target, target); - return; - } - // Spellcloth - case 31373: - { - // Summon Elemental after create item - target->SummonCreature(17870, 0, 0, 0, target->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0); - return; - } - // Eye of Grillok - case 38495: - triggerSpellId = 38530; - break; - // Absorb Eye of Grillok (Zezzak's Shard) - case 38554: - { - if (!caster || target->GetTypeId() != TYPEID_UNIT) + } + // Nitrous Boost + case 27746: + if (caster && target->GetPower(POWER_MANA) >= 10) + { + target->ModifyPower(POWER_MANA, -10); + target->SendEnergizeSpellLog(caster, 27746, 10, POWER_MANA); + } + else + target->RemoveAurasDueToSpell(27746); return; + // Frost Blast + case 27808: + if (caster) + { + caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, NULL, this); + if (GetTickNumber() == 1) + caster->CastSpell(target, 27808, true); + } + return; + // Inoculate Nestlewood Owlkin + case 29528: + if (target->GetTypeId() != TYPEID_UNIT) // prevent error reports in case ignored player target + return; + break; + // Feed Captured Animal + case 29917: + triggerSpellId = 29916; + break; + // Extract Gas + case 30427: + { + // move loot to player inventory and despawn target + if (caster && caster->GetTypeId() == TYPEID_PLAYER && + target->GetTypeId() == TYPEID_UNIT && + target->ToCreature()->GetCreatureTemplate()->type == CREATURE_TYPE_GAS_CLOUD) + { + Player* player = caster->ToPlayer(); + Creature* creature = target->ToCreature(); + // missing lootid has been reported on startup - just return + if (!creature->GetCreatureTemplate()->SkinLootId) + return; - caster->CastSpell(caster, 38495, true, NULL, this); + player->AutoStoreLoot(creature->GetCreatureTemplate()->SkinLootId, LootTemplates_Skinning, true); - Creature* creatureTarget = target->ToCreature(); + creature->DespawnOrUnsummon(); + } + return; + } + // Quake + case 30576: + triggerSpellId = 30571; + break; + // Doom + // TODO: effect trigger spell may be independant on spell targets, and executed in spell finish phase + // so instakill will be naturally done before trigger spell + case 31347: + { + target->CastSpell(target, 31350, true, NULL, this); + Unit::Kill(target, target); + return; + } + // Spellcloth + case 31373: + { + // Summon Elemental after create item + target->SummonCreature(17870, 0, 0, 0, target->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0); + return; + } + // Eye of Grillok + case 38495: + triggerSpellId = 38530; + break; + // Absorb Eye of Grillok (Zezzak's Shard) + case 38554: + { + if (!caster || target->GetTypeId() != TYPEID_UNIT) + return; - creatureTarget->DespawnOrUnsummon(); - return; - } - // Tear of Azzinoth Summon Channel - it's not really supposed to do anything, and this only prevents the console spam - case 39857: - triggerSpellId = 39856; - break; - // Personalized Weather - case 46736: - triggerSpellId = 46737; - break; - // Shield Level 1 - case 63130: - // Shield Level 2 - case 63131: - // Shield Level 3 - case 63132: - // Ball of Flames Visual - case 71706: - return; - // Oculus, Mage-Lord Urom, Time Bomb - case 51121: - case 59376: - { - const int32 dmg = target->GetMaxHealth()-target->GetHealth(); - target->CastCustomSpell(target, 51132, &dmg, 0, 0, true); - return; + caster->CastSpell(caster, 38495, true, NULL, this); + + Creature* creatureTarget = target->ToCreature(); + + creatureTarget->DespawnOrUnsummon(); + return; + } + // Tear of Azzinoth Summon Channel - it's not really supposed to do anything, and this only prevents the console spam + case 39857: + triggerSpellId = 39856; + break; + // Personalized Weather + case 46736: + triggerSpellId = 46737; + break; + // Shield Level 1 + case 63130: + // Shield Level 2 + case 63131: + // Shield Level 3 + case 63132: + // Ball of Flames Visual + case 71706: + return; + // Oculus, Mage-Lord Urom, Time Bomb + case 51121: + case 59376: + { + const int32 dmg = target->GetMaxHealth() - target->GetHealth(); + target->CastCustomSpell(target, 51132, &dmg, 0, 0, true); + return; + } } + break; } - break; - } case SPELLFAMILY_SHAMAN: - { - switch (auraId) { - // Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield) - case 28820: + switch (auraId) { - // Need remove self if Lightning Shield not active - if (!target->GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400)) - target->RemoveAurasDueToSpell(28820); - return; + // Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield) + case 28820: + { + // Need remove self if Lightning Shield not active + if (!target->GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_SHAMAN, 0x400)) + target->RemoveAurasDueToSpell(28820); + return; + } } + break; } - break; - } default: break; } @@ -5916,31 +5964,31 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) return; // Eye of Eternity, Malygos, Arcane Overload case 56432: - if (triggerSpellId==56438) + if (triggerSpellId == 56438) { - target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)(10000*(1.0f-0.02f*(m_tickNumber+1))), NULL, true, NULL, this); + target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)(10000 * (1.0f - 0.02f * (m_tickNumber + 1))), NULL, true, NULL, this); return; } break; // Beacon of Light case 53563: - { - // area aura owner casts the spell - GetBase()->GetUnitOwner()->CastSpell(target, triggeredSpellInfo, true, 0, this, GetBase()->GetUnitOwner()->GetGUID()); - return; - } + { + // area aura owner casts the spell + GetBase()->GetUnitOwner()->CastSpell(target, triggeredSpellInfo, true, 0, this, GetBase()->GetUnitOwner()->GetGUID()); + return; + } // Slime Spray - temporary here until preventing default effect works again // added on 9.10.2010 case 69508: - { - if (caster) - caster->CastSpell(target, triggerSpellId, true, nullptr, nullptr, caster->GetGUID()); - return; - } + { + if (caster) + caster->CastSpell(target, triggerSpellId, true, nullptr, nullptr, caster->GetGUID()); + return; + } // Trial of the Crusader, Jaraxxus, Spinning Pain Spike case 66283: { - const int32 dmg = target->GetMaxHealth()/2; + const int32 dmg = target->GetMaxHealth() / 2; target->CastCustomSpell(target, 66316, &dmg, nullptr, nullptr, true); return; } @@ -5949,24 +5997,24 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) case 59524: case 54438: case 59523: - { - if (caster) - if (Unit* victim = caster->GetVictim()) - if(victim->GetDistance(caster)<45.0f) - { - target = victim; - break; - } - return; - } + { + if (caster) + if (Unit* victim = caster->GetVictim()) + if(victim->GetDistance(caster) < 45.0f) + { + target = victim; + break; + } + return; + } // quest A Tangled Skein (12555) case 51165: - { - if( caster && caster->GetTypeId() == TYPEID_PLAYER ) - caster->ToPlayer()->KilledMonsterCredit(28289, 0); + { + if( caster && caster->GetTypeId() == TYPEID_PLAYER ) + caster->ToPlayer()->KilledMonsterCredit(28289, 0); - break; - } + break; + } case 24745: // Summon Templar, Trigger case 24747: // Summon Templar Fire, Trigger case 24757: // Summon Templar Air, Trigger @@ -5982,13 +6030,13 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) case 24791: // Summon Royal Air, Trigger case 24792: // Summon Royal Earth, Trigger case 24793: // Summon Royal Water, Trigger - { - // All this spells trigger a spell that requires reagents; if the - // triggered spell is cast as "triggered", reagents are not consumed - if (caster) - caster->CastSpell(target, triggerSpellId, false); - return; - } + { + // All this spells trigger a spell that requires reagents; if the + // triggered spell is cast as "triggered", reagents are not consumed + if (caster) + caster->CastSpell(target, triggerSpellId, false); + return; + } // Hunter - Rapid Recuperation case 56654: case 58882: @@ -6016,9 +6064,9 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) // Xinef: do not skip reagent cost for entry casts TriggerCastFlags triggerFlags = TRIGGERED_FULL_MASK; if (GetSpellInfo()->Effects[GetEffIndex()].TargetA.GetCheckType() == TARGET_CHECK_ENTRY || GetSpellInfo()->Effects[GetEffIndex()].TargetB.GetCheckType() == TARGET_CHECK_ENTRY) - triggerFlags = TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST); + triggerFlags = TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST); - triggerCaster->CastSpell(targets, triggeredSpellInfo, NULL, triggerFlags, NULL, this); + triggerCaster->CastSpell(targets, triggeredSpellInfo, NULL, triggerFlags, NULL, this); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandlePeriodicTriggerSpellAuraTick: Spell %u Trigger %u", GetId(), triggeredSpellInfo->Id); #endif @@ -6040,17 +6088,18 @@ void AuraEffect::HandlePeriodicTriggerSpellWithValueAuraTick(Unit* target, Unit* targets.SetDstChannel(m_channelData->spellDst); targets.SetObjectTargetChannel(m_channelData->channelGUID); } - + CustomSpellValues values; values.AddSpellMod(SPELLVALUE_BASE_POINT0, GetAmount()); - triggerCaster->CastSpell(targets, triggeredSpellInfo, &values, TRIGGERED_FULL_MASK, NULL, this); + triggerCaster->CastSpell(targets, triggeredSpellInfo, &values, TRIGGERED_FULL_MASK, NULL, this); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandlePeriodicTriggerSpellWithValueAuraTick: Spell %u Trigger %u", GetId(), triggeredSpellInfo->Id); #endif } } - else { + else + { #ifdef ELUNA Creature* c = target->ToCreature(); if (c && caster) @@ -6075,7 +6124,7 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const // Consecrate ticks can miss and will not show up in the combat log if (caster && GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA && - caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE) + caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE) return; // some auras remove at specific health level or more @@ -6083,8 +6132,12 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const { switch (GetSpellInfo()->Id) { - case 43093: case 31956: case 38801: // Grievous Wound - case 35321: case 38363: case 39215: // Gushing Wound + case 43093: + case 31956: + case 38801: // Grievous Wound + case 35321: + case 38363: + case 39215: // Gushing Wound if (target->IsFullHealth()) { target->RemoveAurasDueToSpell(GetSpellInfo()->Id); @@ -6092,15 +6145,15 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const } break; case 38772: // Grievous Wound - { - uint32 percent = GetSpellInfo()->Effects[EFFECT_1].CalcValue(caster); - if (!target->HealthBelowPct(percent)) { - target->RemoveAurasDueToSpell(GetSpellInfo()->Id); - return; + uint32 percent = GetSpellInfo()->Effects[EFFECT_1].CalcValue(caster); + if (!target->HealthBelowPct(percent)) + { + target->RemoveAurasDueToSpell(GetSpellInfo()->Id); + return; + } + break; } - break; - } } } @@ -6110,10 +6163,10 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const // ignore non positive values (can be result apply spellmods to aura damage uint32 damage = std::max(GetAmount(), 0); - + // Script Hook For HandlePeriodicDamageAurasTick -- Allow scripts to change the Damage pre class mitigation calculations sScriptMgr->ModifyPeriodicDamageAurasTick(target, caster, damage); - + if (GetAuraType() == SPELL_AURA_PERIODIC_DAMAGE) { // xinef: leave only target depending bonuses, rest is handled in calculate amount @@ -6135,10 +6188,10 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const uint32 totalTick = GetTotalTicks(); // 1..4 ticks, 1/2 from normal tick damage if (m_tickNumber <= totalTick / 3) - damage = damage/2; + damage = damage / 2; // 9..12 ticks, 3/2 from normal tick damage else if (m_tickNumber > totalTick * 2 / 3) - damage += (damage+1)/2; // +1 prevent 0.5 damage possible lost at 1..4 ticks + damage += (damage + 1) / 2; // +1 prevent 0.5 damage possible lost at 1..4 ticks // 5..8 ticks have normal tick damage } // There is a Chance to make a Soul Shard when Drain soul does damage @@ -6174,7 +6227,7 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("PeriodicTick: %u (TypeId: %u) attacked %u (TypeId: %u) for %u dmg inflicted by %u abs is %u", - GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId(), absorb); + GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId(), absorb); #endif Unit::DealDamageMods(target, damage, &absorb); @@ -6191,7 +6244,7 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const if (absorb > 0) procEx |= PROC_EX_ABSORB; - damage = (damage <= absorb+resist) ? 0 : (damage-absorb-resist); + damage = (damage <= absorb + resist) ? 0 : (damage - absorb - resist); if (damage) procVictim |= PROC_FLAG_TAKEN_DAMAGE; @@ -6219,7 +6272,7 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c } if (caster && GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA && - caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE) + caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE) return; uint32 absorb = 0; @@ -6227,10 +6280,10 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c CleanDamage cleanDamage = CleanDamage(0, 0, BASE_ATTACK, MELEE_HIT_NORMAL); uint32 damage = std::max(GetAmount(), 0); - + // Script Hook For HandlePeriodicHealthLeechAurasTick -- Allow scripts to change the Damage pre class mitigation calculations sScriptMgr->ModifyPeriodicDamageAurasTick(target, caster, damage); - + if (GetBase()->GetType() == DYNOBJ_AURA_TYPE) damage = caster->SpellDamageBonusDone(target, GetSpellInfo(), damage, DOT, 0.0f, GetBase()->GetStackAmount()); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); @@ -6261,7 +6314,7 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c if (absorb > 0) procEx |= PROC_EX_ABSORB; - damage = (damage <= absorb+resist) ? 0 : (damage-absorb-resist); + damage = (damage <= absorb + resist) ? 0 : (damage - absorb - resist); if (damage) procVictim |= PROC_FLAG_TAKEN_DAMAGE; @@ -6270,12 +6323,12 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("PeriodicTick: %u (TypeId: %u) health leech of %u (TypeId: %u) for %u dmg inflicted by %u abs is %u", - GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId(), absorb); + GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId(), absorb); #endif if (caster) - caster->SendSpellNonMeleeDamageLog(target, GetId(), damage+absorb+resist, GetSpellInfo()->GetSchoolMask(), absorb, resist, false, 0, crit); + caster->SendSpellNonMeleeDamageLog(target, GetId(), damage + absorb + resist, GetSpellInfo()->GetSchoolMask(), absorb, resist, false, 0, crit); + - int32 new_damage; new_damage = Unit::DealDamage(caster, target, damage, &cleanDamage, DOT, GetSpellInfo()->GetSchoolMask(), GetSpellInfo(), false); @@ -6383,7 +6436,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const // the most ugly hack i made :P the other option is to change all spellvalues to float... // demonic aegis if (caster && GetSpellInfo()->SpellFamilyName == SPELLFAMILY_WARLOCK && (GetSpellInfo()->SpellFamilyFlags[1] & 0x20000000)) - if (AuraEffect *aurEff = caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_WARLOCK, 89, 0)) + if (AuraEffect* aurEff = caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_WARLOCK, 89, 0)) AddPct(TakenTotalMod, aurEff->GetAmount()); damage = uint32(target->CountPctFromMaxHealth(damage)); @@ -6394,7 +6447,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const // Wild Growth = amount + (6 - 2*doneTicks) * ticks* amount / 100 if (GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID && GetSpellInfo()->SpellIconID == 2864) { - uint32 tickNumber = GetTickNumber()-1; + uint32 tickNumber = GetTickNumber() - 1; int32 tempAmount = m_spellInfo->Effects[m_effIndex].CalcValue(caster, &m_baseAmount, nullptr); float drop = 2.0f; @@ -6404,7 +6457,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const if (AuraEffect* aurEff = caster->GetAuraEffect(70658, 0)) AddPct(drop, -aurEff->GetAmount()); - damage += GetTotalTicks() * tempAmount * (6-(drop*tickNumber)) * 0.01f; + damage += GetTotalTicks() * tempAmount * (6 - (drop * tickNumber)) * 0.01f; } if (GetBase()->GetType() == DYNOBJ_AURA_TYPE) @@ -6418,7 +6471,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("PeriodicTick: %u (TypeId: %u) heal of %u (TypeId: %u) for %u health inflicted by %u", - GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId()); + GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId()); #endif uint32 absorb = 0; uint32 heal = uint32(damage); @@ -6479,7 +6532,7 @@ void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) con } if (GetSpellInfo()->Effects[GetEffIndex()].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA && - caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE) + caster->SpellHitResult(target, GetSpellInfo(), false) != SPELL_MISS_NONE) return; // ignore negative values (can be result apply spellmods to aura damage @@ -6498,7 +6551,7 @@ void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) con #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("PeriodicTick: %u (TypeId: %u) power leech of %u (TypeId: %u) for %u dmg inflicted by %u", - GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), drainAmount, GetId()); + GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), drainAmount, GetId()); #endif // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (powerType == POWER_MANA) @@ -6520,13 +6573,13 @@ void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) con } target->AddThreat(caster, float(gainedAmount) * 0.5f, GetSpellInfo()->GetSchoolMask(), GetSpellInfo()); - + // remove CC auras target->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE); // Drain Mana if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK - && m_spellInfo->SpellFamilyFlags[0] & 0x00000010) + && m_spellInfo->SpellFamilyFlags[0] & 0x00000010) { int32 manaFeedVal = 0; if (AuraEffect const* aurEff = GetBase()->GetEffect(1)) @@ -6562,10 +6615,10 @@ void AuraEffect::HandleObsModPowerAuraTick(Unit* target, Unit* caster) const return; // ignore negative values (can be result apply spellmods to aura damage - uint32 amount = std::max(m_amount, 0) * target->GetMaxPower(powerType) /100; + uint32 amount = std::max(m_amount, 0) * target->GetMaxPower(powerType) / 100; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("PeriodicTick: %u (TypeId: %u) energize %u (TypeId: %u) for %u dmg inflicted by %u", - GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), amount, GetId()); + GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), amount, GetId()); #endif SpellPeriodicAuraLogInfo pInfo(this, amount, 0, 0, 0, 0.0f, false); target->SendPeriodicAuraLog(&pInfo); @@ -6604,7 +6657,7 @@ void AuraEffect::HandlePeriodicEnergizeAuraTick(Unit* target, Unit* caster) cons #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDetail("PeriodicTick: %u (TypeId: %u) energize %u (TypeId: %u) for %u dmg inflicted by %u", - GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), amount, GetId()); + GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), amount, GetId()); #endif int32 gain = target->ModifyPower(powerType, amount); @@ -6670,7 +6723,8 @@ void AuraEffect::HandleProcTriggerSpellAuraProc(AuraApplication* aurApp, ProcEve #endif triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this); } - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleProcTriggerSpellAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); #endif @@ -6694,7 +6748,8 @@ void AuraEffect::HandleProcTriggerSpellWithValueAuraProc(AuraApplication* aurApp #endif triggerCaster->CastCustomSpell(triggerTarget, triggerSpellId, &basepoints0, nullptr, nullptr, true, NULL, this); } - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); #endif diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.h b/src/server/game/Spells/Auras/SpellAuraEffects.h index 04d696dd9..51a846b88 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.h +++ b/src/server/game/Spells/Auras/SpellAuraEffects.h @@ -19,305 +19,305 @@ typedef void(AuraEffect::*pAuraEffectHandler)(AuraApplication const* aurApp, uin class AuraEffect { - friend void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount); + friend void Aura::_InitEffects(uint8 effMask, Unit* caster, int32* baseAmount); friend Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID, bool noPeriodicReset); friend Aura::~Aura(); - private: - ~AuraEffect(); - explicit AuraEffect(Aura* base, uint8 effIndex, int32 *baseAmount, Unit* caster); - public: - Unit* GetCaster() const { return GetBase()->GetCaster(); } - uint64 GetCasterGUID() const { return GetBase()->GetCasterGUID(); } - Aura* GetBase() const { return m_base; } - void GetTargetList(std::list & targetList) const; - void GetApplicationList(std::list & applicationList) const; - SpellModifier* GetSpellModifier() const { return m_spellmod; } +private: + ~AuraEffect(); + explicit AuraEffect(Aura* base, uint8 effIndex, int32* baseAmount, Unit* caster); +public: + Unit* GetCaster() const { return GetBase()->GetCaster(); } + uint64 GetCasterGUID() const { return GetBase()->GetCasterGUID(); } + Aura* GetBase() const { return m_base; } + void GetTargetList(std::list& targetList) const; + void GetApplicationList(std::list& applicationList) const; + SpellModifier* GetSpellModifier() const { return m_spellmod; } - SpellInfo const* GetSpellInfo() const { return m_spellInfo; } - uint32 GetId() const; - uint32 GetEffIndex() const { return m_effIndex; } - int32 GetBaseAmount() const { return m_baseAmount; } - int32 GetAmplitude() const { return m_amplitude; } + SpellInfo const* GetSpellInfo() const { return m_spellInfo; } + uint32 GetId() const; + uint32 GetEffIndex() const { return m_effIndex; } + int32 GetBaseAmount() const { return m_baseAmount; } + int32 GetAmplitude() const { return m_amplitude; } - int32 GetMiscValueB() const; - int32 GetMiscValue() const; - AuraType GetAuraType() const; - int32 GetAmount() const { return m_isAuraEnabled ? m_amount : 0; } - int32 GetForcedAmount() const { return m_amount; } - void SetAmount(int32 amount) { m_amount = amount; m_canBeRecalculated = false;} + int32 GetMiscValueB() const; + int32 GetMiscValue() const; + AuraType GetAuraType() const; + int32 GetAmount() const { return m_isAuraEnabled ? m_amount : 0; } + int32 GetForcedAmount() const { return m_amount; } + void SetAmount(int32 amount) { m_amount = amount; m_canBeRecalculated = false;} - int32 GetPeriodicTimer() const { return m_periodicTimer; } - void SetPeriodicTimer(int32 periodicTimer) { m_periodicTimer = periodicTimer; } + int32 GetPeriodicTimer() const { return m_periodicTimer; } + void SetPeriodicTimer(int32 periodicTimer) { m_periodicTimer = periodicTimer; } - int32 CalculateAmount(Unit* caster); - void CalculatePeriodic(Unit* caster, bool create = false, bool load = false); - void CalculatePeriodicData(); - void CalculateSpellMod(); - void ChangeAmount(int32 newAmount, bool mark = true, bool onStackOrReapply = false); - void RecalculateAmount() { if (!CanBeRecalculated()) return; ChangeAmount(CalculateAmount(GetCaster()), false); } - void RecalculateAmount(Unit* caster) { if (!CanBeRecalculated()) return; ChangeAmount(CalculateAmount(caster), false); } - bool CanBeRecalculated() const { return m_canBeRecalculated; } - void SetCanBeRecalculated(bool val) { m_canBeRecalculated = val; } - void HandleEffect(AuraApplication * aurApp, uint8 mode, bool apply); - void HandleEffect(Unit* target, uint8 mode, bool apply); - void ApplySpellMod(Unit* target, bool apply); + int32 CalculateAmount(Unit* caster); + void CalculatePeriodic(Unit* caster, bool create = false, bool load = false); + void CalculatePeriodicData(); + void CalculateSpellMod(); + void ChangeAmount(int32 newAmount, bool mark = true, bool onStackOrReapply = false); + void RecalculateAmount() { if (!CanBeRecalculated()) return; ChangeAmount(CalculateAmount(GetCaster()), false); } + void RecalculateAmount(Unit* caster) { if (!CanBeRecalculated()) return; ChangeAmount(CalculateAmount(caster), false); } + bool CanBeRecalculated() const { return m_canBeRecalculated; } + void SetCanBeRecalculated(bool val) { m_canBeRecalculated = val; } + void HandleEffect(AuraApplication* aurApp, uint8 mode, bool apply); + void HandleEffect(Unit* target, uint8 mode, bool apply); + void ApplySpellMod(Unit* target, bool apply); - void Update(uint32 diff, Unit* caster); - void UpdatePeriodic(Unit* caster); + void Update(uint32 diff, Unit* caster); + void UpdatePeriodic(Unit* caster); - uint32 GetTickNumber() const { return m_tickNumber; } - int32 GetTotalTicks() const { return m_amplitude ? (GetBase()->GetMaxDuration() / m_amplitude) : 1;} - void ResetPeriodic(bool resetPeriodicTimer = false) { if (resetPeriodicTimer) m_periodicTimer = m_amplitude; m_tickNumber = 0;} + uint32 GetTickNumber() const { return m_tickNumber; } + int32 GetTotalTicks() const { return m_amplitude ? (GetBase()->GetMaxDuration() / m_amplitude) : 1;} + void ResetPeriodic(bool resetPeriodicTimer = false) { if (resetPeriodicTimer) m_periodicTimer = m_amplitude; m_tickNumber = 0;} - bool IsPeriodic() const { return m_isPeriodic; } - void SetPeriodic(bool isPeriodic) { m_isPeriodic = isPeriodic; } - bool IsAffectedOnSpell(SpellInfo const* spell) const; - bool HasSpellClassMask() const; + bool IsPeriodic() const { return m_isPeriodic; } + void SetPeriodic(bool isPeriodic) { m_isPeriodic = isPeriodic; } + bool IsAffectedOnSpell(SpellInfo const* spell) const; + bool HasSpellClassMask() const; - void SendTickImmune(Unit* target, Unit* caster) const; - void PeriodicTick(AuraApplication * aurApp, Unit* caster) const; + void SendTickImmune(Unit* target, Unit* caster) const; + void PeriodicTick(AuraApplication* aurApp, Unit* caster) const; - void HandleProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); + void HandleProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); - void CleanupTriggeredSpells(Unit* target); + void CleanupTriggeredSpells(Unit* target); - // add/remove SPELL_AURA_MOD_SHAPESHIFT (36) linked auras - void HandleShapeshiftBoosts(Unit* target, bool apply) const; + // add/remove SPELL_AURA_MOD_SHAPESHIFT (36) linked auras + void HandleShapeshiftBoosts(Unit* target, bool apply) const; - // xinef: storing initial crit chance - float GetCritChance() const { return m_critChance; } - void SetCritChance(float crit) { m_critChance = crit; } - uint8 GetCasterLevel() const { return m_casterLevel; } - bool CanApplyResilience() const { return m_applyResilience; } - float GetPctMods() const { return m_pctMods; } + // xinef: storing initial crit chance + float GetCritChance() const { return m_critChance; } + void SetCritChance(float crit) { m_critChance = crit; } + uint8 GetCasterLevel() const { return m_casterLevel; } + bool CanApplyResilience() const { return m_applyResilience; } + float GetPctMods() const { return m_pctMods; } - // xinef: stacking - uint32 GetAuraGroup() const { return m_auraGroup; } - int32 GetOldAmount() const { return m_oldAmount; } - void SetOldAmount(int32 amount) { m_oldAmount = amount; } - void SetEnabled(bool enabled) { m_isAuraEnabled = enabled; } + // xinef: stacking + uint32 GetAuraGroup() const { return m_auraGroup; } + int32 GetOldAmount() const { return m_oldAmount; } + void SetOldAmount(int32 amount) { m_oldAmount = amount; } + void SetEnabled(bool enabled) { m_isAuraEnabled = enabled; } - private: - Aura* const m_base; +private: + Aura* const m_base; - SpellInfo const* const m_spellInfo; - int32 const m_baseAmount; + SpellInfo const* const m_spellInfo; + int32 const m_baseAmount; - bool m_applyResilience; - uint8 m_casterLevel; - int32 m_amount; - float m_critChance; - float m_pctMods; + bool m_applyResilience; + uint8 m_casterLevel; + int32 m_amount; + float m_critChance; + float m_pctMods; - // xinef: stacking - uint32 m_auraGroup; - int32 m_oldAmount; - bool m_isAuraEnabled; - // xinef: channel information for channel triggering - ChannelTargetData* m_channelData; + // xinef: stacking + uint32 m_auraGroup; + int32 m_oldAmount; + bool m_isAuraEnabled; + // xinef: channel information for channel triggering + ChannelTargetData* m_channelData; - SpellModifier* m_spellmod; + SpellModifier* m_spellmod; - int32 m_periodicTimer; - int32 m_amplitude; - uint32 m_tickNumber; + int32 m_periodicTimer; + int32 m_amplitude; + uint32 m_tickNumber; - uint8 const m_effIndex; - bool m_canBeRecalculated; - bool m_isPeriodic; - private: - float CalcPeriodicCritChance(Unit const* caster, Unit const* target) const; + uint8 const m_effIndex; + bool m_canBeRecalculated; + bool m_isPeriodic; +private: + float CalcPeriodicCritChance(Unit const* caster, Unit const* target) const; - public: - // aura effect apply/remove handlers - void HandleNULL(AuraApplication const* /*aurApp*/, uint8 /*mode*/, bool /*apply*/) const - { - // not implemented - } - void HandleUnused(AuraApplication const* /*aurApp*/, uint8 /*mode*/, bool /*apply*/) const - { - // useless - } - void HandleNoImmediateEffect(AuraApplication const* /*aurApp*/, uint8 /*mode*/, bool /*apply*/) const - { - // aura type not have immediate effect at add/remove and handled by ID in other code place - } - // visibility & phases - void HandleModInvisibilityDetect(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModInvisibility(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModStealth(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModStealthLevel(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModStealthDetect(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleSpiritOfRedemption(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraGhost(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandlePhase(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // unit model - void HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraTransform(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModScale(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraCloneCaster(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // fight - void HandleFeignDeath(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModUnattackable(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModDisarm(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModSilence(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModPacify(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModPacifyAndSilence(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraAllowOnlyAbility(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // tracking - void HandleAuraTrackResources(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraTrackCreatures(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraTrackStealthed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModStalked(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraUntrackable(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // skills & talents - void HandleAuraModPetTalentsPoints(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModSkill(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // movement - void HandleAuraMounted(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraAllowFlight(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraWaterWalk(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraFeatherFall(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraHover(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleWaterBreathing(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleForceMoveForward(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // threat - void HandleModThreat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModTotalThreat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModTaunt(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // control - void HandleModConfuse(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModFear(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModStun(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModRoot(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandlePreventFleeing(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // charm - void HandleModPossess(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModPossessPet(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModCharm(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleCharmConvert(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraControlVehicle(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // modify speed - void HandleAuraModIncreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseMountedSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseFlightSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseSwimSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModDecreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModUseNormalSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // immunity - void HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModMechanicImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModEffectImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModStateImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModSchoolImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModDmgImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModDispelImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // modify stats - // resistance - void HandleAuraModResistanceExclusive(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModBaseResistancePCT(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModResistancePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModBaseResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModTargetResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // stat - void HandleAuraModStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModPercentStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellDamagePercentFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellHealingPercentFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellDamagePercentFromAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellHealingPercentFromAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModHealingDone(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModTotalPercentStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModResistenceOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModExpertise(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // heal and energize - void HandleModPowerRegen(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModPowerRegenPCT(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModManaRegen(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseHealth(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseMaxHealth(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseEnergy(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseEnergyPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModIncreaseHealthPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraIncreaseBaseHealthPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // fight - void HandleAuraModParryPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModDodgePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModBlockPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModRegenInterrupt(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModWeaponCritPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModHitChance(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellHitChance(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellCritChance(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModSpellCritChanceShool(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModCritPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // attack speed - void HandleModCastingSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModMeleeRangedSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModCombatSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModAttackSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModMeleeSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModRangedHaste(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleRangedAmmoHaste(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // combat rating - void HandleModRating(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModRatingFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // attack power - void HandleAuraModAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModRangedAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModAttackPowerPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModRangedAttackPowerPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModRangedAttackPowerOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModAttackPowerOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModAttackPowerOfArmor(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // damage bonus - void HandleModDamageDone(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModDamagePercentDone(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModOffhandDamagePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleShieldBlockValue(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // power cost - void HandleModPowerCostPCT(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleModPowerCost(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleArenaPreparation(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleNoReagentUseAura(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraRetainComboPoints(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // others - void HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleBindSight(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleForceReaction(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraEmpathy(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModFaction(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleComprehendLanguage(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraConvertRune(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraLinked(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraOpenStable(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraModFakeInebriation(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraOverrideSpells(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandleAuraSetVehicle(AuraApplication const* aurApp, uint8 mode, bool apply) const; - void HandlePreventResurrection(AuraApplication const* aurApp, uint8 mode, bool apply) const; +public: + // aura effect apply/remove handlers + void HandleNULL(AuraApplication const* /*aurApp*/, uint8 /*mode*/, bool /*apply*/) const + { + // not implemented + } + void HandleUnused(AuraApplication const* /*aurApp*/, uint8 /*mode*/, bool /*apply*/) const + { + // useless + } + void HandleNoImmediateEffect(AuraApplication const* /*aurApp*/, uint8 /*mode*/, bool /*apply*/) const + { + // aura type not have immediate effect at add/remove and handled by ID in other code place + } + // visibility & phases + void HandleModInvisibilityDetect(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModInvisibility(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModStealth(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModStealthLevel(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModStealthDetect(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleSpiritOfRedemption(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraGhost(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandlePhase(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // unit model + void HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraTransform(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModScale(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraCloneCaster(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // fight + void HandleFeignDeath(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModUnattackable(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModDisarm(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModSilence(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModPacify(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModPacifyAndSilence(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraAllowOnlyAbility(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // tracking + void HandleAuraTrackResources(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraTrackCreatures(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraTrackStealthed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModStalked(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraUntrackable(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // skills & talents + void HandleAuraModPetTalentsPoints(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModSkill(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // movement + void HandleAuraMounted(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraAllowFlight(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraWaterWalk(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraFeatherFall(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraHover(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleWaterBreathing(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleForceMoveForward(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // threat + void HandleModThreat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModTotalThreat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModTaunt(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // control + void HandleModConfuse(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModFear(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModStun(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModRoot(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandlePreventFleeing(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // charm + void HandleModPossess(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModPossessPet(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModCharm(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleCharmConvert(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraControlVehicle(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // modify speed + void HandleAuraModIncreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseMountedSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseFlightSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseSwimSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModDecreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModUseNormalSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // immunity + void HandleModStateImmunityMask(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModMechanicImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModEffectImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModStateImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModSchoolImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModDmgImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModDispelImmunity(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // modify stats + // resistance + void HandleAuraModResistanceExclusive(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModBaseResistancePCT(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModResistancePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModBaseResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModTargetResistance(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // stat + void HandleAuraModStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModPercentStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellDamagePercentFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellHealingPercentFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellDamagePercentFromAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellHealingPercentFromAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModHealingDone(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModTotalPercentStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModResistenceOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModExpertise(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // heal and energize + void HandleModPowerRegen(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModPowerRegenPCT(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModManaRegen(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseHealth(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseMaxHealth(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseEnergy(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseEnergyPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModIncreaseHealthPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraIncreaseBaseHealthPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // fight + void HandleAuraModParryPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModDodgePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModBlockPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModRegenInterrupt(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModWeaponCritPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModHitChance(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellHitChance(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellCritChance(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModSpellCritChanceShool(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModCritPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // attack speed + void HandleModCastingSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModMeleeRangedSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModCombatSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModAttackSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModMeleeSpeedPct(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModRangedHaste(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleRangedAmmoHaste(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // combat rating + void HandleModRating(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModRatingFromStat(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // attack power + void HandleAuraModAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModRangedAttackPower(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModAttackPowerPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModRangedAttackPowerPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModRangedAttackPowerOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModAttackPowerOfStatPercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModAttackPowerOfArmor(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // damage bonus + void HandleModDamageDone(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModDamagePercentDone(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModOffhandDamagePercent(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleShieldBlockValue(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // power cost + void HandleModPowerCostPCT(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleModPowerCost(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleArenaPreparation(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleNoReagentUseAura(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraRetainComboPoints(AuraApplication const* aurApp, uint8 mode, bool apply) const; + // others + void HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleBindSight(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleForceReaction(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraEmpathy(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModFaction(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleComprehendLanguage(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraConvertRune(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraLinked(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraOpenStable(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraModFakeInebriation(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraOverrideSpells(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandleAuraSetVehicle(AuraApplication const* aurApp, uint8 mode, bool apply) const; + void HandlePreventResurrection(AuraApplication const* aurApp, uint8 mode, bool apply) const; - // aura effect periodic tick handlers - void HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicTriggerSpellWithValueAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const; - void HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicHealthFunnelAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const; - void HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) const; - void HandleObsModPowerAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicEnergizeAuraTick(Unit* target, Unit* caster) const; - void HandlePeriodicPowerBurnAuraTick(Unit* target, Unit* caster) const; + // aura effect periodic tick handlers + void HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicTriggerSpellWithValueAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const; + void HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicHealthFunnelAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const; + void HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) const; + void HandleObsModPowerAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicEnergizeAuraTick(Unit* target, Unit* caster) const; + void HandlePeriodicPowerBurnAuraTick(Unit* target, Unit* caster) const; - // aura effect proc handlers - void HandleProcTriggerSpellAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); - void HandleProcTriggerSpellWithValueAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); - void HandleProcTriggerDamageAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); - void HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); - void HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); + // aura effect proc handlers + void HandleProcTriggerSpellAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); + void HandleProcTriggerSpellWithValueAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); + void HandleProcTriggerDamageAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); + void HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); + void HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo); }; namespace acore @@ -325,57 +325,57 @@ namespace acore // Binary predicate for sorting the priority of absorption aura effects class AbsorbAuraOrderPred { - public: - AbsorbAuraOrderPred() { } - bool operator() (AuraEffect* aurEffA, AuraEffect* aurEffB) const - { - SpellInfo const* spellProtoA = aurEffA->GetSpellInfo(); - SpellInfo const* spellProtoB = aurEffB->GetSpellInfo(); + public: + AbsorbAuraOrderPred() { } + bool operator() (AuraEffect* aurEffA, AuraEffect* aurEffB) const + { + SpellInfo const* spellProtoA = aurEffA->GetSpellInfo(); + SpellInfo const* spellProtoB = aurEffB->GetSpellInfo(); - // Wards - if ((spellProtoA->SpellFamilyName == SPELLFAMILY_MAGE) || + // Wards + if ((spellProtoA->SpellFamilyName == SPELLFAMILY_MAGE) || (spellProtoA->SpellFamilyName == SPELLFAMILY_WARLOCK)) - if (spellProtoA->GetCategory() == 56) - return true; - if ((spellProtoB->SpellFamilyName == SPELLFAMILY_MAGE) || + if (spellProtoA->GetCategory() == 56) + return true; + if ((spellProtoB->SpellFamilyName == SPELLFAMILY_MAGE) || (spellProtoB->SpellFamilyName == SPELLFAMILY_WARLOCK)) - if (spellProtoB->GetCategory() == 56) - return false; - - // Sacred Shield - if (spellProtoA->Id == 58597) - return true; - if (spellProtoB->Id == 58597) - return false; - - // Fel Blossom - if (spellProtoA->Id == 28527) - return true; - if (spellProtoB->Id == 28527) - return false; - - // Divine Aegis - if (spellProtoA->Id == 47753) - return true; - if (spellProtoB->Id == 47753) - return false; - - // Ice Barrier - if (spellProtoA->GetCategory() == 471) - return true; - if (spellProtoB->GetCategory() == 471) - return false; - - // Sacrifice - if ((spellProtoA->SpellFamilyName == SPELLFAMILY_WARLOCK) && - (spellProtoA->SpellIconID == 693)) - return true; - if ((spellProtoB->SpellFamilyName == SPELLFAMILY_WARLOCK) && - (spellProtoB->SpellIconID == 693)) + if (spellProtoB->GetCategory() == 56) return false; + // Sacred Shield + if (spellProtoA->Id == 58597) + return true; + if (spellProtoB->Id == 58597) return false; - } + + // Fel Blossom + if (spellProtoA->Id == 28527) + return true; + if (spellProtoB->Id == 28527) + return false; + + // Divine Aegis + if (spellProtoA->Id == 47753) + return true; + if (spellProtoB->Id == 47753) + return false; + + // Ice Barrier + if (spellProtoA->GetCategory() == 471) + return true; + if (spellProtoB->GetCategory() == 471) + return false; + + // Sacrifice + if ((spellProtoA->SpellFamilyName == SPELLFAMILY_WARLOCK) && + (spellProtoA->SpellIconID == 693)) + return true; + if ((spellProtoB->SpellFamilyName == SPELLFAMILY_WARLOCK) && + (spellProtoB->SpellIconID == 693)) + return false; + + return false; + } }; } #endif diff --git a/src/server/game/Spells/Auras/SpellAuras.cpp b/src/server/game/Spells/Auras/SpellAuras.cpp index 9e36b8f8a..f71189093 100644 --- a/src/server/game/Spells/Auras/SpellAuras.cpp +++ b/src/server/game/Spells/Auras/SpellAuras.cpp @@ -29,8 +29,8 @@ static constexpr int32 UPDATE_TARGET_MAP_INTERVAL = 500; AuraApplication::AuraApplication(Unit* target, Unit* caster, Aura* aura, uint8 effMask): -_target(target), _base(aura), _removeMode(AURA_REMOVE_NONE), _slot(MAX_AURAS), -_flags(AFLAG_NONE), _effectsToApply(effMask), _needClientUpdate(false), _disableMask(0) + _target(target), _base(aura), _removeMode(AURA_REMOVE_NONE), _slot(MAX_AURAS), + _flags(AFLAG_NONE), _effectsToApply(effMask), _needClientUpdate(false), _disableMask(0) { ASSERT(GetTarget() && GetBase()); @@ -39,7 +39,7 @@ _flags(AFLAG_NONE), _effectsToApply(effMask), _needClientUpdate(false), _disable // Try find slot for aura uint8 slot = MAX_AURAS; // Lookup for auras already applied from spell - if (AuraApplication * foundAura = GetTarget()->GetAuraApplication(GetBase()->GetId(), GetBase()->GetCasterGUID(), GetBase()->GetCastItemGUID())) + if (AuraApplication* foundAura = GetTarget()->GetAuraApplication(GetBase()->GetId(), GetBase()->GetCasterGUID(), GetBase()->GetCastItemGUID())) { // allow use single slot only by auras from same caster slot = foundAura->GetSlot(); @@ -69,7 +69,8 @@ _flags(AFLAG_NONE), _effectsToApply(effMask), _needClientUpdate(false), _disable sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Aura: %u Effect: %d put to unit visible auras slot: %u", GetBase()->GetId(), GetEffectMask(), slot); #endif } - else { + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outError(LOG_FILTER_SPELLS_AURAS, "Aura: %u Effect: %d could not find empty unit visible slot", GetBase()->GetId(), GetEffectMask()); #endif @@ -85,7 +86,7 @@ void AuraApplication::_Remove() if (slot >= MAX_AURAS) return; - if (AuraApplication * foundAura = _target->GetAuraApplication(GetBase()->GetId(), GetBase()->GetCasterGUID(), GetBase()->GetCastItemGUID())) + if (AuraApplication* foundAura = _target->GetAuraApplication(GetBase()->GetId(), GetBase()->GetCasterGUID(), GetBase()->GetCastItemGUID())) { // Reuse visible aura slot by aura which is still applied - prevent storing dead pointers if (slot == foundAura->GetSlot()) @@ -120,7 +121,7 @@ void AuraApplication::_InitFlags(Unit* caster, uint8 effMask) bool negativeFound = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - if (((1<GetSpellInfo()->IsPositiveEffect(i)) + if (((1 << i) & effMask) && !GetBase()->GetSpellInfo()->IsPositiveEffect(i)) { negativeFound = true; break; @@ -135,7 +136,7 @@ void AuraApplication::_InitFlags(Unit* caster, uint8 effMask) bool positiveFound = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - if (((1<GetSpellInfo()->IsPositiveEffect(i)) + if (((1 << i) & effMask) && GetBase()->GetSpellInfo()->IsPositiveEffect(i)) { positiveFound = true; break; @@ -150,21 +151,21 @@ void AuraApplication::_HandleEffect(uint8 effIndex, bool apply) AuraEffect* aurEff = GetBase()->GetEffect(effIndex); ASSERT(aurEff); ASSERT(HasEffect(effIndex) == (!apply)); - ASSERT((1<outDebug(LOG_FILTER_SPELLS_AURAS, "AuraApplication::_HandleEffect: %u, apply: %u: amount: %u", aurEff->GetAuraType(), apply, aurEff->GetAmount()); #endif if (apply) { - ASSERT(!(_flags & (1<HandleEffect(this, AURA_EFFECT_HANDLE_REAL, true); } else { - ASSERT(_flags & (1<HandleEffect(this, AURA_EFFECT_HANDLE_REAL, false); // Remove all triggered by aura spells vs unlimited duration @@ -189,7 +190,7 @@ void AuraApplication::_HandleEffect(uint8 effIndex, bool apply) // xinef: skip different misc values if (aurEff->GetAuraType() != SPELL_AURA_230 /*SPELL_AURA_MOD_INCREASE_HEALTH_2*/ && aurEff->GetAuraType() != SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK && - aurEff->GetMiscValue() != (*iter)->GetMiscValue()) + aurEff->GetMiscValue() != (*iter)->GetMiscValue()) continue; // xinef: should not happen @@ -279,7 +280,7 @@ void AuraApplication::ClientUpdate(bool remove) if (const Player* plr = GetTarget()->ToPlayer()) if (Aura* aura = GetBase()) if (plr->NeedSendSpectatorData() && ArenaSpectator::ShouldSendAura(aura, GetEffectMask(), GetTarget()->GetGUID(), remove)) - ArenaSpectator::SendCommand_Aura(plr->FindMap(), plr->GetGUID(), "AUR", aura->GetCasterGUID(), aura->GetSpellInfo()->Id, aura->GetSpellInfo()->IsPositive(), aura->GetSpellInfo()->Dispel, aura->GetDuration(), aura->GetMaxDuration(), (aura->GetCharges() > 1 ? aura->GetCharges() : aura->GetStackAmount()), remove); + ArenaSpectator::SendCommand_Aura(plr->FindMap(), plr->GetGUID(), "AUR", aura->GetCasterGUID(), aura->GetSpellInfo()->Id, aura->GetSpellInfo()->IsPositive(), aura->GetSpellInfo()->Dispel, aura->GetDuration(), aura->GetMaxDuration(), (aura->GetCharges() > 1 ? aura->GetCharges() : aura->GetStackAmount()), remove); _target->SendMessageToSet(&data, true); } @@ -293,14 +294,14 @@ uint8 Aura::BuildEffectMaskForOwner(SpellInfo const* spellProto, uint8 avalibleE { case TYPEID_UNIT: case TYPEID_PLAYER: - for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (spellProto->Effects[i].IsUnitOwnedAuraEffect()) effMask |= 1 << i; } break; case TYPEID_DYNAMICOBJECT: - for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (spellProto->Effects[i].Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA) effMask |= 1 << i; @@ -396,11 +397,11 @@ Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owne } Aura::Aura(SpellInfo const* spellproto, WorldObject* owner, Unit* caster, Item* castItem, uint64 casterGUID) : -m_spellInfo(spellproto), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), -m_castItemGuid(castItem ? castItem->GetGUID() : 0),m_castItemEntry(castItem ? castItem->GetEntry() : 0), m_applyTime(time(nullptr)), -m_owner(owner), m_timeCla(0), m_updateTargetMapInterval(0), -m_casterLevel(caster ? caster->getLevel() : m_spellInfo->SpellLevel), m_procCharges(0), m_stackAmount(1), -m_isRemoved(false), m_isSingleTarget(false), m_isUsingCharges(false) + m_spellInfo(spellproto), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), + m_castItemGuid(castItem ? castItem->GetGUID() : 0), m_castItemEntry(castItem ? castItem->GetEntry() : 0), m_applyTime(time(nullptr)), + m_owner(owner), m_timeCla(0), m_updateTargetMapInterval(0), + m_casterLevel(caster ? caster->getLevel() : m_spellInfo->SpellLevel), m_procCharges(0), m_stackAmount(1), + m_isRemoved(false), m_isSingleTarget(false), m_isUsingCharges(false) { if ((m_spellInfo->ManaPerSecond || m_spellInfo->ManaPerSecondPerLevel) && !m_spellInfo->HasAttribute(SPELL_ATTR2_HEALTH_FUNNEL)) m_timeCla = 1 * IN_MILLISECONDS; @@ -421,7 +422,7 @@ AuraScript* Aura::GetScriptByName(std::string const& scriptName) const return nullptr; } -void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount) +void Aura::_InitEffects(uint8 effMask, Unit* caster, int32* baseAmount) { // shouldn't be in constructor - functions in AuraEffect::AuraEffect use polymorphism for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) @@ -446,7 +447,7 @@ Aura::~Aura() // free effects memory for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - delete m_effects[i]; + delete m_effects[i]; ASSERT(m_applications.empty()); _DeleteRemovedApplications(); @@ -472,7 +473,7 @@ AuraObjectType Aura::GetType() const return (m_owner->GetTypeId() == TYPEID_DYNAMICOBJECT) ? DYNOBJ_AURA_TYPE : UNIT_AURA_TYPE; } -void Aura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp) +void Aura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication* auraApp) { ASSERT(target); ASSERT(auraApp); @@ -492,7 +493,7 @@ void Aura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp } } -void Aura::_UnapplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp) +void Aura::_UnapplyForTarget(Unit* target, Unit* caster, AuraApplication* auraApp) { ASSERT(target); ASSERT(auraApp->GetRemoveMode()); @@ -504,7 +505,7 @@ void Aura::_UnapplyForTarget(Unit* target, Unit* caster, AuraApplication * auraA if (itr == m_applications.end()) { sLog->outError("Aura::_UnapplyForTarget, target:%u, caster:%u, spell:%u was not found in owners application map!", - target->GetGUIDLow(), caster ? caster->GetGUIDLow() : 0, auraApp->GetBase()->GetSpellInfo()->Id); + target->GetGUIDLow(), caster ? caster->GetGUIDLow() : 0, auraApp->GetBase()->GetSpellInfo()->Id); ABORT(); } @@ -532,7 +533,7 @@ void Aura::_Remove(AuraRemoveMode removeMode) ApplicationMap::iterator appItr = m_applications.begin(); for (appItr = m_applications.begin(); appItr != m_applications.end();) { - AuraApplication * aurApp = appItr->second; + AuraApplication* aurApp = appItr->second; Unit* target = aurApp->GetTarget(); target->_UnapplyAura(aurApp, removeMode); appItr = m_applications.begin(); @@ -555,7 +556,7 @@ void Aura::UpdateTargetMap(Unit* caster, bool apply) UnitList targetsToRemove; // mark all auras as ready to remove - for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end();++appIter) + for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) { std::map::iterator existing = targets.find(appIter->second->GetTarget()); // not found in current area - remove the aura @@ -582,10 +583,10 @@ void Aura::UpdateTargetMap(Unit* caster, bool apply) } // register auras for units - for (std::map::iterator itr = targets.begin(); itr!= targets.end();) + for (std::map::iterator itr = targets.begin(); itr != targets.end();) { // aura mustn't be already applied on target - if (AuraApplication * aurApp = GetApplicationOfTarget(itr->first->GetGUID())) + if (AuraApplication* aurApp = GetApplicationOfTarget(itr->first->GetGUID())) { // the core created 2 different units with same guid // this is a major failue, which i can't fix right now @@ -613,8 +614,8 @@ void Aura::UpdateTargetMap(Unit* caster, bool apply) itr->second &= ~(1 << effIndex); } if (!itr->second - || itr->first->IsImmunedToSpell(GetSpellInfo()) - || !CanBeAppliedOn(itr->first)) + || itr->first->IsImmunedToSpell(GetSpellInfo()) + || !CanBeAppliedOn(itr->first)) addUnit = false; if (addUnit) @@ -630,7 +631,10 @@ void Aura::UpdateTargetMap(Unit* caster, bool apply) case 62821: // Ulduar, Hodir, Toasty Fire case 62807: // Ulduar, Hodir, Starlight case 51103: // Oculus, Mage-Lord Urom, Frostbomb - case 69146: case 70823: case 70824: case 70825: // Icecrown Citadel, Lord Marrowgar, Coldflame + case 69146: + case 70823: + case 70824: + case 70825: // Icecrown Citadel, Lord Marrowgar, Coldflame { if( itr->first->HasAura(GetId()) ) addUnit = false; @@ -667,8 +671,8 @@ void Aura::UpdateTargetMap(Unit* caster, bool apply) { //TODO: There is a crash caused by shadowfiend load addon sLog->outCrash("Aura %u: Owner %s (map %u) is not in the same map as target %s (map %u).", GetSpellInfo()->Id, - GetOwner()->GetName().c_str(), GetOwner()->IsInWorld() ? GetOwner()->GetMap()->GetId() : uint32(-1), - itr->first->GetName().c_str(), itr->first->IsInWorld() ? itr->first->GetMap()->GetId() : uint32(-1)); + GetOwner()->GetName().c_str(), GetOwner()->IsInWorld() ? GetOwner()->GetMap()->GetId() : uint32(-1), + itr->first->GetName().c_str(), itr->first->IsInWorld() ? itr->first->GetMap()->GetId() : uint32(-1)); ABORT(); } itr->first->_CreateAuraApplication(this, itr->second); @@ -677,17 +681,17 @@ void Aura::UpdateTargetMap(Unit* caster, bool apply) } // remove auras from units no longer needing them - for (UnitList::iterator itr = targetsToRemove.begin(); itr != targetsToRemove.end();++itr) - if (AuraApplication * aurApp = GetApplicationOfTarget((*itr)->GetGUID())) + for (UnitList::iterator itr = targetsToRemove.begin(); itr != targetsToRemove.end(); ++itr) + if (AuraApplication* aurApp = GetApplicationOfTarget((*itr)->GetGUID())) (*itr)->_UnapplyAura(aurApp, AURA_REMOVE_BY_DEFAULT); if (!apply) return; // apply aura effects for units - for (std::map::iterator itr = targets.begin(); itr!= targets.end();++itr) + for (std::map::iterator itr = targets.begin(); itr != targets.end(); ++itr) { - if (AuraApplication * aurApp = GetApplicationOfTarget(itr->first->GetGUID())) + if (AuraApplication* aurApp = GetApplicationOfTarget(itr->first->GetGUID())) { // owner has to be in world, or effect has to be applied to self ASSERT((!GetOwner()->IsInWorld() && GetOwner() == itr->first) || GetOwner()->IsInMap(itr->first)); @@ -703,7 +707,7 @@ void Aura::_ApplyEffectForTargets(uint8 effIndex) UnitList targetList; for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) { - if ((appIter->second->GetEffectsToApply() & (1<second->HasEffect(effIndex)) + if ((appIter->second->GetEffectsToApply() & (1 << effIndex)) && !appIter->second->HasEffect(effIndex)) targetList.push_back(appIter->second->GetTarget()); } @@ -870,7 +874,7 @@ void Aura::RefreshTimersWithMods() m_maxDuration = CalcMaxDuration(); if ((caster && caster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, m_spellInfo)) || m_spellInfo->HasAttribute(SPELL_ATTR5_HASTE_AFFECT_DURATION)) m_maxDuration = int32(m_maxDuration * caster->GetFloatValue(UNIT_MOD_CAST_SPEED)); - + // xinef: we should take ModSpellDuration into account, but none of the spells using this function is affected by contents of ModSpellDuration RefreshDuration(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) @@ -1015,7 +1019,7 @@ bool Aura::IsDeathPersistent() const return GetSpellInfo()->IsDeathPersistent(); } -bool Aura::IsRemovedOnShapeLost(Unit *target) const +bool Aura::IsRemovedOnShapeLost(Unit* target) const { return (GetCasterGUID() == target->GetGUID() && m_spellInfo->Stances && !m_spellInfo->HasAttribute(SPELL_ATTR2_NOT_NEED_SHAPESHIFT) && !m_spellInfo->HasAttribute(SPELL_ATTR0_NOT_SHAPESHIFT)); } @@ -1138,7 +1142,7 @@ int32 Aura::CalcDispelChance(Unit* auraTarget, bool offensive) const return 100 - resistChance; } -void Aura::SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32 * amount) +void Aura::SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32* amount) { m_maxDuration = maxduration; m_duration = duration; @@ -1150,7 +1154,7 @@ void Aura::SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint if (m_effects[i]) { m_effects[i]->SetAmount(amount[i]); - m_effects[i]->SetCanBeRecalculated(recalculateMask & (1<SetCanBeRecalculated(recalculateMask & (1 << i)); m_effects[i]->CalculatePeriodic(caster, false, true); m_effects[i]->CalculateSpellMod(); m_effects[i]->RecalculateAmount(caster); @@ -1176,7 +1180,7 @@ void Aura::RecalculateAmountOfEffects() m_effects[i]->RecalculateAmount(caster); } -void Aura::HandleAllEffects(AuraApplication * aurApp, uint8 mode, bool apply) +void Aura::HandleAllEffects(AuraApplication* aurApp, uint8 mode, bool apply) { ASSERT (!IsRemoved()); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) @@ -1184,7 +1188,7 @@ void Aura::HandleAllEffects(AuraApplication * aurApp, uint8 mode, bool apply) m_effects[i]->HandleEffect(aurApp, mode, apply); } -void Aura::GetApplicationList(std::list & applicationList) const +void Aura::GetApplicationList(std::list& applicationList) const { for (Aura::ApplicationMap::const_iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) { @@ -1344,8 +1348,12 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b switch (aurEff->GetId()) { - case 31571: spellId = 57529; break; - case 31572: spellId = 57531; break; + case 31571: + spellId = 57529; + break; + case 31572: + spellId = 57531; + break; default: sLog->outError("Aura::HandleAuraSpecificMods: Unknown rank of Arcane Potency (%d) found", aurEff->GetId()); } @@ -1354,17 +1362,17 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b } break; case 44544: // Fingers of Frost - { - // See if we already have the indicator aura. If not, create one. - if (Aura* aur = target->GetAura(74396)) { - // Aura already there. Refresh duration and set original charges - aur->SetCharges(2); - aur->RefreshDuration(); + // See if we already have the indicator aura. If not, create one. + if (Aura* aur = target->GetAura(74396)) + { + // Aura already there. Refresh duration and set original charges + aur->SetCharges(2); + aur->RefreshDuration(); + } + else + target->AddAura(74396, target); } - else - target->AddAura(74396, target); - } default: break; } @@ -1411,7 +1419,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (AuraEffect* glyph = caster->GetAuraEffect(55672, 0)) { // instantly heal m_amount% of the absorb-value - int32 heal = glyph->GetAmount() * GetEffect(0)->GetAmount()/100; + int32 heal = glyph->GetAmount() * GetEffect(0)->GetAmount() / 100; caster->CastCustomSpell(GetUnitOwner(), 56160, &heal, nullptr, nullptr, true, 0, GetEffect(0)); } } @@ -1452,13 +1460,25 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b switch (aurEff->GetId()) { // Ebon Plague - case 51161: spellId = 51735; break; - case 51160: spellId = 51734; break; - case 51099: spellId = 51726; break; + case 51161: + spellId = 51735; + break; + case 51160: + spellId = 51734; + break; + case 51099: + spellId = 51726; + break; // Crypt Fever - case 49632: spellId = 50510; break; - case 49631: spellId = 50509; break; - case 49032: spellId = 50508; break; + case 49632: + spellId = 50510; + break; + case 49631: + spellId = 50509; + break; + case 49032: + spellId = 50508; + break; default: sLog->outError("Aura::HandleAuraSpecificMods: Unknown rank of Crypt Fever/Ebon Plague (%d) found", aurEff->GetId()); } @@ -1482,9 +1502,9 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b { for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) if (GetEffect(i)) - GetEffect(i)->SetAmount(CalculatePct(GetEffect(i)->GetAmount(), 100+sSpellMgr->GetSpellMixologyBonus(GetId()))); + GetEffect(i)->SetAmount(CalculatePct(GetEffect(i)->GetAmount(), 100 + sSpellMgr->GetSpellMixologyBonus(GetId()))); - SetMaxDuration(caster->CalcSpellDuration(GetSpellInfo())*2); + SetMaxDuration(caster->CalcSpellDuration(GetSpellInfo()) * 2); SetDuration(GetMaxDuration()); } } @@ -1570,8 +1590,12 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b uint32 spellId = 0; switch (aurEff->GetId()) { - case 53759: spellId = 60947; break; - case 53754: spellId = 60946; break; + case 53759: + spellId = 60947; + break; + case 53754: + spellId = 60946; + break; default: sLog->outError("Aura::HandleAuraSpecificMods: Unknown rank of Improved Fear (%d) found", aurEff->GetId()); } @@ -1610,7 +1634,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b break; } else // and add if needed - caster->ToPlayer()->AddSpellCooldown(aura->GetId(), 0, 12*IN_MILLISECONDS); + caster->ToPlayer()->AddSpellCooldown(aura->GetId(), 0, 12 * IN_MILLISECONDS); } // effect on caster @@ -1635,14 +1659,20 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b switch (target->getPowerType()) { case POWER_MANA: - { - int32 basepoints0 = int32(CalculatePct(target->GetMaxPower(POWER_MANA), 2)); - caster->CastCustomSpell(target, 63654, &basepoints0, nullptr, nullptr, true); + { + int32 basepoints0 = int32(CalculatePct(target->GetMaxPower(POWER_MANA), 2)); + caster->CastCustomSpell(target, 63654, &basepoints0, nullptr, nullptr, true); + break; + } + case POWER_RAGE: + triggeredSpellId = 63653; + break; + case POWER_ENERGY: + triggeredSpellId = (!target->HasAura(70405) ? 63655 : 0); + break; + case POWER_RUNIC_POWER: + triggeredSpellId = 63652; break; - } - case POWER_RAGE: triggeredSpellId = 63653; break; - case POWER_ENERGY: triggeredSpellId = (!target->HasAura(70405) ? 63655 : 0); break; - case POWER_RUNIC_POWER: triggeredSpellId = 63652; break; default: break; } @@ -1668,7 +1698,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b player->AddSpellCooldown(GetSpellInfo()->Id, 0, aurEff->GetAmount()*IN_MILLISECONDS); - WorldPacket data(SMSG_MODIFY_COOLDOWN, 4+8+4); + WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4); data << uint32(GetId()); // Spell ID data << uint64(player->GetGUID()); // Player GUID data << int32(-110000); // Cooldown mod in milliseconds @@ -1707,7 +1737,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (target->ToPlayer()->getClass() != CLASS_DEATH_KNIGHT) break; - // aura removed - remove death runes + // aura removed - remove death runes target->ToPlayer()->RemoveRunesByAuraEffect(GetEffect(0)); } break; @@ -1801,7 +1831,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (apply) target->CastSpell(target, 70725, true); } - else if (AuraEffect *aurEff = caster->GetAuraEffect(SPELL_AURA_MOD_BASE_RESISTANCE_PCT, SPELLFAMILY_DRUID, 107, 0)) + else if (AuraEffect* aurEff = caster->GetAuraEffect(SPELL_AURA_MOD_BASE_RESISTANCE_PCT, SPELLFAMILY_DRUID, 107, 0)) aurEff->RecalculateAmount(); } break; @@ -1886,14 +1916,14 @@ bool Aura::CanStackWith(Aura const* existingAura, bool remove) const { // prevent remove triggering aura by triggered aura if (existingSpellInfo->Effects[i].TriggerSpell == GetId() - // prevent remove triggered aura by triggering aura refresh - || m_spellInfo->Effects[i].TriggerSpell == existingAura->GetId()) + // prevent remove triggered aura by triggering aura refresh + || m_spellInfo->Effects[i].TriggerSpell == existingAura->GetId()) return true; } // check spell specific stack rules if (m_spellInfo->IsAuraExclusiveBySpecificWith(existingSpellInfo) - || (sameCaster && m_spellInfo->IsAuraExclusiveBySpecificPerCasterWith(existingSpellInfo))) + || (sameCaster && m_spellInfo->IsAuraExclusiveBySpecificPerCasterWith(existingSpellInfo))) return false; // check spell group stack rules @@ -1902,8 +1932,8 @@ bool Aura::CanStackWith(Aura const* existingAura, bool remove) const if (stackFlags) { // xinef: same caster rule is bounded by spellfamily - if (sameCaster && m_spellInfo->SpellFamilyName == existingSpellInfo->SpellFamilyName && - (stackFlags & SPELL_GROUP_STACK_FLAG_NOT_SAME_CASTER)) + if (sameCaster && m_spellInfo->SpellFamilyName == existingSpellInfo->SpellFamilyName && + (stackFlags & SPELL_GROUP_STACK_FLAG_NOT_SAME_CASTER)) return false; // xinef: normal exclusive stacking, remove if auras are equal by effects @@ -1980,9 +2010,9 @@ bool Aura::CanStackWith(Aura const* existingAura, bool remove) const while (i < MAX_SPELL_EFFECTS && !(VehicleAura1 && VehicleAura2)) { if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_CONTROL_VEHICLE) - VehicleAura1 = i+1; + VehicleAura1 = i + 1; if (existingSpellInfo->Effects[i].ApplyAuraName == SPELL_AURA_CONTROL_VEHICLE) - VehicleAura2 = i+1; + VehicleAura2 = i + 1; ++i; } @@ -1997,9 +2027,9 @@ bool Aura::CanStackWith(Aura const* existingAura, bool remove) const return true; // xinef: allow direct auras to stack if there is no passenger in this slot - if (AuraEffect* aurEff = GetEffect(VehicleAura1-1)) + if (AuraEffect* aurEff = GetEffect(VehicleAura1 - 1)) if (aurEff->GetAmount() > 0) - if (!veh->GetPassenger(aurEff->GetAmount()-1)) + if (!veh->GetPassenger(aurEff->GetAmount() - 1)) return true; if (!veh->GetAvailableSeatCount()) @@ -2120,7 +2150,7 @@ bool Aura::IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventI else item = target->ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); - if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1<GetTemplate()->SubClass) & GetSpellInfo()->EquippedItemSubClassMask)) + if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1 << item->GetTemplate()->SubClass) & GetSpellInfo()->EquippedItemSubClassMask)) return false; } } @@ -2128,7 +2158,7 @@ bool Aura::IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventI { // Check if player is wearing shield Item* item = target->ToPlayer()->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); - if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1<GetTemplate()->SubClass) & GetSpellInfo()->EquippedItemSubClassMask)) + if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1 << item->GetTemplate()->SubClass) & GetSpellInfo()->EquippedItemSubClassMask)) return false; } } @@ -2344,7 +2374,7 @@ void Aura::CallScriptEffectUpdatePeriodicHandlers(AuraEffect* aurEff) } } -void Aura::CallScriptEffectCalcAmountHandlers(AuraEffect const* aurEff, int32 & amount, bool & canBeRecalculated) +void Aura::CallScriptEffectCalcAmountHandlers(AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2358,7 +2388,7 @@ void Aura::CallScriptEffectCalcAmountHandlers(AuraEffect const* aurEff, int32 & } } -void Aura::CallScriptEffectCalcPeriodicHandlers(AuraEffect const* aurEff, bool & isPeriodic, int32 & amplitude) +void Aura::CallScriptEffectCalcPeriodicHandlers(AuraEffect const* aurEff, bool& isPeriodic, int32& amplitude) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2372,7 +2402,7 @@ void Aura::CallScriptEffectCalcPeriodicHandlers(AuraEffect const* aurEff, bool & } } -void Aura::CallScriptEffectCalcSpellModHandlers(AuraEffect const* aurEff, SpellModifier* & spellMod) +void Aura::CallScriptEffectCalcSpellModHandlers(AuraEffect const* aurEff, SpellModifier*& spellMod) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2386,7 +2416,7 @@ void Aura::CallScriptEffectCalcSpellModHandlers(AuraEffect const* aurEff, SpellM } } -void Aura::CallScriptEffectAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount, bool& defaultPrevented) +void Aura::CallScriptEffectAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount, bool& defaultPrevented) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2404,7 +2434,7 @@ void Aura::CallScriptEffectAbsorbHandlers(AuraEffect* aurEff, AuraApplication co } } -void Aura::CallScriptEffectAfterAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount) +void Aura::CallScriptEffectAfterAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2418,7 +2448,7 @@ void Aura::CallScriptEffectAfterAbsorbHandlers(AuraEffect* aurEff, AuraApplicati } } -void Aura::CallScriptEffectManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount, bool & /*defaultPrevented*/) +void Aura::CallScriptEffectManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount, bool& /*defaultPrevented*/) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2432,7 +2462,7 @@ void Aura::CallScriptEffectManaShieldHandlers(AuraEffect* aurEff, AuraApplicatio } } -void Aura::CallScriptEffectAfterManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount) +void Aura::CallScriptEffectAfterManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2446,7 +2476,7 @@ void Aura::CallScriptEffectAfterManaShieldHandlers(AuraEffect* aurEff, AuraAppli } } -void Aura::CallScriptEffectSplitHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & splitAmount) +void Aura::CallScriptEffectSplitHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& splitAmount) { for (std::list::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { @@ -2558,7 +2588,7 @@ void Aura::CallScriptAfterEffectProcHandlers(AuraEffect const* aurEff, AuraAppli } } -UnitAura::UnitAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, uint64 casterGUID) +UnitAura::UnitAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID) : Aura(spellproto, owner, caster, castItem, casterGUID) { m_AuraDRGroup = DIMINISHING_NONE; @@ -2567,7 +2597,7 @@ UnitAura::UnitAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owne GetUnitOwner()->_AddAura(this, caster); }; -void UnitAura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication * aurApp) +void UnitAura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication* aurApp) { Aura::_ApplyForTarget(target, caster, aurApp); @@ -2576,7 +2606,7 @@ void UnitAura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication * aur target->ApplyDiminishingAura(group, true); } -void UnitAura::_UnapplyForTarget(Unit* target, Unit* caster, AuraApplication * aurApp) +void UnitAura::_UnapplyForTarget(Unit* target, Unit* caster, AuraApplication* aurApp) { Aura::_UnapplyForTarget(target, caster, aurApp); @@ -2592,7 +2622,7 @@ void UnitAura::Remove(AuraRemoveMode removeMode) GetUnitOwner()->RemoveOwnedAura(this, removeMode); } -void UnitAura::FillTargetMap(std::map & targets, Unit* caster) +void UnitAura::FillTargetMap(std::map& targets, Unit* caster) { for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { @@ -2614,54 +2644,54 @@ void UnitAura::FillTargetMap(std::map & targets, Unit* caster) { case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: case SPELL_EFFECT_APPLY_AREA_AURA_RAID: - { - targetList.push_back(GetUnitOwner()); - acore::AnyGroupedUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius, GetSpellInfo()->Effects[effIndex].Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID); - acore::UnitListSearcher searcher(GetUnitOwner(), targetList, u_check); - GetUnitOwner()->VisitNearbyObject(radius, searcher); - break; - } + { + targetList.push_back(GetUnitOwner()); + acore::AnyGroupedUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius, GetSpellInfo()->Effects[effIndex].Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID); + acore::UnitListSearcher searcher(GetUnitOwner(), targetList, u_check); + GetUnitOwner()->VisitNearbyObject(radius, searcher); + break; + } case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: - { - targetList.push_back(GetUnitOwner()); - acore::AnyFriendlyUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); - acore::UnitListSearcher searcher(GetUnitOwner(), targetList, u_check); - GetUnitOwner()->VisitNearbyObject(radius, searcher); - break; - } + { + targetList.push_back(GetUnitOwner()); + acore::AnyFriendlyUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); + acore::UnitListSearcher searcher(GetUnitOwner(), targetList, u_check); + GetUnitOwner()->VisitNearbyObject(radius, searcher); + break; + } case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY: - { - acore::AnyAoETargetUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); // No GetCharmer in searcher - acore::UnitListSearcher searcher(GetUnitOwner(), targetList, u_check); - GetUnitOwner()->VisitNearbyObject(radius, searcher); - break; - } + { + acore::AnyAoETargetUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); // No GetCharmer in searcher + acore::UnitListSearcher searcher(GetUnitOwner(), targetList, u_check); + GetUnitOwner()->VisitNearbyObject(radius, searcher); + break; + } case SPELL_EFFECT_APPLY_AREA_AURA_PET: targetList.push_back(GetUnitOwner()); [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: - { - if (Unit* owner = GetUnitOwner()->GetCharmerOrOwner()) - if (GetUnitOwner()->IsWithinDistInMap(owner, radius)) - targetList.push_back(owner); - break; - } + { + if (Unit* owner = GetUnitOwner()->GetCharmerOrOwner()) + if (GetUnitOwner()->IsWithinDistInMap(owner, radius)) + targetList.push_back(owner); + break; + } } } } - for (UnitList::iterator itr = targetList.begin(); itr!= targetList.end();++itr) + for (UnitList::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { std::map::iterator existing = targets.find(*itr); if (existing != targets.end()) - existing->second |= 1<second |= 1 << effIndex; else - targets[*itr] = 1< & targets, Unit* /*caster*/) +void DynObjAura::FillTargetMap(std::map& targets, Unit* /*caster*/) { Unit* dynObjOwnerCaster = GetDynobjOwner()->GetCaster(); float radius = GetDynobjOwner()->GetRadius(); @@ -2690,7 +2720,7 @@ void DynObjAura::FillTargetMap(std::map & targets, Unit* /*caster* continue; UnitList targetList; if (GetSpellInfo()->Effects[effIndex].TargetB.GetTarget() == TARGET_DEST_DYNOBJ_ALLY - || GetSpellInfo()->Effects[effIndex].TargetB.GetTarget() == TARGET_UNIT_DEST_AREA_ALLY) + || GetSpellInfo()->Effects[effIndex].TargetB.GetTarget() == TARGET_UNIT_DEST_AREA_ALLY) { acore::AnyFriendlyUnitInObjectRangeCheck u_check(GetDynobjOwner(), dynObjOwnerCaster, radius); acore::UnitListSearcher searcher(GetDynobjOwner(), targetList, u_check); @@ -2711,20 +2741,20 @@ void DynObjAura::FillTargetMap(std::map & targets, Unit* /*caster* GetDynobjOwner()->VisitNearbyObject(radius, searcher); } - for (UnitList::iterator itr = targetList.begin(); itr!= targetList.end();++itr) + for (UnitList::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { // xinef: check z level and los dependence Unit* target = *itr; float zLevel = GetDynobjOwner()->GetPositionZ(); - if (target->GetPositionZ()+3.0f < zLevel || target->GetPositionZ()-5.0f > zLevel) + if (target->GetPositionZ() + 3.0f < zLevel || target->GetPositionZ() - 5.0f > zLevel) if (!target->IsWithinLOSInMap(GetDynobjOwner())) continue; std::map::iterator existing = targets.find(*itr); if (existing != targets.end()) - existing->second |= 1<second |= 1 << effIndex; else - targets[*itr] = 1< ApplicationMap; + friend Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID, bool noPeriodicReset); +public: + typedef std::map ApplicationMap; - static uint8 BuildEffectMaskForOwner(SpellInfo const* spellProto, uint8 avalibleEffectMask, WorldObject* owner); - static Aura* TryRefreshStackOrCreate(SpellInfo const* spellproto, uint8 tryEffMask, WorldObject* owner, Unit* caster, int32* baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0, bool* refresh = NULL, bool periodicReset = false); - static Aura* TryCreate(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0); - static Aura* Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID); - explicit Aura(SpellInfo const* spellproto, WorldObject* owner, Unit* caster, Item* castItem, uint64 casterGUID); - void _InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount); - virtual ~Aura(); + static uint8 BuildEffectMaskForOwner(SpellInfo const* spellProto, uint8 avalibleEffectMask, WorldObject* owner); + static Aura* TryRefreshStackOrCreate(SpellInfo const* spellproto, uint8 tryEffMask, WorldObject* owner, Unit* caster, int32* baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0, bool* refresh = NULL, bool periodicReset = false); + static Aura* TryCreate(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0); + static Aura* Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID); + explicit Aura(SpellInfo const* spellproto, WorldObject* owner, Unit* caster, Item* castItem, uint64 casterGUID); + void _InitEffects(uint8 effMask, Unit* caster, int32* baseAmount); + virtual ~Aura(); - SpellInfo const* GetSpellInfo() const { return m_spellInfo; } - uint32 GetId() const; + SpellInfo const* GetSpellInfo() const { return m_spellInfo; } + uint32 GetId() const; - uint64 GetCastItemGUID() const { return m_castItemGuid; } - uint32 GetCastItemEntry() const { return m_castItemEntry; } - uint64 GetCasterGUID() const { return m_casterGuid; } - Unit* GetCaster() const; - WorldObject* GetOwner() const { return m_owner; } - Unit* GetUnitOwner() const { ASSERT(GetType() == UNIT_AURA_TYPE); return (Unit*)m_owner; } - DynamicObject* GetDynobjOwner() const { ASSERT(GetType() == DYNOBJ_AURA_TYPE); return (DynamicObject*)m_owner; } + uint64 GetCastItemGUID() const { return m_castItemGuid; } + uint32 GetCastItemEntry() const { return m_castItemEntry; } + uint64 GetCasterGUID() const { return m_casterGuid; } + Unit* GetCaster() const; + WorldObject* GetOwner() const { return m_owner; } + Unit* GetUnitOwner() const { ASSERT(GetType() == UNIT_AURA_TYPE); return (Unit*)m_owner; } + DynamicObject* GetDynobjOwner() const { ASSERT(GetType() == DYNOBJ_AURA_TYPE); return (DynamicObject*)m_owner; } - AuraObjectType GetType() const; + AuraObjectType GetType() const; - virtual void _ApplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp); - virtual void _UnapplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp); - void _Remove(AuraRemoveMode removeMode); - virtual void Remove(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT) = 0; + virtual void _ApplyForTarget(Unit* target, Unit* caster, AuraApplication* auraApp); + virtual void _UnapplyForTarget(Unit* target, Unit* caster, AuraApplication* auraApp); + void _Remove(AuraRemoveMode removeMode); + virtual void Remove(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT) = 0; - virtual void FillTargetMap(std::map & targets, Unit* caster) = 0; - void UpdateTargetMap(Unit* caster, bool apply = true); + virtual void FillTargetMap(std::map& targets, Unit* caster) = 0; + void UpdateTargetMap(Unit* caster, bool apply = true); - void _RegisterForTargets() {Unit* caster = GetCaster(); UpdateTargetMap(caster, false);} - void ApplyForTargets() {Unit* caster = GetCaster(); UpdateTargetMap(caster, true);} - void _ApplyEffectForTargets(uint8 effIndex); + void _RegisterForTargets() {Unit* caster = GetCaster(); UpdateTargetMap(caster, false);} + void ApplyForTargets() {Unit* caster = GetCaster(); UpdateTargetMap(caster, true);} + void _ApplyEffectForTargets(uint8 effIndex); - void UpdateOwner(uint32 diff, WorldObject* owner); - void Update(uint32 diff, Unit* caster); + void UpdateOwner(uint32 diff, WorldObject* owner); + void Update(uint32 diff, Unit* caster); - time_t GetApplyTime() const { return m_applyTime; } - int32 GetMaxDuration() const { return m_maxDuration; } - void SetMaxDuration(int32 duration) { m_maxDuration = duration; } - int32 CalcMaxDuration() const { return CalcMaxDuration(GetCaster()); } - int32 CalcMaxDuration(Unit* caster) const; - int32 GetDuration() const { return m_duration; } - void SetDuration(int32 duration, bool withMods = false); - void RefreshDuration(); - void RefreshTimers(bool periodicReset = false); - void RefreshTimersWithMods(); - bool IsExpired() const { return !GetDuration();} - bool IsPermanent() const { return GetMaxDuration() == -1; } + time_t GetApplyTime() const { return m_applyTime; } + int32 GetMaxDuration() const { return m_maxDuration; } + void SetMaxDuration(int32 duration) { m_maxDuration = duration; } + int32 CalcMaxDuration() const { return CalcMaxDuration(GetCaster()); } + int32 CalcMaxDuration(Unit* caster) const; + int32 GetDuration() const { return m_duration; } + void SetDuration(int32 duration, bool withMods = false); + void RefreshDuration(); + void RefreshTimers(bool periodicReset = false); + void RefreshTimersWithMods(); + bool IsExpired() const { return !GetDuration();} + bool IsPermanent() const { return GetMaxDuration() == -1; } - uint8 GetCharges() const { return m_procCharges; } - void SetCharges(uint8 charges); - uint8 CalcMaxCharges(Unit* caster) const; - uint8 CalcMaxCharges() const { return CalcMaxCharges(GetCaster()); } - bool ModCharges(int32 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - bool DropCharge(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT) { return ModCharges(-1, removeMode); } + uint8 GetCharges() const { return m_procCharges; } + void SetCharges(uint8 charges); + uint8 CalcMaxCharges(Unit* caster) const; + uint8 CalcMaxCharges() const { return CalcMaxCharges(GetCaster()); } + bool ModCharges(int32 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + bool DropCharge(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT) { return ModCharges(-1, removeMode); } - uint8 GetStackAmount() const { return m_stackAmount; } - void SetStackAmount(uint8 num); - bool ModStackAmount(int32 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT, bool periodicReset = false); + uint8 GetStackAmount() const { return m_stackAmount; } + void SetStackAmount(uint8 num); + bool ModStackAmount(int32 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT, bool periodicReset = false); - void RefreshSpellMods(); + void RefreshSpellMods(); - uint8 GetCasterLevel() const { return m_casterLevel; } + uint8 GetCasterLevel() const { return m_casterLevel; } - bool IsArea() const; - bool IsPassive() const; - bool IsDeathPersistent() const; - bool IsRemovedOnShapeLost(Unit* target) const; - bool CanBeSaved() const; - bool IsRemoved() const { return m_isRemoved; } - bool CanBeSentToClient() const; - // Single cast aura helpers - bool IsSingleTarget() const {return m_isSingleTarget; } - bool IsSingleTargetWith(Aura const* aura) const; - void SetIsSingleTarget(bool val) { m_isSingleTarget = val; } - void UnregisterSingleTarget(); - int32 CalcDispelChance(Unit* auraTarget, bool offensive) const; + bool IsArea() const; + bool IsPassive() const; + bool IsDeathPersistent() const; + bool IsRemovedOnShapeLost(Unit* target) const; + bool CanBeSaved() const; + bool IsRemoved() const { return m_isRemoved; } + bool CanBeSentToClient() const; + // Single cast aura helpers + bool IsSingleTarget() const {return m_isSingleTarget; } + bool IsSingleTargetWith(Aura const* aura) const; + void SetIsSingleTarget(bool val) { m_isSingleTarget = val; } + void UnregisterSingleTarget(); + int32 CalcDispelChance(Unit* auraTarget, bool offensive) const; - void SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32 * amount); + void SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32* amount); - // helpers for aura effects - bool HasEffect(uint8 effIndex) const { return bool(GetEffect(effIndex)); } - bool HasEffectType(AuraType type) const; - AuraEffect* GetEffect(uint8 effIndex) const { ASSERT (effIndex < MAX_SPELL_EFFECTS); return m_effects[effIndex]; } - uint8 GetEffectMask() const { uint8 effMask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) effMask |= 1< & applicationList) const; - const AuraApplication * GetApplicationOfTarget (uint64 guid) const { ApplicationMap::const_iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } - AuraApplication * GetApplicationOfTarget (uint64 guid) { ApplicationMap::iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } - bool IsAppliedOnTarget(uint64 guid) const { return m_applications.find(guid) != m_applications.end(); } + // Helpers for targets + ApplicationMap const& GetApplicationMap() {return m_applications;} + void GetApplicationList(std::list& applicationList) const; + const AuraApplication* GetApplicationOfTarget (uint64 guid) const { ApplicationMap::const_iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } + AuraApplication* GetApplicationOfTarget (uint64 guid) { ApplicationMap::iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } + bool IsAppliedOnTarget(uint64 guid) const { return m_applications.find(guid) != m_applications.end(); } - void SetNeedClientUpdateForTargets() const; - void HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, bool apply, bool onReapply); - bool CanBeAppliedOn(Unit* target); - bool CheckAreaTarget(Unit* target); - bool CanStackWith(Aura const* checkAura, bool remove) const; - bool IsAuraStronger(Aura const* newAura) const; + void SetNeedClientUpdateForTargets() const; + void HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, bool apply, bool onReapply); + bool CanBeAppliedOn(Unit* target); + bool CheckAreaTarget(Unit* target); + bool CanStackWith(Aura const* checkAura, bool remove) const; + bool IsAuraStronger(Aura const* newAura) const; - // Proc system - // this subsystem is not yet in use - the core of it is functional, but still some research has to be done - // and some dependant problems fixed before it can replace old proc system (for example cooldown handling) - // currently proc system functionality is implemented in Unit::ProcDamageAndSpell - bool IsProcOnCooldown() const; - void AddProcCooldown(uint32 msec); - bool IsUsingCharges() const { return m_isUsingCharges; } - void SetUsingCharges(bool val) { m_isUsingCharges = val; } - void PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo); - bool IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo) const; - float CalcProcChance(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const; - void TriggerProcOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo); + // Proc system + // this subsystem is not yet in use - the core of it is functional, but still some research has to be done + // and some dependant problems fixed before it can replace old proc system (for example cooldown handling) + // currently proc system functionality is implemented in Unit::ProcDamageAndSpell + bool IsProcOnCooldown() const; + void AddProcCooldown(uint32 msec); + bool IsUsingCharges() const { return m_isUsingCharges; } + void SetUsingCharges(bool val) { m_isUsingCharges = val; } + void PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo); + bool IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo) const; + float CalcProcChance(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const; + void TriggerProcOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo); - // AuraScript - void LoadScripts(); - bool CallScriptCheckAreaTargetHandlers(Unit* target); - void CallScriptDispel(DispelInfo* dispelInfo); - void CallScriptAfterDispel(DispelInfo* dispelInfo); - bool CallScriptEffectApplyHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); - bool CallScriptEffectRemoveHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); - void CallScriptAfterEffectApplyHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); - void CallScriptAfterEffectRemoveHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); - bool CallScriptEffectPeriodicHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp); - void CallScriptEffectUpdatePeriodicHandlers(AuraEffect* aurEff); - void CallScriptEffectCalcAmountHandlers(AuraEffect const* aurEff, int32 & amount, bool & canBeRecalculated); - void CallScriptEffectCalcPeriodicHandlers(AuraEffect const* aurEff, bool & isPeriodic, int32 & amplitude); - void CallScriptEffectCalcSpellModHandlers(AuraEffect const* aurEff, SpellModifier* & spellMod); - void CallScriptEffectAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount, bool & defaultPrevented); - void CallScriptEffectAfterAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount); - void CallScriptEffectManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount, bool & defaultPrevented); - void CallScriptEffectAfterManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & absorbAmount); - void CallScriptEffectSplitHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo & dmgInfo, uint32 & splitAmount); + // AuraScript + void LoadScripts(); + bool CallScriptCheckAreaTargetHandlers(Unit* target); + void CallScriptDispel(DispelInfo* dispelInfo); + void CallScriptAfterDispel(DispelInfo* dispelInfo); + bool CallScriptEffectApplyHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); + bool CallScriptEffectRemoveHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); + void CallScriptAfterEffectApplyHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); + void CallScriptAfterEffectRemoveHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, AuraEffectHandleModes mode); + bool CallScriptEffectPeriodicHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp); + void CallScriptEffectUpdatePeriodicHandlers(AuraEffect* aurEff); + void CallScriptEffectCalcAmountHandlers(AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated); + void CallScriptEffectCalcPeriodicHandlers(AuraEffect const* aurEff, bool& isPeriodic, int32& amplitude); + void CallScriptEffectCalcSpellModHandlers(AuraEffect const* aurEff, SpellModifier*& spellMod); + void CallScriptEffectAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount, bool& defaultPrevented); + void CallScriptEffectAfterAbsorbHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount); + void CallScriptEffectManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount, bool& defaultPrevented); + void CallScriptEffectAfterManaShieldHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& absorbAmount); + void CallScriptEffectSplitHandlers(AuraEffect* aurEff, AuraApplication const* aurApp, DamageInfo& dmgInfo, uint32& splitAmount); - // Spell Proc Hooks - bool CallScriptCheckProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); - bool CallScriptPrepareProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); - bool CallScriptProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); - void CallScriptAfterProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); - bool CallScriptEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); - void CallScriptAfterEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); + // Spell Proc Hooks + bool CallScriptCheckProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); + bool CallScriptPrepareProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); + bool CallScriptProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); + void CallScriptAfterProcHandlers(AuraApplication const* aurApp, ProcEventInfo& eventInfo); + bool CallScriptEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); + void CallScriptAfterEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); - AuraScript* GetScriptByName(std::string const& scriptName) const; + AuraScript* GetScriptByName(std::string const& scriptName) const; - std::list m_loadedScripts; - private: - void _DeleteRemovedApplications(); - protected: - SpellInfo const* const m_spellInfo; - uint64 const m_casterGuid; - uint64 const m_castItemGuid; // it is NOT safe to keep a pointer to the item because it may get deleted - uint32 const m_castItemEntry; // when deleted, we could retrieve some information from template instead - time_t const m_applyTime; - WorldObject* const m_owner; // + std::list m_loadedScripts; +private: + void _DeleteRemovedApplications(); +protected: + SpellInfo const* const m_spellInfo; + uint64 const m_casterGuid; + uint64 const m_castItemGuid; // it is NOT safe to keep a pointer to the item because it may get deleted + uint32 const m_castItemEntry; // when deleted, we could retrieve some information from template instead + time_t const m_applyTime; + WorldObject* const m_owner; // - int32 m_maxDuration; // Max aura duration - int32 m_duration; // Current time - int32 m_timeCla; // Timer for power per sec calcultion - int32 m_updateTargetMapInterval; // Timer for UpdateTargetMapOfEffect + int32 m_maxDuration; // Max aura duration + int32 m_duration; // Current time + int32 m_timeCla; // Timer for power per sec calcultion + int32 m_updateTargetMapInterval; // Timer for UpdateTargetMapOfEffect - uint8 const m_casterLevel; // Aura level (store caster level for correct show level dep amount) - uint8 m_procCharges; // Aura charges (0 for infinite) - uint8 m_stackAmount; // Aura stack amount + uint8 const m_casterLevel; // Aura level (store caster level for correct show level dep amount) + uint8 m_procCharges; // Aura charges (0 for infinite) + uint8 m_stackAmount; // Aura stack amount - AuraEffect* m_effects[3]; - ApplicationMap m_applications; + AuraEffect* m_effects[3]; + ApplicationMap m_applications; - bool m_isRemoved:1; - bool m_isSingleTarget:1; // true if it's a single target spell and registered at caster - can change at spell steal for example - bool m_isUsingCharges:1; + bool m_isRemoved: 1; + bool m_isSingleTarget: 1; // true if it's a single target spell and registered at caster - can change at spell steal for example + bool m_isUsingCharges: 1; - private: - Unit::AuraApplicationList m_removedApplications; +private: + Unit::AuraApplicationList m_removedApplications; }; class UnitAura : public Aura { - friend Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, uint64 casterGUID); - protected: - explicit UnitAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, uint64 casterGUID); - public: - void _ApplyForTarget(Unit* target, Unit* caster, AuraApplication * aurApp); - void _UnapplyForTarget(Unit* target, Unit* caster, AuraApplication * aurApp); + friend Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID); +protected: + explicit UnitAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID); +public: + void _ApplyForTarget(Unit* target, Unit* caster, AuraApplication* aurApp); + void _UnapplyForTarget(Unit* target, Unit* caster, AuraApplication* aurApp); - void Remove(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + void Remove(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void FillTargetMap(std::map & targets, Unit* caster); + void FillTargetMap(std::map& targets, Unit* caster); - // Allow Apply Aura Handler to modify and access m_AuraDRGroup - void SetDiminishGroup(DiminishingGroup group) { m_AuraDRGroup = group; } - DiminishingGroup GetDiminishGroup() const { return m_AuraDRGroup; } + // Allow Apply Aura Handler to modify and access m_AuraDRGroup + void SetDiminishGroup(DiminishingGroup group) { m_AuraDRGroup = group; } + DiminishingGroup GetDiminishGroup() const { return m_AuraDRGroup; } - private: - DiminishingGroup m_AuraDRGroup:8; // Diminishing +private: + DiminishingGroup m_AuraDRGroup: 8; // Diminishing }; class DynObjAura : public Aura { - friend Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, uint64 casterGUID); - protected: - explicit DynObjAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, uint64 casterGUID); - public: - void Remove(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + friend Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID); +protected: + explicit DynObjAura(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32* baseAmount, Item* castItem, uint64 casterGUID); +public: + void Remove(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - void FillTargetMap(std::map & targets, Unit* caster); + void FillTargetMap(std::map& targets, Unit* caster); }; #endif diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 5b95ce650..7add60a80 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -542,9 +542,9 @@ SpellValue::SpellValue(SpellInfo const* proto) } Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID, bool skipCheck) : -m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)), -m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster) -, m_spellValue(new SpellValue(m_spellInfo)) + m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)), + m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster) + , m_spellValue(new SpellValue(m_spellInfo)) { m_customError = SPELL_CUSTOM_ERROR_NONE; m_skipCheck = skipCheck; @@ -572,7 +572,7 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO m_attackType = m_spellInfo->IsRangedWeaponSpell() ? RANGED_ATTACK : BASE_ATTACK; break; default: - // Wands + // Wands if (m_spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) m_attackType = RANGED_ATTACK; else @@ -649,8 +649,8 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO // Determine if spell can be reflected back to the caster // Patch 1.2 notes: Spell Reflection no longer reflects abilities m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !m_spellInfo->HasAttribute(SPELL_ATTR0_ABILITY) - && !m_spellInfo->HasAttribute(SPELL_ATTR1_CANT_BE_REFLECTED) && !m_spellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) - && !m_spellInfo->IsPassive() && (!m_spellInfo->IsPositive() || m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL)); + && !m_spellInfo->HasAttribute(SPELL_ATTR1_CANT_BE_REFLECTED) && !m_spellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) + && !m_spellInfo->IsPassive() && (!m_spellInfo->IsPositive() || m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL)); CleanupTargetList(); memset(m_effectExecuteData, 0, MAX_SPELL_EFFECTS * sizeof(ByteBuffer*)); @@ -700,8 +700,8 @@ void Spell::InitExplicitTargets(SpellCastTargets const& targets) // check if object target is valid with needed target flags // for unit case allow corpse target mask because player with not released corpse is a unit target if ((target->ToUnit() && !(neededTargets & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK))) - || (target->ToGameObject() && !(neededTargets & TARGET_FLAG_GAMEOBJECT_MASK)) - || (target->ToCorpse() && !(neededTargets & TARGET_FLAG_CORPSE_MASK))) + || (target->ToGameObject() && !(neededTargets & TARGET_FLAG_GAMEOBJECT_MASK)) + || (target->ToCorpse() && !(neededTargets & TARGET_FLAG_CORPSE_MASK))) m_targets.RemoveObjectTarget(); } else @@ -763,8 +763,8 @@ void Spell::SelectExplicitTargets() { // check for explicit target redirection, for Grounding Totem for example if (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT_ENEMY - || (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT - && (!m_spellInfo->IsPositive() || (!m_caster->IsFriendlyTo(target) && m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL))))) + || (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT + && (!m_spellInfo->IsPositive() || (!m_caster->IsFriendlyTo(target) && m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL))))) { Unit* redirect; switch (m_spellInfo->DmgClass) @@ -785,7 +785,7 @@ void Spell::SelectExplicitTargets() m_targets.SetUnitTarget(redirect); m_spellFlags |= SPELL_FLAG_REDIRECTED; } - + } } } @@ -846,8 +846,8 @@ void Spell::SelectSpellTargets() // Do not check for selfcast if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID()) { - m_UniqueTargetInfo.erase(ihit++); - continue; + m_UniqueTargetInfo.erase(ihit++); + continue; } } ++ihit; @@ -897,10 +897,10 @@ void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTar { SpellEffectInfo const* effects = GetSpellInfo()->Effects; if (effects[effIndex].TargetA.GetTarget() == effects[j].TargetA.GetTarget() && - effects[effIndex].TargetB.GetTarget() == effects[j].TargetB.GetTarget() && - effects[effIndex].ImplicitTargetConditions == effects[j].ImplicitTargetConditions && - effects[effIndex].CalcRadius(m_caster) == effects[j].CalcRadius(m_caster) && - CheckScriptEffectImplicitTargets(effIndex, j)) + effects[effIndex].TargetB.GetTarget() == effects[j].TargetB.GetTarget() && + effects[effIndex].ImplicitTargetConditions == effects[j].ImplicitTargetConditions && + effects[effIndex].CalcRadius(m_caster) == effects[j].CalcRadius(m_caster) && + CheckScriptEffectImplicitTargets(effIndex, j)) { effectMask |= 1 << j; } @@ -947,22 +947,22 @@ void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTar } break; case TARGET_OBJECT_TYPE_DEST: - switch (targetType.GetReferenceType()) - { - case TARGET_REFERENCE_TYPE_CASTER: - SelectImplicitCasterDestTargets(effIndex, targetType); - break; - case TARGET_REFERENCE_TYPE_TARGET: - SelectImplicitTargetDestTargets(effIndex, targetType); - break; - case TARGET_REFERENCE_TYPE_DEST: - SelectImplicitDestDestTargets(effIndex, targetType); - break; - default: - ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST"); - break; - } - break; + switch (targetType.GetReferenceType()) + { + case TARGET_REFERENCE_TYPE_CASTER: + SelectImplicitCasterDestTargets(effIndex, targetType); + break; + case TARGET_REFERENCE_TYPE_TARGET: + SelectImplicitTargetDestTargets(effIndex, targetType); + break; + case TARGET_REFERENCE_TYPE_DEST: + SelectImplicitDestDestTargets(effIndex, targetType); + break; + default: + ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST"); + break; + } + break; default: switch (targetType.GetReferenceType()) { @@ -1001,24 +1001,24 @@ void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTa switch (targetType.GetTarget()) { case TARGET_UNIT_CHANNEL_TARGET: - { - // Xinef: All channel selectors have needed data passed in m_targets structure - WorldObject* target = m_targets.GetObjectTargetChannel(m_caster); - if (target) - { - CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); - // unit target may be no longer avalible - teleported out of map for example - if (target && target->ToUnit()) - AddUnitTarget(target->ToUnit(), 1 << effIndex); - } - else { + // Xinef: All channel selectors have needed data passed in m_targets structure + WorldObject* target = m_targets.GetObjectTargetChannel(m_caster); + if (target) + { + CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); + // unit target may be no longer avalible - teleported out of map for example + if (target && target->ToUnit()) + AddUnitTarget(target->ToUnit(), 1 << effIndex); + } + else + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); #endif + } + break; } - break; - } case TARGET_DEST_CHANNEL_TARGET: if (m_targets.HasDstChannel()) m_targets.SetDst(*m_targets.GetDstChannel()); @@ -1129,23 +1129,23 @@ void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTar switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_UNIT: - { - if (Unit* unitTarget = target->ToUnit()) { - AddUnitTarget(unitTarget, effMask, true, false); - // xinef: important! if channeling spell have nearby entry, it has no unitTarget by default - // and if channeled spell has target 77, it requires unitTarget, set it here! - // xinef: if we have NO unit target - if (!m_targets.GetUnitTarget()) - m_targets.SetUnitTarget(unitTarget); + if (Unit* unitTarget = target->ToUnit()) + { + AddUnitTarget(unitTarget, effMask, true, false); + // xinef: important! if channeling spell have nearby entry, it has no unitTarget by default + // and if channeled spell has target 77, it requires unitTarget, set it here! + // xinef: if we have NO unit target + if (!m_targets.GetUnitTarget()) + m_targets.SetUnitTarget(unitTarget); + } + else + { + //TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set object of wrong type, expected unit, got %s, effect %u", m_spellInfo->Id, GetLogNameForGuid(target->GetGUID()), effMask); + return; + } + break; } - else - { - //TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set object of wrong type, expected unit, got %s, effect %u", m_spellInfo->Id, GetLogNameForGuid(target->GetGUID()), effMask); - return; - } - break; - } case TARGET_OBJECT_TYPE_GOBJ: if (GameObject* gobjTarget = target->ToGameObject()) AddGOTarget(gobjTarget, effMask); @@ -1177,7 +1177,7 @@ void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTarge SpellTargetObjectTypes objectType = targetType.GetObjectType(); SpellTargetCheckTypes selectionType = targetType.GetCheckType(); ConditionList* condList = m_spellInfo->Effects[effIndex].ImplicitTargetConditions; - float coneAngle = M_PI/2; + float coneAngle = M_PI / 2; float radius = m_spellInfo->Effects[effIndex].CalcRadius(m_caster) * m_spellValue->RadiusMod; if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList)) @@ -1226,18 +1226,18 @@ void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTarge referer = m_targets.GetUnitTarget(); break; case TARGET_REFERENCE_TYPE_LAST: - { - // find last added target for this effect - for (std::list::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit) { - if (ihit->effectMask & (1<::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit) { - referer = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); - break; + if (ihit->effectMask & (1 << effIndex)) + { + referer = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); + break; + } } + break; } - break; - } default: ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); return; @@ -1259,9 +1259,9 @@ void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTarge case TARGET_REFERENCE_TYPE_LAST: center = referer; break; - default: - ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); - return; + default: + ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); + return; } // Xinef: the distance should be increased by caster size, it is neglected in latter calculations @@ -1326,295 +1326,295 @@ void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplici } break; case TARGET_DEST_CASTER_FISHING: - { - float min_dis = m_spellInfo->GetMinRange(true); - float max_dis = m_spellInfo->GetMaxRange(true); - float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; - float x, y, z, angle; - angle = (float)rand_norm() * static_cast(M_PI * 35.0f / 180.0f) - static_cast(M_PI * 17.5f / 180.0f); - //m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, angle); this contains extra code that breaks fishing - m_caster->GetNearPoint(m_caster, x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, m_caster->GetOrientation() + angle); - - float ground = m_caster->GetMap()->GetHeight(m_caster->GetPhaseMask(), x, y, z, true, 120.0f); - float liquidLevel = VMAP_INVALID_HEIGHT_VALUE; - LiquidData liquidData; - if (m_caster->GetMap()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquidData)) - liquidLevel = liquidData.level; - - if (liquidLevel <= ground) // When there is no liquid Map::GetWaterOrGroundLevel returns ground level - { - SendCastResult(SPELL_FAILED_NOT_HERE); - SendChannelUpdate(0); - finish(false); - return; - } - - if (ground + 0.75 > liquidLevel) - { - SendCastResult(SPELL_FAILED_TOO_SHALLOW); - SendChannelUpdate(0); - finish(false); - return; - } - - dest = SpellDestination(x, y, liquidLevel, m_caster->GetOrientation()); - break; - } - case TARGET_DEST_CASTER_FRONT_LEAP: - { - float distance = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); - Map* map = m_caster->GetMap(); - uint32 mapid = m_caster->GetMapId(); - uint32 phasemask = m_caster->GetPhaseMask(); - float destx, desty, destz = 0, ground, startx, starty, startz, starto; - - Position pos; - Position lastpos; - m_caster->GetPosition(startx, starty, startz, starto); - pos.Relocate(startx, starty, startz, starto); - destx = pos.GetPositionX() + distance * cos(pos.GetOrientation()); - desty = pos.GetPositionY() + distance * sin(pos.GetOrientation()); - - ground = map->GetHeight(phasemask, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); - - if (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || (pos.GetPositionZ() - ground < distance)) { - float tstX = 0, tstY = 0, tstZ = 0, prevX = 0, prevY = 0, prevZ = 0; - float tstZ1 = 0, tstZ2 = 0, tstZ3 = 0, destz1 = 0, destz2 = 0, destz3 = 0, srange = 0, srange1 = 0, srange2 = 0, srange3 = 0; - float maxtravelDistZ = 2.65f; - float overdistance = 0.0f; - float totalpath = 0.0f; - float beforewaterz = 0.0f; - bool inwater = false; - bool wcol = false; - const float step = 2.0f; - const uint8 numChecks = ceil(fabs(distance / step)); - const float DELTA_X = (destx - pos.GetPositionX()) / numChecks; - const float DELTA_Y = (desty - pos.GetPositionY()) / numChecks; - int j = 1; - for (; j < (numChecks + 1); j++) + float min_dis = m_spellInfo->GetMinRange(true); + float max_dis = m_spellInfo->GetMaxRange(true); + float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; + float x, y, z, angle; + angle = (float)rand_norm() * static_cast(M_PI * 35.0f / 180.0f) - static_cast(M_PI * 17.5f / 180.0f); + //m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, angle); this contains extra code that breaks fishing + m_caster->GetNearPoint(m_caster, x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis, m_caster->GetOrientation() + angle); + + float ground = m_caster->GetMap()->GetHeight(m_caster->GetPhaseMask(), x, y, z, true, 120.0f); + float liquidLevel = VMAP_INVALID_HEIGHT_VALUE; + LiquidData liquidData; + if (m_caster->GetMap()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquidData)) + liquidLevel = liquidData.level; + + if (liquidLevel <= ground) // When there is no liquid Map::GetWaterOrGroundLevel returns ground level { - prevX = pos.GetPositionX() + (float(j - 1)*DELTA_X); - prevY = pos.GetPositionY() + (float(j - 1)*DELTA_Y); - tstX = pos.GetPositionX() + (float(j)*DELTA_X); - tstY = pos.GetPositionY() + (float(j)*DELTA_Y); + SendCastResult(SPELL_FAILED_NOT_HERE); + SendChannelUpdate(0); + finish(false); + return; + } - if (j < 2) - { - prevZ = pos.GetPositionZ(); - } - else - { - prevZ = tstZ; - } + if (ground + 0.75 > liquidLevel) + { + SendCastResult(SPELL_FAILED_TOO_SHALLOW); + SendChannelUpdate(0); + finish(false); + return; + } - tstZ = map->GetHeight(phasemask, tstX, tstY, prevZ + maxtravelDistZ, true); - ground = tstZ; + dest = SpellDestination(x, y, liquidLevel, m_caster->GetOrientation()); + break; + } + case TARGET_DEST_CASTER_FRONT_LEAP: + { + float distance = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); + Map* map = m_caster->GetMap(); + uint32 mapid = m_caster->GetMapId(); + uint32 phasemask = m_caster->GetPhaseMask(); + float destx, desty, destz = 0, ground, startx, starty, startz, starto; - if (!map->IsInWater(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ())) + Position pos; + Position lastpos; + m_caster->GetPosition(startx, starty, startz, starto); + pos.Relocate(startx, starty, startz, starto); + destx = pos.GetPositionX() + distance * cos(pos.GetOrientation()); + desty = pos.GetPositionY() + distance * sin(pos.GetOrientation()); + + ground = map->GetHeight(phasemask, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); + + if (!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || (pos.GetPositionZ() - ground < distance)) + { + float tstX = 0, tstY = 0, tstZ = 0, prevX = 0, prevY = 0, prevZ = 0; + float tstZ1 = 0, tstZ2 = 0, tstZ3 = 0, destz1 = 0, destz2 = 0, destz3 = 0, srange = 0, srange1 = 0, srange2 = 0, srange3 = 0; + float maxtravelDistZ = 2.65f; + float overdistance = 0.0f; + float totalpath = 0.0f; + float beforewaterz = 0.0f; + bool inwater = false; + bool wcol = false; + const float step = 2.0f; + const uint8 numChecks = ceil(fabs(distance / step)); + const float DELTA_X = (destx - pos.GetPositionX()) / numChecks; + const float DELTA_Y = (desty - pos.GetPositionY()) / numChecks; + int j = 1; + for (; j < (numChecks + 1); j++) { - if (map->IsInWater(tstX, tstY, tstZ)) + prevX = pos.GetPositionX() + (float(j - 1) * DELTA_X); + prevY = pos.GetPositionY() + (float(j - 1) * DELTA_Y); + tstX = pos.GetPositionX() + (float(j) * DELTA_X); + tstY = pos.GetPositionY() + (float(j) * DELTA_Y); + + if (j < 2) { - if (!(beforewaterz != 0.0f)) - beforewaterz = prevZ; - tstZ = beforewaterz; - srange = sqrt((tstY - prevY)*(tstY - prevY) + (tstX - prevX)*(tstX - prevX)); - //TC_LOG_ERROR("server", "(start was from land) step in water , number of cycle = %i , distance of step = %f, total path = %f, Z = %f", j, srange, totalpath, tstZ); - } - } - else if (map->IsInWater(tstX, tstY, tstZ)) - { - prevZ = pos.GetPositionZ(); - tstZ = pos.GetPositionZ(); - srange = sqrt((tstY - prevY)*(tstY - prevY) + (tstX - prevX)*(tstX - prevX)); - - inwater = true; - if (inwater && (fabs(tstZ - ground) < 2.0f)) - { - wcol = true; - //TC_LOG_ERROR("server", "step in water with collide and use standart check (for continue way after possible collide), number of cycle = %i ", j); - } - - // if (j < 2) - // TC_LOG_ERROR("server", "(start in water) step in water, number of cycle = %i , distance of step = %f, total path = %f", j, srange, totalpath); - // else - // TC_LOG_ERROR("server", "step in water, number of cycle = %i , distance of step = %f, total path = %f", j, srange, totalpath); - } - - if ((!map->IsInWater(tstX, tstY, tstZ) && tstZ != beforewaterz) || wcol) // second safety check z for blink way if on the ground - { - if (inwater && !map->IsInWater(tstX, tstY, tstZ)) - inwater = false; - - // highest available point - tstZ1 = map->GetHeight(phasemask, tstX, tstY, prevZ + maxtravelDistZ, true, 25.0f); - // upper or floor - tstZ2 = map->GetHeight(phasemask, tstX, tstY, prevZ, true, 25.0f); - //lower than floor - tstZ3 = map->GetHeight(phasemask, tstX, tstY, prevZ - maxtravelDistZ / 2, true, 25.0f); - - //distance of rays, will select the shortest in 3D - srange1 = sqrt((tstY - prevY)*(tstY - prevY) + (tstX - prevX)*(tstX - prevX) + (tstZ1 - prevZ)*(tstZ1 - prevZ)); - //TC_LOG_ERROR("server", "step = %i, distance of ray1 = %f", j, srange1); - srange2 = sqrt((tstY - prevY)*(tstY - prevY) + (tstX - prevX)*(tstX - prevX) + (tstZ2 - prevZ)*(tstZ2 - prevZ)); - //TC_LOG_ERROR("server", "step = %i, distance of ray2 = %f", j, srange2); - srange3 = sqrt((tstY - prevY)*(tstY - prevY) + (tstX - prevX)*(tstX - prevX) + (tstZ3 - prevZ)*(tstZ3 - prevZ)); - //TC_LOG_ERROR("server", "step = %i, distance of ray3 = %f", j, srange3); - - if (srange1 < srange2) - { - tstZ = tstZ1; - srange = srange1; - } - else if (srange3 < srange2) - { - tstZ = tstZ3; - srange = srange3; + prevZ = pos.GetPositionZ(); } else { - tstZ = tstZ2; - srange = srange2; + prevZ = tstZ; } - //TC_LOG_ERROR("server", "step on ground, number of cycle = %i , distance of step = %f, total path = %f", j, srange, totalpath); + tstZ = map->GetHeight(phasemask, tstX, tstY, prevZ + maxtravelDistZ, true); + ground = tstZ; + + if (!map->IsInWater(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ())) + { + if (map->IsInWater(tstX, tstY, tstZ)) + { + if (!(beforewaterz != 0.0f)) + beforewaterz = prevZ; + tstZ = beforewaterz; + srange = sqrt((tstY - prevY) * (tstY - prevY) + (tstX - prevX) * (tstX - prevX)); + //TC_LOG_ERROR("server", "(start was from land) step in water , number of cycle = %i , distance of step = %f, total path = %f, Z = %f", j, srange, totalpath, tstZ); + } + } + else if (map->IsInWater(tstX, tstY, tstZ)) + { + prevZ = pos.GetPositionZ(); + tstZ = pos.GetPositionZ(); + srange = sqrt((tstY - prevY) * (tstY - prevY) + (tstX - prevX) * (tstX - prevX)); + + inwater = true; + if (inwater && (fabs(tstZ - ground) < 2.0f)) + { + wcol = true; + //TC_LOG_ERROR("server", "step in water with collide and use standart check (for continue way after possible collide), number of cycle = %i ", j); + } + + // if (j < 2) + // TC_LOG_ERROR("server", "(start in water) step in water, number of cycle = %i , distance of step = %f, total path = %f", j, srange, totalpath); + // else + // TC_LOG_ERROR("server", "step in water, number of cycle = %i , distance of step = %f, total path = %f", j, srange, totalpath); + } + + if ((!map->IsInWater(tstX, tstY, tstZ) && tstZ != beforewaterz) || wcol) // second safety check z for blink way if on the ground + { + if (inwater && !map->IsInWater(tstX, tstY, tstZ)) + inwater = false; + + // highest available point + tstZ1 = map->GetHeight(phasemask, tstX, tstY, prevZ + maxtravelDistZ, true, 25.0f); + // upper or floor + tstZ2 = map->GetHeight(phasemask, tstX, tstY, prevZ, true, 25.0f); + //lower than floor + tstZ3 = map->GetHeight(phasemask, tstX, tstY, prevZ - maxtravelDistZ / 2, true, 25.0f); + + //distance of rays, will select the shortest in 3D + srange1 = sqrt((tstY - prevY) * (tstY - prevY) + (tstX - prevX) * (tstX - prevX) + (tstZ1 - prevZ) * (tstZ1 - prevZ)); + //TC_LOG_ERROR("server", "step = %i, distance of ray1 = %f", j, srange1); + srange2 = sqrt((tstY - prevY) * (tstY - prevY) + (tstX - prevX) * (tstX - prevX) + (tstZ2 - prevZ) * (tstZ2 - prevZ)); + //TC_LOG_ERROR("server", "step = %i, distance of ray2 = %f", j, srange2); + srange3 = sqrt((tstY - prevY) * (tstY - prevY) + (tstX - prevX) * (tstX - prevX) + (tstZ3 - prevZ) * (tstZ3 - prevZ)); + //TC_LOG_ERROR("server", "step = %i, distance of ray3 = %f", j, srange3); + + if (srange1 < srange2) + { + tstZ = tstZ1; + srange = srange1; + } + else if (srange3 < srange2) + { + tstZ = tstZ3; + srange = srange3; + } + else + { + tstZ = tstZ2; + srange = srange2; + } + + //TC_LOG_ERROR("server", "step on ground, number of cycle = %i , distance of step = %f, total path = %f", j, srange, totalpath); + } + + destx = tstX; + desty = tstY; + destz = tstZ; + + totalpath += srange; + + if (totalpath > distance) + { + overdistance = totalpath - distance; + //TC_LOG_ERROR("server", "total path > than distance in 3D , need to move back a bit for save distance, total path = %f, overdistance = %f", totalpath, overdistance); + } + + bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(mapid, prevX, prevY, prevZ + 0.5f, tstX, tstY, tstZ + 0.5f, tstX, tstY, tstZ, -0.5f); + // check dynamic collision + bool dcol = m_caster->GetMap()->getObjectHitPos(phasemask, prevX, prevY, prevZ + 0.5f, tstX, tstY, tstZ + 0.5f, tstX, tstY, tstZ, -0.5f); + + // collision occured + if (col || dcol || (overdistance > 0.0f && !map->IsInWater(tstX, tstY, ground)) || (fabs(prevZ - tstZ) > maxtravelDistZ && (tstZ > prevZ))) + { + if ((overdistance > 0.0f) && (overdistance < step)) + { + destx = prevX + overdistance * cos(pos.GetOrientation()); + desty = prevY + overdistance * sin(pos.GetOrientation()); + //TC_LOG_ERROR("server", "(collision) collision occured 1"); + } + else + { + // move back a bit + destx = tstX - (0.6 * cos(pos.GetOrientation())); + desty = tstY - (0.6 * sin(pos.GetOrientation())); + //TC_LOG_ERROR("server", "(collision) collision occured 2"); + } + + // highest available point + destz1 = map->GetHeight(phasemask, destx, desty, prevZ + maxtravelDistZ, true, 25.0f); + // upper or floor + destz2 = map->GetHeight(phasemask, destx, desty, prevZ, true, 25.0f); + //lower than floor + destz3 = map->GetHeight(phasemask, destx, desty, prevZ - maxtravelDistZ / 2, true, 25.0f); + + //distance of rays, will select the shortest in 3D + srange1 = sqrt((desty - prevY) * (desty - prevY) + (destx - prevX) * (destx - prevX) + (destz1 - prevZ) * (destz1 - prevZ)); + srange2 = sqrt((desty - prevY) * (desty - prevY) + (destx - prevX) * (destx - prevX) + (destz2 - prevZ) * (destz2 - prevZ)); + srange3 = sqrt((desty - prevY) * (desty - prevY) + (destx - prevX) * (destx - prevX) + (destz3 - prevZ) * (destz3 - prevZ)); + + if (srange1 < srange2) + destz = destz1; + else if (srange3 < srange2) + destz = destz3; + else + destz = destz2; + + if (inwater && destz < prevZ && !wcol) + destz = prevZ; + //TC_LOG_ERROR("server", "(collision) destZ rewrited in prevZ"); + + break; + } + // we have correct destz now } + //} - destx = tstX; - desty = tstY; - destz = tstZ; - - totalpath += srange; - - if (totalpath > distance) - { - overdistance = totalpath - distance; - //TC_LOG_ERROR("server", "total path > than distance in 3D , need to move back a bit for save distance, total path = %f, overdistance = %f", totalpath, overdistance); - } - - bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(mapid, prevX, prevY, prevZ + 0.5f, tstX, tstY, tstZ + 0.5f, tstX, tstY, tstZ, -0.5f); + lastpos.Relocate(destx, desty, destz + 0.5f, pos.GetOrientation()); + dest = SpellDestination(lastpos); + } + else + { + float z = pos.GetPositionZ(); + bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(mapid, pos.GetPositionX(), pos.GetPositionY(), z + 0.5f, destx, desty, z + 0.5f, destx, desty, z, -0.5f); // check dynamic collision - bool dcol = m_caster->GetMap()->getObjectHitPos(phasemask, prevX, prevY, prevZ + 0.5f, tstX, tstY, tstZ + 0.5f, tstX, tstY, tstZ, -0.5f); + bool dcol = m_caster->GetMap()->getObjectHitPos(phasemask, pos.GetPositionX(), pos.GetPositionY(), z + 0.5f, destx, desty, z + 0.5f, destx, desty, z, -0.5f); // collision occured - if (col || dcol || (overdistance > 0.0f && !map->IsInWater(tstX, tstY, ground)) || (fabs(prevZ - tstZ) > maxtravelDistZ && (tstZ > prevZ))) + if (col || dcol) { - if ((overdistance > 0.0f) && (overdistance < step)) - { - destx = prevX + overdistance * cos(pos.GetOrientation()); - desty = prevY + overdistance * sin(pos.GetOrientation()); - //TC_LOG_ERROR("server", "(collision) collision occured 1"); - } - else - { - // move back a bit - destx = tstX - (0.6 * cos(pos.GetOrientation())); - desty = tstY - (0.6 * sin(pos.GetOrientation())); - //TC_LOG_ERROR("server", "(collision) collision occured 2"); - } - - // highest available point - destz1 = map->GetHeight(phasemask, destx, desty, prevZ + maxtravelDistZ, true, 25.0f); - // upper or floor - destz2 = map->GetHeight(phasemask, destx, desty, prevZ, true, 25.0f); - //lower than floor - destz3 = map->GetHeight(phasemask, destx, desty, prevZ - maxtravelDistZ / 2, true, 25.0f); - - //distance of rays, will select the shortest in 3D - srange1 = sqrt((desty - prevY)*(desty - prevY) + (destx - prevX)*(destx - prevX) + (destz1 - prevZ)*(destz1 - prevZ)); - srange2 = sqrt((desty - prevY)*(desty - prevY) + (destx - prevX)*(destx - prevX) + (destz2 - prevZ)*(destz2 - prevZ)); - srange3 = sqrt((desty - prevY)*(desty - prevY) + (destx - prevX)*(destx - prevX) + (destz3 - prevZ)*(destz3 - prevZ)); - - if (srange1 < srange2) - destz = destz1; - else if (srange3 < srange2) - destz = destz3; - else - destz = destz2; - - if (inwater && destz < prevZ && !wcol) - destz = prevZ; - //TC_LOG_ERROR("server", "(collision) destZ rewrited in prevZ"); - - break; + // move back a bit + destx = destx - (0.6 * cos(pos.GetOrientation())); + desty = desty - (0.6 * sin(pos.GetOrientation())); } - // we have correct destz now - } - //} - lastpos.Relocate(destx, desty, destz + 0.5f, pos.GetOrientation()); - dest = SpellDestination(lastpos); - } - else - { - float z = pos.GetPositionZ(); - bool col = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(mapid, pos.GetPositionX(), pos.GetPositionY(), z + 0.5f, destx, desty, z + 0.5f, destx, desty, z, -0.5f); - // check dynamic collision - bool dcol = m_caster->GetMap()->getObjectHitPos(phasemask, pos.GetPositionX(), pos.GetPositionY(), z + 0.5f, destx, desty, z + 0.5f, destx, desty, z, -0.5f); - - // collision occured - if (col || dcol) - { - // move back a bit - destx = destx - (0.6 * cos(pos.GetOrientation())); - desty = desty - (0.6 * sin(pos.GetOrientation())); + lastpos.Relocate(destx, desty, z, pos.GetOrientation()); + dest = SpellDestination(lastpos); + //float range = sqrt((desty - pos.GetPositionY())*(desty - pos.GetPositionY()) + (destx - pos.GetPositionX())*(destx - pos.GetPositionX())); + //TC_LOG_ERROR("server", "Blink number 2, in falling but at a hight, distance of blink = %f", range); } - lastpos.Relocate(destx, desty, z, pos.GetOrientation()); - dest = SpellDestination(lastpos); - //float range = sqrt((desty - pos.GetPositionY())*(desty - pos.GetPositionY()) + (destx - pos.GetPositionX())*(destx - pos.GetPositionX())); - //TC_LOG_ERROR("server", "Blink number 2, in falling but at a hight, distance of blink = %f", range); + break; } - - break; - } default: - { - float dist; - float angle = targetType.CalcDirectionAngle(); - float objSize = m_caster->GetObjectSize(); - if (targetType.GetTarget() == TARGET_DEST_CASTER_SUMMON) - dist = PET_FOLLOW_DIST; - else - dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); - - if (dist < objSize) { - dist = objSize; - // xinef: give the summon some space (eg. totems) - if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Effects[effIndex].IsEffect(SPELL_EFFECT_SUMMON)) - dist += objSize; - } - else if (targetType.GetTarget() == TARGET_DEST_CASTER_RANDOM) - dist = objSize + (dist - objSize) * (float)rand_norm(); + float dist; + float angle = targetType.CalcDirectionAngle(); + float objSize = m_caster->GetObjectSize(); + if (targetType.GetTarget() == TARGET_DEST_CASTER_SUMMON) + dist = PET_FOLLOW_DIST; + else + dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); - Position pos; - bool totemCollision = false; - if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SUMMON) - { - SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[effIndex].MiscValueB); - if (properties && (properties->Type == SUMMON_TYPE_TOTEM || properties->Type == SUMMON_TYPE_LIGHTWELL)) + if (dist < objSize) + { + dist = objSize; + // xinef: give the summon some space (eg. totems) + if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Effects[effIndex].IsEffect(SPELL_EFFECT_SUMMON)) + dist += objSize; + } + else if (targetType.GetTarget() == TARGET_DEST_CASTER_RANDOM) + dist = objSize + (dist - objSize) * (float)rand_norm(); + + Position pos; + bool totemCollision = false; + if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SUMMON) + { + SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[effIndex].MiscValueB); + if (properties && (properties->Type == SUMMON_TYPE_TOTEM || properties->Type == SUMMON_TYPE_LIGHTWELL)) + { + totemCollision = true; + m_caster->GetFirstCollisionPositionForTotem(pos, dist, angle, false); + } + } + else if (m_spellInfo->Effects[effIndex].Effect >= SPELL_EFFECT_SUMMON_OBJECT_SLOT1 && m_spellInfo->Effects[effIndex].Effect <= SPELL_EFFECT_SUMMON_OBJECT_SLOT4) { totemCollision = true; - m_caster->GetFirstCollisionPositionForTotem(pos, dist, angle, false); + m_caster->GetFirstCollisionPositionForTotem(pos, dist, angle, true); } - } - else if (m_spellInfo->Effects[effIndex].Effect >= SPELL_EFFECT_SUMMON_OBJECT_SLOT1 && m_spellInfo->Effects[effIndex].Effect <= SPELL_EFFECT_SUMMON_OBJECT_SLOT4) - { - totemCollision = true; - m_caster->GetFirstCollisionPositionForTotem(pos, dist, angle, true); - } - if (!totemCollision) - { - if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_LEAP || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_JUMP_DEST || (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SUMMON)) - m_caster->GetFirstCollisionPosition(pos, dist, angle); - else - m_caster->GetNearPosition(pos, dist, angle); + if (!totemCollision) + { + if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_LEAP || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_JUMP_DEST || (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SUMMON)) + m_caster->GetFirstCollisionPosition(pos, dist, angle); + else + m_caster->GetNearPosition(pos, dist, angle); + } + dest.Relocate(pos); + break; } - dest.Relocate(pos); - break; - } } CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); @@ -1633,24 +1633,24 @@ void Spell::SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplici case TARGET_DEST_TARGET_ANY: break; default: - { - float angle = targetType.CalcDirectionAngle(); - float objSize = target->GetObjectSize(); - float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); - if (dist < objSize) - dist = objSize; - else if (targetType.GetTarget() == TARGET_DEST_TARGET_RANDOM) - dist = objSize + (dist - objSize) * (float)rand_norm(); + { + float angle = targetType.CalcDirectionAngle(); + float objSize = target->GetObjectSize(); + float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); + if (dist < objSize) + dist = objSize; + else if (targetType.GetTarget() == TARGET_DEST_TARGET_RANDOM) + dist = objSize + (dist - objSize) * (float)rand_norm(); - Position pos; - if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_LEAP || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_JUMP_DEST || (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SUMMON)) - target->GetFirstCollisionPosition(pos, dist, angle); - else - target->GetNearPosition(pos, dist, angle); + Position pos; + if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_LEAP || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_JUMP_DEST || (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SUMMON)) + target->GetFirstCollisionPosition(pos, dist, angle); + else + target->GetNearPosition(pos, dist, angle); - dest.Relocate(pos); - break;; - } + dest.Relocate(pos); + break;; + } } CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); @@ -1678,18 +1678,18 @@ void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitT SelectImplicitTrajTargets(effIndex, targetType); return; default: - { - float angle = targetType.CalcDirectionAngle(); - float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); - if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM) - dist *= float(rand_norm()); + { + float angle = targetType.CalcDirectionAngle(); + float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); + if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM) + dist *= float(rand_norm()); - Position pos = dest._position; - m_caster->MovePosition(pos, dist, angle); + Position pos = dest._position; + m_caster->MovePosition(pos, dist, angle); - dest.Relocate(pos); - break; - } + dest.Relocate(pos); + break; + } } CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); @@ -1781,7 +1781,7 @@ void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTarg std::list targets; SearchChainTargets(targets, maxTargets - 1, target, targetType.GetObjectType(), targetType.GetCheckType(), targetType.GetSelectionCategory() - , m_spellInfo->Effects[effIndex].ImplicitTargetConditions, targetType.GetTarget() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY); + , m_spellInfo->Effects[effIndex].ImplicitTargetConditions, targetType.GetTarget() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY); // Chain primary target is added earlier CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType); @@ -1836,7 +1836,7 @@ void Spell::SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTarge DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: a %f b %f", a, b);) // Xinef: hack for distance, many trajectory spells have RangeEntry 1 (self) - float bestDist = m_spellInfo->GetMaxRange(false)*2; + float bestDist = m_spellInfo->GetMaxRange(false) * 2; if (bestDist < 1.0f) bestDist = 300.0f; @@ -1882,7 +1882,7 @@ void Spell::SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTarge bestDist = dist; break; } - + continue; } @@ -1890,9 +1890,9 @@ void Spell::SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTarge { // Xinef: everything remade dist = m_targets.GetSrcPos()->GetExactDist(*itr); - height = m_targets.GetSrcPos()->GetExactDist2d(*itr)*b; + height = m_targets.GetSrcPos()->GetExactDist2d(*itr) * b; - if (height < dz + size*(b+1) && height > dz - size*(b+1) && dist < bestDist) + if (height < dz + size * (b + 1) && height > dz - size * (b + 1) && dist < bestDist) { bestDist = dist; break; @@ -2092,7 +2092,7 @@ void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* refere if (searchInGrid || searchInWorld) { - float x,y; + float x, y; x = pos->GetPositionX(); y = pos->GetPositionY(); @@ -2110,7 +2110,7 @@ void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* refere if (searchInGrid) { TypeContainerVisitor grid_object_notifier(searcher); - cell.Visit(p, grid_object_notifier, map, radius + SPELL_SEARCHER_COMPENSATION, x , y); + cell.Visit(p, grid_object_notifier, map, radius + SPELL_SEARCHER_COMPENSATION, x, y); } } } @@ -2164,8 +2164,8 @@ void Spell::SearchChainTargets(std::list& targets, uint32 chainTar // chain lightning/heal spells and similar - allow to jump at larger distance and go out of los bool isBouncingFar = (m_spellInfo->HasAttribute(SPELL_ATTR4_AREA_TARGET_CHAIN) - || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE - || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC); + || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE + || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC); // max dist which spell can reach float searchRadius = jumpRadius; @@ -2268,8 +2268,8 @@ void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/) break; default: if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && - m_spellInfo->EquippedItemSubClassMask & (1<HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) // Wands auto attack + m_spellInfo->EquippedItemSubClassMask & (1 << ITEM_SUBCLASS_WEAPON_WAND) + && m_spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) // Wands auto attack { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; @@ -2281,9 +2281,9 @@ void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/) // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && - (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow - m_spellInfo->Id == 57879 || m_spellInfo->Id == 45145 || // Snake Trap - done this way to avoid double proc - m_spellInfo->SpellFamilyFlags[2] & 0x00064000)) // Explosive and Immolation Trap + (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow + m_spellInfo->Id == 57879 || m_spellInfo->Id == 45145 || // Snake Trap - done this way to avoid double proc + m_spellInfo->SpellFamilyFlags[2] & 0x00064000)) // Explosive and Immolation Trap { m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION; } @@ -2302,8 +2302,8 @@ void Spell::prepareDataForTriggerSystem(AuraEffect const* /*triggeredByAura*/) if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK)) { if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS && - (m_spellInfo->HasAttribute(SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC) || - m_spellInfo->HasAttribute(SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2))) + (m_spellInfo->HasAttribute(SPELL_ATTR2_TRIGGERED_CAN_TRIGGER_PROC) || + m_spellInfo->HasAttribute(SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_PROC_2))) m_procEx |= PROC_EX_INTERNAL_CANT_PROC; else if (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) m_procEx |= PROC_EX_INTERNAL_TRIGGERED; @@ -2424,7 +2424,7 @@ void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= targetInfo.timeDelay += targetInfo.timeDelay >> 1; m_spellFlags |= SPELL_FLAG_REFLECTED; - + // HACK: workaround check for succubus seduction case // TODO: seduction should be casted only on humanoids (not demons) if (m_caster->IsPet()) @@ -2433,11 +2433,11 @@ void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= switch (ci->family) { case CREATURE_FAMILY_SUCCUBUS: - { - if (m_spellInfo->SpellIconID != 694) // Soothing Kiss - cancel(); - } - break; + { + if (m_spellInfo->SpellIconID != 694) // Soothing Kiss + cancel(); + } + break; return; } } @@ -2459,14 +2459,14 @@ void Spell::AddGOTarget(GameObject* go, uint32 effectMask) { switch (m_spellInfo->Effects[effIndex].Effect) { - case SPELL_EFFECT_GAMEOBJECT_DAMAGE: - case SPELL_EFFECT_GAMEOBJECT_REPAIR: - case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE: - if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) - effectMask &= ~(1 << effIndex); - break; - default: - break; + case SPELL_EFFECT_GAMEOBJECT_DAMAGE: + case SPELL_EFFECT_GAMEOBJECT_REPAIR: + case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE: + if (go->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) + effectMask &= ~(1 << effIndex); + break; + default: + break; } } } @@ -2585,10 +2585,10 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) return; // Xinef: absorb delayed projectiles for 500ms - if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsTargetingArea() && !m_spellInfo->IsPositive() && - (World::GetGameTimeMS() - target->timeDelay) <= effectUnit->m_lastSanctuaryTime && World::GetGameTimeMS() < (effectUnit->m_lastSanctuaryTime + 500) && - effectUnit->FindMap() && !effectUnit->FindMap()->IsDungeon() - ) + if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsTargetingArea() && !m_spellInfo->IsPositive() && + (World::GetGameTimeMS() - target->timeDelay) <= effectUnit->m_lastSanctuaryTime && World::GetGameTimeMS() < (effectUnit->m_lastSanctuaryTime + 500) && + effectUnit->FindMap() && !effectUnit->FindMap()->IsDungeon() + ) return; // No missinfo in that case // Get original caster (if exist) and calculate damage/healing from him data @@ -2610,7 +2610,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) m_spellAura = nullptr; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied - //Spells with this flag cannot trigger if effect is casted on self + //Spells with this flag cannot trigger if effect is casted on self bool canEffectTrigger = !m_spellInfo->HasAttribute(SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && (CanExecuteTriggersOnHit(mask) || missInfo == SPELL_MISS_IMMUNE2); bool reflectedSpell = missInfo == SPELL_MISS_REFLECT; Unit* spellHitTarget = nullptr; @@ -2668,10 +2668,10 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) positive = false; else if (!m_healing) { - for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // If at least one effect negative spell is negative hit // Xinef: if missInfo is immune state check all effects to properly determine positiveness of spell - if ((missInfo == SPELL_MISS_IMMUNE2 || (mask & (1<IsPositiveEffect(i)) + if ((missInfo == SPELL_MISS_IMMUNE2 || (mask & (1 << i))) && !m_spellInfo->IsPositiveEffect(i)) { positive = false; break; @@ -2690,7 +2690,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; } - break; + break; case SPELL_DAMAGE_CLASS_NONE: if (positive) { @@ -2702,7 +2702,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; } - break; + break; } } CallScriptOnHitHandlers(); @@ -2815,7 +2815,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) { caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell); if (caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 && - m_spellInfo->HasAttribute(SPELL_ATTR4_CANT_TRIGGER_ITEM_SPELLS) == 0 && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) + m_spellInfo->HasAttribute(SPELL_ATTR4_CANT_TRIGGER_ITEM_SPELLS) == 0 && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx); } @@ -2834,8 +2834,8 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // Xinef: eg. rogue poisons can proc off cheap shot, etc. so this block should be here also // Xinef: ofc count only spells that HIT the target, little hack used to fool the system if ((procEx & PROC_EX_NORMAL_HIT || procEx & PROC_EX_CRITICAL_HIT) && caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 && - m_spellInfo->HasAttribute(SPELL_ATTR4_CANT_TRIGGER_ITEM_SPELLS) == 0 && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) - caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim|PROC_FLAG_TAKEN_DAMAGE, procEx); + m_spellInfo->HasAttribute(SPELL_ATTR4_CANT_TRIGGER_ITEM_SPELLS) == 0 && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) + caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim | PROC_FLAG_TAKEN_DAMAGE, procEx); } // Failed Pickpocket, reveal rogue @@ -2851,7 +2851,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) { if (missInfo != SPELL_MISS_EVADE && !m_caster->IsFriendlyTo(effectUnit) && (!m_spellInfo->IsPositive() || m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL))) { - m_caster->CombatStart(effectUnit, !(m_spellInfo->AttributesEx3& SPELL_ATTR3_NO_INITIAL_AGGRO)); + m_caster->CombatStart(effectUnit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)); if (!effectUnit->IsStandState()) effectUnit->SetStandState(UNIT_STAND_STATE_STAND); @@ -2991,7 +2991,7 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleA if (effectMask & (1 << i) && m_spellInfo->Effects[i].IsUnitOwnedAuraEffect()) aura_effmask |= 1 << i; - Unit * originalCaster = GetOriginalCaster(); + Unit* originalCaster = GetOriginalCaster(); if (!originalCaster) originalCaster = m_caster; @@ -3008,8 +3008,8 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleA // Increase Diminishing on unit, current informations for actually casts will use values above if ((type == DRTYPE_PLAYER && ( - unit->GetCharmerOrOwnerPlayerOrPlayerItself() || flagsExtra & CREATURE_FLAG_EXTRA_ALL_DIMINISH || (m_diminishGroup == DIMINISHING_TAUNT && (flagsExtra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH)) - )) || type == DRTYPE_ALL) + unit->GetCharmerOrOwnerPlayerOrPlayerItself() || flagsExtra & CREATURE_FLAG_EXTRA_ALL_DIMINISH || (m_diminishGroup == DIMINISHING_TAUNT && (flagsExtra & CREATURE_FLAG_EXTRA_TAUNT_DIMINISH)) + )) || type == DRTYPE_ALL) unit->IncrDiminishing(m_diminishGroup); } @@ -3040,8 +3040,8 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleA if (m_originalCaster) { bool refresh = false; - m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit, m_originalCaster, - (aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem, 0, &refresh, !(_triggeredCastFlags & TRIGGERED_NO_PERIODIC_RESET)); + m_spellAura = Aura::TryRefreshStackOrCreate(aurSpellInfo, effectMask, unit, m_originalCaster, + (aurSpellInfo == m_spellInfo) ? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem, 0, &refresh, !(_triggeredCastFlags & TRIGGERED_NO_PERIODIC_RESET)); // xinef: if aura was not refreshed, add proc ex if (!refresh) @@ -3125,7 +3125,7 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleA HandleEffects(unit, nullptr, nullptr, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); } - if( sanct_effect >= 0 && (effectMask & (1<= 0 && (effectMask & (1 << sanct_effect)) ) HandleEffects(unit, nullptr, nullptr, sanct_effect, SPELL_EFFECT_HANDLE_HIT_TARGET); return SPELL_MISS_NONE; @@ -3196,11 +3196,15 @@ void Spell::DoTriggersOnSpellHit(Unit* unit, uint8 effMask) // trigger linked auras remove/apply // TODO: remove/cleanup this, as this table is not documented and people are doing stupid things with it - if (std::vector const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) { + if (std::vector const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) + { for (std::vector::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i) - if (*i < 0) { + if (*i < 0) + { unit->RemoveAurasDueToSpell(-(*i)); - } else { + } + else + { unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID()); } } @@ -3263,7 +3267,7 @@ bool Spell::UpdateChanneledTargetList() uint8 channelAuraMask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA) - channelAuraMask |= 1<GetMaxRange(m_spellInfo->IsPositive()); if (range == 0) for(int i = EFFECT_0; i <= EFFECT_2; ++i) - if (channelAuraMask & (1<Effects[i].RadiusEntry) + if (channelAuraMask & (1 << i) && m_spellInfo->Effects[i].RadiusEntry) { range = m_spellInfo->Effects[i].CalcRadius(nullptr, nullptr); break; @@ -3283,10 +3287,10 @@ bool Spell::UpdateChanneledTargetList() modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); // xinef: add little tolerance level - range += std::min(3.0f, range*0.1f); // 10% but no more than 3yd + range += std::min(3.0f, range * 0.1f); // 10% but no more than 3yd } - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask)) { @@ -3299,7 +3303,7 @@ bool Spell::UpdateChanneledTargetList() { if (channelAuraMask & ihit->effectMask) { - if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) + if (AuraApplication* aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) { if (m_caster != unit) { @@ -3326,11 +3330,11 @@ bool Spell::UpdateChanneledTargetList() // Xinef: not all effects are covered, remove applications from all targets if (channelTargetEffectMask != 0) { - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->missCondition == SPELL_MISS_NONE && (channelAuraMask & ihit->effectMask)) if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) if (IsValidDeadOrAliveTarget(unit)) - if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) + if (AuraApplication* aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) { ihit->effectMask &= ~aurApp->GetEffectMask(); unit->RemoveAura(aurApp); @@ -3357,8 +3361,8 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AURA || - m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || - m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID) + m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || + m_spellInfo->Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID) { // Change aura with ranks only if basepoints are taken from spellInfo and aura is positive if (m_spellInfo->IsPositiveEffect(i)) @@ -3400,7 +3404,7 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered LoadScripts(); OnSpellLaunch(); - + m_powerCost = m_CastItem ? 0 : m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask, this); // Set combo point requirement @@ -3455,7 +3459,7 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered { if (!m_spellInfo->Effects[i].IsEffect()) continue; - + if (m_spellInfo->Effects[i].TargetA.GetSelectionCategory() != TARGET_SELECT_CATEGORY_NEARBY || m_spellInfo->Effects[i].TargetA.GetCheckType() != TARGET_CHECK_ENTRY) { selectTargets = false; @@ -3531,8 +3535,8 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered // set target for proper facing if ((m_casttime || m_spellInfo->IsChanneled()) && !(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING)) { - if (m_caster->GetTypeId() == TYPEID_UNIT && !m_caster->ToCreature()->IsInEvadeMode() && - ((m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget()) || m_spellInfo->IsPositive())) + if (m_caster->GetTypeId() == TYPEID_UNIT && !m_caster->ToCreature()->IsInEvadeMode() && + ((m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget()) || m_spellInfo->IsPositive())) { // Xinef: Creature should focus to cast target if there is explicit target or self if casting positive spell // Xinef: Creature should not rotate like a retard when casting spell... based on halion behavior @@ -3679,7 +3683,7 @@ void Spell::_cast(bool skipCheck) for (Unit::ControlSet::iterator itr = playerCaster->m_Controlled.begin(); itr != playerCaster->m_Controlled.end(); ++itr) if (Unit* pet = *itr) if (pet->IsAlive() && pet->GetTypeId() == TYPEID_UNIT) - pet->ToCreature()->AI()->OwnerAttacked(m_targets.GetUnitTarget()); + pet->ToCreature()->AI()->OwnerAttacked(m_targets.GetUnitTarget()); } SetExecutedCurrently(true); @@ -3835,7 +3839,7 @@ void Spell::_cast(bool skipCheck) if (modOwner) modOwner->SetSpellModTakingSpell(this, false); - if (const std::vector *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id)) + if (const std::vector* spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id)) { for (std::vector::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i) if (*i < 0) @@ -3949,7 +3953,7 @@ uint64 Spell::handle_delayed(uint64 t_offset) bool single_missile = (m_targets.HasDst()); // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases) - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->processed == false) { @@ -3964,7 +3968,7 @@ uint64 Spell::handle_delayed(uint64 t_offset) } // now recheck gameobject targeting correctness - for (std::list::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) + for (std::list::iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) { if (ighit->processed == false) { @@ -4022,7 +4026,7 @@ void Spell::_handle_immediate_phase() } // process items - for (std::list::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); } @@ -4118,8 +4122,8 @@ void Spell::update(uint32 difftime) // check if the player caster has moved before the spell finished // xinef: added preparing state (real cast, skip channels as they have other flags for this) if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) && - m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && m_spellState == SPELL_STATE_PREPARING && - (m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR))) + m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && m_spellState == SPELL_STATE_PREPARING && + (m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR))) { // don't cancel for melee, autorepeat, triggered and instant spells if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered()) @@ -4129,23 +4133,6 @@ void Spell::update(uint32 difftime) switch (m_spellState) { case SPELL_STATE_PREPARING: - { - if (m_timer > 0) - { - if (difftime >= (uint32)m_timer) - m_timer = 0; - else - m_timer -= difftime; - } - - if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat()) - // don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example - cast(!m_casttime); - break; - } - case SPELL_STATE_CASTING: - { - if (m_timer) { if (m_timer > 0) { @@ -4154,28 +4141,45 @@ void Spell::update(uint32 difftime) else m_timer -= difftime; } - } - if (m_timer == 0) - { - SendChannelUpdate(0); - - finish(); + if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat()) + // don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example + cast(!m_casttime); + break; } - // Xinef: Dont update channeled target list on last tick, allow auras to update duration properly - // Xinef: Added this strange check because of diffrent update routines for players / creatures - // Xinef: If creature gets new aura in 800ms and in 840ms its updated with diff 270, not 40 is removed from duration but 270 - // Xinef: so the aura can be removed in different updates for all units - else if ((m_timer < 0 || m_timer > 300) && !UpdateChanneledTargetList()) + case SPELL_STATE_CASTING: { + if (m_timer) + { + if (m_timer > 0) + { + if (difftime >= (uint32)m_timer) + m_timer = 0; + else + m_timer -= difftime; + } + } + + if (m_timer == 0) + { + SendChannelUpdate(0); + + finish(); + } + // Xinef: Dont update channeled target list on last tick, allow auras to update duration properly + // Xinef: Added this strange check because of diffrent update routines for players / creatures + // Xinef: If creature gets new aura in 800ms and in 840ms its updated with diff 270, not 40 is removed from duration but 270 + // Xinef: so the aura can be removed in different updates for all units + else if ((m_timer < 0 || m_timer > 300) && !UpdateChanneledTargetList()) + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id); + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id); #endif - SendChannelUpdate(0); - finish(); + SendChannelUpdate(0); + finish(); + } + break; } - break; - } default: break; } @@ -4201,8 +4205,8 @@ void Spell::finish(bool ok) { if (Unit* charm = m_caster->GetCharm()) if (charm->GetTypeId() == TYPEID_UNIT - && charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET) - && charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id) + && charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET) + && charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id) ((Puppet*)charm)->UnSummon(); } @@ -4337,40 +4341,40 @@ void Spell::WriteCastResultInfo(WorldPacket& data, Player* caster, SpellInfo con data << uint32(spellInfo->EquippedItemSubClassMask); break; case SPELL_FAILED_TOO_MANY_OF_ITEM: - { - uint32 item = 0; - for (int8 eff = 0; eff < MAX_SPELL_EFFECTS; eff++) - if (spellInfo->Effects[eff].ItemType) - item = spellInfo->Effects[eff].ItemType; - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item); - if (proto && proto->ItemLimitCategory) - data << uint32(proto->ItemLimitCategory); - break; - } + { + uint32 item = 0; + for (int8 eff = 0; eff < MAX_SPELL_EFFECTS; eff++) + if (spellInfo->Effects[eff].ItemType) + item = spellInfo->Effects[eff].ItemType; + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item); + if (proto && proto->ItemLimitCategory) + data << uint32(proto->ItemLimitCategory); + break; + } case SPELL_FAILED_CUSTOM_ERROR: data << uint32(customError); break; case SPELL_FAILED_REAGENTS: - { - uint32 missingItem = 0; - for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { - if (spellInfo->Reagent[i] <= 0) - continue; - - uint32 itemid = spellInfo->Reagent[i]; - uint32 itemcount = spellInfo->ReagentCount[i]; - - if (!caster->HasItemCount(itemid, itemcount)) + uint32 missingItem = 0; + for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { - missingItem = itemid; - break; - } - } + if (spellInfo->Reagent[i] <= 0) + continue; - data << uint32(missingItem); // first missing item - break; - } + uint32 itemid = spellInfo->Reagent[i]; + uint32 itemcount = spellInfo->ReagentCount[i]; + + if (!caster->HasItemCount(itemid, itemcount)) + { + missingItem = itemid; + break; + } + } + + data << uint32(missingItem); // first missing item + break; + } case SPELL_FAILED_PREVENTED_BY_MECHANIC: data << uint32(spellInfo->Mechanic); break; @@ -4456,14 +4460,14 @@ void Spell::SendSpellStart() if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO)) castFlags |= CAST_FLAG_AMMO; if ((m_caster->GetTypeId() == TYPEID_PLAYER || - (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) - && m_spellInfo->PowerType != POWER_HEALTH) + (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) + && m_spellInfo->PowerType != POWER_HEALTH) castFlags |= CAST_FLAG_POWER_LEFT_SELF; if (m_spellInfo->RuneCostID && m_spellInfo->PowerType == POWER_RUNE) castFlags |= CAST_FLAG_NO_GCD; // not needed, but Blizzard sends it - WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2)); + WorldPacket data(SMSG_SPELL_START, (8 + 8 + 4 + 4 + 2)); if (m_CastItem) data.append(m_CastItem->GetPackGUID()); else @@ -4513,14 +4517,14 @@ void Spell::SendSpellGo() castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual if ((m_caster->GetTypeId() == TYPEID_PLAYER || - (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) - && m_spellInfo->PowerType != POWER_HEALTH) + (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) + && m_spellInfo->PowerType != POWER_HEALTH) castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible if ((m_caster->GetTypeId() == TYPEID_PLAYER) - && (m_caster->getClass() == CLASS_DEATH_KNIGHT) - && m_spellInfo->RuneCostID - && m_spellInfo->PowerType == POWER_RUNE) + && (m_caster->getClass() == CLASS_DEATH_KNIGHT) + && m_spellInfo->RuneCostID + && m_spellInfo->PowerType == POWER_RUNE) { castFlags |= CAST_FLAG_NO_GCD; // not needed, but Blizzard sends it castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list @@ -4735,7 +4739,7 @@ void Spell::WriteSpellGoTargets(WorldPacket* data) void Spell::SendLogExecute() { - WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8)); + WorldPacket data(SMSG_SPELLLOGEXECUTE, (8 + 4 + 4 + 4 + 4 + 8)); data.append(m_caster->GetPackGUID()); @@ -4836,14 +4840,14 @@ void Spell::ExecuteLogEffectResurrect(uint8 effIndex, Unit* target) void Spell::SendInterrupted(uint8 result) { - WorldPacket data(SMSG_SPELL_FAILURE, (8+1+4+1)); + WorldPacket data(SMSG_SPELL_FAILURE, (8 + 1 + 4 + 1)); data.append(m_caster->GetPackGUID()); data << uint8(m_cast_count); data << uint32(m_spellInfo->Id); data << uint8(result); m_caster->SendMessageToSet(&data, true); - data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+1+4+1)); + data.Initialize(SMSG_SPELL_FAILED_OTHER, (8 + 1 + 4 + 1)); data.append(m_caster->GetPackGUID()); data << uint8(m_cast_count); data << uint32(m_spellInfo->Id); @@ -4859,7 +4863,7 @@ void Spell::SendChannelUpdate(uint32 time) m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0); } - WorldPacket data(MSG_CHANNEL_UPDATE, 8+4); + WorldPacket data(MSG_CHANNEL_UPDATE, 8 + 4); data.append(m_caster->GetPackGUID()); data << uint32(time); @@ -4873,7 +4877,7 @@ void Spell::SendChannelStart(uint32 duration) if (m_UniqueTargetInfo.size() + m_UniqueGOTargetInfo.size() == 1) // this is for TARGET_SELECT_CATEGORY_NEARBY channelTarget = !m_UniqueTargetInfo.empty() ? m_UniqueTargetInfo.front().targetGUID : m_UniqueGOTargetInfo.front().targetGUID; - WorldPacket data(MSG_CHANNEL_START, (8+4+4)); + WorldPacket data(MSG_CHANNEL_START, (8 + 4 + 4)); data.append(m_caster->GetPackGUID()); data << uint32(m_spellInfo->Id); data << uint32(duration); @@ -4898,7 +4902,7 @@ void Spell::SendResurrectRequest(Player* target) ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex())); - WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+sentName.size()+1+1+1+4)); + WorldPacket data(SMSG_RESURRECT_REQUEST, (8 + 4 + sentName.size() + 1 + 1 + 1 + 4)); data << uint64(m_caster->GetGUID()); data << uint32(sentName.size() + 1); @@ -4991,7 +4995,7 @@ void Spell::TakePower() { if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNE || powerType == POWER_RUNIC_POWER) if (uint64 targetGUID = m_targets.GetUnitTargetGUID()) - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_BLOCK && ihit->missCondition != SPELL_MISS_ABSORB && ihit->missCondition != SPELL_MISS_REFLECT) @@ -5030,7 +5034,7 @@ void Spell::TakePower() if (hit) m_caster->ModifyPower(powerType, -m_powerCost); else - m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4)); + m_caster->ModifyPower(powerType, -irand(0, m_powerCost / 4)); // Set the five second timer if (powerType == POWER_MANA && m_powerCost > 0) @@ -5411,7 +5415,7 @@ SpellCastResult Spell::CheckCast(bool strict) m_needComboPoints = false; if ((*j)->GetMiscValue() == 1) { - reqCombat=false; + reqCombat = false; break; } } @@ -5464,7 +5468,7 @@ SpellCastResult Spell::CheckCast(bool strict) { // skip stuck spell to allow use it in falling case and apply spell limitations at movement if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR) || m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK) && - (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0)) + (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0)) return SPELL_FAILED_MOVING; } @@ -5494,7 +5498,7 @@ SpellCastResult Spell::CheckCast(bool strict) // All creatures should be able to cast as passengers freely, restriction and attribute are only for players VehicleSeatEntry const* vehicleSeat = vehicle->GetSeatForPassenger(m_caster); if (!m_spellInfo->HasAttribute(SPELL_ATTR6_CASTABLE_WHILE_ON_VEHICLE) && !m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED) - && (vehicleSeat->m_flags & checkMask) != checkMask && m_caster->GetTypeId() == TYPEID_PLAYER) + && (vehicleSeat->m_flags & checkMask) != checkMask && m_caster->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_DONT_REPORT; } @@ -5592,7 +5596,7 @@ SpellCastResult Spell::CheckCast(bool strict) // - with greater than 10 min CD without SPELL_ATTR4_USABLE_IN_ARENA flag // - with SPELL_ATTR4_NOT_USABLE_IN_ARENA flag if (m_spellInfo->HasAttribute(SPELL_ATTR4_NOT_USABLE_IN_ARENA) || - (m_spellInfo->GetRecoveryTime() >= 10 * MINUTE * IN_MILLISECONDS && !m_spellInfo->HasAttribute(SPELL_ATTR4_USABLE_IN_ARENA))) + (m_spellInfo->GetRecoveryTime() >= 10 * MINUTE * IN_MILLISECONDS && !m_spellInfo->HasAttribute(SPELL_ATTR4_USABLE_IN_ARENA))) if (MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId())) if (mapEntry->IsBattleArena()) return SPELL_FAILED_NOT_IN_ARENA; @@ -5603,15 +5607,15 @@ SpellCastResult Spell::CheckCast(bool strict) uint32 zone, area; m_caster->GetZoneAndAreaId(zone, area); - SpellCastResult locRes= m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area, - m_caster->GetTypeId() == TYPEID_PLAYER ? m_caster->ToPlayer() : nullptr); + SpellCastResult locRes = m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area, + m_caster->GetTypeId() == TYPEID_PLAYER ? m_caster->ToPlayer() : nullptr); if (locRes != SPELL_CAST_OK) return locRes; } // not let players cast spells at mount (and let do it to creatures) if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE) && - !m_spellInfo->IsPassive() && !m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED)) + !m_spellInfo->IsPassive() && !m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED)) { if (m_caster->IsInFlight()) return SPELL_FAILED_NOT_ON_TAXI; @@ -5718,69 +5722,47 @@ SpellCastResult Spell::CheckCast(bool strict) switch (m_spellInfo->Effects[i].Effect) { case SPELL_EFFECT_DUMMY: - { - if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT) { - // Raise Ally - if( m_spellInfo->Id == 61999 ) + if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT) { - Unit *target = m_targets.GetUnitTarget(); - if (!target) + // Raise Ally + if( m_spellInfo->Id == 61999 ) + { + Unit* target = m_targets.GetUnitTarget(); + if (!target) + return SPELL_FAILED_BAD_TARGETS; + + if (target->IsAlive()) // not discovered attributeEx5? + return SPELL_FAILED_TARGET_NOT_DEAD; + } + } + else if (m_spellInfo->Id == 53271) // Master's Call + { + if (!m_caster->ToPlayer()) return SPELL_FAILED_BAD_TARGETS; - if (target->IsAlive()) // not discovered attributeEx5? - return SPELL_FAILED_TARGET_NOT_DEAD; + Unit* target = m_targets.GetUnitTarget(); + Pet* pet = m_caster->ToPlayer()->GetPet(); + if (!target || !pet || pet->isDead() || target->isDead()) + return SPELL_FAILED_BAD_TARGETS; + + if (!pet->IsWithinLOSInMap(target, LINEOFSIGHT_ALL_CHECKS)) + return SPELL_FAILED_LINE_OF_SIGHT; } - } - else if (m_spellInfo->Id == 53271) // Master's Call - { - if (!m_caster->ToPlayer()) - return SPELL_FAILED_BAD_TARGETS; - - Unit* target = m_targets.GetUnitTarget(); - Pet *pet = m_caster->ToPlayer()->GetPet(); - if (!target || !pet || pet->isDead() || target->isDead()) - return SPELL_FAILED_BAD_TARGETS; - - if (!pet->IsWithinLOSInMap(target, LINEOFSIGHT_ALL_CHECKS)) - return SPELL_FAILED_LINE_OF_SIGHT; - } - break; - } - case SPELL_EFFECT_LEARN_SPELL: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; - - if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_PET) break; - - Pet* pet = m_caster->ToPlayer()->GetPet(); - - if (!pet) - return SPELL_FAILED_NO_PET; - - SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell); - - if (!learn_spellproto) - return SPELL_FAILED_NOT_KNOWN; - - if (m_spellInfo->SpellLevel > pet->getLevel()) - return SPELL_FAILED_LOWLEVEL; - - break; - } - case SPELL_EFFECT_LEARN_PET_SPELL: - { - // check target only for unit target case - if (Unit* unitTarget = m_targets.GetUnitTarget()) + } + case SPELL_EFFECT_LEARN_SPELL: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; - Pet* pet = unitTarget->ToPet(); - if (!pet || pet->GetOwner() != m_caster) - return SPELL_FAILED_BAD_TARGETS; + if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_PET) + break; + + Pet* pet = m_caster->ToPlayer()->GetPet(); + + if (!pet) + return SPELL_FAILED_NO_PET; SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell); @@ -5789,372 +5771,394 @@ SpellCastResult Spell::CheckCast(bool strict) if (m_spellInfo->SpellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; + + break; + } + case SPELL_EFFECT_LEARN_PET_SPELL: + { + // check target only for unit target case + if (Unit* unitTarget = m_targets.GetUnitTarget()) + { + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; + + Pet* pet = unitTarget->ToPet(); + if (!pet || pet->GetOwner() != m_caster) + return SPELL_FAILED_BAD_TARGETS; + + SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(m_spellInfo->Effects[i].TriggerSpell); + + if (!learn_spellproto) + return SPELL_FAILED_NOT_KNOWN; + + if (m_spellInfo->SpellLevel > pet->getLevel()) + return SPELL_FAILED_LOWLEVEL; + } + break; } - break; - } case SPELL_EFFECT_APPLY_GLYPH: - { - uint32 glyphId = m_spellInfo->Effects[i].MiscValue; - if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyphId)) - if (m_caster->HasAura(gp->SpellId)) - return SPELL_FAILED_UNIQUE_GLYPH; - break; - } + { + uint32 glyphId = m_spellInfo->Effects[i].MiscValue; + if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyphId)) + if (m_caster->HasAura(gp->SpellId)) + return SPELL_FAILED_UNIQUE_GLYPH; + break; + } case SPELL_EFFECT_FEED_PET: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; + { + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; - Item* foodItem = m_targets.GetItemTarget(); - if (!foodItem) - return SPELL_FAILED_BAD_TARGETS; + Item* foodItem = m_targets.GetItemTarget(); + if (!foodItem) + return SPELL_FAILED_BAD_TARGETS; - Pet* pet = m_caster->ToPlayer()->GetPet(); + Pet* pet = m_caster->ToPlayer()->GetPet(); - if (!pet) - return SPELL_FAILED_NO_PET; + if (!pet) + return SPELL_FAILED_NO_PET; - if (!pet->HaveInDiet(foodItem->GetTemplate())) - return SPELL_FAILED_WRONG_PET_FOOD; + if (!pet->HaveInDiet(foodItem->GetTemplate())) + return SPELL_FAILED_WRONG_PET_FOOD; - if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel)) - return SPELL_FAILED_FOOD_LOWLEVEL; + if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel)) + return SPELL_FAILED_FOOD_LOWLEVEL; - if (m_caster->IsInCombat() || pet->IsInCombat()) - return SPELL_FAILED_AFFECTING_COMBAT; + if (m_caster->IsInCombat() || pet->IsInCombat()) + return SPELL_FAILED_AFFECTING_COMBAT; - break; - } + break; + } case SPELL_EFFECT_POWER_BURN: case SPELL_EFFECT_POWER_DRAIN: - { - // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects) - if (m_caster->GetTypeId() == TYPEID_PLAYER) - if (Unit* target = m_targets.GetUnitTarget()) - if (target != m_caster && target->getPowerType() != Powers(m_spellInfo->Effects[i].MiscValue)) - return SPELL_FAILED_BAD_TARGETS; - break; - } - case SPELL_EFFECT_CHARGE: - { - if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR) { - // Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process - if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953)) - m_caster->RemoveMovementImpairingAuras(true); + // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects) + if (m_caster->GetTypeId() == TYPEID_PLAYER) + if (Unit* target = m_targets.GetUnitTarget()) + if (target != m_caster && target->getPowerType() != Powers(m_spellInfo->Effects[i].MiscValue)) + return SPELL_FAILED_BAD_TARGETS; + break; } - if (m_caster->HasUnitState(UNIT_STATE_ROOT)) - return SPELL_FAILED_ROOTED; - if (m_caster->GetTypeId() == TYPEID_PLAYER) - if (Unit* target = m_targets.GetUnitTarget()) - if (!target->IsAlive()) - return SPELL_FAILED_BAD_TARGETS; - // Xinef: Pass only explicit unit target spells - // pussywizard: - if (MMAP::MMapFactory::IsPathfindingEnabled(m_caster->FindMap()) && m_spellInfo->NeedsExplicitUnitTarget()) + case SPELL_EFFECT_CHARGE: { - Unit* target = m_targets.GetUnitTarget(); - if (!target) + if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR) + { + // Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process + if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953)) + m_caster->RemoveMovementImpairingAuras(true); + } + if (m_caster->HasUnitState(UNIT_STATE_ROOT)) + return SPELL_FAILED_ROOTED; + if (m_caster->GetTypeId() == TYPEID_PLAYER) + if (Unit* target = m_targets.GetUnitTarget()) + if (!target->IsAlive()) + return SPELL_FAILED_BAD_TARGETS; + // Xinef: Pass only explicit unit target spells + // pussywizard: + if (MMAP::MMapFactory::IsPathfindingEnabled(m_caster->FindMap()) && m_spellInfo->NeedsExplicitUnitTarget()) + { + Unit* target = m_targets.GetUnitTarget(); + if (!target) + return SPELL_FAILED_BAD_TARGETS; + + Position pos; + target->GetChargeContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ); + + if (m_caster->GetMapId() == 618) // pussywizard: 618 Ring of Valor + pos.m_positionZ = std::max(pos.m_positionZ, 28.28f); + + float maxdist = MELEE_RANGE + m_caster->GetMeleeReach() + target->GetMeleeReach(); + if (target->GetExactDistSq(&pos) > maxdist * maxdist) + return SPELL_FAILED_NOPATH; + + if (m_caster->GetMapId() == 618) // pussywizard: 618 Ring of Valor + { + if (!((target->GetPositionZ() > 32.0f) ^ (m_caster->GetPositionZ() > 32.0f))) + break; + return SPELL_FAILED_NOPATH; + } + else if (m_caster->GetMapId() == 572) // pussywizard: 572 Ruins of Lordaeron + { + if (pos.GetPositionX() < 1275.0f || m_caster->GetPositionX() < 1275.0f) // special case (acid) + break; // can't force path because the way is around and the path is too long + } + + if (m_caster->GetTransport() != target->GetTransport()) + return SPELL_FAILED_NOPATH; + if (m_caster->GetTransport()) + break; + + m_pathFinder = new PathGenerator(m_caster); + m_pathFinder->CalculatePath(pos.m_positionX, pos.m_positionY, pos.m_positionZ + 0.15f, false); + G3D::Vector3 endPos = m_pathFinder->GetEndPosition(); // also check distance between target and the point calculated by mmaps + if (m_pathFinder->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE) || target->GetExactDistSq(endPos.x, endPos.y, endPos.z) > maxdist * maxdist || m_pathFinder->getPathLength() > (40.0f + (m_caster->HasAura(58097) ? 5.0f : 0.0f))) + return SPELL_FAILED_NOPATH; + } + break; + } + case SPELL_EFFECT_SKINNING: + { + if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT) return SPELL_FAILED_BAD_TARGETS; - Position pos; - target->GetChargeContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ); + if (!(m_targets.GetUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE)) + return SPELL_FAILED_TARGET_UNSKINNABLE; - if (m_caster->GetMapId() == 618) // pussywizard: 618 Ring of Valor - pos.m_positionZ = std::max(pos.m_positionZ, 28.28f); + Creature* creature = m_targets.GetUnitTarget()->ToCreature(); + if (!creature->IsCritter() && !creature->loot.isLooted()) + return SPELL_FAILED_TARGET_NOT_LOOTED; - float maxdist = MELEE_RANGE + m_caster->GetMeleeReach() + target->GetMeleeReach(); - if (target->GetExactDistSq(&pos) > maxdist*maxdist) - return SPELL_FAILED_NOPATH; + uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill(); - if (m_caster->GetMapId() == 618) // pussywizard: 618 Ring of Valor - { - if (!((target->GetPositionZ() > 32.0f) ^ (m_caster->GetPositionZ() > 32.0f))) - break; - return SPELL_FAILED_NOPATH; - } - else if (m_caster->GetMapId() == 572) // pussywizard: 572 Ruins of Lordaeron - { - if (pos.GetPositionX() < 1275.0f || m_caster->GetPositionX() < 1275.0f) // special case (acid) - break; // can't force path because the way is around and the path is too long - } + int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill); + int32 TargetLevel = m_targets.GetUnitTarget()->getLevel(); + int32 ReqValue = (skillValue < 100 ? (TargetLevel - 10) * 10 : TargetLevel * 5); + if (ReqValue > skillValue) + return SPELL_FAILED_LOW_CASTLEVEL; - if (m_caster->GetTransport() != target->GetTransport()) - return SPELL_FAILED_NOPATH; - if (m_caster->GetTransport()) + // chance for fail at orange skinning attempt + if ((m_selfContainer && (*m_selfContainer) == this) && + skillValue < sWorld->GetConfigMaxSkillValue() && + (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37)) + return SPELL_FAILED_TRY_AGAIN; + + break; + } + case SPELL_EFFECT_OPEN_LOCK: + { + if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_TARGET && + m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM_TARGET) break; - m_pathFinder = new PathGenerator(m_caster); - m_pathFinder->CalculatePath(pos.m_positionX, pos.m_positionY, pos.m_positionZ+0.15f, false); - G3D::Vector3 endPos = m_pathFinder->GetEndPosition(); // also check distance between target and the point calculated by mmaps - if (m_pathFinder->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE) || target->GetExactDistSq(endPos.x, endPos.y, endPos.z) > maxdist*maxdist || m_pathFinder->getPathLength() > (40.0f + (m_caster->HasAura(58097) ? 5.0f : 0.0f))) - return SPELL_FAILED_NOPATH; - } - break; - } - case SPELL_EFFECT_SKINNING: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT) - return SPELL_FAILED_BAD_TARGETS; + if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc. + // we need a go target in case of TARGET_GAMEOBJECT_TARGET + || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget())) + return SPELL_FAILED_BAD_TARGETS; - if (!(m_targets.GetUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE)) - return SPELL_FAILED_TARGET_UNSKINNABLE; - - Creature* creature = m_targets.GetUnitTarget()->ToCreature(); - if (!creature->IsCritter() && !creature->loot.isLooted()) - return SPELL_FAILED_TARGET_NOT_LOOTED; - - uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill(); - - int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill); - int32 TargetLevel = m_targets.GetUnitTarget()->getLevel(); - int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5); - if (ReqValue > skillValue) - return SPELL_FAILED_LOW_CASTLEVEL; - - // chance for fail at orange skinning attempt - if ((m_selfContainer && (*m_selfContainer) == this) && - skillValue < sWorld->GetConfigMaxSkillValue() && - (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37)) - return SPELL_FAILED_TRY_AGAIN; - - break; - } - case SPELL_EFFECT_OPEN_LOCK: - { - if (m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_TARGET && - m_spellInfo->Effects[i].TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM_TARGET) - break; - - if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc. - // we need a go target in case of TARGET_GAMEOBJECT_TARGET - || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget())) - return SPELL_FAILED_BAD_TARGETS; - - Item* pTempItem = nullptr; - if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) - { - if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) - pTempItem = pTrade->GetTraderData()->GetItem(TradeSlots(m_targets.GetItemTargetGUID())); - } - else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM) - pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID()); - - // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM_TARGET - if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET && - !m_targets.GetGOTarget() && - (!pTempItem || !pTempItem->GetTemplate()->LockID || !pTempItem->IsLocked())) - return SPELL_FAILED_BAD_TARGETS; - - if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() && - m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP)) - { - if (m_targets.GetGOTarget() && m_targets.GetGOTarget()->GetEntry() == 179697) + Item* pTempItem = nullptr; + if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { - if (!m_caster->ToPlayer()->CanUseBattlegroundObject(nullptr)) + if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) + pTempItem = pTrade->GetTraderData()->GetItem(TradeSlots(m_targets.GetItemTargetGUID())); + } + else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM) + pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID()); + + // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM_TARGET + if (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET && + !m_targets.GetGOTarget() && + (!pTempItem || !pTempItem->GetTemplate()->LockID || !pTempItem->IsLocked())) + return SPELL_FAILED_BAD_TARGETS; + + if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() && + m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP)) + { + if (m_targets.GetGOTarget() && m_targets.GetGOTarget()->GetEntry() == 179697) + { + if (!m_caster->ToPlayer()->CanUseBattlegroundObject(nullptr)) + return SPELL_FAILED_TRY_AGAIN; + } + else if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners, or Gurubashi chest + !m_caster->ToPlayer()->CanUseBattlegroundObject(m_targets.GetGOTarget())) return SPELL_FAILED_TRY_AGAIN; } - else if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners, or Gurubashi chest - !m_caster->ToPlayer()->CanUseBattlegroundObject(m_targets.GetGOTarget())) - return SPELL_FAILED_TRY_AGAIN; + + // get the lock entry + uint32 lockId = 0; + if (GameObject* go = m_targets.GetGOTarget()) + { + lockId = go->GetGOInfo()->GetLockId(); + if (!lockId) + return SPELL_FAILED_BAD_TARGETS; + } + else if (Item* itm = m_targets.GetItemTarget()) + lockId = itm->GetTemplate()->LockID; + + SkillType skillId = SKILL_NONE; + int32 reqSkillValue = 0; + int32 skillValue = 0; + + // check lock compatibility + SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue); + if (res != SPELL_CAST_OK) + return res; + + // chance for fail at orange mining/herb/LockPicking gathering attempt + // second check prevent fail at rechecks + if (skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this))) + { + bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING; + + // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill) + if ((canFailAtMax || skillValue < sWorld->GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37)) + return SPELL_FAILED_TRY_AGAIN; + } + break; } - - // get the lock entry - uint32 lockId = 0; - if (GameObject* go = m_targets.GetGOTarget()) - { - lockId = go->GetGOInfo()->GetLockId(); - if (!lockId) - return SPELL_FAILED_BAD_TARGETS; - } - else if (Item* itm = m_targets.GetItemTarget()) - lockId = itm->GetTemplate()->LockID; - - SkillType skillId = SKILL_NONE; - int32 reqSkillValue = 0; - int32 skillValue = 0; - - // check lock compatibility - SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue); - if (res != SPELL_CAST_OK) - return res; - - // chance for fail at orange mining/herb/LockPicking gathering attempt - // second check prevent fail at rechecks - if (skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this))) - { - bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING; - - // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill) - if ((canFailAtMax || skillValue < sWorld->GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37)) - return SPELL_FAILED_TRY_AGAIN; - } - break; - } case SPELL_EFFECT_RESURRECT_PET: - { - Creature* pet = m_caster->GetGuardianPet(); + { + Creature* pet = m_caster->GetGuardianPet(); - if (pet && pet->IsAlive()) - return SPELL_FAILED_ALREADY_HAVE_SUMMON; + if (pet && pet->IsAlive()) + return SPELL_FAILED_ALREADY_HAVE_SUMMON; - break; - } + break; + } // This is generic summon effect case SPELL_EFFECT_SUMMON: - { - SummonPropertiesEntry const* SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[i].MiscValueB); - if (!SummonProperties || m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) - break; - switch (SummonProperties->Category) { - case SUMMON_CATEGORY_PET: + SummonPropertiesEntry const* SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[i].MiscValueB); + if (!SummonProperties || m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) + break; + switch (SummonProperties->Category) + { + case SUMMON_CATEGORY_PET: + if (m_caster->GetPetGUID()) + return SPELL_FAILED_ALREADY_HAVE_SUMMON; + [[fallthrough]]; + case SUMMON_CATEGORY_PUPPET: + if (m_caster->GetCharmGUID()) + return SPELL_FAILED_ALREADY_HAVE_CHARM; + break; + } + break; + } + case SPELL_EFFECT_CREATE_TAMED_PET: + { + if (m_targets.GetUnitTarget()) + { + if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; + if (m_targets.GetUnitTarget()->GetPetGUID()) + return SPELL_FAILED_ALREADY_HAVE_SUMMON; + } + break; + } + case SPELL_EFFECT_SUMMON_PET: + { + if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) + { if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; - [[fallthrough]]; - case SUMMON_CATEGORY_PUPPET: if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; - break; - } - break; - } - case SPELL_EFFECT_CREATE_TAMED_PET: - { - if (m_targets.GetUnitTarget()) - { - if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; - if (m_targets.GetUnitTarget()->GetPetGUID()) - return SPELL_FAILED_ALREADY_HAVE_SUMMON; - } - break; - } - case SPELL_EFFECT_SUMMON_PET: - { - if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) - { - if (m_caster->GetPetGUID()) - return SPELL_FAILED_ALREADY_HAVE_SUMMON; - if (m_caster->GetCharmGUID()) - return SPELL_FAILED_ALREADY_HAVE_CHARM; - } + } - if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK && strict) - if (Pet* pet = m_caster->ToPlayer()->GetPet()) - pet->CastSpell(pet, 32752, true, nullptr, nullptr, pet->GetGUID()); //starting cast, trigger pet stun (cast by pet so it doesn't attack player) - break; - } - case SPELL_EFFECT_SUMMON_PLAYER: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; - if (!m_caster->GetTarget()) - return SPELL_FAILED_BAD_TARGETS; - - Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget()); - if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell - return SPELL_FAILED_BAD_TARGETS; - - // Xinef: Implement summon pending error - if (target->GetSummonExpireTimer() > time(nullptr)) - return SPELL_FAILED_SUMMON_PENDING; - - // check if our map is dungeon - MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId()); - if (map->IsDungeon()) - { - uint32 mapId = m_caster->GetMap()->GetId(); - Difficulty difficulty = m_caster->GetMap()->GetDifficulty(); - /*if (map->IsRaid()) - if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty)) - if (targetBind->perm && targetBind != m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty)) - return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE;*/ - - InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId); - if (!instance) - return SPELL_FAILED_TARGET_NOT_IN_INSTANCE; - if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId)) - return SPELL_FAILED_BAD_TARGETS; - } - break; - } - // RETURN HERE - case SPELL_EFFECT_SUMMON_RAF_FRIEND: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; - - Player* playerCaster = m_caster->ToPlayer(); - // - if (!(playerCaster->GetTarget())) - return SPELL_FAILED_BAD_TARGETS; - - Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget()); - - if (!target || - !(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId())) - return SPELL_FAILED_BAD_TARGETS; - - // Xinef: Implement summon pending error - if (target->GetSummonExpireTimer() > time(nullptr)) - return SPELL_FAILED_SUMMON_PENDING; - - break; - } - case SPELL_EFFECT_LEAP: - case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER: - { - //Do not allow to cast it before BG starts. - if (m_caster->GetTypeId() == TYPEID_PLAYER) - if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground()) - if (bg->GetStatus() != STATUS_IN_PROGRESS) - return SPELL_FAILED_TRY_AGAIN; - break; - } - case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF: - { - if( !m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster) - return SPELL_FAILED_BAD_TARGETS; - - bool found = false; - Unit::VisibleAuraMap const *visibleAuras = m_targets.GetUnitTarget()->GetVisibleAuras(); - for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr) - { - if( itr->second->GetBase()->IsPassive() ) - continue; - - if( !itr->second->IsPositive() ) - continue; - - found = true; + if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK && strict) + if (Pet* pet = m_caster->ToPlayer()->GetPet()) + pet->CastSpell(pet, 32752, true, nullptr, nullptr, pet->GetGUID()); //starting cast, trigger pet stun (cast by pet so it doesn't attack player) break; } - - if( !found ) - return SPELL_FAILED_NOTHING_TO_STEAL; - - break; - } - case SPELL_EFFECT_LEAP_BACK: - { - if (m_caster->HasUnitState(UNIT_STATE_ROOT)) + case SPELL_EFFECT_SUMMON_PLAYER: { - if (m_caster->GetTypeId() == TYPEID_PLAYER) - return SPELL_FAILED_ROOTED; - else - return SPELL_FAILED_DONT_REPORT; + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; + if (!m_caster->GetTarget()) + return SPELL_FAILED_BAD_TARGETS; + + Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget()); + if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell + return SPELL_FAILED_BAD_TARGETS; + + // Xinef: Implement summon pending error + if (target->GetSummonExpireTimer() > time(nullptr)) + return SPELL_FAILED_SUMMON_PENDING; + + // check if our map is dungeon + MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId()); + if (map->IsDungeon()) + { + uint32 mapId = m_caster->GetMap()->GetId(); + Difficulty difficulty = m_caster->GetMap()->GetDifficulty(); + /*if (map->IsRaid()) + if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty)) + if (targetBind->perm && targetBind != m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty)) + return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE;*/ + + InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId); + if (!instance) + return SPELL_FAILED_TARGET_NOT_IN_INSTANCE; + if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId)) + return SPELL_FAILED_BAD_TARGETS; + } + break; + } + // RETURN HERE + case SPELL_EFFECT_SUMMON_RAF_FRIEND: + { + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; + + Player* playerCaster = m_caster->ToPlayer(); + // + if (!(playerCaster->GetTarget())) + return SPELL_FAILED_BAD_TARGETS; + + Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget()); + + if (!target || + !(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId())) + return SPELL_FAILED_BAD_TARGETS; + + // Xinef: Implement summon pending error + if (target->GetSummonExpireTimer() > time(nullptr)) + return SPELL_FAILED_SUMMON_PENDING; + + break; + } + case SPELL_EFFECT_LEAP: + case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER: + { + //Do not allow to cast it before BG starts. + if (m_caster->GetTypeId() == TYPEID_PLAYER) + if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground()) + if (bg->GetStatus() != STATUS_IN_PROGRESS) + return SPELL_FAILED_TRY_AGAIN; + break; + } + case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF: + { + if( !m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster) + return SPELL_FAILED_BAD_TARGETS; + + bool found = false; + Unit::VisibleAuraMap const* visibleAuras = m_targets.GetUnitTarget()->GetVisibleAuras(); + for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr) + { + if( itr->second->GetBase()->IsPassive() ) + continue; + + if( !itr->second->IsPositive() ) + continue; + + found = true; + break; + } + + if( !found ) + return SPELL_FAILED_NOTHING_TO_STEAL; + + break; + } + case SPELL_EFFECT_LEAP_BACK: + { + if (m_caster->HasUnitState(UNIT_STATE_ROOT)) + { + if (m_caster->GetTypeId() == TYPEID_PLAYER) + return SPELL_FAILED_ROOTED; + else + return SPELL_FAILED_DONT_REPORT; + } + break; } - break; - } // xinef: do not allow to use leaps while rooted case SPELL_EFFECT_JUMP: case SPELL_EFFECT_JUMP_DEST: - { - if (m_caster->HasUnitState(UNIT_STATE_ROOT)) - return SPELL_FAILED_ROOTED; - break; - } + { + if (m_caster->HasUnitState(UNIT_STATE_ROOT)) + return SPELL_FAILED_ROOTED; + break; + } case SPELL_EFFECT_TALENT_SPEC_SELECT: // can't change during already started arena/battleground if (m_caster->GetTypeId() == TYPEID_PLAYER) @@ -6174,135 +6178,135 @@ SpellCastResult Spell::CheckCast(bool strict) case SPELL_AURA_DUMMY: break; case SPELL_AURA_MOD_POSSESS_PET: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_NO_PET; + { + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_NO_PET; - Pet* pet = m_caster->ToPlayer()->GetPet(); - if (!pet) - return SPELL_FAILED_NO_PET; + Pet* pet = m_caster->ToPlayer()->GetPet(); + if (!pet) + return SPELL_FAILED_NO_PET; - if (pet->GetCharmerGUID()) - return SPELL_FAILED_CHARMED; - break; - } + if (pet->GetCharmerGUID()) + return SPELL_FAILED_CHARMED; + break; + } case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_AOE_CHARM: - { - if (m_caster->GetCharmerGUID()) - return SPELL_FAILED_CHARMED; - - // Xinef: allow SPELL_AURA_MOD_POSSESS to posses target if caster has some pet - if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_CHARM && !m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) { - if (m_caster->GetPetGUID()) - return SPELL_FAILED_ALREADY_HAVE_SUMMON; + if (m_caster->GetCharmerGUID()) + return SPELL_FAILED_CHARMED; - if (m_caster->GetCharmGUID()) - return SPELL_FAILED_ALREADY_HAVE_CHARM; + // Xinef: allow SPELL_AURA_MOD_POSSESS to posses target if caster has some pet + if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_CHARM && !m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) + { + if (m_caster->GetPetGUID()) + return SPELL_FAILED_ALREADY_HAVE_SUMMON; + + if (m_caster->GetCharmGUID()) + return SPELL_FAILED_ALREADY_HAVE_CHARM; + } + else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_POSSESS) + { + if (m_caster->GetCharmGUID()) + return SPELL_FAILED_ALREADY_HAVE_CHARM; + } + + if (Unit* target = m_targets.GetUnitTarget()) + { + if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle()) + return SPELL_FAILED_BAD_IMPLICIT_TARGETS; + + if (target->IsMounted()) + return SPELL_FAILED_CANT_BE_CHARMED; + + if (target->GetCharmerGUID()) + return SPELL_FAILED_CHARMED; + + if (target->GetOwnerGUID() && IS_PLAYER_GUID(target->GetOwnerGUID())) + return SPELL_FAILED_TARGET_IS_PLAYER_CONTROLLED; + + if (target->IsPet() && (!target->GetOwner() || target->GetOwner()->ToPlayer())) + return SPELL_FAILED_CANT_BE_CHARMED; + + int32 damage = CalculateSpellDamage(i, target); + if (damage && int32(target->getLevel()) > damage) + return SPELL_FAILED_HIGHLEVEL; + } + + break; } - else if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_POSSESS) + case SPELL_AURA_MOUNTED: { - if (m_caster->GetCharmGUID()) - return SPELL_FAILED_ALREADY_HAVE_CHARM; - } + // Xinef: disallow casting in water for mounts not increasing water movement speed + if (m_caster->IsInWater() && !m_spellInfo->HasAura(SPELL_AURA_MOD_INCREASE_SWIM_SPEED)) + return SPELL_FAILED_ONLY_ABOVEWATER; - if (Unit* target = m_targets.GetUnitTarget()) + // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells + bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena(); + InstanceTemplate const* it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId()); + if (it) + allowMount = it->AllowMount; + if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->AreaGroupId) + return SPELL_FAILED_NO_MOUNTS_ALLOWED; + + if (m_caster->IsInDisallowedMountForm()) + return SPELL_FAILED_NOT_SHAPESHIFT; + + // xinef: dont allow to cast mounts in specific transforms + if (m_caster->getTransForm()) + if (SpellInfo const* transformSpellInfo = sSpellMgr->GetSpellInfo(m_caster->getTransForm())) + if (transformSpellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) && + !transformSpellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED | SPELL_ATTR0_NEGATIVE_1))) + return SPELL_FAILED_NOT_SHAPESHIFT; + + break; + } + case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS: { - if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle()) + if (!m_targets.GetUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; - if (target->IsMounted()) - return SPELL_FAILED_CANT_BE_CHARMED; + // can be casted at non-friendly unit or own pet/charm + if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget())) + return SPELL_FAILED_TARGET_FRIENDLY; - if (target->GetCharmerGUID()) - return SPELL_FAILED_CHARMED; - - if (target->GetOwnerGUID() && IS_PLAYER_GUID(target->GetOwnerGUID())) - return SPELL_FAILED_TARGET_IS_PLAYER_CONTROLLED; - - if (target->IsPet() && (!target->GetOwner() || target->GetOwner()->ToPlayer())) - return SPELL_FAILED_CANT_BE_CHARMED; - - int32 damage = CalculateSpellDamage(i, target); - if (damage && int32(target->getLevel()) > damage) - return SPELL_FAILED_HIGHLEVEL; + break; } - - break; - } - case SPELL_AURA_MOUNTED: - { - // Xinef: disallow casting in water for mounts not increasing water movement speed - if (m_caster->IsInWater() && !m_spellInfo->HasAura(SPELL_AURA_MOD_INCREASE_SWIM_SPEED)) - return SPELL_FAILED_ONLY_ABOVEWATER; - - // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells - bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena(); - InstanceTemplate const* it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId()); - if (it) - allowMount = it->AllowMount; - if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->AreaGroupId) - return SPELL_FAILED_NO_MOUNTS_ALLOWED; - - if (m_caster->IsInDisallowedMountForm()) - return SPELL_FAILED_NOT_SHAPESHIFT; - - // xinef: dont allow to cast mounts in specific transforms - if (m_caster->getTransForm()) - if (SpellInfo const* transformSpellInfo = sSpellMgr->GetSpellInfo(m_caster->getTransForm())) - if (transformSpellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) && - !transformSpellInfo->HasAttribute(SpellAttr0(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED|SPELL_ATTR0_NEGATIVE_1))) - return SPELL_FAILED_NOT_SHAPESHIFT; - - break; - } - case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS: - { - if (!m_targets.GetUnitTarget()) - return SPELL_FAILED_BAD_IMPLICIT_TARGETS; - - // can be casted at non-friendly unit or own pet/charm - if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget())) - return SPELL_FAILED_TARGET_FRIENDLY; - - break; - } case SPELL_AURA_FLY: case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED: - { - // Xinef: added water check - if (m_caster->IsInWater()) - return SPELL_FAILED_ONLY_ABOVEWATER; - - // not allow cast fly spells if not have req. skills (all spells is self target) - // allow always ghost flight spells - if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->IsAlive()) { - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(m_originalCaster->GetZoneId()); - if (AreaTableEntry const* pArea = sAreaTableStore.LookupEntry(m_originalCaster->GetAreaId())) - if ((pArea->flags & AREA_FLAG_NO_FLY_ZONE) || (Bf && !Bf->CanFlyIn())) - return SPELL_FAILED_NOT_HERE; + // Xinef: added water check + if (m_caster->IsInWater()) + return SPELL_FAILED_ONLY_ABOVEWATER; + + // not allow cast fly spells if not have req. skills (all spells is self target) + // allow always ghost flight spells + if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->IsAlive()) + { + Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(m_originalCaster->GetZoneId()); + if (AreaTableEntry const* pArea = sAreaTableStore.LookupEntry(m_originalCaster->GetAreaId())) + if ((pArea->flags & AREA_FLAG_NO_FLY_ZONE) || (Bf && !Bf->CanFlyIn())) + return SPELL_FAILED_NOT_HERE; + } + break; } - break; - } case SPELL_AURA_PERIODIC_MANA_LEECH: - { - if (m_spellInfo->Effects[i].IsTargetingArea()) + { + if (m_spellInfo->Effects[i].IsTargetingArea()) + break; + + if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem) + break; + + if (!m_targets.GetUnitTarget()) + return SPELL_FAILED_BAD_IMPLICIT_TARGETS; + + if (m_targets.GetUnitTarget()->getPowerType() != POWER_MANA) + return SPELL_FAILED_BAD_TARGETS; + break; - - if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem) - break; - - if (!m_targets.GetUnitTarget()) - return SPELL_FAILED_BAD_IMPLICIT_TARGETS; - - if (m_targets.GetUnitTarget()->getPowerType() != POWER_MANA) - return SPELL_FAILED_BAD_TARGETS; - - break; - } + } default: break; } @@ -6435,10 +6439,10 @@ SpellCastResult Spell::CheckCasterAuras(bool preventionOnly) const uint32 mask = (1 << MECHANIC_STUN) | (1 << MECHANIC_FREEZE) | (1 << MECHANIC_HORROR); // Barkskin should skip sleep effects, sap and fears if (m_spellInfo->Id == 22812) - mask |= 1<Id == 1044) - mask |= 1<GetAuraEffectsByType(SPELL_AURA_MOD_STUN); for (Unit::AuraEffectList::const_iterator i = stunAuras.begin(); i != stunAuras.end(); ++i) { @@ -6496,19 +6500,19 @@ SpellCastResult Spell::CheckCasterAuras(bool preventionOnly) const switch (part->GetAuraType()) { case SPELL_AURA_MOD_STUN: - { - uint32 mask = 1<Id == 22812) - mask |= 1<Id == 1044) - mask |= 1<Id == 22812) + mask |= 1 << MECHANIC_SAPPED | 1 << MECHANIC_HORROR | 1 << MECHANIC_SLEEP; + // Hand of Freedom, can be used while sapped + if (m_spellInfo->Id == 1044) + mask |= 1 << MECHANIC_SAPPED; - if (!usableInStun || !(auraInfo->GetAllEffectsMechanicMask() & mask)) - return SPELL_FAILED_STUNNED; - break; - } + if (!usableInStun || !(auraInfo->GetAllEffectsMechanicMask() & mask)) + return SPELL_FAILED_STUNNED; + break; + } case SPELL_AURA_MOD_CONFUSE: if (!m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_CONFUSED)) return SPELL_FAILED_CONFUSED; @@ -6525,7 +6529,8 @@ SpellCastResult Spell::CheckCasterAuras(bool preventionOnly) const else if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) return SPELL_FAILED_SILENCED; break; - default: break; + default: + break; } } } @@ -6571,7 +6576,7 @@ bool Spell::CanAutoCast(Unit* target) { SelectSpellTargets(); //check if among target units, our WANTED target is as well (->only self cast spells return false) - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetguid) return true; } @@ -6609,7 +6614,7 @@ SpellCastResult Spell::CheckRange(bool strict) // xinef: dont check max_range to strictly after cast if (range_type != SPELL_RANGE_MELEE && !strict) - max_range += std::min(3.0f, max_range*0.1f); // 10% but no more than 3yd + max_range += std::min(3.0f, max_range * 0.1f); // 10% but no more than 3yd if (target) { @@ -6622,7 +6627,7 @@ SpellCastResult Spell::CheckRange(bool strict) if (m_caster->GetTypeId() != TYPEID_UNIT && m_caster->isMoving() && target->isMoving() && !m_caster->IsWalking() && !target->IsWalking()) real_max_range -= MIN_MELEE_REACH; // Because of lag, we can not check too strictly here (is only used if both caster and target are moving) else - real_max_range -= 2*MIN_MELEE_REACH; + real_max_range -= 2 * MIN_MELEE_REACH; if (!m_caster->IsWithinMeleeRange(target, std::max(real_max_range, 0.0f))) return SPELL_FAILED_OUT_OF_RANGE; @@ -6788,8 +6793,8 @@ SpellCastResult Spell::CheckItems() { // Xinef: this is not true in my opinion, in eg bladestorm will not be canceled after disarm //if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT)) - if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->ToPlayer()->HasItemFitToSpellRequirements(m_spellInfo)) - return SPELL_FAILED_EQUIPPED_ITEM_CLASS; + if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->ToPlayer()->HasItemFitToSpellRequirements(m_spellInfo)) + return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // do not take reagents for these item casts @@ -6819,7 +6824,7 @@ SpellCastResult Spell::CheckItems() ItemTemplate const* proto = m_CastItem->GetTemplate(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; - for (int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s) + for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s) { // CastItem will be used up and does not count as reagent int32 charges = m_CastItem->GetSpellCharges(s); @@ -6846,15 +6851,16 @@ SpellCastResult Spell::CheckItems() totems -= 1; continue; } - }else - totems -= 1; + } + else + totems -= 1; } if (totems != 0) return SPELL_FAILED_TOTEMS; //0x7C // Check items for TotemCategory (items presence in inventory) uint32 TotemCategory = 2; - for (int i= 0; i < 2; ++i) + for (int i = 0; i < 2; ++i) { if (m_spellInfo->TotemCategory[i] != 0) { @@ -6878,44 +6884,44 @@ SpellCastResult Spell::CheckItems() { case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_ITEM_2: - { - // xinef: m_targets.GetUnitTarget() means explicit cast, otherwise we dont check for possible equip error - Unit* target = m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster; - if (target && target->GetTypeId() == TYPEID_PLAYER && !IsTriggered() && m_spellInfo->Effects[i].ItemType) { - ItemPosCountVec dest; - - // xinef: why do we check p_caster? retards p_caster->CanStoreNewItem(...) - InventoryResult msg = target->ToPlayer()->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1); - if (msg != EQUIP_ERR_OK) + // xinef: m_targets.GetUnitTarget() means explicit cast, otherwise we dont check for possible equip error + Unit* target = m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster; + if (target && target->GetTypeId() == TYPEID_PLAYER && !IsTriggered() && m_spellInfo->Effects[i].ItemType) { - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(m_spellInfo->Effects[i].ItemType); - // TODO: Needs review - if (pProto && !(pProto->ItemLimitCategory)) + ItemPosCountVec dest; + + // xinef: why do we check p_caster? retards p_caster->CanStoreNewItem(...) + InventoryResult msg = target->ToPlayer()->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->Effects[i].ItemType, 1); + if (msg != EQUIP_ERR_OK) { - p_caster->SendEquipError(msg, nullptr, nullptr, m_spellInfo->Effects[i].ItemType); - return SPELL_FAILED_DONT_REPORT; - } - else - { - if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000))) - return SPELL_FAILED_TOO_MANY_OF_ITEM; - else if (!(target->ToPlayer()->HasItemCount(m_spellInfo->Effects[i].ItemType))) + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(m_spellInfo->Effects[i].ItemType); + // TODO: Needs review + if (pProto && !(pProto->ItemLimitCategory)) { p_caster->SendEquipError(msg, nullptr, nullptr, m_spellInfo->Effects[i].ItemType); return SPELL_FAILED_DONT_REPORT; } else - p_caster->CastSpell(m_caster, m_spellInfo->Effects[EFFECT_1].CalcValue(), false); // move this to anywhere - return SPELL_FAILED_DONT_REPORT; + { + if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000))) + return SPELL_FAILED_TOO_MANY_OF_ITEM; + else if (!(target->ToPlayer()->HasItemCount(m_spellInfo->Effects[i].ItemType))) + { + p_caster->SendEquipError(msg, nullptr, nullptr, m_spellInfo->Effects[i].ItemType); + return SPELL_FAILED_DONT_REPORT; + } + else + p_caster->CastSpell(m_caster, m_spellInfo->Effects[EFFECT_1].CalcValue(), false); // move this to anywhere + return SPELL_FAILED_DONT_REPORT; + } } } + break; } - break; - } case SPELL_EFFECT_ENCHANT_ITEM: if (m_spellInfo->Effects[i].ItemType && m_targets.GetItemTarget() - && (m_targets.GetItemTarget()->IsWeaponVellum() || m_targets.GetItemTarget()->IsArmorVellum())) + && (m_targets.GetItemTarget()->IsWeaponVellum() || m_targets.GetItemTarget()->IsArmorVellum())) { // cannot enchant vellum for other player if (m_targets.GetItemTarget()->GetOwner() != m_caster) @@ -6933,264 +6939,265 @@ SpellCastResult Spell::CheckItems() } [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC: - { - Item* targetItem = m_targets.GetItemTarget(); - if (!targetItem) - return SPELL_FAILED_ITEM_NOT_FOUND; - - // xinef: required level has to be checked also! Exploit fix - if (targetItem->GetTemplate()->ItemLevel < m_spellInfo->BaseLevel || (targetItem->GetTemplate()->RequiredLevel && targetItem->GetTemplate()->RequiredLevel < m_spellInfo->BaseLevel)) - return SPELL_FAILED_LOWLEVEL; - - bool isItemUsable = false; - for (uint8 e = 0; e < MAX_ITEM_PROTO_SPELLS; ++e) { - ItemTemplate const* proto = targetItem->GetTemplate(); - if (proto->Spells[e].SpellId && ( - proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE || - proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)) - { - isItemUsable = true; - break; - } - } + Item* targetItem = m_targets.GetItemTarget(); + if (!targetItem) + return SPELL_FAILED_ITEM_NOT_FOUND; - SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(m_spellInfo->Effects[i].MiscValue); - // do not allow adding usable enchantments to items that have use effect already - if (enchantEntry) - { - for (uint8 s = 0; s < MAX_SPELL_ITEM_ENCHANTMENT_EFFECTS; ++s) + // xinef: required level has to be checked also! Exploit fix + if (targetItem->GetTemplate()->ItemLevel < m_spellInfo->BaseLevel || (targetItem->GetTemplate()->RequiredLevel && targetItem->GetTemplate()->RequiredLevel < m_spellInfo->BaseLevel)) + return SPELL_FAILED_LOWLEVEL; + + bool isItemUsable = false; + for (uint8 e = 0; e < MAX_ITEM_PROTO_SPELLS; ++e) { - switch (enchantEntry->type[s]) + ItemTemplate const* proto = targetItem->GetTemplate(); + if (proto->Spells[e].SpellId && ( + proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE || + proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)) { - case ITEM_ENCHANTMENT_TYPE_USE_SPELL: - if (isItemUsable) - return SPELL_FAILED_ON_USE_ENCHANT; - break; - case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET: - { - uint32 numSockets = 0; - for (uint32 socket = 0; socket < MAX_ITEM_PROTO_SOCKETS; ++socket) - if (targetItem->GetTemplate()->Socket[socket].Color) - ++numSockets; + isItemUsable = true; + break; + } + } - if (numSockets == MAX_ITEM_PROTO_SOCKETS || targetItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)) - return SPELL_FAILED_MAX_SOCKETS; - break; + SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(m_spellInfo->Effects[i].MiscValue); + // do not allow adding usable enchantments to items that have use effect already + if (enchantEntry) + { + for (uint8 s = 0; s < MAX_SPELL_ITEM_ENCHANTMENT_EFFECTS; ++s) + { + switch (enchantEntry->type[s]) + { + case ITEM_ENCHANTMENT_TYPE_USE_SPELL: + if (isItemUsable) + return SPELL_FAILED_ON_USE_ENCHANT; + break; + case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET: + { + uint32 numSockets = 0; + for (uint32 socket = 0; socket < MAX_ITEM_PROTO_SOCKETS; ++socket) + if (targetItem->GetTemplate()->Socket[socket].Color) + ++numSockets; + + if (numSockets == MAX_ITEM_PROTO_SOCKETS || targetItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)) + return SPELL_FAILED_MAX_SOCKETS; + break; + } } } } - } - // Not allow enchant in trade slot for some enchant type - if (targetItem->GetOwner() != m_caster) - { - if (!enchantEntry) - return SPELL_FAILED_ERROR; - if (enchantEntry->slot & ENCHANTMENT_CAN_SOULBOUND) - return SPELL_FAILED_NOT_TRADEABLE; + // Not allow enchant in trade slot for some enchant type + if (targetItem->GetOwner() != m_caster) + { + if (!enchantEntry) + return SPELL_FAILED_ERROR; + if (enchantEntry->slot & ENCHANTMENT_CAN_SOULBOUND) + return SPELL_FAILED_NOT_TRADEABLE; + } + break; } - break; - } case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: - { - Item* item = m_targets.GetItemTarget(); - if (!item) - return SPELL_FAILED_ITEM_NOT_FOUND; - // Not allow enchant in trade slot for some enchant type - if (item->GetOwner() != m_caster) { - uint32 enchant_id = m_spellInfo->Effects[i].MiscValue; - SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); - if (!pEnchant) - return SPELL_FAILED_ERROR; - if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND) - return SPELL_FAILED_NOT_TRADEABLE; - } + Item* item = m_targets.GetItemTarget(); + if (!item) + return SPELL_FAILED_ITEM_NOT_FOUND; + // Not allow enchant in trade slot for some enchant type + if (item->GetOwner() != m_caster) + { + uint32 enchant_id = m_spellInfo->Effects[i].MiscValue; + SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); + if (!pEnchant) + return SPELL_FAILED_ERROR; + if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND) + return SPELL_FAILED_NOT_TRADEABLE; + } - // Xinef: Apply item level restriction if the enchanting spell has max level restrition set - if (m_CastItem && m_spellInfo->MaxLevel > 0) - { - if (item->GetTemplate()->ItemLevel < m_CastItem->GetTemplate()->RequiredLevel) - return SPELL_FAILED_LOWLEVEL; - if (item->GetTemplate()->ItemLevel > m_spellInfo->MaxLevel) - return SPELL_FAILED_HIGHLEVEL; - } + // Xinef: Apply item level restriction if the enchanting spell has max level restrition set + if (m_CastItem && m_spellInfo->MaxLevel > 0) + { + if (item->GetTemplate()->ItemLevel < m_CastItem->GetTemplate()->RequiredLevel) + return SPELL_FAILED_LOWLEVEL; + if (item->GetTemplate()->ItemLevel > m_spellInfo->MaxLevel) + return SPELL_FAILED_HIGHLEVEL; + } - break; - } + break; + } case SPELL_EFFECT_ENCHANT_HELD_ITEM: // check item existence in effect code (not output errors at offhand hold item effect to main hand for example break; case SPELL_EFFECT_DISENCHANT: - { - if (!m_targets.GetItemTarget()) - return SPELL_FAILED_CANT_BE_DISENCHANTED; + { + if (!m_targets.GetItemTarget()) + return SPELL_FAILED_CANT_BE_DISENCHANTED; - // prevent disenchanting in trade slot - if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) - return SPELL_FAILED_CANT_BE_DISENCHANTED; + // prevent disenchanting in trade slot + if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) + return SPELL_FAILED_CANT_BE_DISENCHANTED; - ItemTemplate const* itemProto = m_targets.GetItemTarget()->GetTemplate(); - if (!itemProto) - return SPELL_FAILED_CANT_BE_DISENCHANTED; + ItemTemplate const* itemProto = m_targets.GetItemTarget()->GetTemplate(); + if (!itemProto) + return SPELL_FAILED_CANT_BE_DISENCHANTED; - uint32 item_quality = itemProto->Quality; - // 2.0.x addon: Check player enchanting level against the item disenchanting requirements - uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill; - if (item_disenchantskilllevel == uint32(-1)) - return SPELL_FAILED_CANT_BE_DISENCHANTED; - if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING)) - return SPELL_FAILED_LOW_CASTLEVEL; - if (item_quality > 4 || item_quality < 2) - return SPELL_FAILED_CANT_BE_DISENCHANTED; - if (itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR) - return SPELL_FAILED_CANT_BE_DISENCHANTED; - if (!itemProto->DisenchantID) - return SPELL_FAILED_CANT_BE_DISENCHANTED; - break; - } + uint32 item_quality = itemProto->Quality; + // 2.0.x addon: Check player enchanting level against the item disenchanting requirements + uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill; + if (item_disenchantskilllevel == uint32(-1)) + return SPELL_FAILED_CANT_BE_DISENCHANTED; + if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING)) + return SPELL_FAILED_LOW_CASTLEVEL; + if (item_quality > 4 || item_quality < 2) + return SPELL_FAILED_CANT_BE_DISENCHANTED; + if (itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR) + return SPELL_FAILED_CANT_BE_DISENCHANTED; + if (!itemProto->DisenchantID) + return SPELL_FAILED_CANT_BE_DISENCHANTED; + break; + } case SPELL_EFFECT_PROSPECTING: - { - if (!m_targets.GetItemTarget()) - return SPELL_FAILED_CANT_BE_PROSPECTED; - //ensure item is a prospectable ore - if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_FLAG_IS_PROSPECTABLE)) - return SPELL_FAILED_CANT_BE_PROSPECTED; - //prevent prospecting in trade slot - if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) - return SPELL_FAILED_CANT_BE_PROSPECTED; - //Check for enough skill in jewelcrafting - uint32 item_prospectingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank; - if (item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING)) - return SPELL_FAILED_LOW_CASTLEVEL; - //make sure the player has the required ores in inventory - if (m_targets.GetItemTarget()->GetCount() < 5) - return SPELL_FAILED_NEED_MORE_ITEMS; + { + if (!m_targets.GetItemTarget()) + return SPELL_FAILED_CANT_BE_PROSPECTED; + //ensure item is a prospectable ore + if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_FLAG_IS_PROSPECTABLE)) + return SPELL_FAILED_CANT_BE_PROSPECTED; + //prevent prospecting in trade slot + if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) + return SPELL_FAILED_CANT_BE_PROSPECTED; + //Check for enough skill in jewelcrafting + uint32 item_prospectingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank; + if (item_prospectingskilllevel > p_caster->GetSkillValue(SKILL_JEWELCRAFTING)) + return SPELL_FAILED_LOW_CASTLEVEL; + //make sure the player has the required ores in inventory + if (m_targets.GetItemTarget()->GetCount() < 5) + return SPELL_FAILED_NEED_MORE_ITEMS; - if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry())) - return SPELL_FAILED_CANT_BE_PROSPECTED; + if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry())) + return SPELL_FAILED_CANT_BE_PROSPECTED; - break; - } + break; + } case SPELL_EFFECT_MILLING: - { - if (!m_targets.GetItemTarget()) - return SPELL_FAILED_CANT_BE_MILLED; - //ensure item is a millable herb - if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_FLAG_IS_MILLABLE)) - return SPELL_FAILED_CANT_BE_MILLED; - //prevent milling in trade slot - if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) - return SPELL_FAILED_CANT_BE_MILLED; - //Check for enough skill in inscription - uint32 item_millingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank; - if (item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION)) - return SPELL_FAILED_LOW_CASTLEVEL; - //make sure the player has the required herbs in inventory - if (m_targets.GetItemTarget()->GetCount() < 5) - return SPELL_FAILED_NEED_MORE_ITEMS; + { + if (!m_targets.GetItemTarget()) + return SPELL_FAILED_CANT_BE_MILLED; + //ensure item is a millable herb + if (!(m_targets.GetItemTarget()->GetTemplate()->Flags & ITEM_FLAG_IS_MILLABLE)) + return SPELL_FAILED_CANT_BE_MILLED; + //prevent milling in trade slot + if (m_targets.GetItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) + return SPELL_FAILED_CANT_BE_MILLED; + //Check for enough skill in inscription + uint32 item_millingskilllevel = m_targets.GetItemTarget()->GetTemplate()->RequiredSkillRank; + if (item_millingskilllevel > p_caster->GetSkillValue(SKILL_INSCRIPTION)) + return SPELL_FAILED_LOW_CASTLEVEL; + //make sure the player has the required herbs in inventory + if (m_targets.GetItemTarget()->GetCount() < 5) + return SPELL_FAILED_NEED_MORE_ITEMS; - if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry())) - return SPELL_FAILED_CANT_BE_MILLED; + if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry())) + return SPELL_FAILED_CANT_BE_MILLED; - break; - } + break; + } case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_TARGET_NOT_PLAYER; - - if (m_attackType != RANGED_ATTACK) - break; - - Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType); - if (!pItem || pItem->IsBroken()) - return SPELL_FAILED_EQUIPPED_ITEM; - - switch (pItem->GetTemplate()->SubClass) { - case ITEM_SUBCLASS_WEAPON_THROWN: + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return SPELL_FAILED_TARGET_NOT_PLAYER; + + if (m_attackType != RANGED_ATTACK) + break; + + Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType); + if (!pItem || pItem->IsBroken()) + return SPELL_FAILED_EQUIPPED_ITEM; + + switch (pItem->GetTemplate()->SubClass) { - uint32 ammo = pItem->GetEntry(); - if (!m_caster->ToPlayer()->HasItemCount(ammo)) - return SPELL_FAILED_NO_AMMO; - }; + case ITEM_SUBCLASS_WEAPON_THROWN: + { + uint32 ammo = pItem->GetEntry(); + if (!m_caster->ToPlayer()->HasItemCount(ammo)) + return SPELL_FAILED_NO_AMMO; + }; + break; + case ITEM_SUBCLASS_WEAPON_GUN: + case ITEM_SUBCLASS_WEAPON_BOW: + case ITEM_SUBCLASS_WEAPON_CROSSBOW: + { + uint32 ammo = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID); + if (!ammo) + { + // Requires No Ammo + if (m_caster->HasAura(46699)) + break; // skip other checks + + return SPELL_FAILED_NO_AMMO; + } + + ItemTemplate const* ammoProto = sObjectMgr->GetItemTemplate(ammo); + if (!ammoProto) + return SPELL_FAILED_NO_AMMO; + + if (ammoProto->Class != ITEM_CLASS_PROJECTILE) + return SPELL_FAILED_NO_AMMO; + + // check ammo ws. weapon compatibility + switch (pItem->GetTemplate()->SubClass) + { + case ITEM_SUBCLASS_WEAPON_BOW: + case ITEM_SUBCLASS_WEAPON_CROSSBOW: + if (ammoProto->SubClass != ITEM_SUBCLASS_ARROW) + return SPELL_FAILED_NO_AMMO; + break; + case ITEM_SUBCLASS_WEAPON_GUN: + if (ammoProto->SubClass != ITEM_SUBCLASS_BULLET) + return SPELL_FAILED_NO_AMMO; + break; + default: + return SPELL_FAILED_NO_AMMO; + } + + if (!m_caster->ToPlayer()->HasItemCount(ammo)) + { + m_caster->ToPlayer()->SetUInt32Value(PLAYER_AMMO_ID, 0); + return SPELL_FAILED_NO_AMMO; + } + }; + break; + case ITEM_SUBCLASS_WEAPON_WAND: + break; + default: + break; + } break; - case ITEM_SUBCLASS_WEAPON_GUN: - case ITEM_SUBCLASS_WEAPON_BOW: - case ITEM_SUBCLASS_WEAPON_CROSSBOW: - { - uint32 ammo = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID); - if (!ammo) - { - // Requires No Ammo - if (m_caster->HasAura(46699)) - break; // skip other checks - - return SPELL_FAILED_NO_AMMO; - } - - ItemTemplate const* ammoProto = sObjectMgr->GetItemTemplate(ammo); - if (!ammoProto) - return SPELL_FAILED_NO_AMMO; - - if (ammoProto->Class != ITEM_CLASS_PROJECTILE) - return SPELL_FAILED_NO_AMMO; - - // check ammo ws. weapon compatibility - switch (pItem->GetTemplate()->SubClass) - { - case ITEM_SUBCLASS_WEAPON_BOW: - case ITEM_SUBCLASS_WEAPON_CROSSBOW: - if (ammoProto->SubClass != ITEM_SUBCLASS_ARROW) - return SPELL_FAILED_NO_AMMO; - break; - case ITEM_SUBCLASS_WEAPON_GUN: - if (ammoProto->SubClass != ITEM_SUBCLASS_BULLET) - return SPELL_FAILED_NO_AMMO; - break; - default: - return SPELL_FAILED_NO_AMMO; - } - - if (!m_caster->ToPlayer()->HasItemCount(ammo)) - { - m_caster->ToPlayer()->SetUInt32Value(PLAYER_AMMO_ID, 0); - return SPELL_FAILED_NO_AMMO; - } - }; break; - case ITEM_SUBCLASS_WEAPON_WAND: - break; - default: - break; } - break; - } case SPELL_EFFECT_CREATE_MANA_GEM: - { - uint32 item_id = m_spellInfo->Effects[i].ItemType; - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id); + { + uint32 item_id = m_spellInfo->Effects[i].ItemType; + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id); - if (!pProto) - return SPELL_FAILED_ITEM_AT_MAX_CHARGES; + if (!pProto) + return SPELL_FAILED_ITEM_AT_MAX_CHARGES; - if (Item* pitem = p_caster->GetItemByEntry(item_id)) - { - for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) - if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges) - return SPELL_FAILED_ITEM_AT_MAX_CHARGES; - } - break; - } + if (Item* pitem = p_caster->GetItemByEntry(item_id)) + { + for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) + if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges) + return SPELL_FAILED_ITEM_AT_MAX_CHARGES; + } + break; + } default: break; } } // check weapon presence in slots for main/offhand weapons - if (/*Moar retardnes! never skip those checks !(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT) &&*/ m_spellInfo->EquippedItemClass >=0) + if (/*Moar retardnes! never skip those checks !(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT) &&*/ m_spellInfo->EquippedItemClass >= 0) { // main hand weapon required if (m_spellInfo->HasAttribute(SPELL_ATTR3_MAIN_HAND)) @@ -7285,7 +7292,7 @@ void Spell::Delayed() // only called in DealDamage() sLog->outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime); #endif - WorldPacket data(SMSG_SPELL_DELAYED, 8+4); + WorldPacket data(SMSG_SPELL_DELAYED, 8 + 4); data.append(m_caster->GetPackGUID()); data << uint32(delaytime); @@ -7548,7 +7555,7 @@ bool Spell::IsAutoActionResetSpell() const bool Spell::IsNeedSendToClient(bool go) const { return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || m_spellInfo->IsChanneled() || - m_spellInfo->Speed > 0.0f || (!m_triggeredByAuraSpell && !IsTriggered()) || (go && m_triggeredByAuraSpell && m_triggeredByAuraSpell->IsChanneled()); + m_spellInfo->Speed > 0.0f || (!m_triggeredByAuraSpell && !IsTriggered()) || (go && m_triggeredByAuraSpell && m_triggeredByAuraSpell->IsChanneled()); } bool Spell::HaveTargetsForEffect(uint8 effect) const @@ -7585,7 +7592,7 @@ SpellEvent::~SpellEvent() else { sLog->outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.", - (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id); + (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id); ABORT(); } } @@ -7600,50 +7607,52 @@ bool SpellEvent::Execute(uint64 e_time, uint32 p_time) switch (m_Spell->getState()) { case SPELL_STATE_FINISHED: - { - // spell was finished, check deletable state - if (m_Spell->IsDeletable()) { - // check, if we do have unfinished triggered spells - return true; // spell is deletable, finish event + // spell was finished, check deletable state + if (m_Spell->IsDeletable()) + { + // check, if we do have unfinished triggered spells + return true; // spell is deletable, finish event + } + // event will be re-added automatically at the end of routine) } - // event will be re-added automatically at the end of routine) - } break; + break; case SPELL_STATE_DELAYED: - { - // first, check, if we have just started - if (m_Spell->GetDelayStart() != 0) { + // first, check, if we have just started + if (m_Spell->GetDelayStart() != 0) { - // run the spell handler and think about what we can do next - uint64 t_offset = e_time - m_Spell->GetDelayStart(); - uint64 n_offset = m_Spell->handle_delayed(t_offset); - if (n_offset) { - // re-add us to the queue - m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false); - return false; // event not complete + // run the spell handler and think about what we can do next + uint64 t_offset = e_time - m_Spell->GetDelayStart(); + uint64 n_offset = m_Spell->handle_delayed(t_offset); + if (n_offset) + { + // re-add us to the queue + m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false); + return false; // event not complete + } + // event complete + // finish update event will be re-added automatically at the end of routine) } - // event complete - // finish update event will be re-added automatically at the end of routine) + } + else + { + // delaying had just started, record the moment + m_Spell->SetDelayStart(e_time); + // re-plan the event for the delay moment + m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false); + return false; // event not complete } } - else - { - // delaying had just started, record the moment - m_Spell->SetDelayStart(e_time); - // re-plan the event for the delay moment - m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false); - return false; // event not complete - } - } break; + break; default: - { - // all other states - // event will be re-added automatically at the end of routine) - } break; + { + // all other states + // event will be re-added automatically at the end of routine) + } break; } // spell processing not complete, plan event on the next update interval @@ -7702,11 +7711,11 @@ void Spell::HandleLaunchPhase() for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) { if ((*j)->IsAffectedOnSpell(m_spellInfo)) - usesAmmo=false; + usesAmmo = false; } bool firstTarget = true; - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { TargetInfo& target = *ihit; @@ -7723,7 +7732,7 @@ void Spell::HandleLaunchPhase() bool ammoTaken = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) { - if (!(mask & 1<Effects[i].Effect) { @@ -7732,8 +7741,8 @@ void Spell::HandleLaunchPhase() case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: - ammoTaken=true; - TakeAmmo(); + ammoTaken = true; + TakeAmmo(); } if (ammoTaken) break; @@ -7759,7 +7768,7 @@ void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier, uint8 ssEffect = MAX_SPELL_EFFECTS; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - if (targetInfo.effectMask & (1< 10) - m_damage = m_damage * 10/targetAmount; + m_damage = m_damage * 10 / targetAmount; } } } @@ -7811,14 +7820,14 @@ void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier, } else if (m_originalCaster) caster = m_originalCaster; - + float critChance = caster->SpellDoneCritChance(unit, m_spellInfo, m_spellSchoolMask, m_attackType, false); critChance = unit->SpellTakenCritChance(caster, m_spellInfo, m_spellSchoolMask, critChance, m_attackType, false); targetInfo.crit = roll_chance_f(std::max(0.0f, critChance)); // Sweeping strikes wtf shit ;d - if (m_caster->getClass() == CLASS_WARRIOR && ssEffect < MAX_SPELL_EFFECTS && m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && - ((m_spellInfo->Id != 50622 && m_spellInfo->Id != 44949) || firstTarget)) + if (m_caster->getClass() == CLASS_WARRIOR && ssEffect < MAX_SPELL_EFFECTS && m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && + ((m_spellInfo->Id != 50622 && m_spellInfo->Id != 44949) || firstTarget)) { if (Aura* aur = m_caster->GetAura(12328)) { @@ -7865,36 +7874,36 @@ SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& sk return SPELL_CAST_OK; reqKey = true; break; - // check key skill (only single first fit case can be) + // check key skill (only single first fit case can be) case LOCK_KEY_SKILL: - { - reqKey = true; - - // wrong locktype, skip - if (uint32(m_spellInfo->Effects[effIndex].MiscValue) != lockInfo->Index[j]) - continue; - - skillId = SkillByLockType(LockType(lockInfo->Index[j])); - - if (skillId != SKILL_NONE) { - reqSkillValue = lockInfo->Skill[j]; + reqKey = true; - // castitem check: rogue using skeleton keys. the skill values should not be added in this case. - skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ? - 0 : m_caster->ToPlayer()->GetSkillValue(skillId); + // wrong locktype, skip + if (uint32(m_spellInfo->Effects[effIndex].MiscValue) != lockInfo->Index[j]) + continue; - // skill bonus provided by casting spell (mostly item spells) - // add the effect base points modifier from the spell casted (cheat lock / skeleton key etc.) - if (m_spellInfo->Effects[effIndex].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || m_spellInfo->Effects[effIndex].TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET) - skillValue += m_spellInfo->Effects[effIndex].CalcValue(); + skillId = SkillByLockType(LockType(lockInfo->Index[j])); - if (skillValue < reqSkillValue) - return SPELL_FAILED_LOW_CASTLEVEL; + if (skillId != SKILL_NONE) + { + reqSkillValue = lockInfo->Skill[j]; + + // castitem check: rogue using skeleton keys. the skill values should not be added in this case. + skillValue = m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER ? + 0 : m_caster->ToPlayer()->GetSkillValue(skillId); + + // skill bonus provided by casting spell (mostly item spells) + // add the effect base points modifier from the spell casted (cheat lock / skeleton key etc.) + if (m_spellInfo->Effects[effIndex].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || m_spellInfo->Effects[effIndex].TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET) + skillValue += m_spellInfo->Effects[effIndex].CalcValue(); + + if (skillValue < reqSkillValue) + return SPELL_FAILED_LOW_CASTLEVEL; + } + + return SPELL_CAST_OK; } - - return SPELL_CAST_OK; - } } } @@ -8193,13 +8202,13 @@ bool Spell::CheckScriptEffectImplicitTargets(uint32 effIndex, uint32 effIndexToC std::list::iterator targetSelectHookEnd = (*itr)->OnObjectTargetSelect.end(), targetSelectHookItr = (*itr)->OnObjectTargetSelect.begin(); for (; targetSelectHookItr != targetSelectHookEnd; ++targetSelectHookItr) if (((*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) || - (!(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck))) + (!(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck))) return false; - + std::list::iterator areaTargetSelectHookEnd = (*itr)->OnObjectAreaTargetSelect.end(), areaTargetSelectHookItr = (*itr)->OnObjectAreaTargetSelect.begin(); for (; areaTargetSelectHookItr != areaTargetSelectHookEnd; ++areaTargetSelectHookItr) if (((*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) || - (!(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck))) + (!(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck))) return false; } return true; @@ -8213,7 +8222,7 @@ bool Spell::CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByA bool only_on_caster = (triggeredByAura && triggeredByAura->HasAttribute(SPELL_ATTR4_PROC_ONLY_ON_CASTER)); // If triggeredByAura has SPELL_ATTR4_PROC_ONLY_ON_CASTER then it can only proc on a casted spell with TARGET_UNIT_CASTER - for (uint8 i = 0;i < MAX_SPELL_EFFECTS; ++i) + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((effMask & (1 << i)) && (!only_on_caster || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_UNIT_CASTER))) return true; @@ -8238,31 +8247,31 @@ void Spell::PrepareTriggersExecutedOnHit() switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_PALADIN: - { - if( m_spellInfo->SpellFamilyFlags[1] & 0x40000000 ) { - Unit::AuraEffectList const& mVindication = m_caster->GetAuraEffectsByType(SPELL_AURA_PROC_TRIGGER_SPELL); - for(Unit::AuraEffectList::const_iterator itr = mVindication.begin(); itr != mVindication.end(); ++itr) + if( m_spellInfo->SpellFamilyFlags[1] & 0x40000000 ) { - if( (*itr)->GetSpellInfo()->Effects[EFFECT_0].TriggerSpell == 26017 ) + Unit::AuraEffectList const& mVindication = m_caster->GetAuraEffectsByType(SPELL_AURA_PROC_TRIGGER_SPELL); + for(Unit::AuraEffectList::const_iterator itr = mVindication.begin(); itr != mVindication.end(); ++itr) { - m_preCastSpell = 26017; - break; + if( (*itr)->GetSpellInfo()->Effects[EFFECT_0].TriggerSpell == 26017 ) + { + m_preCastSpell = 26017; + break; + } + else if( (*itr)->GetSpellInfo()->Effects[EFFECT_0].TriggerSpell == 67 ) + m_preCastSpell = 67; } - else if( (*itr)->GetSpellInfo()->Effects[EFFECT_0].TriggerSpell == 67 ) - m_preCastSpell = 67; } + break; } - break; - } case SPELLFAMILY_DRUID: - { - // Faerie Fire (Feral) - if( m_spellInfo->Id == 16857 && (m_caster->GetShapeshiftForm() == FORM_BEAR || m_caster->GetShapeshiftForm() == FORM_DIREBEAR) ) - m_preCastSpell = 60089; + { + // Faerie Fire (Feral) + if( m_spellInfo->Id == 16857 && (m_caster->GetShapeshiftForm() == FORM_BEAR || m_caster->GetShapeshiftForm() == FORM_DIREBEAR) ) + m_preCastSpell = 60089; - break; - } + break; + } } // handle SPELL_AURA_ADD_TARGET_TRIGGER auras: @@ -8368,185 +8377,185 @@ void Spell::CancelGlobalCooldown() void Spell::OnSpellLaunch() { - if (!m_caster || !m_caster->IsInWorld()) - return; + if (!m_caster || !m_caster->IsInWorld()) + return; - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(24390); + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(24390); - // Make sure the player is sending a valid GO target and lock ID. SPELL_EFFECT_OPEN_LOCK - // can succeed with a lockId of 0 - if (m_spellInfo->Id == 21651) - { - if (GameObject *go = m_targets.GetGOTarget()) - { - LockEntry const *lockInfo = sLockStore.LookupEntry(go->GetGOInfo()->GetLockId()); - if (lockInfo && lockInfo->Index[1] == LOCKTYPE_SLOW_OPEN) - { - Spell* visual = new Spell(m_caster, spellInfo, TRIGGERED_NONE); - visual->prepare(&m_targets); - } - } - } + // Make sure the player is sending a valid GO target and lock ID. SPELL_EFFECT_OPEN_LOCK + // can succeed with a lockId of 0 + if (m_spellInfo->Id == 21651) + { + if (GameObject* go = m_targets.GetGOTarget()) + { + LockEntry const* lockInfo = sLockStore.LookupEntry(go->GetGOInfo()->GetLockId()); + if (lockInfo && lockInfo->Index[1] == LOCKTYPE_SLOW_OPEN) + { + Spell* visual = new Spell(m_caster, spellInfo, TRIGGERED_NONE); + visual->prepare(&m_targets); + } + } + } } namespace acore { -WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo, + WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) : _caster(caster), _referer(referer), _spellInfo(spellInfo), - _targetSelectionType(selectionType), _condList(condList) -{ - if (condList) - _condSrcInfo = new ConditionSourceInfo(nullptr, caster); - else - _condSrcInfo = nullptr; -} - -WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck() -{ - if (_condSrcInfo) - delete _condSrcInfo; -} - -bool WorldObjectSpellTargetCheck::operator()(WorldObject* target) -{ - if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK) - return false; - Unit* unitTarget = target->ToUnit(); - if (Corpse* corpseTarget = target->ToCorpse()) + _targetSelectionType(selectionType), _condList(condList) { - // use ofter for party/assistance checks - if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) - unitTarget = owner; + if (condList) + _condSrcInfo = new ConditionSourceInfo(nullptr, caster); else - return false; + _condSrcInfo = nullptr; } - if (unitTarget) + + WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck() { - switch (_targetSelectionType) + if (_condSrcInfo) + delete _condSrcInfo; + } + + bool WorldObjectSpellTargetCheck::operator()(WorldObject* target) + { + if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK) + return false; + Unit* unitTarget = target->ToUnit(); + if (Corpse* corpseTarget = target->ToCorpse()) { - case TARGET_CHECK_ENEMY: - if (unitTarget->IsTotem()) - return false; - if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo)) - return false; - break; - case TARGET_CHECK_ALLY: - if (unitTarget->IsTotem()) - return false; - if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) - return false; - break; - case TARGET_CHECK_PARTY: - if (unitTarget->IsTotem()) - return false; - if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) - return false; - if (!_referer->IsInPartyWith(unitTarget)) - return false; - break; - case TARGET_CHECK_RAID_CLASS: - if (_referer->getClass() != unitTarget->getClass()) - return false; - [[fallthrough]]; - case TARGET_CHECK_RAID: - if (unitTarget->IsTotem()) - return false; - if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) - return false; - if (!_referer->IsInRaidWith(unitTarget)) - return false; - break; - case TARGET_CHECK_CORPSE: - if (_caster->IsFriendlyTo(unitTarget)) - return false; - break; - default: - break; + // use ofter for party/assistance checks + if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) + unitTarget = owner; + else + return false; } + if (unitTarget) + { + switch (_targetSelectionType) + { + case TARGET_CHECK_ENEMY: + if (unitTarget->IsTotem()) + return false; + if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo)) + return false; + break; + case TARGET_CHECK_ALLY: + if (unitTarget->IsTotem()) + return false; + if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) + return false; + break; + case TARGET_CHECK_PARTY: + if (unitTarget->IsTotem()) + return false; + if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) + return false; + if (!_referer->IsInPartyWith(unitTarget)) + return false; + break; + case TARGET_CHECK_RAID_CLASS: + if (_referer->getClass() != unitTarget->getClass()) + return false; + [[fallthrough]]; + case TARGET_CHECK_RAID: + if (unitTarget->IsTotem()) + return false; + if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) + return false; + if (!_referer->IsInRaidWith(unitTarget)) + return false; + break; + case TARGET_CHECK_CORPSE: + if (_caster->IsFriendlyTo(unitTarget)) + return false; + break; + default: + break; + } + } + if (!_condSrcInfo) + return true; + _condSrcInfo->mConditionTargets[0] = target; + return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList); } - if (!_condSrcInfo) - return true; - _condSrcInfo->mConditionTargets[0] = target; - return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList); -} -WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo, - SpellTargetCheckTypes selectionType, ConditionList* condList) - : WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) -{ -} - -bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target) -{ - float dist = target->GetDistance(*_position); - if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target)) + WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo, + SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) { - _range = dist; - return true; } - return false; -} -WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster, - Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) - : WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) -{ -} - -bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target) -{ - if (target->GetTypeId() == TYPEID_GAMEOBJECT) + bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target) { - if (!target->ToGameObject()->IsInRange(_position->GetPositionX(), _position->GetPositionY(), _position->GetPositionZ(), _range)) - return false; - } - else if (!target->IsWithinDist3d(_position, _range)) + float dist = target->GetDistance(*_position); + if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target)) + { + _range = dist; + return true; + } return false; - else if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsAvoidingAOE()) // pussywizard - return false; - return WorldObjectSpellTargetCheck::operator ()(target); -} - -WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster, - SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) - : WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle) -{ -} - -bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target) -{ - if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_BACK)) - { - if (!_caster->isInBack(target, _coneAngle)) - return false; } - else if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_LINE)) - { - if (!_caster->HasInLine(target, _caster->GetObjectSize())) - return false; - } - else - { - if (!_caster->isInFront(target, _coneAngle)) - return false; - } - return WorldObjectSpellAreaTargetCheck::operator ()(target); -} -WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, - SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) - : WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, selectionType, condList) -{ -} + WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster, + Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) + { + } -bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target) -{ - // return all targets on missile trajectory (0 - size of a missile) - if (!_caster->HasInLine(target, 0)) - return false; - return WorldObjectSpellAreaTargetCheck::operator ()(target); -} + bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target) + { + if (target->GetTypeId() == TYPEID_GAMEOBJECT) + { + if (!target->ToGameObject()->IsInRange(_position->GetPositionX(), _position->GetPositionY(), _position->GetPositionZ(), _range)) + return false; + } + else if (!target->IsWithinDist3d(_position, _range)) + return false; + else if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsAvoidingAOE()) // pussywizard + return false; + return WorldObjectSpellTargetCheck::operator ()(target); + } + + WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster, + SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle) + { + } + + bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target) + { + if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_BACK)) + { + if (!_caster->isInBack(target, _coneAngle)) + return false; + } + else if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_LINE)) + { + if (!_caster->HasInLine(target, _caster->GetObjectSize())) + return false; + } + else + { + if (!_caster->isInFront(target, _coneAngle)) + return false; + } + return WorldObjectSpellAreaTargetCheck::operator ()(target); + } + + WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, + SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList) + : WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, selectionType, condList) + { + } + + bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target) + { + // return all targets on missile trajectory (0 - size of a missile) + if (!_caster->HasInLine(target, 0)) + return false; + return WorldObjectSpellAreaTargetCheck::operator ()(target); + } } //namespace acore diff --git a/src/server/game/Spells/Spell.h b/src/server/game/Spells/Spell.h index 3da61d021..4c86892ae 100644 --- a/src/server/game/Spells/Spell.h +++ b/src/server/game/Spells/Spell.h @@ -93,104 +93,104 @@ struct SpellDestination class SpellCastTargets { - public: - SpellCastTargets(); - ~SpellCastTargets(); +public: + SpellCastTargets(); + ~SpellCastTargets(); - void Read(ByteBuffer& data, Unit* caster); - void Write(ByteBuffer& data); + void Read(ByteBuffer& data, Unit* caster); + void Write(ByteBuffer& data); - uint32 GetTargetMask() const { return m_targetMask; } - void SetTargetMask(uint32 newMask) { m_targetMask = newMask; } + uint32 GetTargetMask() const { return m_targetMask; } + void SetTargetMask(uint32 newMask) { m_targetMask = newMask; } - void SetTargetFlag(SpellCastTargetFlags flag) { m_targetMask |= flag; } + void SetTargetFlag(SpellCastTargetFlags flag) { m_targetMask |= flag; } - uint64 GetUnitTargetGUID() const; - Unit* GetUnitTarget() const; - void SetUnitTarget(Unit* target); + uint64 GetUnitTargetGUID() const; + Unit* GetUnitTarget() const; + void SetUnitTarget(Unit* target); - uint64 GetGOTargetGUID() const; - GameObject* GetGOTarget() const; - void SetGOTarget(GameObject* target); + uint64 GetGOTargetGUID() const; + GameObject* GetGOTarget() const; + void SetGOTarget(GameObject* target); - uint64 GetCorpseTargetGUID() const; - Corpse* GetCorpseTarget() const; - void SetCorpseTarget(Corpse* target); + uint64 GetCorpseTargetGUID() const; + Corpse* GetCorpseTarget() const; + void SetCorpseTarget(Corpse* target); - WorldObject* GetObjectTarget() const; - uint64 GetObjectTargetGUID() const; - void RemoveObjectTarget(); + WorldObject* GetObjectTarget() const; + uint64 GetObjectTargetGUID() const; + void RemoveObjectTarget(); - uint64 GetItemTargetGUID() const { return m_itemTargetGUID; } - Item* GetItemTarget() const { return m_itemTarget; } - uint32 GetItemTargetEntry() const { return m_itemTargetEntry; } - void SetItemTarget(Item* item); - void SetTradeItemTarget(Player* caster); - void UpdateTradeSlotItem(); + uint64 GetItemTargetGUID() const { return m_itemTargetGUID; } + Item* GetItemTarget() const { return m_itemTarget; } + uint32 GetItemTargetEntry() const { return m_itemTargetEntry; } + void SetItemTarget(Item* item); + void SetTradeItemTarget(Player* caster); + void UpdateTradeSlotItem(); - SpellDestination const* GetSrc() const; - Position const* GetSrcPos() const; - void SetSrc(float x, float y, float z); - void SetSrc(Position const& pos); - void SetSrc(WorldObject const& wObj); - void ModSrc(Position const& pos); - void RemoveSrc(); + SpellDestination const* GetSrc() const; + Position const* GetSrcPos() const; + void SetSrc(float x, float y, float z); + void SetSrc(Position const& pos); + void SetSrc(WorldObject const& wObj); + void ModSrc(Position const& pos); + void RemoveSrc(); - SpellDestination const* GetDst() const; - WorldLocation const* GetDstPos() const; - void SetDst(float x, float y, float z, float orientation, uint32 mapId = MAPID_INVALID); - void SetDst(Position const& pos); - void SetDst(WorldObject const& wObj); - void SetDst(SpellDestination const& spellDest); - void SetDst(SpellCastTargets const& spellTargets); - void ModDst(Position const& pos); - void ModDst(SpellDestination const& spellDest); - void RemoveDst(); + SpellDestination const* GetDst() const; + WorldLocation const* GetDstPos() const; + void SetDst(float x, float y, float z, float orientation, uint32 mapId = MAPID_INVALID); + void SetDst(Position const& pos); + void SetDst(WorldObject const& wObj); + void SetDst(SpellDestination const& spellDest); + void SetDst(SpellCastTargets const& spellTargets); + void ModDst(Position const& pos); + void ModDst(SpellDestination const& spellDest); + void RemoveDst(); - bool HasSrc() const { return GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION; } - bool HasDst() const { return GetTargetMask() & TARGET_FLAG_DEST_LOCATION; } - bool HasTraj() const { return m_speed != 0; } + bool HasSrc() const { return GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION; } + bool HasDst() const { return GetTargetMask() & TARGET_FLAG_DEST_LOCATION; } + bool HasTraj() const { return m_speed != 0; } - float GetElevation() const { return m_elevation; } - void SetElevation(float elevation) { m_elevation = elevation; } - float GetSpeed() const { return m_speed; } - void SetSpeed(float speed) { m_speed = speed; } + float GetElevation() const { return m_elevation; } + void SetElevation(float elevation) { m_elevation = elevation; } + float GetSpeed() const { return m_speed; } + void SetSpeed(float speed) { m_speed = speed; } - float GetDist2d() const { return m_src._position.GetExactDist2d(&m_dst._position); } - float GetSpeedXY() const { return m_speed * cos(m_elevation); } - float GetSpeedZ() const { return m_speed * sin(m_elevation); } + float GetDist2d() const { return m_src._position.GetExactDist2d(&m_dst._position); } + float GetSpeedXY() const { return m_speed * cos(m_elevation); } + float GetSpeedZ() const { return m_speed * sin(m_elevation); } - void Update(Unit* caster); - void OutDebug() const; + void Update(Unit* caster); + void OutDebug() const; - // Xinef: Channel data - void SetObjectTargetChannel(uint64 targetGUID); - void SetDstChannel(SpellDestination const& spellDest); - WorldObject* GetObjectTargetChannel(Unit* caster) const; - bool HasDstChannel() const; - SpellDestination const* GetDstChannel() const; + // Xinef: Channel data + void SetObjectTargetChannel(uint64 targetGUID); + void SetDstChannel(SpellDestination const& spellDest); + WorldObject* GetObjectTargetChannel(Unit* caster) const; + bool HasDstChannel() const; + SpellDestination const* GetDstChannel() const; - private: - uint32 m_targetMask; +private: + uint32 m_targetMask; - // objects (can be used at spell creating and after Update at casting) - WorldObject* m_objectTarget; - Item* m_itemTarget; + // objects (can be used at spell creating and after Update at casting) + WorldObject* m_objectTarget; + Item* m_itemTarget; - // object GUID/etc, can be used always - uint64 m_objectTargetGUID; - uint64 m_itemTargetGUID; - uint32 m_itemTargetEntry; + // object GUID/etc, can be used always + uint64 m_objectTargetGUID; + uint64 m_itemTargetGUID; + uint32 m_itemTargetEntry; - SpellDestination m_src; - SpellDestination m_dst; + SpellDestination m_src; + SpellDestination m_dst; - float m_elevation, m_speed; - std::string m_strTarget; + float m_elevation, m_speed; + std::string m_strTarget; - // Xinef: Save channel data - SpellDestination m_dstChannel; - uint64 m_objectTargetGUIDChannel; + // Xinef: Save channel data + SpellDestination m_dstChannel; + uint64 m_objectTargetGUIDChannel; }; struct SpellValue @@ -240,495 +240,495 @@ class Spell { friend void Unit::SetCurrentCastedSpell(Spell* pSpell); friend class SpellScript; - public: - - void EffectNULL(SpellEffIndex effIndex); - void EffectUnused(SpellEffIndex effIndex); - void EffectDistract(SpellEffIndex effIndex); - void EffectPull(SpellEffIndex effIndex); - void EffectSchoolDMG(SpellEffIndex effIndex); - void EffectEnvironmentalDMG(SpellEffIndex effIndex); - void EffectInstaKill(SpellEffIndex effIndex); - void EffectDummy(SpellEffIndex effIndex); - void EffectTeleportUnits(SpellEffIndex effIndex); - void EffectApplyAura(SpellEffIndex effIndex); - void EffectSendEvent(SpellEffIndex effIndex); - void EffectPowerBurn(SpellEffIndex effIndex); - void EffectPowerDrain(SpellEffIndex effIndex); - void EffectHeal(SpellEffIndex effIndex); - void EffectBind(SpellEffIndex effIndex); - void EffectHealthLeech(SpellEffIndex effIndex); - void EffectQuestComplete(SpellEffIndex effIndex); - void EffectCreateItem(SpellEffIndex effIndex); - void EffectCreateItem2(SpellEffIndex effIndex); - void EffectCreateRandomItem(SpellEffIndex effIndex); - void EffectPersistentAA(SpellEffIndex effIndex); - void EffectEnergize(SpellEffIndex effIndex); - void EffectOpenLock(SpellEffIndex effIndex); - void EffectSummonChangeItem(SpellEffIndex effIndex); - void EffectProficiency(SpellEffIndex effIndex); - void EffectApplyAreaAura(SpellEffIndex effIndex); - void EffectSummonType(SpellEffIndex effIndex); - void EffectLearnSpell(SpellEffIndex effIndex); - void EffectDispel(SpellEffIndex effIndex); - void EffectDualWield(SpellEffIndex effIndex); - void EffectPickPocket(SpellEffIndex effIndex); - void EffectAddFarsight(SpellEffIndex effIndex); - void EffectUntrainTalents(SpellEffIndex effIndex); - void EffectHealMechanical(SpellEffIndex effIndex); - void EffectJump(SpellEffIndex effIndex); - void EffectJumpDest(SpellEffIndex effIndex); - void EffectLeapBack(SpellEffIndex effIndex); - void EffectQuestClear(SpellEffIndex effIndex); - void EffectTeleUnitsFaceCaster(SpellEffIndex effIndex); - void EffectLearnSkill(SpellEffIndex effIndex); - void EffectAddHonor(SpellEffIndex effIndex); - void EffectTradeSkill(SpellEffIndex effIndex); - void EffectEnchantItemPerm(SpellEffIndex effIndex); - void EffectEnchantItemTmp(SpellEffIndex effIndex); - void EffectTameCreature(SpellEffIndex effIndex); - void EffectSummonPet(SpellEffIndex effIndex); - void EffectLearnPetSpell(SpellEffIndex effIndex); - void EffectWeaponDmg(SpellEffIndex effIndex); - void EffectForceCast(SpellEffIndex effIndex); - void EffectTriggerSpell(SpellEffIndex effIndex); - void EffectTriggerMissileSpell(SpellEffIndex effIndex); - void EffectThreat(SpellEffIndex effIndex); - void EffectHealMaxHealth(SpellEffIndex effIndex); - void EffectInterruptCast(SpellEffIndex effIndex); - void EffectSummonObjectWild(SpellEffIndex effIndex); - void EffectScriptEffect(SpellEffIndex effIndex); - void EffectSanctuary(SpellEffIndex effIndex); - void EffectAddComboPoints(SpellEffIndex effIndex); - void EffectDuel(SpellEffIndex effIndex); - void EffectStuck(SpellEffIndex effIndex); - void EffectSummonPlayer(SpellEffIndex effIndex); - void EffectActivateObject(SpellEffIndex effIndex); - void EffectApplyGlyph(SpellEffIndex effIndex); - void EffectEnchantHeldItem(SpellEffIndex effIndex); - void EffectSummonObject(SpellEffIndex effIndex); - void EffectResurrect(SpellEffIndex effIndex); - void EffectParry(SpellEffIndex effIndex); - void EffectBlock(SpellEffIndex effIndex); - void EffectLeap(SpellEffIndex effIndex); - void EffectTransmitted(SpellEffIndex effIndex); - void EffectDisEnchant(SpellEffIndex effIndex); - void EffectInebriate(SpellEffIndex effIndex); - void EffectFeedPet(SpellEffIndex effIndex); - void EffectDismissPet(SpellEffIndex effIndex); - void EffectReputation(SpellEffIndex effIndex); - void EffectForceDeselect(SpellEffIndex effIndex); - void EffectSelfResurrect(SpellEffIndex effIndex); - void EffectSkinning(SpellEffIndex effIndex); - void EffectCharge(SpellEffIndex effIndex); - void EffectChargeDest(SpellEffIndex effIndex); - void EffectProspecting(SpellEffIndex effIndex); - void EffectMilling(SpellEffIndex effIndex); - void EffectRenamePet(SpellEffIndex effIndex); - void EffectSendTaxi(SpellEffIndex effIndex); - void EffectSummonCritter(SpellEffIndex effIndex); - void EffectKnockBack(SpellEffIndex effIndex); - void EffectPullTowards(SpellEffIndex effIndex); - void EffectDispelMechanic(SpellEffIndex effIndex); - void EffectResurrectPet(SpellEffIndex effIndex); - void EffectDestroyAllTotems(SpellEffIndex effIndex); - void EffectDurabilityDamage(SpellEffIndex effIndex); - void EffectSkill(SpellEffIndex effIndex); - void EffectTaunt(SpellEffIndex effIndex); - void EffectDurabilityDamagePCT(SpellEffIndex effIndex); - void EffectModifyThreatPercent(SpellEffIndex effIndex); - void EffectResurrectNew(SpellEffIndex effIndex); - void EffectAddExtraAttacks(SpellEffIndex effIndex); - void EffectSpiritHeal(SpellEffIndex effIndex); - void EffectSkinPlayerCorpse(SpellEffIndex effIndex); - void EffectStealBeneficialBuff(SpellEffIndex effIndex); - void EffectUnlearnSpecialization(SpellEffIndex effIndex); - void EffectHealPct(SpellEffIndex effIndex); - void EffectEnergizePct(SpellEffIndex effIndex); - void EffectTriggerRitualOfSummoning(SpellEffIndex effIndex); - void EffectSummonRaFFriend(SpellEffIndex effIndex); - void EffectKillCreditPersonal(SpellEffIndex effIndex); - void EffectKillCredit(SpellEffIndex effIndex); - void EffectQuestFail(SpellEffIndex effIndex); - void EffectQuestStart(SpellEffIndex effIndex); - void EffectRedirectThreat(SpellEffIndex effIndex); - void EffectGameObjectDamage(SpellEffIndex effIndex); - void EffectGameObjectRepair(SpellEffIndex effIndex); - void EffectGameObjectSetDestructionState(SpellEffIndex effIndex); - void EffectActivateRune(SpellEffIndex effIndex); - void EffectCreateTamedPet(SpellEffIndex effIndex); - void EffectDiscoverTaxi(SpellEffIndex effIndex); - void EffectTitanGrip(SpellEffIndex effIndex); - void EffectEnchantItemPrismatic(SpellEffIndex effIndex); - void EffectPlayMusic(SpellEffIndex effIndex); - void EffectSpecCount(SpellEffIndex effIndex); - void EffectActivateSpec(SpellEffIndex effIndex); - void EffectPlaySound(SpellEffIndex effIndex); - void EffectRemoveAura(SpellEffIndex effIndex); - void EffectCastButtons(SpellEffIndex effIndex); - void EffectRechargeManaGem(SpellEffIndex effIndex); - - typedef std::set UsedSpellMods; - - Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID = 0, bool skipCheck = false); - ~Spell(); - - void InitExplicitTargets(SpellCastTargets const& targets); - void SelectExplicitTargets(); - - void SelectSpellTargets(); - void SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask); - void SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask); - void SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask); - void SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask); - void SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask); - void SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - - void SelectEffectTypeImplicitTargets(uint8 effIndex); - - uint32 GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionList* condList); - template void SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius); - - WorldObject* SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList = nullptr); - void SearchAreaTargets(std::list& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList); - void SearchChainTargets(std::list& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, SpellTargetSelectionCategories selectCategory, ConditionList* condList, bool isChainHeal); - - void prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura = nullptr); - void cancel(bool bySelf = false); - void update(uint32 difftime); - void cast(bool skipCheck = false); - void _cast(bool skipCheck); - void finish(bool ok = true); - void TakePower(); - void TakeAmmo(); - - void TakeRunePower(bool didHit); - void TakeReagents(); - void TakeCastItem(); - - SpellCastResult CheckCast(bool strict); - SpellCastResult CheckPetCast(Unit* target); - - // handlers - void handle_immediate(); - uint64 handle_delayed(uint64 t_offset); - // handler helpers - void _handle_immediate_phase(); - void _handle_finish_phase(); - - void OnSpellLaunch(); - - SpellCastResult CheckItems(); - SpellCastResult CheckSpellFocus(); - SpellCastResult CheckRange(bool strict); - SpellCastResult CheckPower(); - SpellCastResult CheckRuneCost(uint32 runeCostID); - SpellCastResult CheckCasterAuras(bool preventionOnly) const; - - int32 CalculateSpellDamage(uint8 i, Unit const* target) const { return m_caster->CalculateSpellDamage(target, m_spellInfo, i, &m_spellValue->EffectBasePoints[i]); } - - bool HaveTargetsForEffect(uint8 effect) const; - void Delayed(); - void DelayedChannel(); - uint32 getState() const { return m_spellState; } - void setState(uint32 state) { m_spellState = state; } - - void DoCreateItem(uint8 effIndex, uint32 itemId); - void WriteSpellGoTargets(WorldPacket* data); - void WriteAmmoToPacket(WorldPacket* data); - - bool CheckEffectTarget(Unit const* target, uint32 eff) const; - bool CanAutoCast(Unit* target); - void CheckSrc() { if (!m_targets.HasSrc()) m_targets.SetSrc(*m_caster); } - void CheckDst() { if (!m_targets.HasDst()) m_targets.SetDst(*m_caster); } - - static void WriteCastResultInfo(WorldPacket& data, Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError); - static void SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError = SPELL_CUSTOM_ERROR_NONE); - void SendCastResult(SpellCastResult result); - void SendPetCastResult(SpellCastResult result); - void SendSpellStart(); - void SendSpellGo(); - void SendSpellCooldown(); - void SendLogExecute(); - void ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 powerTaken, float gainMultiplier); - void ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 attCount); - void ExecuteLogEffectInterruptCast(uint8 effIndex, Unit* victim, uint32 spellId); - void ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, int32 itemId, int32 slot); - void ExecuteLogEffectOpenLock(uint8 effIndex, Object* obj); - void ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry); - void ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry); - void ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject* obj); - void ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject* obj); - void ExecuteLogEffectResurrect(uint8 effIndex, Unit* target); - void SendInterrupted(uint8 result); - void SendChannelUpdate(uint32 time); - void SendChannelStart(uint32 duration); - void SendResurrectRequest(Player* target); - - void HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOTarget, uint32 i, SpellEffectHandleMode mode); - void HandleThreatSpells(); - - SpellInfo const* const m_spellInfo; - Item* m_CastItem; - uint64 m_castItemGUID; - uint8 m_cast_count; - uint32 m_glyphIndex; - uint32 m_preCastSpell; - SpellCastTargets m_targets; - SpellCustomErrors m_customError; - - UsedSpellMods m_appliedMods; - - PathGenerator* m_pathFinder; // pussywizard: for precomputing path for charge - - int32 GetCastTime() const { return m_casttime; } - bool IsAutoRepeat() const { return m_autoRepeat; } - void SetAutoRepeat(bool rep) { m_autoRepeat = rep; } - void ReSetTimer() { m_timer = m_casttime > 0 ? m_casttime : 0; } - bool IsNextMeleeSwingSpell() const; - bool IsTriggered() const { return _triggeredCastFlags & TRIGGERED_FULL_MASK; }; - bool IsChannelActive() const { return m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != 0; } - bool IsAutoActionResetSpell() const; - - bool IsDeletable() const { return !m_referencedFromCurrentSpell && !m_executedCurrently; } - void SetReferencedFromCurrent(bool yes) { m_referencedFromCurrentSpell = yes; } - bool IsInterruptable() const { return !m_executedCurrently; } - void SetExecutedCurrently(bool yes) {m_executedCurrently = yes;} - uint64 GetDelayStart() const { return m_delayStart; } - void SetDelayStart(uint64 m_time) { m_delayStart = m_time; } - uint64 GetDelayMoment() const { return m_delayMoment; } - uint64 GetDelayTrajectory() const { return m_delayTrajectory; } - - bool IsNeedSendToClient(bool go) const; - - CurrentSpellTypes GetCurrentContainer() const; - - Unit* GetCaster() const { return m_caster; } - Unit* GetOriginalCaster() const { return m_originalCaster; } - SpellInfo const* GetSpellInfo() const { return m_spellInfo; } - int32 GetPowerCost() const { return m_powerCost; } - - bool UpdatePointers(); // must be used at call Spell code after time delay (non triggered spell cast/update spell call/etc) - - void CleanupTargetList(); - - void SetSpellValue(SpellValueMod mod, int32 value); - SpellValue const* GetSpellValue() { return m_spellValue; } - - // xinef: moved to public - void LoadScripts(); - - // Targets store structures and data - struct TargetInfo - { - uint64 targetGUID; - uint64 timeDelay; - SpellMissInfo missCondition:8; - SpellMissInfo reflectResult:8; - uint8 effectMask:8; - bool processed:1; - bool alive:1; - bool crit:1; - bool scaleAura:1; - int32 damage; - }; - std::list* GetUniqueTargetInfo() { return &m_UniqueTargetInfo; } - protected: - bool HasGlobalCooldown() const; - void TriggerGlobalCooldown(); - void CancelGlobalCooldown(); - - void SendLoot(uint64 guid, LootType loottype); - - Unit* const m_caster; - - SpellValue * const m_spellValue; - - uint64 m_originalCasterGUID; // real source of cast (aura caster/etc), used for spell targets selection - // e.g. damage around area spell trigered by victim aura and damage enemies of aura caster - Unit* m_originalCaster; // cached pointer for m_originalCaster, updated at Spell::UpdatePointers() - - Spell** m_selfContainer; // pointer to our spell container (if applicable) - - //Spell data - SpellSchoolMask m_spellSchoolMask; // Spell school (can be overwrite for some spells (wand shoot for example) - WeaponAttackType m_attackType; // For weapon based attack - int32 m_powerCost; // Calculated spell cost initialized only in Spell::prepare - int32 m_casttime; // Calculated spell cast time initialized only in Spell::prepare - int32 m_channeledDuration; // Calculated channeled spell duration in order to calculate correct pushback. - bool m_canReflect; // can reflect this spell? - - uint8 m_spellFlags; // for spells whose target was changed in cast i.e. due to reflect - - bool m_autoRepeat; - uint8 m_runesState; - - uint8 m_delayAtDamageCount; - bool isDelayableNoMore() - { - if (m_delayAtDamageCount >= 2) - return true; - - m_delayAtDamageCount++; - return false; - } - - // Delayed spells system - uint64 m_delayStart; // time of spell delay start, filled by event handler, zero = just started - uint64 m_delayMoment; // moment of next delay call, used internally - uint64 m_delayTrajectory; // Xinef: Trajectory delay - bool m_immediateHandled; // were immediate actions handled? (used by delayed spells only) - - // These vars are used in both delayed spell system and modified immediate spell system - bool m_referencedFromCurrentSpell; // mark as references to prevent deleted and access by dead pointers - bool m_executedCurrently; // mark as executed to prevent deleted and access by dead pointers - bool m_needComboPoints; - uint8 m_applyMultiplierMask; - float m_damageMultipliers[3]; - - // Current targets, to be used in SpellEffects (MUST BE USED ONLY IN SPELL EFFECTS) - Unit* unitTarget; - Item* itemTarget; - GameObject* gameObjTarget; - WorldLocation* destTarget; - int32 damage; - SpellEffectHandleMode effectHandleMode; - // used in effects handlers - Aura* m_spellAura; - - // this is set in Spell Hit, but used in Apply Aura handler - DiminishingLevels m_diminishLevel; - DiminishingGroup m_diminishGroup; - - // ------------------------------------------- - GameObject* focusObject; - - // Damage and healing in effects need just calculate - int32 m_damage; // Damge in effects count here - int32 m_healing; // Healing in effects count here - - // ****************************************** - // Spell trigger system - // ****************************************** - uint32 m_procAttacker; // Attacker trigger flags - uint32 m_procVictim; // Victim trigger flags - uint32 m_procEx; - void prepareDataForTriggerSystem(AuraEffect const* triggeredByAura); - - // ***************************************** - // Spell target subsystem - // ***************************************** - std::list m_UniqueTargetInfo; - uint8 m_channelTargetEffectMask; // Mask req. alive targets - - struct GOTargetInfo - { - uint64 targetGUID; - uint64 timeDelay; - uint8 effectMask:8; - bool processed:1; - }; - std::list m_UniqueGOTargetInfo; - - struct ItemTargetInfo - { - Item *item; - uint8 effectMask; - }; - std::list m_UniqueItemInfo; - - SpellDestination m_destTargets[MAX_SPELL_EFFECTS]; - - void AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid = true, bool implicit = true); - void AddGOTarget(GameObject* target, uint32 effectMask); - void AddItemTarget(Item* item, uint32 effectMask); - void AddDestTarget(SpellDestination const& dest, uint32 effIndex); - - void DoAllEffectOnTarget(TargetInfo* target); - SpellMissInfo DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleAura); - void DoTriggersOnSpellHit(Unit* unit, uint8 effMask); - void DoAllEffectOnTarget(GOTargetInfo* target); - void DoAllEffectOnTarget(ItemTargetInfo* target); - bool UpdateChanneledTargetList(); - bool IsValidDeadOrAliveTarget(Unit const* target) const; - void HandleLaunchPhase(); - void DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier, bool firstTarget); - - void PrepareTargetProcessing(); - void FinishTargetProcessing(); - - // spell execution log - void InitEffectExecuteData(uint8 effIndex); - void CheckEffectExecuteData(); - - // Scripting system - bool _scriptsLoaded; - //void LoadScripts(); - void CallScriptBeforeCastHandlers(); - void CallScriptOnCastHandlers(); - void CallScriptAfterCastHandlers(); - SpellCastResult CallScriptCheckCastHandlers(); - void PrepareScriptHitHandlers(); - bool CallScriptEffectHandlers(SpellEffIndex effIndex, SpellEffectHandleMode mode); - void CallScriptBeforeHitHandlers(); - void CallScriptOnHitHandlers(); - void CallScriptAfterHitHandlers(); - void CallScriptObjectAreaTargetSelectHandlers(std::list& targets, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void CallScriptObjectTargetSelectHandlers(WorldObject*& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - void CallScriptDestinationTargetSelectHandlers(SpellDestination& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); - bool CheckScriptEffectImplicitTargets(uint32 effIndex, uint32 effIndexToCheck); - std::list m_loadedScripts; - - struct HitTriggerSpell - { - SpellInfo const* triggeredSpell; - SpellInfo const* triggeredByAura; - // uint8 triggeredByEffIdx This might be needed at a later stage - No need known for now - int32 chance; - }; - - bool CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByAura = nullptr) const; - void PrepareTriggersExecutedOnHit(); - typedef std::list HitTriggerSpellList; - HitTriggerSpellList m_hitTriggerSpells; - - // effect helpers - void SummonGuardian(uint32 i, uint32 entry, SummonPropertiesEntry const* properties, uint32 numSummons); - void CalculateJumpSpeeds(uint8 i, float dist, float & speedxy, float & speedz); - - SpellCastResult CanOpenLock(uint32 effIndex, uint32 lockid, SkillType& skillid, int32& reqSkillValue, int32& skillValue); - // ------------------------------------------- - - uint32 m_spellState; - int32 m_timer; - - TriggerCastFlags _triggeredCastFlags; - - // if need this can be replaced by Aura copy - // we can't store original aura link to prevent access to deleted auras - // and in same time need aura data and after aura deleting. - SpellInfo const* m_triggeredByAuraSpell; - - bool m_skipCheck; - uint8 m_auraScaleMask; - - // xinef: - bool _spellTargetsSelected; - - ByteBuffer * m_effectExecuteData[MAX_SPELL_EFFECTS]; +public: + + void EffectNULL(SpellEffIndex effIndex); + void EffectUnused(SpellEffIndex effIndex); + void EffectDistract(SpellEffIndex effIndex); + void EffectPull(SpellEffIndex effIndex); + void EffectSchoolDMG(SpellEffIndex effIndex); + void EffectEnvironmentalDMG(SpellEffIndex effIndex); + void EffectInstaKill(SpellEffIndex effIndex); + void EffectDummy(SpellEffIndex effIndex); + void EffectTeleportUnits(SpellEffIndex effIndex); + void EffectApplyAura(SpellEffIndex effIndex); + void EffectSendEvent(SpellEffIndex effIndex); + void EffectPowerBurn(SpellEffIndex effIndex); + void EffectPowerDrain(SpellEffIndex effIndex); + void EffectHeal(SpellEffIndex effIndex); + void EffectBind(SpellEffIndex effIndex); + void EffectHealthLeech(SpellEffIndex effIndex); + void EffectQuestComplete(SpellEffIndex effIndex); + void EffectCreateItem(SpellEffIndex effIndex); + void EffectCreateItem2(SpellEffIndex effIndex); + void EffectCreateRandomItem(SpellEffIndex effIndex); + void EffectPersistentAA(SpellEffIndex effIndex); + void EffectEnergize(SpellEffIndex effIndex); + void EffectOpenLock(SpellEffIndex effIndex); + void EffectSummonChangeItem(SpellEffIndex effIndex); + void EffectProficiency(SpellEffIndex effIndex); + void EffectApplyAreaAura(SpellEffIndex effIndex); + void EffectSummonType(SpellEffIndex effIndex); + void EffectLearnSpell(SpellEffIndex effIndex); + void EffectDispel(SpellEffIndex effIndex); + void EffectDualWield(SpellEffIndex effIndex); + void EffectPickPocket(SpellEffIndex effIndex); + void EffectAddFarsight(SpellEffIndex effIndex); + void EffectUntrainTalents(SpellEffIndex effIndex); + void EffectHealMechanical(SpellEffIndex effIndex); + void EffectJump(SpellEffIndex effIndex); + void EffectJumpDest(SpellEffIndex effIndex); + void EffectLeapBack(SpellEffIndex effIndex); + void EffectQuestClear(SpellEffIndex effIndex); + void EffectTeleUnitsFaceCaster(SpellEffIndex effIndex); + void EffectLearnSkill(SpellEffIndex effIndex); + void EffectAddHonor(SpellEffIndex effIndex); + void EffectTradeSkill(SpellEffIndex effIndex); + void EffectEnchantItemPerm(SpellEffIndex effIndex); + void EffectEnchantItemTmp(SpellEffIndex effIndex); + void EffectTameCreature(SpellEffIndex effIndex); + void EffectSummonPet(SpellEffIndex effIndex); + void EffectLearnPetSpell(SpellEffIndex effIndex); + void EffectWeaponDmg(SpellEffIndex effIndex); + void EffectForceCast(SpellEffIndex effIndex); + void EffectTriggerSpell(SpellEffIndex effIndex); + void EffectTriggerMissileSpell(SpellEffIndex effIndex); + void EffectThreat(SpellEffIndex effIndex); + void EffectHealMaxHealth(SpellEffIndex effIndex); + void EffectInterruptCast(SpellEffIndex effIndex); + void EffectSummonObjectWild(SpellEffIndex effIndex); + void EffectScriptEffect(SpellEffIndex effIndex); + void EffectSanctuary(SpellEffIndex effIndex); + void EffectAddComboPoints(SpellEffIndex effIndex); + void EffectDuel(SpellEffIndex effIndex); + void EffectStuck(SpellEffIndex effIndex); + void EffectSummonPlayer(SpellEffIndex effIndex); + void EffectActivateObject(SpellEffIndex effIndex); + void EffectApplyGlyph(SpellEffIndex effIndex); + void EffectEnchantHeldItem(SpellEffIndex effIndex); + void EffectSummonObject(SpellEffIndex effIndex); + void EffectResurrect(SpellEffIndex effIndex); + void EffectParry(SpellEffIndex effIndex); + void EffectBlock(SpellEffIndex effIndex); + void EffectLeap(SpellEffIndex effIndex); + void EffectTransmitted(SpellEffIndex effIndex); + void EffectDisEnchant(SpellEffIndex effIndex); + void EffectInebriate(SpellEffIndex effIndex); + void EffectFeedPet(SpellEffIndex effIndex); + void EffectDismissPet(SpellEffIndex effIndex); + void EffectReputation(SpellEffIndex effIndex); + void EffectForceDeselect(SpellEffIndex effIndex); + void EffectSelfResurrect(SpellEffIndex effIndex); + void EffectSkinning(SpellEffIndex effIndex); + void EffectCharge(SpellEffIndex effIndex); + void EffectChargeDest(SpellEffIndex effIndex); + void EffectProspecting(SpellEffIndex effIndex); + void EffectMilling(SpellEffIndex effIndex); + void EffectRenamePet(SpellEffIndex effIndex); + void EffectSendTaxi(SpellEffIndex effIndex); + void EffectSummonCritter(SpellEffIndex effIndex); + void EffectKnockBack(SpellEffIndex effIndex); + void EffectPullTowards(SpellEffIndex effIndex); + void EffectDispelMechanic(SpellEffIndex effIndex); + void EffectResurrectPet(SpellEffIndex effIndex); + void EffectDestroyAllTotems(SpellEffIndex effIndex); + void EffectDurabilityDamage(SpellEffIndex effIndex); + void EffectSkill(SpellEffIndex effIndex); + void EffectTaunt(SpellEffIndex effIndex); + void EffectDurabilityDamagePCT(SpellEffIndex effIndex); + void EffectModifyThreatPercent(SpellEffIndex effIndex); + void EffectResurrectNew(SpellEffIndex effIndex); + void EffectAddExtraAttacks(SpellEffIndex effIndex); + void EffectSpiritHeal(SpellEffIndex effIndex); + void EffectSkinPlayerCorpse(SpellEffIndex effIndex); + void EffectStealBeneficialBuff(SpellEffIndex effIndex); + void EffectUnlearnSpecialization(SpellEffIndex effIndex); + void EffectHealPct(SpellEffIndex effIndex); + void EffectEnergizePct(SpellEffIndex effIndex); + void EffectTriggerRitualOfSummoning(SpellEffIndex effIndex); + void EffectSummonRaFFriend(SpellEffIndex effIndex); + void EffectKillCreditPersonal(SpellEffIndex effIndex); + void EffectKillCredit(SpellEffIndex effIndex); + void EffectQuestFail(SpellEffIndex effIndex); + void EffectQuestStart(SpellEffIndex effIndex); + void EffectRedirectThreat(SpellEffIndex effIndex); + void EffectGameObjectDamage(SpellEffIndex effIndex); + void EffectGameObjectRepair(SpellEffIndex effIndex); + void EffectGameObjectSetDestructionState(SpellEffIndex effIndex); + void EffectActivateRune(SpellEffIndex effIndex); + void EffectCreateTamedPet(SpellEffIndex effIndex); + void EffectDiscoverTaxi(SpellEffIndex effIndex); + void EffectTitanGrip(SpellEffIndex effIndex); + void EffectEnchantItemPrismatic(SpellEffIndex effIndex); + void EffectPlayMusic(SpellEffIndex effIndex); + void EffectSpecCount(SpellEffIndex effIndex); + void EffectActivateSpec(SpellEffIndex effIndex); + void EffectPlaySound(SpellEffIndex effIndex); + void EffectRemoveAura(SpellEffIndex effIndex); + void EffectCastButtons(SpellEffIndex effIndex); + void EffectRechargeManaGem(SpellEffIndex effIndex); + + typedef std::set UsedSpellMods; + + Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, uint64 originalCasterGUID = 0, bool skipCheck = false); + ~Spell(); + + void InitExplicitTargets(SpellCastTargets const& targets); + void SelectExplicitTargets(); + + void SelectSpellTargets(); + void SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask); + void SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask); + void SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask); + void SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask); + void SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask); + void SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + + void SelectEffectTypeImplicitTargets(uint8 effIndex); + + uint32 GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionList* condList); + template void SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius); + + WorldObject* SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList = nullptr); + void SearchAreaTargets(std::list& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionList* condList); + void SearchChainTargets(std::list& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, SpellTargetSelectionCategories selectCategory, ConditionList* condList, bool isChainHeal); + + void prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura = nullptr); + void cancel(bool bySelf = false); + void update(uint32 difftime); + void cast(bool skipCheck = false); + void _cast(bool skipCheck); + void finish(bool ok = true); + void TakePower(); + void TakeAmmo(); + + void TakeRunePower(bool didHit); + void TakeReagents(); + void TakeCastItem(); + + SpellCastResult CheckCast(bool strict); + SpellCastResult CheckPetCast(Unit* target); + + // handlers + void handle_immediate(); + uint64 handle_delayed(uint64 t_offset); + // handler helpers + void _handle_immediate_phase(); + void _handle_finish_phase(); + + void OnSpellLaunch(); + + SpellCastResult CheckItems(); + SpellCastResult CheckSpellFocus(); + SpellCastResult CheckRange(bool strict); + SpellCastResult CheckPower(); + SpellCastResult CheckRuneCost(uint32 runeCostID); + SpellCastResult CheckCasterAuras(bool preventionOnly) const; + + int32 CalculateSpellDamage(uint8 i, Unit const* target) const { return m_caster->CalculateSpellDamage(target, m_spellInfo, i, &m_spellValue->EffectBasePoints[i]); } + + bool HaveTargetsForEffect(uint8 effect) const; + void Delayed(); + void DelayedChannel(); + uint32 getState() const { return m_spellState; } + void setState(uint32 state) { m_spellState = state; } + + void DoCreateItem(uint8 effIndex, uint32 itemId); + void WriteSpellGoTargets(WorldPacket* data); + void WriteAmmoToPacket(WorldPacket* data); + + bool CheckEffectTarget(Unit const* target, uint32 eff) const; + bool CanAutoCast(Unit* target); + void CheckSrc() { if (!m_targets.HasSrc()) m_targets.SetSrc(*m_caster); } + void CheckDst() { if (!m_targets.HasDst()) m_targets.SetDst(*m_caster); } + + static void WriteCastResultInfo(WorldPacket& data, Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError); + static void SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError = SPELL_CUSTOM_ERROR_NONE); + void SendCastResult(SpellCastResult result); + void SendPetCastResult(SpellCastResult result); + void SendSpellStart(); + void SendSpellGo(); + void SendSpellCooldown(); + void SendLogExecute(); + void ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 powerTaken, float gainMultiplier); + void ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 attCount); + void ExecuteLogEffectInterruptCast(uint8 effIndex, Unit* victim, uint32 spellId); + void ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, int32 itemId, int32 slot); + void ExecuteLogEffectOpenLock(uint8 effIndex, Object* obj); + void ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry); + void ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry); + void ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject* obj); + void ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject* obj); + void ExecuteLogEffectResurrect(uint8 effIndex, Unit* target); + void SendInterrupted(uint8 result); + void SendChannelUpdate(uint32 time); + void SendChannelStart(uint32 duration); + void SendResurrectRequest(Player* target); + + void HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOTarget, uint32 i, SpellEffectHandleMode mode); + void HandleThreatSpells(); + + SpellInfo const* const m_spellInfo; + Item* m_CastItem; + uint64 m_castItemGUID; + uint8 m_cast_count; + uint32 m_glyphIndex; + uint32 m_preCastSpell; + SpellCastTargets m_targets; + SpellCustomErrors m_customError; + + UsedSpellMods m_appliedMods; + + PathGenerator* m_pathFinder; // pussywizard: for precomputing path for charge + + int32 GetCastTime() const { return m_casttime; } + bool IsAutoRepeat() const { return m_autoRepeat; } + void SetAutoRepeat(bool rep) { m_autoRepeat = rep; } + void ReSetTimer() { m_timer = m_casttime > 0 ? m_casttime : 0; } + bool IsNextMeleeSwingSpell() const; + bool IsTriggered() const { return _triggeredCastFlags & TRIGGERED_FULL_MASK; }; + bool IsChannelActive() const { return m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != 0; } + bool IsAutoActionResetSpell() const; + + bool IsDeletable() const { return !m_referencedFromCurrentSpell && !m_executedCurrently; } + void SetReferencedFromCurrent(bool yes) { m_referencedFromCurrentSpell = yes; } + bool IsInterruptable() const { return !m_executedCurrently; } + void SetExecutedCurrently(bool yes) {m_executedCurrently = yes;} + uint64 GetDelayStart() const { return m_delayStart; } + void SetDelayStart(uint64 m_time) { m_delayStart = m_time; } + uint64 GetDelayMoment() const { return m_delayMoment; } + uint64 GetDelayTrajectory() const { return m_delayTrajectory; } + + bool IsNeedSendToClient(bool go) const; + + CurrentSpellTypes GetCurrentContainer() const; + + Unit* GetCaster() const { return m_caster; } + Unit* GetOriginalCaster() const { return m_originalCaster; } + SpellInfo const* GetSpellInfo() const { return m_spellInfo; } + int32 GetPowerCost() const { return m_powerCost; } + + bool UpdatePointers(); // must be used at call Spell code after time delay (non triggered spell cast/update spell call/etc) + + void CleanupTargetList(); + + void SetSpellValue(SpellValueMod mod, int32 value); + SpellValue const* GetSpellValue() { return m_spellValue; } + + // xinef: moved to public + void LoadScripts(); + + // Targets store structures and data + struct TargetInfo + { + uint64 targetGUID; + uint64 timeDelay; + SpellMissInfo missCondition: 8; + SpellMissInfo reflectResult: 8; + uint8 effectMask: 8; + bool processed: 1; + bool alive: 1; + bool crit: 1; + bool scaleAura: 1; + int32 damage; + }; + std::list* GetUniqueTargetInfo() { return &m_UniqueTargetInfo; } +protected: + bool HasGlobalCooldown() const; + void TriggerGlobalCooldown(); + void CancelGlobalCooldown(); + + void SendLoot(uint64 guid, LootType loottype); + + Unit* const m_caster; + + SpellValue* const m_spellValue; + + uint64 m_originalCasterGUID; // real source of cast (aura caster/etc), used for spell targets selection + // e.g. damage around area spell trigered by victim aura and damage enemies of aura caster + Unit* m_originalCaster; // cached pointer for m_originalCaster, updated at Spell::UpdatePointers() + + Spell** m_selfContainer; // pointer to our spell container (if applicable) + + //Spell data + SpellSchoolMask m_spellSchoolMask; // Spell school (can be overwrite for some spells (wand shoot for example) + WeaponAttackType m_attackType; // For weapon based attack + int32 m_powerCost; // Calculated spell cost initialized only in Spell::prepare + int32 m_casttime; // Calculated spell cast time initialized only in Spell::prepare + int32 m_channeledDuration; // Calculated channeled spell duration in order to calculate correct pushback. + bool m_canReflect; // can reflect this spell? + + uint8 m_spellFlags; // for spells whose target was changed in cast i.e. due to reflect + + bool m_autoRepeat; + uint8 m_runesState; + + uint8 m_delayAtDamageCount; + bool isDelayableNoMore() + { + if (m_delayAtDamageCount >= 2) + return true; + + m_delayAtDamageCount++; + return false; + } + + // Delayed spells system + uint64 m_delayStart; // time of spell delay start, filled by event handler, zero = just started + uint64 m_delayMoment; // moment of next delay call, used internally + uint64 m_delayTrajectory; // Xinef: Trajectory delay + bool m_immediateHandled; // were immediate actions handled? (used by delayed spells only) + + // These vars are used in both delayed spell system and modified immediate spell system + bool m_referencedFromCurrentSpell; // mark as references to prevent deleted and access by dead pointers + bool m_executedCurrently; // mark as executed to prevent deleted and access by dead pointers + bool m_needComboPoints; + uint8 m_applyMultiplierMask; + float m_damageMultipliers[3]; + + // Current targets, to be used in SpellEffects (MUST BE USED ONLY IN SPELL EFFECTS) + Unit* unitTarget; + Item* itemTarget; + GameObject* gameObjTarget; + WorldLocation* destTarget; + int32 damage; + SpellEffectHandleMode effectHandleMode; + // used in effects handlers + Aura* m_spellAura; + + // this is set in Spell Hit, but used in Apply Aura handler + DiminishingLevels m_diminishLevel; + DiminishingGroup m_diminishGroup; + + // ------------------------------------------- + GameObject* focusObject; + + // Damage and healing in effects need just calculate + int32 m_damage; // Damge in effects count here + int32 m_healing; // Healing in effects count here + + // ****************************************** + // Spell trigger system + // ****************************************** + uint32 m_procAttacker; // Attacker trigger flags + uint32 m_procVictim; // Victim trigger flags + uint32 m_procEx; + void prepareDataForTriggerSystem(AuraEffect const* triggeredByAura); + + // ***************************************** + // Spell target subsystem + // ***************************************** + std::list m_UniqueTargetInfo; + uint8 m_channelTargetEffectMask; // Mask req. alive targets + + struct GOTargetInfo + { + uint64 targetGUID; + uint64 timeDelay; + uint8 effectMask: 8; + bool processed: 1; + }; + std::list m_UniqueGOTargetInfo; + + struct ItemTargetInfo + { + Item* item; + uint8 effectMask; + }; + std::list m_UniqueItemInfo; + + SpellDestination m_destTargets[MAX_SPELL_EFFECTS]; + + void AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid = true, bool implicit = true); + void AddGOTarget(GameObject* target, uint32 effectMask); + void AddItemTarget(Item* item, uint32 effectMask); + void AddDestTarget(SpellDestination const& dest, uint32 effIndex); + + void DoAllEffectOnTarget(TargetInfo* target); + SpellMissInfo DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleAura); + void DoTriggersOnSpellHit(Unit* unit, uint8 effMask); + void DoAllEffectOnTarget(GOTargetInfo* target); + void DoAllEffectOnTarget(ItemTargetInfo* target); + bool UpdateChanneledTargetList(); + bool IsValidDeadOrAliveTarget(Unit const* target) const; + void HandleLaunchPhase(); + void DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier, bool firstTarget); + + void PrepareTargetProcessing(); + void FinishTargetProcessing(); + + // spell execution log + void InitEffectExecuteData(uint8 effIndex); + void CheckEffectExecuteData(); + + // Scripting system + bool _scriptsLoaded; + //void LoadScripts(); + void CallScriptBeforeCastHandlers(); + void CallScriptOnCastHandlers(); + void CallScriptAfterCastHandlers(); + SpellCastResult CallScriptCheckCastHandlers(); + void PrepareScriptHitHandlers(); + bool CallScriptEffectHandlers(SpellEffIndex effIndex, SpellEffectHandleMode mode); + void CallScriptBeforeHitHandlers(); + void CallScriptOnHitHandlers(); + void CallScriptAfterHitHandlers(); + void CallScriptObjectAreaTargetSelectHandlers(std::list& targets, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void CallScriptObjectTargetSelectHandlers(WorldObject*& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + void CallScriptDestinationTargetSelectHandlers(SpellDestination& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType); + bool CheckScriptEffectImplicitTargets(uint32 effIndex, uint32 effIndexToCheck); + std::list m_loadedScripts; + + struct HitTriggerSpell + { + SpellInfo const* triggeredSpell; + SpellInfo const* triggeredByAura; + // uint8 triggeredByEffIdx This might be needed at a later stage - No need known for now + int32 chance; + }; + + bool CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByAura = nullptr) const; + void PrepareTriggersExecutedOnHit(); + typedef std::list HitTriggerSpellList; + HitTriggerSpellList m_hitTriggerSpells; + + // effect helpers + void SummonGuardian(uint32 i, uint32 entry, SummonPropertiesEntry const* properties, uint32 numSummons); + void CalculateJumpSpeeds(uint8 i, float dist, float& speedxy, float& speedz); + + SpellCastResult CanOpenLock(uint32 effIndex, uint32 lockid, SkillType& skillid, int32& reqSkillValue, int32& skillValue); + // ------------------------------------------- + + uint32 m_spellState; + int32 m_timer; + + TriggerCastFlags _triggeredCastFlags; + + // if need this can be replaced by Aura copy + // we can't store original aura link to prevent access to deleted auras + // and in same time need aura data and after aura deleting. + SpellInfo const* m_triggeredByAuraSpell; + + bool m_skipCheck; + uint8 m_auraScaleMask; + + // xinef: + bool _spellTargetsSelected; + + ByteBuffer* m_effectExecuteData[MAX_SPELL_EFFECTS]; #ifdef MAP_BASED_RAND_GEN - int32 irand(int32 min, int32 max) { return int32 (m_caster->GetMap()->mtRand.randInt(max - min)) + min; } - uint32 urand(uint32 min, uint32 max) { return m_caster->GetMap()->mtRand.randInt(max - min) + min; } - int32 rand32() { return m_caster->GetMap()->mtRand.randInt(); } - double rand_norm() { return m_caster->GetMap()->mtRand.randExc(); } - double rand_chance() { return m_caster->GetMap()->mtRand.randExc(100.0); } + int32 irand(int32 min, int32 max) { return int32 (m_caster->GetMap()->mtRand.randInt(max - min)) + min; } + uint32 urand(uint32 min, uint32 max) { return m_caster->GetMap()->mtRand.randInt(max - min) + min; } + int32 rand32() { return m_caster->GetMap()->mtRand.randInt(); } + double rand_norm() { return m_caster->GetMap()->mtRand.randExc(); } + double rand_chance() { return m_caster->GetMap()->mtRand.randExc(100.0); } #endif }; @@ -744,7 +744,7 @@ namespace acore ConditionList* _condList; WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo, - SpellTargetCheckTypes selectionType, ConditionList* condList); + SpellTargetCheckTypes selectionType, ConditionList* condList); ~WorldObjectSpellTargetCheck(); bool operator()(WorldObject* target); }; @@ -754,7 +754,7 @@ namespace acore float _range; Position const* _position; WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo, - SpellTargetCheckTypes selectionType, ConditionList* condList); + SpellTargetCheckTypes selectionType, ConditionList* condList); bool operator()(WorldObject* target); }; @@ -763,7 +763,7 @@ namespace acore float _range; Position const* _position; WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster, - Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList); + Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList); bool operator()(WorldObject* target); }; @@ -771,14 +771,14 @@ namespace acore { float _coneAngle; WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster, - SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList); + SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList); bool operator()(WorldObject* target); }; struct WorldObjectSpellTrajTargetCheck : public WorldObjectSpellAreaTargetCheck { WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, - SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList); + SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionList* condList); bool operator()(WorldObject* target); }; } @@ -787,27 +787,27 @@ typedef void(Spell::*pEffect)(SpellEffIndex effIndex); class SpellEvent : public BasicEvent { - public: - SpellEvent(Spell* spell); - virtual ~SpellEvent(); +public: + SpellEvent(Spell* spell); + virtual ~SpellEvent(); - virtual bool Execute(uint64 e_time, uint32 p_time); - virtual void Abort(uint64 e_time); - virtual bool IsDeletable() const; - protected: - Spell* m_Spell; + virtual bool Execute(uint64 e_time, uint32 p_time); + virtual void Abort(uint64 e_time); + virtual bool IsDeletable() const; +protected: + Spell* m_Spell; }; class ReflectEvent : public BasicEvent { - public: - ReflectEvent(uint64 casterGUID, uint64 targetGUID, const SpellInfo* spellInfo) : _casterGUID(casterGUID), _targetGUID(targetGUID), _spellInfo(spellInfo) { } - virtual bool Execute(uint64 e_time, uint32 p_time); +public: + ReflectEvent(uint64 casterGUID, uint64 targetGUID, const SpellInfo* spellInfo) : _casterGUID(casterGUID), _targetGUID(targetGUID), _spellInfo(spellInfo) { } + virtual bool Execute(uint64 e_time, uint32 p_time); - protected: - uint64 _casterGUID; - uint64 _targetGUID; - const SpellInfo* _spellInfo; +protected: + uint64 _casterGUID; + uint64 _targetGUID; + const SpellInfo* _spellInfo; }; #endif diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index f40f3996c..6ec4d9683 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -61,7 +61,7 @@ #include "LuaEngine.h" #endif -pEffect SpellEffects[TOTAL_SPELL_EFFECTS]= +pEffect SpellEffects[TOTAL_SPELL_EFFECTS] = { &Spell::EffectNULL, // 0 &Spell::EffectInstaKill, // 1 SPELL_EFFECT_INSTAKILL @@ -283,7 +283,7 @@ void Spell::EffectInstaKill(SpellEffIndex /*effIndex*/) if (m_caster == unitTarget) // prevent interrupt message finish(); - WorldPacket data(SMSG_SPELLINSTAKILLLOG, 8+8+4); + WorldPacket data(SMSG_SPELLINSTAKILLLOG, 8 + 8 + 4); data << uint64(m_caster->GetGUID()); data << uint64(unitTarget->GetGUID()); data << uint32(m_spellInfo->Id); @@ -305,7 +305,7 @@ void Spell::EffectEnvironmentalDMG(SpellEffIndex /*effIndex*/) Unit::CalcAbsorbResist(m_caster, unitTarget, m_spellInfo->GetSchoolMask(), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist, m_spellInfo); - m_caster->SendSpellNonMeleeDamageLog(unitTarget, m_spellInfo->Id, damage+absorb+resist, m_spellInfo->GetSchoolMask(), absorb, resist, false, 0, false); + m_caster->SendSpellNonMeleeDamageLog(unitTarget, m_spellInfo->Id, damage + absorb + resist, m_spellInfo->GetSchoolMask(), absorb, resist, false, 0, false); if (unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->EnvironmentalDamage(DAMAGE_FIRE, damage); } @@ -321,339 +321,339 @@ void Spell::EffectSchoolDMG(SpellEffIndex effIndex) switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - // Meteor like spells (divided damage to targets) - if (m_spellInfo->HasAttribute(SPELL_ATTR0_CU_SHARE_DAMAGE)) { - uint32 count = 0; - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) - if (ihit->effectMask & (1<Id) // better way to check unknown - { - // Consumption - case 28865: - damage = (m_caster->GetMap()->ToInstanceMap()->GetDifficulty() == REGULAR_DIFFICULTY ? 2750 : 4250); - break; - // percent from health with min - case 25599: // Thundercrash + // Meteor like spells (divided damage to targets) + if (m_spellInfo->HasAttribute(SPELL_ATTR0_CU_SHARE_DAMAGE)) { - damage = unitTarget->GetHealth() / 2; - if (damage < 200) - damage = 200; - break; - } - // arcane charge. must only affect demons (also undead?) - case 45072: - { - if (unitTarget->GetCreatureType() != CREATURE_TYPE_DEMON - && unitTarget->GetCreatureType() != CREATURE_TYPE_UNDEAD) - return; - break; - } - // Gargoyle Strike - case 51963: - { - // about +4 base spell dmg per level - damage = (m_caster->getLevel() - 60) * 4 + 60; - break; - } - } - break; - } - case SPELLFAMILY_WARRIOR: - { - // Shield Slam - if (m_spellInfo->SpellFamilyFlags[1] & 0x200 && m_spellInfo->GetCategory() == 1209) - { - uint8 level = m_caster->getLevel(); - // xinef: shield block should increase the limit - float limit = m_caster->HasAura(2565) ? 2.0f : 1.0f; - uint32 block_value = m_caster->GetShieldBlockValue(uint32(float(level) * 24.5f * limit), uint32(float(level) * 34.5f * limit)); + uint32 count = 0; + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + if (ihit->effectMask & (1 << effIndex)) + ++count; - damage += int32(m_caster->ApplyEffectModifiers(m_spellInfo, effIndex, float(block_value))); - } - // Victory Rush - else if (m_spellInfo->SpellFamilyFlags[1] & 0x100) - ApplyPct(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); - // Shockwave - else if (m_spellInfo->Id == 46968) - { - int32 pct = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, 2); - if (pct > 0) - damage += int32(CalculatePct(m_caster->GetTotalAttackPowerValue(BASE_ATTACK), pct)); + damage /= count; // divide to all targets + } + + switch (m_spellInfo->Id) // better way to check unknown + { + // Consumption + case 28865: + damage = (m_caster->GetMap()->ToInstanceMap()->GetDifficulty() == REGULAR_DIFFICULTY ? 2750 : 4250); + break; + // percent from health with min + case 25599: // Thundercrash + { + damage = unitTarget->GetHealth() / 2; + if (damage < 200) + damage = 200; + break; + } + // arcane charge. must only affect demons (also undead?) + case 45072: + { + if (unitTarget->GetCreatureType() != CREATURE_TYPE_DEMON + && unitTarget->GetCreatureType() != CREATURE_TYPE_UNDEAD) + return; + break; + } + // Gargoyle Strike + case 51963: + { + // about +4 base spell dmg per level + damage = (m_caster->getLevel() - 60) * 4 + 60; + break; + } + } break; } - break; - } - case SPELLFAMILY_WARLOCK: - { - // Incinerate Rank 1 & 2 - if ((m_spellInfo->SpellFamilyFlags[1] & 0x000040) && m_spellInfo->SpellIconID == 2128) + case SPELLFAMILY_WARRIOR: { - // Incinerate does more dmg (dmg*0.25) if the target have Immolate debuff. - // Check aura state for speed but aura state set not only for Immolate spell - if (unitTarget->HasAuraState(AURA_STATE_CONFLAGRATE)) + // Shield Slam + if (m_spellInfo->SpellFamilyFlags[1] & 0x200 && m_spellInfo->GetCategory() == 1209) { - if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0)) - damage += damage/4; + uint8 level = m_caster->getLevel(); + // xinef: shield block should increase the limit + float limit = m_caster->HasAura(2565) ? 2.0f : 1.0f; + uint32 block_value = m_caster->GetShieldBlockValue(uint32(float(level) * 24.5f * limit), uint32(float(level) * 34.5f * limit)); + + damage += int32(m_caster->ApplyEffectModifiers(m_spellInfo, effIndex, float(block_value))); } - } - // Immolate - hidden delay for conflagrate - else if (m_spellInfo->SpellFamilyFlags[0] & 0x4) - { - } - // Conflagrate - consumes Immolate or Shadowflame - else if (m_spellInfo->TargetAuraState == AURA_STATE_CONFLAGRATE) - { - AuraEffect const* aura = nullptr; // found req. aura for damage calculation - - Unit::AuraEffectList const &mPeriodic = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE); - for (Unit::AuraEffectList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i) + // Victory Rush + else if (m_spellInfo->SpellFamilyFlags[1] & 0x100) + ApplyPct(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); + // Shockwave + else if (m_spellInfo->Id == 46968) { - // for caster applied auras only - if ((*i)->GetSpellInfo()->SpellFamilyName != SPELLFAMILY_WARLOCK || - (*i)->GetCasterGUID() != m_caster->GetGUID()) - continue; - - // Immolate - if ((*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x4) - { - aura = *i; // it selected always if exist - break; - } - - // Shadowflame - if ((*i)->GetSpellInfo()->SpellFamilyFlags[2] & 0x00000002) - aura = *i; // remember but wait possible Immolate as primary priority - } - - // found Immolate or Shadowflame - if (aura) - { - uint32 pdamage = uint32(std::max(aura->GetAmount(), 0)); - pdamage = unitTarget->SpellDamageBonusTaken(m_caster, aura->GetSpellInfo(), pdamage, DOT, aura->GetBase()->GetStackAmount()); - uint32 pct_dir = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 1)); - uint8 baseTotalTicks = uint8(m_caster->CalcSpellDuration(aura->GetSpellInfo()) / aura->GetSpellInfo()->Effects[EFFECT_0].Amplitude); - - damage += int32(CalculatePct(pdamage * baseTotalTicks, pct_dir)); - - uint32 pct_dot = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 2)) / 3; - m_spellValue->EffectBasePoints[1] = m_spellInfo->Effects[EFFECT_1].CalcBaseValue(int32(CalculatePct(pdamage * baseTotalTicks, pct_dot))); - - apply_direct_bonus = false; - // Glyph of Conflagrate - if (!m_caster->HasAura(56235)) - unitTarget->RemoveAurasDueToSpell(aura->GetId(), m_caster->GetGUID()); - + int32 pct = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, 2); + if (pct > 0) + damage += int32(CalculatePct(m_caster->GetTotalAttackPowerValue(BASE_ATTACK), pct)); break; } + break; } - // Shadow Bite - else if (m_spellInfo->SpellFamilyFlags[1] & 0x400000) + case SPELLFAMILY_WARLOCK: { - if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet()) + // Incinerate Rank 1 & 2 + if ((m_spellInfo->SpellFamilyFlags[1] & 0x000040) && m_spellInfo->SpellIconID == 2128) { - if (Player* owner = m_caster->GetOwner()->ToPlayer()) + // Incinerate does more dmg (dmg*0.25) if the target have Immolate debuff. + // Check aura state for speed but aura state set not only for Immolate spell + if (unitTarget->HasAuraState(AURA_STATE_CONFLAGRATE)) { - if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 214, 0)) + if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0)) + damage += damage / 4; + } + } + // Immolate - hidden delay for conflagrate + else if (m_spellInfo->SpellFamilyFlags[0] & 0x4) + { + } + // Conflagrate - consumes Immolate or Shadowflame + else if (m_spellInfo->TargetAuraState == AURA_STATE_CONFLAGRATE) + { + AuraEffect const* aura = nullptr; // found req. aura for damage calculation + + Unit::AuraEffectList const& mPeriodic = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE); + for (Unit::AuraEffectList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i) + { + // for caster applied auras only + if ((*i)->GetSpellInfo()->SpellFamilyName != SPELLFAMILY_WARLOCK || + (*i)->GetCasterGUID() != m_caster->GetGUID()) + continue; + + // Immolate + if ((*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x4) { - int32 bp0 = aurEff->GetId() == 54037 ? 4 : 8; - m_caster->CastCustomSpell(m_caster, 54425, &bp0, nullptr, nullptr, true); + aura = *i; // it selected always if exist + break; + } + + // Shadowflame + if ((*i)->GetSpellInfo()->SpellFamilyFlags[2] & 0x00000002) + aura = *i; // remember but wait possible Immolate as primary priority + } + + // found Immolate or Shadowflame + if (aura) + { + uint32 pdamage = uint32(std::max(aura->GetAmount(), 0)); + pdamage = unitTarget->SpellDamageBonusTaken(m_caster, aura->GetSpellInfo(), pdamage, DOT, aura->GetBase()->GetStackAmount()); + uint32 pct_dir = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 1)); + uint8 baseTotalTicks = uint8(m_caster->CalcSpellDuration(aura->GetSpellInfo()) / aura->GetSpellInfo()->Effects[EFFECT_0].Amplitude); + + damage += int32(CalculatePct(pdamage * baseTotalTicks, pct_dir)); + + uint32 pct_dot = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 2)) / 3; + m_spellValue->EffectBasePoints[1] = m_spellInfo->Effects[EFFECT_1].CalcBaseValue(int32(CalculatePct(pdamage * baseTotalTicks, pct_dot))); + + apply_direct_bonus = false; + // Glyph of Conflagrate + if (!m_caster->HasAura(56235)) + unitTarget->RemoveAurasDueToSpell(aura->GetId(), m_caster->GetGUID()); + + break; + } + } + // Shadow Bite + else if (m_spellInfo->SpellFamilyFlags[1] & 0x400000) + { + if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet()) + { + if (Player* owner = m_caster->GetOwner()->ToPlayer()) + { + if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 214, 0)) + { + int32 bp0 = aurEff->GetId() == 54037 ? 4 : 8; + m_caster->CastCustomSpell(m_caster, 54425, &bp0, nullptr, nullptr, true); + } } } } + break; } - break; - } case SPELLFAMILY_PRIEST: - { - // Improved Mind Blast (Mind Blast in shadow form bonus) - if (m_caster->GetShapeshiftForm() == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000)) { - Unit::AuraEffectList const& ImprMindBlast = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_FLAT_MODIFIER); - for (Unit::AuraEffectList::const_iterator i = ImprMindBlast.begin(); i != ImprMindBlast.end(); ++i) + // Improved Mind Blast (Mind Blast in shadow form bonus) + if (m_caster->GetShapeshiftForm() == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000)) { - if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_PRIEST && - ((*i)->GetSpellInfo()->SpellIconID == 95)) + Unit::AuraEffectList const& ImprMindBlast = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_FLAT_MODIFIER); + for (Unit::AuraEffectList::const_iterator i = ImprMindBlast.begin(); i != ImprMindBlast.end(); ++i) { - int chance = (*i)->GetSpellInfo()->Effects[EFFECT_1].CalcValue(m_caster); - if (roll_chance_i(chance)) - // Mind Trauma - m_caster->CastSpell(unitTarget, 48301, true, 0); - break; + if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_PRIEST && + ((*i)->GetSpellInfo()->SpellIconID == 95)) + { + int chance = (*i)->GetSpellInfo()->Effects[EFFECT_1].CalcValue(m_caster); + if (roll_chance_i(chance)) + // Mind Trauma + m_caster->CastSpell(unitTarget, 48301, true, 0); + break; + } } } + break; } - break; - } case SPELLFAMILY_DRUID: - { - // Ferocious Bite - if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->SpellFamilyFlags[0] & 0x000800000) && m_spellInfo->SpellVisual[0] == 6587) { - // converts each extra point of energy into ($f1+$AP/410) additional damage - float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); - float multiple = ap / 410 + m_spellInfo->Effects[effIndex].DamageMultiplier; - int32 energy = -(m_caster->ModifyPower(POWER_ENERGY, -30)); - damage += int32(energy * multiple); - damage += int32(CalculatePct(m_caster->ToPlayer()->GetComboPoints() * ap, 7)); - } - // Wrath - else if (m_spellInfo->SpellFamilyFlags[0] & 0x00000001) - { - // Improved Insect Swarm - if (AuraEffect const* aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) - if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00200000, 0, 0)) - AddPct(damage, aurEff->GetAmount()); - } - break; - } - case SPELLFAMILY_ROGUE: - { - // Envenom - if (m_spellInfo->SpellFamilyFlags[1] & 0x00000008) - { - if (Player* player = m_caster->ToPlayer()) + // Ferocious Bite + if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->SpellFamilyFlags[0] & 0x000800000) && m_spellInfo->SpellVisual[0] == 6587) { - // consume from stack dozes not more that have combo-points - if (uint32 combo = player->GetComboPoints()) + // converts each extra point of energy into ($f1+$AP/410) additional damage + float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); + float multiple = ap / 410 + m_spellInfo->Effects[effIndex].DamageMultiplier; + int32 energy = -(m_caster->ModifyPower(POWER_ENERGY, -30)); + damage += int32(energy * multiple); + damage += int32(CalculatePct(m_caster->ToPlayer()->GetComboPoints() * ap, 7)); + } + // Wrath + else if (m_spellInfo->SpellFamilyFlags[0] & 0x00000001) + { + // Improved Insect Swarm + if (AuraEffect const* aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) + if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00200000, 0, 0)) + AddPct(damage, aurEff->GetAmount()); + } + break; + } + case SPELLFAMILY_ROGUE: + { + // Envenom + if (m_spellInfo->SpellFamilyFlags[1] & 0x00000008) + { + if (Player* player = m_caster->ToPlayer()) { - // Lookup for Deadly poison (only attacker applied) - if (AuraEffect const* aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x00010000, 0, 0, m_caster->GetGUID())) + // consume from stack dozes not more that have combo-points + if (uint32 combo = player->GetComboPoints()) { - // count consumed deadly poison doses at target - bool needConsume = true; - uint32 spellId = aurEff->GetId(); - - uint32 doses = aurEff->GetBase()->GetStackAmount(); - if (doses > combo) - doses = combo; - - // Master Poisoner - Unit::AuraEffectList const& auraList = player->GetAuraEffectsByType(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK); - for (Unit::AuraEffectList::const_iterator iter = auraList.begin(); iter != auraList.end(); ++iter) + // Lookup for Deadly poison (only attacker applied) + if (AuraEffect const* aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x00010000, 0, 0, m_caster->GetGUID())) { - if ((*iter)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_ROGUE && (*iter)->GetSpellInfo()->SpellIconID == 1960) + // count consumed deadly poison doses at target + bool needConsume = true; + uint32 spellId = aurEff->GetId(); + + uint32 doses = aurEff->GetBase()->GetStackAmount(); + if (doses > combo) + doses = combo; + + // Master Poisoner + Unit::AuraEffectList const& auraList = player->GetAuraEffectsByType(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK); + for (Unit::AuraEffectList::const_iterator iter = auraList.begin(); iter != auraList.end(); ++iter) { - uint32 chance = (*iter)->GetSpellInfo()->Effects[EFFECT_2].CalcValue(m_caster); + if ((*iter)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_ROGUE && (*iter)->GetSpellInfo()->SpellIconID == 1960) + { + uint32 chance = (*iter)->GetSpellInfo()->Effects[EFFECT_2].CalcValue(m_caster); - if (chance && roll_chance_i(chance)) - needConsume = false; + if (chance && roll_chance_i(chance)) + needConsume = false; - break; + break; + } } + + if (needConsume) + for (uint32 i = 0; i < doses; ++i) + unitTarget->RemoveAuraFromStack(spellId, m_caster->GetGUID()); + + damage *= doses; + damage += int32(player->GetTotalAttackPowerValue(BASE_ATTACK) * 0.09f * combo); } - if (needConsume) - for (uint32 i = 0; i < doses; ++i) - unitTarget->RemoveAuraFromStack(spellId, m_caster->GetGUID()); - - damage *= doses; - damage += int32(player->GetTotalAttackPowerValue(BASE_ATTACK) * 0.09f * combo); + // Eviscerate and Envenom Bonus Damage (item set effect) + if (m_caster->HasAura(37169)) + damage += combo * 40; } - - // Eviscerate and Envenom Bonus Damage (item set effect) - if (m_caster->HasAura(37169)) - damage += combo * 40; } } - } - // Eviscerate - else if (m_spellInfo->SpellFamilyFlags[0] & 0x00020000) - { - if (m_caster->GetTypeId() == TYPEID_PLAYER) + // Eviscerate + else if (m_spellInfo->SpellFamilyFlags[0] & 0x00020000) { - if (uint32 combo = m_caster->ToPlayer()->GetComboPoints()) + if (m_caster->GetTypeId() == TYPEID_PLAYER) { - float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); - damage += int32(ap * combo * 0.07f); + if (uint32 combo = m_caster->ToPlayer()->GetComboPoints()) + { + float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); + damage += int32(ap * combo * 0.07f); - // Eviscerate and Envenom Bonus Damage (item set effect) - if (m_caster->HasAura(37169)) - damage += combo*40; + // Eviscerate and Envenom Bonus Damage (item set effect) + if (m_caster->HasAura(37169)) + damage += combo * 40; + } } } + break; } - break; - } case SPELLFAMILY_HUNTER: - { - //Gore - if (m_spellInfo->SpellIconID == 1578) { - if (m_caster->HasAura(57627)) // Charge 6 sec post-affect - damage *= 2; - } - // Steady Shot - else if (m_spellInfo->SpellFamilyFlags[1] & 0x1) - { - bool found = false; - // check dazed affect - Unit::AuraEffectList const& decSpeedList = unitTarget->GetAuraEffectsByType(SPELL_AURA_MOD_DECREASE_SPEED); - for (Unit::AuraEffectList::const_iterator iter = decSpeedList.begin(); iter != decSpeedList.end(); ++iter) + //Gore + if (m_spellInfo->SpellIconID == 1578) { - if ((*iter)->GetSpellInfo()->SpellIconID == 15 && (*iter)->GetSpellInfo()->Dispel == 0) + if (m_caster->HasAura(57627)) // Charge 6 sec post-affect + damage *= 2; + } + // Steady Shot + else if (m_spellInfo->SpellFamilyFlags[1] & 0x1) + { + bool found = false; + // check dazed affect + Unit::AuraEffectList const& decSpeedList = unitTarget->GetAuraEffectsByType(SPELL_AURA_MOD_DECREASE_SPEED); + for (Unit::AuraEffectList::const_iterator iter = decSpeedList.begin(); iter != decSpeedList.end(); ++iter) { - found = true; - break; - } - } - - // TODO: should this be put on taken but not done? - if (found) - damage += m_spellInfo->Effects[EFFECT_1].CalcValue(); - - if (Player* caster = m_caster->ToPlayer()) - { - // Add Ammo and Weapon damage plus RAP * 0.1 - if (Item* item = caster->GetWeaponForAttack(RANGED_ATTACK)) - { - ItemTemplate const* weaponTemplate = item->GetTemplate(); - float dmg_min = weaponTemplate->Damage[0].DamageMin; - float dmg_max = weaponTemplate->Damage[0].DamageMax; - if (dmg_max == 0.0f && dmg_min > dmg_max) - damage += int32(dmg_min); - else - damage += irand(int32(dmg_min), int32(dmg_max)); - damage += int32(caster->GetAmmoDPS() * weaponTemplate->Delay * 0.001f); + if ((*iter)->GetSpellInfo()->SpellIconID == 15 && (*iter)->GetSpellInfo()->Dispel == 0) + { + found = true; + break; + } + } + + // TODO: should this be put on taken but not done? + if (found) + damage += m_spellInfo->Effects[EFFECT_1].CalcValue(); + + if (Player* caster = m_caster->ToPlayer()) + { + // Add Ammo and Weapon damage plus RAP * 0.1 + if (Item* item = caster->GetWeaponForAttack(RANGED_ATTACK)) + { + ItemTemplate const* weaponTemplate = item->GetTemplate(); + float dmg_min = weaponTemplate->Damage[0].DamageMin; + float dmg_max = weaponTemplate->Damage[0].DamageMax; + if (dmg_max == 0.0f && dmg_min > dmg_max) + damage += int32(dmg_min); + else + damage += irand(int32(dmg_min), int32(dmg_max)); + damage += int32(caster->GetAmmoDPS() * weaponTemplate->Delay * 0.001f); + } } } + break; } - break; - } case SPELLFAMILY_PALADIN: - { - // Hammer of the Righteous - if (m_spellInfo->SpellFamilyFlags[1]&0x00040000) { - // Add main hand dps * effect[2] amount - if (Player* player = m_caster->ToPlayer()) + // Hammer of the Righteous + if (m_spellInfo->SpellFamilyFlags[1] & 0x00040000) { - float mindamage, maxdamage; - player->CalculateMinMaxDamage(BASE_ATTACK, false, false, mindamage, maxdamage); - float average = (mindamage + maxdamage) / 2; - int32 count = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, EFFECT_2); - damage += count * int32(average * IN_MILLISECONDS) / m_caster->GetAttackTime(BASE_ATTACK); + // Add main hand dps * effect[2] amount + if (Player* player = m_caster->ToPlayer()) + { + float mindamage, maxdamage; + player->CalculateMinMaxDamage(BASE_ATTACK, false, false, mindamage, maxdamage); + float average = (mindamage + maxdamage) / 2; + int32 count = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, EFFECT_2); + damage += count * int32(average * IN_MILLISECONDS) / m_caster->GetAttackTime(BASE_ATTACK); + } + break; + } + // Shield of Righteousness + if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x100000) + { + uint8 level = m_caster->getLevel(); + uint32 block_value = m_caster->GetShieldBlockValue(uint32(float(level) * 29.5f), uint32(float(level) * 34.5f)); + if (m_caster->GetAuraEffect(64882, EFFECT_0)) + block_value += 225; + damage += CalculatePct(block_value, m_spellInfo->Effects[EFFECT_1].CalcValue()); + break; } break; } - // Shield of Righteousness - if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x100000) - { - uint8 level = m_caster->getLevel(); - uint32 block_value = m_caster->GetShieldBlockValue(uint32(float(level) * 29.5f), uint32(float(level) * 34.5f)); - if (m_caster->GetAuraEffect(64882, EFFECT_0)) - block_value += 225; - damage += CalculatePct(block_value, m_spellInfo->Effects[EFFECT_1].CalcValue()); - break; - } - break; - } } if (m_originalCaster /*&& damage > 0 Xinef: this can be increased from 0*/ && apply_direct_bonus) @@ -682,80 +682,80 @@ void Spell::EffectDummy(SpellEffIndex effIndex) switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - switch (m_spellInfo->Id) { - // Trial of the Champion, Trample - case 67866: + switch (m_spellInfo->Id) { - if( unitTarget && !unitTarget->IsVehicle() && !unitTarget->GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID) ) - unitTarget->CastSpell(unitTarget, 67867, false); - return; - } - // Trial of the Champion, Hammer of the Righteous - case 66867: - { - if( !unitTarget ) - return; - if( unitTarget->HasAura(66940) ) - m_caster->CastSpell(unitTarget, 66903, true); - else - m_caster->CastSpell(unitTarget, 66904, true); - return; - } - case 17731: - case 69294: - { - if( !gameObjTarget || gameObjTarget->GetRespawnTime() > time(nullptr) ) - return; + // Trial of the Champion, Trample + case 67866: + { + if( unitTarget && !unitTarget->IsVehicle() && !unitTarget->GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID) ) + unitTarget->CastSpell(unitTarget, 67867, false); + return; + } + // Trial of the Champion, Hammer of the Righteous + case 66867: + { + if( !unitTarget ) + return; + if( unitTarget->HasAura(66940) ) + m_caster->CastSpell(unitTarget, 66903, true); + else + m_caster->CastSpell(unitTarget, 66904, true); + return; + } + case 17731: + case 69294: + { + if( !gameObjTarget || gameObjTarget->GetRespawnTime() > time(nullptr) ) + return; - gameObjTarget->SetRespawnTime(10); - gameObjTarget->SendCustomAnim(gameObjTarget->GetGoAnimProgress()); - if( Creature* trigger = gameObjTarget->SummonCreature(12758, *gameObjTarget, TEMPSUMMON_TIMED_DESPAWN, 1000) ) - trigger->CastSpell(trigger, 17731, false); + gameObjTarget->SetRespawnTime(10); + gameObjTarget->SendCustomAnim(gameObjTarget->GetGoAnimProgress()); + if( Creature* trigger = gameObjTarget->SummonCreature(12758, *gameObjTarget, TEMPSUMMON_TIMED_DESPAWN, 1000) ) + trigger->CastSpell(trigger, 17731, false); - return; - } - // HoL, Arc Weld - case 59086: - { - if( m_caster && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving() ) - m_caster->CastSpell(m_caster, 59097, true); + return; + } + // HoL, Arc Weld + case 59086: + { + if( m_caster && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving() ) + m_caster->CastSpell(m_caster, 59097, true); - return; + return; + } } + break; } - break; - } case SPELLFAMILY_PALADIN: switch (m_spellInfo->Id) { case 31789: // Righteous Defense (step 1) - { - if (!unitTarget) - return; - // not empty (checked), copy - Unit::AttackerSet attackers = unitTarget->getAttackers(); - - // remove invalid attackers - for (Unit::AttackerSet::iterator aItr = attackers.begin(); aItr != attackers.end();) - if (!(*aItr)->IsValidAttackTarget(m_caster)) - aItr = attackers.erase(aItr); - else - ++aItr; - - // selected from list 3 - uint32 maxTargets = std::min(3, attackers.size()); - for (uint32 i = 0; i < maxTargets; ++i) { - Unit::AttackerSet::iterator aItr = attackers.begin(); - std::advance(aItr, urand(0, attackers.size() - 1)); - m_caster->CastSpell((*aItr), 31790, true); - attackers.erase(aItr); - } + if (!unitTarget) + return; + // not empty (checked), copy + Unit::AttackerSet attackers = unitTarget->getAttackers(); - return; - } + // remove invalid attackers + for (Unit::AttackerSet::iterator aItr = attackers.begin(); aItr != attackers.end();) + if (!(*aItr)->IsValidAttackTarget(m_caster)) + aItr = attackers.erase(aItr); + else + ++aItr; + + // selected from list 3 + uint32 maxTargets = std::min(3, attackers.size()); + for (uint32 i = 0; i < maxTargets; ++i) + { + Unit::AttackerSet::iterator aItr = attackers.begin(); + std::advance(aItr, urand(0, attackers.size() - 1)); + m_caster->CastSpell((*aItr), 31790, true); + attackers.erase(aItr); + } + + return; + } } break; case SPELLFAMILY_ROGUE: @@ -793,121 +793,121 @@ void Spell::EffectDummy(SpellEffIndex effIndex) void Spell::EffectTriggerSpell(SpellEffIndex effIndex) { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET - && effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH) + && effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH) return; uint32 triggered_spell_id = m_spellInfo->Effects[effIndex].TriggerSpell; // todo: move those to spell scripts if (m_spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_TRIGGER_SPELL - && effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET) + && effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET) { // special cases switch (triggered_spell_id) { // Mirror Image case 58832: - { - // Glyph of Mirror Image - if (m_caster->HasAura(63093)) - m_caster->CastSpell(m_caster, 65047, true); // Mirror Image + { + // Glyph of Mirror Image + if (m_caster->HasAura(63093)) + m_caster->CastSpell(m_caster, 65047, true); // Mirror Image - break; - } + break; + } // Vanish (not exist) case 18461: - { - unitTarget->RemoveMovementImpairingAuras(true); - unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); + { + unitTarget->RemoveMovementImpairingAuras(true); + unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); - // See if we already are stealthed. If so, we're done. - if (unitTarget->HasAura(1784)) + // See if we already are stealthed. If so, we're done. + if (unitTarget->HasAura(1784)) + return; + + // Reset cooldown on stealth if needed + if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->ToPlayer()->HasSpellCooldown(1784)) + unitTarget->ToPlayer()->RemoveSpellCooldown(1784); + + unitTarget->CastSpell(unitTarget, 1784, true); return; - - // Reset cooldown on stealth if needed - if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->ToPlayer()->HasSpellCooldown(1784)) - unitTarget->ToPlayer()->RemoveSpellCooldown(1784); - - unitTarget->CastSpell(unitTarget, 1784, true); - return; - } + } // Demonic Empowerment -- succubus case 54437: - { - unitTarget->RemoveMovementImpairingAuras(true); - unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); - unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STUN); + { + unitTarget->RemoveMovementImpairingAuras(true); + unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); + unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STUN); - // Cast Lesser Invisibility - unitTarget->CastSpell(unitTarget, 7870, true); - return; - } + // Cast Lesser Invisibility + unitTarget->CastSpell(unitTarget, 7870, true); + return; + } // just skip case 23770: // Sayge's Dark Fortune of * // not exist, common cooldown can be implemented in scripts if need. return; // Brittle Armor - (need add max stack of 24575 Brittle Armor) case 29284: - { - // Brittle Armor - SpellInfo const* spell = sSpellMgr->GetSpellInfo(24575); - if (!spell) - return; + { + // Brittle Armor + SpellInfo const* spell = sSpellMgr->GetSpellInfo(24575); + if (!spell) + return; - for (uint32 j = 0; j < spell->StackAmount; ++j) - m_caster->CastSpell(unitTarget, spell->Id, true); - return; - } + for (uint32 j = 0; j < spell->StackAmount; ++j) + m_caster->CastSpell(unitTarget, spell->Id, true); + return; + } // Mercurial Shield - (need add max stack of 26464 Mercurial Shield) case 29286: - { - // Mercurial Shield - SpellInfo const* spell = sSpellMgr->GetSpellInfo(26464); - if (!spell) - return; + { + // Mercurial Shield + SpellInfo const* spell = sSpellMgr->GetSpellInfo(26464); + if (!spell) + return; - for (uint32 j = 0; j < spell->StackAmount; ++j) - m_caster->CastSpell(unitTarget, spell->Id, true); - return; - } + for (uint32 j = 0; j < spell->StackAmount; ++j) + m_caster->CastSpell(unitTarget, spell->Id, true); + return; + } // Cloak of Shadows case 35729: - { - uint32 dispelMask = SpellInfo::GetDispelMask(DISPEL_ALL); - Unit::AuraApplicationMap& Auras = unitTarget->GetAppliedAuras(); - for (Unit::AuraApplicationMap::iterator iter = Auras.begin(); iter != Auras.end();) { - // remove all harmful spells on you... - SpellInfo const* spell = iter->second->GetBase()->GetSpellInfo(); - - bool dmgClassNone = false; - if (spell->DmgClass == SPELL_DAMAGE_CLASS_NONE && spell->SpellFamilyName == SPELLFAMILY_GENERIC) - for (uint8 i = EFFECT_0; i < MAX_SPELL_EFFECTS; ++i) - { - if ((iter->second->GetEffectMask() & (1<Effects[i].ApplyAuraName != SPELL_AURA_PERIODIC_DAMAGE && - spell->Effects[i].ApplyAuraName != SPELL_AURA_PERIODIC_TRIGGER_SPELL && - spell->Effects[i].ApplyAuraName != SPELL_AURA_DUMMY) - { - dmgClassNone = false; - break; - } - dmgClassNone = true; - } - - if ((spell->DmgClass == SPELL_DAMAGE_CLASS_MAGIC || (spell->GetDispelMask() & dispelMask) || dmgClassNone) && - // ignore positive and passive auras - !iter->second->IsPositive() && !iter->second->GetBase()->IsPassive() && - // Xinef: Ignore NPC spells having INVULNERABILITY attribute - (!spell->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) || spell->SpellFamilyName != SPELLFAMILY_GENERIC)) + uint32 dispelMask = SpellInfo::GetDispelMask(DISPEL_ALL); + Unit::AuraApplicationMap& Auras = unitTarget->GetAppliedAuras(); + for (Unit::AuraApplicationMap::iterator iter = Auras.begin(); iter != Auras.end();) { - m_caster->RemoveAura(iter); + // remove all harmful spells on you... + SpellInfo const* spell = iter->second->GetBase()->GetSpellInfo(); + + bool dmgClassNone = false; + if (spell->DmgClass == SPELL_DAMAGE_CLASS_NONE && spell->SpellFamilyName == SPELLFAMILY_GENERIC) + for (uint8 i = EFFECT_0; i < MAX_SPELL_EFFECTS; ++i) + { + if ((iter->second->GetEffectMask() & (1 << i)) && + spell->Effects[i].ApplyAuraName != SPELL_AURA_PERIODIC_DAMAGE && + spell->Effects[i].ApplyAuraName != SPELL_AURA_PERIODIC_TRIGGER_SPELL && + spell->Effects[i].ApplyAuraName != SPELL_AURA_DUMMY) + { + dmgClassNone = false; + break; + } + dmgClassNone = true; + } + + if ((spell->DmgClass == SPELL_DAMAGE_CLASS_MAGIC || (spell->GetDispelMask() & dispelMask) || dmgClassNone) && + // ignore positive and passive auras + !iter->second->IsPositive() && !iter->second->GetBase()->IsPassive() && + // Xinef: Ignore NPC spells having INVULNERABILITY attribute + (!spell->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) || spell->SpellFamilyName != SPELLFAMILY_GENERIC)) + { + m_caster->RemoveAura(iter); + } + else + ++iter; } - else - ++iter; + return; } - return; - } // Spell Lock, handled in interrupt effect // launch is handled before hit triggers, thus silence removes current casted spell // and interrupt is unable to detect any cast and doesnt work @@ -959,17 +959,17 @@ void Spell::EffectTriggerSpell(SpellEffIndex effIndex) // Remove spell cooldown (not category) if spell triggering spell with cooldown and same category if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->CategoryRecoveryTime && spellInfo->CategoryRecoveryTime - && m_spellInfo->GetCategory() == spellInfo->GetCategory()) + && m_spellInfo->GetCategory() == spellInfo->GetCategory()) m_caster->ToPlayer()->RemoveSpellCooldown(spellInfo->Id); // original caster guid only for GO cast - m_caster->CastSpell(targets, spellInfo, &values, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_NO_PERIODIC_RESET), nullptr, nullptr, m_originalCasterGUID); + m_caster->CastSpell(targets, spellInfo, &values, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_NO_PERIODIC_RESET), nullptr, nullptr, m_originalCasterGUID); } void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET - && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) + && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; uint32 triggered_spell_id = m_spellInfo->Effects[effIndex].TriggerSpell; @@ -1014,7 +1014,7 @@ void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) // Remove spell cooldown (not category) if spell triggering spell with cooldown and same category if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->CategoryRecoveryTime && spellInfo->CategoryRecoveryTime - && m_spellInfo->GetCategory() == spellInfo->GetCategory()) + && m_spellInfo->GetCategory() == spellInfo->GetCategory()) m_caster->ToPlayer()->RemoveSpellCooldown(spellInfo->Id); // original caster guid only for GO cast @@ -1135,7 +1135,7 @@ void Spell::EffectJumpDest(SpellEffIndex effIndex) // Override, calculations are incorrect if (m_spellInfo->Id == 49376) // feral charge { - speedXY = pow(speedZ*10, 2); + speedXY = pow(speedZ * 10, 2); m_caster->GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ, 0, ObjectAccessor::GetUnit(*m_caster, m_caster->GetUInt64Value(UNIT_FIELD_TARGET))); return; } @@ -1152,12 +1152,12 @@ void Spell::EffectJumpDest(SpellEffIndex effIndex) m_caster->GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ); } -void Spell::CalculateJumpSpeeds(uint8 i, float dist, float & speedXY, float & speedZ) +void Spell::CalculateJumpSpeeds(uint8 i, float dist, float& speedXY, float& speedZ) { if (m_spellInfo->Effects[i].MiscValue) - speedZ = float(m_spellInfo->Effects[i].MiscValue)/10; + speedZ = float(m_spellInfo->Effects[i].MiscValue) / 10; else if (m_spellInfo->Effects[i].MiscValueB) - speedZ = float(m_spellInfo->Effects[i].MiscValueB)/10; + speedZ = float(m_spellInfo->Effects[i].MiscValueB) / 10; else speedZ = 10.0f; speedXY = dist * 10.0f / speedZ; @@ -1229,95 +1229,95 @@ void Spell::EffectTeleportUnits(SpellEffIndex /*effIndex*/) { // Dimensional Ripper - Everlook case 23442: - { - int32 r = irand(0, 119); - if (r >= 70) // 7/12 success { - if (r < 100) // 4/12 evil twin - m_caster->CastSpell(m_caster, 23445, true); - else // 1/12 fire - m_caster->CastSpell(m_caster, 23449, true); + int32 r = irand(0, 119); + if (r >= 70) // 7/12 success + { + if (r < 100) // 4/12 evil twin + m_caster->CastSpell(m_caster, 23445, true); + else // 1/12 fire + m_caster->CastSpell(m_caster, 23449, true); + } + return; } - return; - } // Ultrasafe Transporter: Toshley's Station case 36941: - { - if (roll_chance_i(50)) // 50% success { - int32 rand_eff = urand(1, 7); - switch (rand_eff) + if (roll_chance_i(50)) // 50% success { - case 1: - // soul split - evil - m_caster->CastSpell(m_caster, 36900, true); - break; - case 2: - // soul split - good - m_caster->CastSpell(m_caster, 36901, true); - break; - case 3: - // Increase the size - m_caster->CastSpell(m_caster, 36895, true); - break; - case 4: - // Decrease the size - m_caster->CastSpell(m_caster, 36893, true); - break; - case 5: - // Transform + int32 rand_eff = urand(1, 7); + switch (rand_eff) { - if (m_caster->ToPlayer()->GetTeamId() == TEAM_ALLIANCE) - m_caster->CastSpell(m_caster, 36897, true); - else - m_caster->CastSpell(m_caster, 36899, true); - break; + case 1: + // soul split - evil + m_caster->CastSpell(m_caster, 36900, true); + break; + case 2: + // soul split - good + m_caster->CastSpell(m_caster, 36901, true); + break; + case 3: + // Increase the size + m_caster->CastSpell(m_caster, 36895, true); + break; + case 4: + // Decrease the size + m_caster->CastSpell(m_caster, 36893, true); + break; + case 5: + // Transform + { + if (m_caster->ToPlayer()->GetTeamId() == TEAM_ALLIANCE) + m_caster->CastSpell(m_caster, 36897, true); + else + m_caster->CastSpell(m_caster, 36899, true); + break; + } + case 6: + // chicken + m_caster->CastSpell(m_caster, 36940, true); + break; + case 7: + // evil twin + m_caster->CastSpell(m_caster, 23445, true); + break; } - case 6: - // chicken - m_caster->CastSpell(m_caster, 36940, true); - break; - case 7: - // evil twin - m_caster->CastSpell(m_caster, 23445, true); - break; } + return; } - return; - } // Dimensional Ripper - Area 52 case 36890: - { - if (roll_chance_i(50)) // 50% success { - int32 rand_eff = urand(1, 4); - switch (rand_eff) + if (roll_chance_i(50)) // 50% success { - case 1: - // soul split - evil - m_caster->CastSpell(m_caster, 36900, true); - break; - case 2: - // soul split - good - m_caster->CastSpell(m_caster, 36901, true); - break; - case 3: - // Increase the size - m_caster->CastSpell(m_caster, 36895, true); - break; - case 4: - // Transform + int32 rand_eff = urand(1, 4); + switch (rand_eff) { - if (m_caster->ToPlayer()->GetTeamId() == TEAM_ALLIANCE) - m_caster->CastSpell(m_caster, 36897, true); - else - m_caster->CastSpell(m_caster, 36899, true); - break; + case 1: + // soul split - evil + m_caster->CastSpell(m_caster, 36900, true); + break; + case 2: + // soul split - good + m_caster->CastSpell(m_caster, 36901, true); + break; + case 3: + // Increase the size + m_caster->CastSpell(m_caster, 36895, true); + break; + case 4: + // Transform + { + if (m_caster->ToPlayer()->GetTeamId() == TEAM_ALLIANCE) + m_caster->CastSpell(m_caster, 36897, true); + else + m_caster->CastSpell(m_caster, 36899, true); + break; + } } } + return; } - return; - } } } @@ -1391,7 +1391,7 @@ void Spell::EffectPowerDrain(SpellEffIndex effIndex) { gainMultiplier = m_spellInfo->Effects[effIndex].CalcValueMultiplier(m_originalCaster, this); - int32 gain = int32(newDamage* gainMultiplier); + int32 gain = int32(newDamage * gainMultiplier); m_caster->EnergizeBySpell(m_caster, m_spellInfo->Id, gain, powerType); } @@ -1402,7 +1402,7 @@ void Spell::EffectSendEvent(SpellEffIndex effIndex) { // we do not handle a flag dropping or clicking on flag in battleground by sendevent system if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET - && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) + && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; WorldObject* target = nullptr; @@ -1478,7 +1478,7 @@ void Spell::EffectPowerBurn(SpellEffIndex effIndex) // add log data before multiplication (need power amount, not damage) ExecuteLogEffectTakeTargetPower(effIndex, unitTarget, powerType, newDamage, 0.0f); - newDamage = int32(newDamage* dmgMultiplier); + newDamage = int32(newDamage * dmgMultiplier); m_damage += newDamage; } @@ -1506,7 +1506,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) int damageAmount = 0; if (AuraEffect const* aurEff = m_caster->GetAuraEffect(45062, 0)) { - damageAmount+= aurEff->GetAmount(); + damageAmount += aurEff->GetAmount(); m_caster->RemoveAurasDueToSpell(45062); } @@ -1529,7 +1529,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) for (Unit::AuraEffectList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i) { if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID - && (*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x50) + && (*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x50) { if (m_caster->GetGUID() == (*i)->GetCasterGUID()) { @@ -1773,7 +1773,7 @@ void Spell::DoCreateItem(uint8 /*effIndex*/, uint32 itemId) // send info to the client player->SendNewItem(pItem, addNumber, true, SelfCast); - + sScriptMgr->OnCreateItem(player, pItem, addNumber); // we succeeded in creating at least one item, so a levelup is possible @@ -1890,7 +1890,7 @@ void Spell::EffectEnergize(SpellEffIndex effIndex) Powers power = Powers(m_spellInfo->Effects[effIndex].MiscValue); if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->getPowerType() != power && m_spellInfo->SpellFamilyName != SPELLFAMILY_POTION - && !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER)) + && !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER)) return; if (unitTarget->GetMaxPower(power) == 0) @@ -1922,12 +1922,12 @@ void Spell::EffectEnergize(SpellEffIndex effIndex) damage = int32(CalculatePct(unitTarget->GetMaxPower(power), damage)); break; case 67490: // Runic Mana Injector (mana gain increased by 25% for engineers - 3.2.0 patch change) - { - if (Player* player = m_caster->ToPlayer()) - if (player->HasSkill(SKILL_ENGINEERING)) - AddPct(damage, 25); - break; - } + { + if (Player* player = m_caster->ToPlayer()) + if (player->HasSkill(SKILL_ENGINEERING)) + AddPct(damage, 25); + break; + } case 71132: // Glyph of Shadow Word: Pain damage = int32(CalculatePct(unitTarget->GetCreateMana(), 1)); // set 1 as value, missing in dbc break; @@ -2069,7 +2069,7 @@ void Spell::SendLoot(uint64 guid, LootType loottype) if (uint32 trapEntry = gameObjTarget->GetGOInfo()->chest.linkedTrapId) gameObjTarget->TriggeringLinkedGameObject(trapEntry, m_caster); - // Don't return, let loots been taken + // Don't return, let loots been taken default: break; } @@ -2103,7 +2103,7 @@ void Spell::EffectOpenLock(SpellEffIndex effIndex) GameObjectTemplate const* goInfo = gameObjTarget->GetGOInfo(); // Arathi Basin banner opening. // TODO: Verify correctness of this check if ((goInfo->type == GAMEOBJECT_TYPE_BUTTON && goInfo->button.noDamageImmune) || - (goInfo->type == GAMEOBJECT_TYPE_GOOBER && goInfo->goober.losOK)) + (goInfo->type == GAMEOBJECT_TYPE_GOOBER && goInfo->goober.losOK)) { //CanUseBattlegroundObject() already called in CheckCast() // in battleground check @@ -2128,7 +2128,7 @@ void Spell::EffectOpenLock(SpellEffIndex effIndex) { gameObjTarget->SetLootState(GO_JUST_DEACTIVATED); if (!gameObjTarget->GetOwner()) // pussywizard - gameObjTarget->SetRespawnTime(gameObjTarget->GetGOInfo()->GetAutoCloseTime()/IN_MILLISECONDS/*xinef*/); + gameObjTarget->SetRespawnTime(gameObjTarget->GetGOInfo()->GetAutoCloseTime() / IN_MILLISECONDS/*xinef*/); return; } // TODO: Add script for spell 41920 - Filling, becouse server it freze when use this spell @@ -2182,7 +2182,7 @@ void Spell::EffectOpenLock(SpellEffIndex effIndex) { // Allow one skill-up until respawned if (!gameObjTarget->IsInSkillupList(player->GetGUIDLow()) && - player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue)) + player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue)) gameObjTarget->AddToSkillupList(player->GetGUIDLow()); } else if (itemTarget) @@ -2404,76 +2404,76 @@ void Spell::EffectSummonType(SpellEffIndex effIndex) break; case SUMMON_TYPE_LIGHTWELL: case SUMMON_TYPE_TOTEM: - { - // protection code - summon = m_caster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, m_originalCaster, m_spellInfo->Id); - if (!summon || !summon->IsTotem()) - return; - - // Mana Tide Totem - if (m_spellInfo->Id == 16190) - damage = m_caster->CountPctFromMaxHealth(10); - - if (damage && properties->Type != SUMMON_TYPE_LIGHTWELL) // Health set in script for lightwell { - summon->SetMaxHealth(damage); - summon->SetHealth(damage); + // protection code + summon = m_caster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, m_originalCaster, m_spellInfo->Id); + if (!summon || !summon->IsTotem()) + return; + + // Mana Tide Totem + if (m_spellInfo->Id == 16190) + damage = m_caster->CountPctFromMaxHealth(10); + + if (damage && properties->Type != SUMMON_TYPE_LIGHTWELL) // Health set in script for lightwell + { + summon->SetMaxHealth(damage); + summon->SetHealth(damage); + } + break; } - break; - } case SUMMON_TYPE_JEEVES: case SUMMON_TYPE_MINIPET: - { - summon = m_caster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, m_originalCaster, m_spellInfo->Id); - if (!summon || !summon->HasUnitTypeMask(UNIT_MASK_MINION)) - return; - - summon->SelectLevel(); // some summoned creaters have different from 1 DB data for level/hp - summon->SetUInt32Value(UNIT_NPC_FLAGS, summon->GetCreatureTemplate()->npcflag); - - summon->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); - summon->SetReactState(REACT_PASSIVE); - - // Xinef: Pet can have some auras in creature_addon or in scripts, do not remove them instantly - //summon->AI()->EnterEvadeMode(); - if (properties->Type != SUMMON_TYPE_JEEVES) { - summon->GetMotionMaster()->Clear(false); - summon->GetMotionMaster()->MoveFollow(m_originalCaster, PET_FOLLOW_DIST, summon->GetFollowAngle(), MOTION_SLOT_ACTIVE); - } - break; - } - default: - { - float radius = m_spellInfo->Effects[effIndex].CalcRadius(); + summon = m_caster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, m_originalCaster, m_spellInfo->Id); + if (!summon || !summon->HasUnitTypeMask(UNIT_MASK_MINION)) + return; - TempSummonType summonType = (duration <= 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; + summon->SelectLevel(); // some summoned creaters have different from 1 DB data for level/hp + summon->SetUInt32Value(UNIT_NPC_FLAGS, summon->GetCreatureTemplate()->npcflag); - for (uint32 count = 0; count < numSummons; ++count) - { - Position pos; - if (count == 0) - pos = *destTarget; - else - // randomize position for multiple summons - m_caster->GetRandomPoint(*destTarget, radius, pos); + summon->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + summon->SetReactState(REACT_PASSIVE); - summon = m_originalCaster->SummonCreature(entry, pos, summonType, duration); - if (!summon) - continue; - - summon->SetTempSummonType(summonType); - - if (properties->Category == SUMMON_CATEGORY_ALLY) + // Xinef: Pet can have some auras in creature_addon or in scripts, do not remove them instantly + //summon->AI()->EnterEvadeMode(); + if (properties->Type != SUMMON_TYPE_JEEVES) { - summon->SetOwnerGUID(m_originalCaster->GetGUID()); - summon->setFaction(m_originalCaster->getFaction()); + summon->GetMotionMaster()->Clear(false); + summon->GetMotionMaster()->MoveFollow(m_originalCaster, PET_FOLLOW_DIST, summon->GetFollowAngle(), MOTION_SLOT_ACTIVE); } - - ExecuteLogEffectSummonObject(effIndex, summon); + break; + } + default: + { + float radius = m_spellInfo->Effects[effIndex].CalcRadius(); + + TempSummonType summonType = (duration <= 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; + + for (uint32 count = 0; count < numSummons; ++count) + { + Position pos; + if (count == 0) + pos = *destTarget; + else + // randomize position for multiple summons + m_caster->GetRandomPoint(*destTarget, radius, pos); + + summon = m_originalCaster->SummonCreature(entry, pos, summonType, duration); + if (!summon) + continue; + + summon->SetTempSummonType(summonType); + + if (properties->Category == SUMMON_CATEGORY_ALLY) + { + summon->SetOwnerGUID(m_originalCaster->GetGUID()); + summon->setFaction(m_originalCaster->getFaction()); + } + + ExecuteLogEffectSummonObject(effIndex, summon); + } + return; } - return; - } }//switch break; case SUMMON_CATEGORY_PET: @@ -2491,7 +2491,7 @@ void Spell::EffectSummonType(SpellEffIndex effIndex) //float x, y, z; //m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); // xinef: vehicles summoned in air, eg. Cold Hearted quest - if (fabs(m_caster->GetPositionZ()-destTarget->GetPositionZ()) > 6.0f) + if (fabs(m_caster->GetPositionZ() - destTarget->GetPositionZ()) > 6.0f) destTarget->m_positionZ = m_caster->GetPositionZ(); summon = m_originalCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, m_caster, m_spellInfo->Id); @@ -2576,7 +2576,7 @@ void Spell::EffectDispel(SpellEffIndex effIndex) // Ok if exist some buffs for dispel try dispel it uint32 failCount = 0; DispelChargesList success_list; - WorldPacket dataFail(SMSG_DISPEL_FAILED, 8+8+4+4+damage*4); + WorldPacket dataFail(SMSG_DISPEL_FAILED, 8 + 8 + 4 + 4 + damage * 4); // dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && !dispel_list.empty();) { @@ -2636,7 +2636,7 @@ void Spell::EffectDispel(SpellEffIndex effIndex) if (success_list.empty()) return; - WorldPacket dataSuccess(SMSG_SPELLDISPELLOG, 8+8+4+1+4+success_list.size()*5); + WorldPacket dataSuccess(SMSG_SPELLDISPELLOG, 8 + 8 + 4 + 1 + 4 + success_list.size() * 5); // Send packet header dataSuccess.append(unitTarget->GetPackGUID()); // Victim GUID dataSuccess.append(m_caster->GetPackGUID()); // Caster GUID @@ -2785,7 +2785,7 @@ void Spell::EffectLearnSkill(SpellEffIndex effIndex) uint32 skillid = m_spellInfo->Effects[effIndex].MiscValue; uint16 skillval = unitTarget->ToPlayer()->GetPureSkillValue(skillid); - unitTarget->ToPlayer()->SetSkill(skillid, m_spellInfo->Effects[effIndex].CalcValue(), skillval?skillval:1, damage*75); + unitTarget->ToPlayer()->SetSkill(skillid, m_spellInfo->Effects[effIndex].CalcValue(), skillval ? skillval : 1, damage * 75); } void Spell::EffectAddHonor(SpellEffIndex /*effIndex*/) @@ -2799,9 +2799,9 @@ void Spell::EffectAddHonor(SpellEffIndex /*effIndex*/) // not scale value for item based reward (/10 value expected) if (m_CastItem) { - unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage/10, false); + unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage / 10, false); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SpellEffect::AddHonor (spell_id %u) rewards %d honor points (item %u) for player: %u", m_spellInfo->Id, damage/10, m_CastItem->GetEntry(), unitTarget->ToPlayer()->GetGUIDLow()); + sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "SpellEffect::AddHonor (spell_id %u) rewards %d honor points (item %u) for player: %u", m_spellInfo->Id, damage / 10, m_CastItem->GetEntry(), unitTarget->ToPlayer()->GetGUIDLow()); #endif return; } @@ -2855,10 +2855,10 @@ void Spell::EffectEnchantItemPerm(SpellEffIndex effIndex) // destroy one vellum from stack uint32 count = 1; p_caster->DestroyItemCount(itemTarget, count, true); - unitTarget=p_caster; + unitTarget = p_caster; // and add a scroll DoCreateItem(effIndex, m_spellInfo->Effects[effIndex].ItemType); - itemTarget=NULL; + itemTarget = NULL; m_targets.SetItemTarget(nullptr); } else @@ -2925,7 +2925,7 @@ void Spell::EffectEnchantItemPrismatic(SpellEffIndex effIndex) if (!add_socket) { sLog->outError("Spell::EffectEnchantItemPrismatic: attempt apply enchant spell %u with SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC (%u) but without ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET (%u), not suppoted yet.", - m_spellInfo->Id, SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC, ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET); + m_spellInfo->Id, SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC, ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET); return; } } @@ -2970,17 +2970,33 @@ void Spell::EffectEnchantItemTmp(SpellEffIndex effIndex) switch (damage) { // Rank 1 - case 2: spell_id = 36744; break; // 0% [ 7% == 2, 14% == 2, 20% == 2] + case 2: + spell_id = 36744; + break; // 0% [ 7% == 2, 14% == 2, 20% == 2] // Rank 2 - case 4: spell_id = 36753; break; // 0% [ 7% == 4, 14% == 4] - case 5: spell_id = 36751; break; // 20% + case 4: + spell_id = 36753; + break; // 0% [ 7% == 4, 14% == 4] + case 5: + spell_id = 36751; + break; // 20% // Rank 3 - case 6: spell_id = 36754; break; // 0% [ 7% == 6, 14% == 6] - case 7: spell_id = 36755; break; // 20% + case 6: + spell_id = 36754; + break; // 0% [ 7% == 6, 14% == 6] + case 7: + spell_id = 36755; + break; // 20% // Rank 4 - case 9: spell_id = 36761; break; // 0% [ 7% == 6] - case 10: spell_id = 36758; break; // 14% - case 11: spell_id = 36760; break; // 20% + case 9: + spell_id = 36761; + break; // 0% [ 7% == 6] + case 10: + spell_id = 36758; + break; // 14% + case 11: + spell_id = 36760; + break; // 20% default: sLog->outError("Spell::EffectEnchantItemTmp: Damage %u not handled in S'RW", damage); return; @@ -3130,7 +3146,7 @@ void Spell::EffectSummonPet(SpellEffIndex effIndex) { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; - + if (!m_originalCaster) return; @@ -3186,7 +3202,7 @@ void Spell::EffectSummonPet(SpellEffIndex effIndex) // actually clear cooldowns OldSummon->m_CreatureSpellCooldowns.clear(); - Unit::AuraApplicationMap &myAuras = OldSummon->GetAppliedAuras(); + Unit::AuraApplicationMap& myAuras = OldSummon->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator i = myAuras.begin(); i != myAuras.end();) { Aura const* aura = i->second->GetBase(); @@ -3300,7 +3316,7 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: return; // we must calculate only at last weapon effect - break; + break; } } @@ -3311,217 +3327,217 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - switch (m_spellInfo->Id) { - // Trial of the Champion, Black Knight, Obliterate - case 67725: - case 67883: + switch (m_spellInfo->Id) { - AddPct(totalDamagePercentMod, unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), 1)*30.0f); - break; - } - // sweeping strikes - case 26654: - { - this->damage = 0; - m_damage = m_spellValue->EffectBasePoints[effIndex]; - return; + // Trial of the Champion, Black Knight, Obliterate + case 67725: + case 67883: + { + AddPct(totalDamagePercentMod, unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), 1) * 30.0f); + break; + } + // sweeping strikes + case 26654: + { + this->damage = 0; + m_damage = m_spellValue->EffectBasePoints[effIndex]; + return; + } } + break; } - break; - } case SPELLFAMILY_WARRIOR: - { - // Devastate (player ones) - if (m_spellInfo->SpellFamilyFlags[1] & 0x40) { - // Player can apply only 58567 Sunder Armor effect. - // Xinef: 7386 triggers 58567 - bool needCast = !unitTarget->HasAura(58567); - if (needCast) - m_caster->CastSpell(unitTarget, 7386, true); - - if (Aura* aur = unitTarget->GetAura(58567)) + // Devastate (player ones) + if (m_spellInfo->SpellFamilyFlags[1] & 0x40) { - // 58388 - Glyph of Devastate dummy aura. - if (int32 num = (needCast ? 0 : 1) + (m_caster->HasAura(58388) ? 1 : 0)) - aur->ModStackAmount(num); - spell_bonus += (aur->GetStackAmount() - 1) * CalculateSpellDamage(2, unitTarget); + // Player can apply only 58567 Sunder Armor effect. + // Xinef: 7386 triggers 58567 + bool needCast = !unitTarget->HasAura(58567); + if (needCast) + m_caster->CastSpell(unitTarget, 7386, true); + + if (Aura* aur = unitTarget->GetAura(58567)) + { + // 58388 - Glyph of Devastate dummy aura. + if (int32 num = (needCast ? 0 : 1) + (m_caster->HasAura(58388) ? 1 : 0)) + aur->ModStackAmount(num); + spell_bonus += (aur->GetStackAmount() - 1) * CalculateSpellDamage(2, unitTarget); + } } + break; } - break; - } case SPELLFAMILY_ROGUE: - { - // Fan of Knives, Hemorrhage, Ghostly Strike - if ((m_spellInfo->SpellFamilyFlags[1] & 0x40000) - || (m_spellInfo->SpellFamilyFlags[0] & 0x6000000)) { - // Hemorrhage - if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000) + // Fan of Knives, Hemorrhage, Ghostly Strike + if ((m_spellInfo->SpellFamilyFlags[1] & 0x40000) + || (m_spellInfo->SpellFamilyFlags[0] & 0x6000000)) + { + // Hemorrhage + if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000) + { + if (m_caster->GetTypeId() == TYPEID_PLAYER) + m_caster->ToPlayer()->AddComboPoints(unitTarget, 1); + } + // 50% more damage with daggers + if (m_caster->GetTypeId() == TYPEID_PLAYER) + if (Item* item = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType, true)) + if (item->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) + AddPct(totalDamagePercentMod, 50.0f); + } + // Mutilate (for each hand) + else if (m_spellInfo->SpellFamilyFlags[1] & 0x6) + { + bool found = false; + // fast check + if (unitTarget->HasAuraState(AURA_STATE_DEADLY_POISON, m_spellInfo, m_caster)) + found = true; + // full aura scan + else + { + Unit::AuraApplicationMap const& auras = unitTarget->GetAppliedAuras(); + for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) + { + if (itr->second->GetBase()->GetSpellInfo()->Dispel == DISPEL_POISON) + { + found = true; + break; + } + } + } + + if (found) + AddPct(totalDamagePercentMod, 20.0f); // 120% if poisoned + } + break; + } + case SPELLFAMILY_PALADIN: + { + // Seal of Command Unleashed + if (m_spellInfo->Id == 20467) + { + spell_bonus += int32(0.08f * m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); + spell_bonus += int32(0.13f * m_caster->SpellBaseDamageBonusDone(m_spellInfo->GetSchoolMask())); + } + break; + } + case SPELLFAMILY_SHAMAN: + { + // Skyshatter Harness item set bonus + // Stormstrike + if (AuraEffect* aurEff = m_caster->IsScriptOverriden(m_spellInfo, 5634)) + m_caster->CastSpell(m_caster, 38430, true, NULL, aurEff); + // Lava lash damage increased by Flametongue weapon + if (m_caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 688, EFFECT_0)) + AddPct(totalDamagePercentMod, 25.0f); + break; + } + case SPELLFAMILY_DRUID: + { + // Mangle (Cat): CP + if (m_spellInfo->SpellFamilyFlags[1] & 0x400) { if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->AddComboPoints(unitTarget, 1); } - // 50% more damage with daggers - if (m_caster->GetTypeId() == TYPEID_PLAYER) - if (Item* item = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType, true)) - if (item->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) - AddPct(totalDamagePercentMod, 50.0f); - } - // Mutilate (for each hand) - else if (m_spellInfo->SpellFamilyFlags[1] & 0x6) - { - bool found = false; - // fast check - if (unitTarget->HasAuraState(AURA_STATE_DEADLY_POISON, m_spellInfo, m_caster)) - found = true; - // full aura scan - else + // Shred, Maul - Rend and Tear + else if (m_spellInfo->SpellFamilyFlags[0] & 0x00008800 && unitTarget->HasAuraState(AURA_STATE_BLEEDING)) { - Unit::AuraApplicationMap const& auras = unitTarget->GetAppliedAuras(); - for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) - { - if (itr->second->GetBase()->GetSpellInfo()->Dispel == DISPEL_POISON) - { - found = true; - break; - } - } + if (AuraEffect const* rendAndTear = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 0)) + AddPct(totalDamagePercentMod, rendAndTear->GetAmount()); + } + break; + } + case SPELLFAMILY_HUNTER: + { + // Kill Shot + if( m_spellInfo->SpellFamilyFlags[1] & 0x800000 ) + { + spell_bonus += int32(m_caster->GetTotalAttackPowerValue(RANGED_ATTACK) * 0.4f); + } + break; + } + case SPELLFAMILY_DEATHKNIGHT: + { + // Plague Strike + if (m_spellInfo->SpellFamilyFlags[0] & 0x1) + { + // Glyph of Plague Strike + if (AuraEffect const* aurEff = m_caster->GetAuraEffect(58657, EFFECT_0)) + AddPct(totalDamagePercentMod, aurEff->GetAmount()); + break; + } + // Blood Strike + if (m_spellInfo->SpellFamilyFlags[0] & 0x400000) + { + float disease_amt = m_spellInfo->Effects[EFFECT_2].CalcValue(); + //Death Knight T8 Melee 4P Bonus + if (AuraEffect* aurEff = m_caster->GetAuraEffectDummy(64736) ) + AddPct(disease_amt, aurEff->GetAmount()); + + AddPct(totalDamagePercentMod, disease_amt * unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) / 2.0f); + + // Glyph of Blood Strike + if (m_caster->GetAuraEffect(59332, EFFECT_0)) + if (unitTarget->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED)) + AddPct(totalDamagePercentMod, 20.0f); + break; + } + // Death Strike + if (m_spellInfo->SpellFamilyFlags[0] & 0x10) + { + // Glyph of Death Strike + if (AuraEffect const* aurEff = m_caster->GetAuraEffect(59336, EFFECT_0)) + if (uint32 runic = std::min(m_caster->GetPower(POWER_RUNIC_POWER), aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue())) + AddPct(totalDamagePercentMod, runic); + break; + } + // Obliterate (12.5% more damage per disease) + if (m_spellInfo->SpellFamilyFlags[1] & 0x20000) + { + bool consumeDiseases = true; + // Annihilation + if (AuraEffect const* aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2710, EFFECT_0)) + // Do not consume diseases if roll sucesses + if (roll_chance_i(aurEff->GetAmount())) + consumeDiseases = false; + + float disease_amt = m_spellInfo->Effects[EFFECT_2].CalcValue(); + //Death Knight T8 Melee 4P Bonus + if (AuraEffect* aurEff = m_caster->GetAuraEffectDummy(64736) ) + AddPct(disease_amt, aurEff->GetAmount()); + + AddPct(totalDamagePercentMod, disease_amt * unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), consumeDiseases) / 2.0f); + break; + } + // Blood-Caked Strike - Blood-Caked Blade + if (m_spellInfo->SpellIconID == 1736) + { + int32 weaponDamage = m_caster->CalculateDamage(m_attackType, false, true); + ApplyPct(weaponDamage, std::min(uint32(3), unitTarget->GetDiseasesByCaster(m_caster->GetGUID())) * 12.5f); + spell_bonus = weaponDamage; + break; + } + // Heart Strike + if (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) + { + float disease_amt = m_spellInfo->Effects[EFFECT_2].CalcValue(); + //Death Knight T8 Melee 4P Bonus + if (AuraEffect* aurEff = m_caster->GetAuraEffectDummy(64736) ) + AddPct(disease_amt, aurEff->GetAmount()); + + AddPct(totalDamagePercentMod, disease_amt * unitTarget->GetDiseasesByCaster(m_caster->GetGUID())); + break; + } + // Rune Strike + if (m_spellInfo->SpellFamilyFlags[1] & 0x20000000) + { + spell_bonus += int32(0.15f * m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); } - if (found) - AddPct(totalDamagePercentMod, 20.0f); // 120% if poisoned - } - break; - } - case SPELLFAMILY_PALADIN: - { - // Seal of Command Unleashed - if (m_spellInfo->Id == 20467) - { - spell_bonus += int32(0.08f * m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); - spell_bonus += int32(0.13f * m_caster->SpellBaseDamageBonusDone(m_spellInfo->GetSchoolMask())); - } - break; - } - case SPELLFAMILY_SHAMAN: - { - // Skyshatter Harness item set bonus - // Stormstrike - if (AuraEffect* aurEff = m_caster->IsScriptOverriden(m_spellInfo, 5634)) - m_caster->CastSpell(m_caster, 38430, true, NULL, aurEff); - // Lava lash damage increased by Flametongue weapon - if (m_caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 688, EFFECT_0)) - AddPct(totalDamagePercentMod, 25.0f); - break; - } - case SPELLFAMILY_DRUID: - { - // Mangle (Cat): CP - if (m_spellInfo->SpellFamilyFlags[1] & 0x400) - { - if (m_caster->GetTypeId() == TYPEID_PLAYER) - m_caster->ToPlayer()->AddComboPoints(unitTarget,1); - } - // Shred, Maul - Rend and Tear - else if (m_spellInfo->SpellFamilyFlags[0] & 0x00008800 && unitTarget->HasAuraState(AURA_STATE_BLEEDING)) - { - if (AuraEffect const* rendAndTear = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 0)) - AddPct(totalDamagePercentMod, rendAndTear->GetAmount()); - } - break; - } - case SPELLFAMILY_HUNTER: - { - // Kill Shot - if( m_spellInfo->SpellFamilyFlags[1] & 0x800000 ) - { - spell_bonus += int32(m_caster->GetTotalAttackPowerValue(RANGED_ATTACK) * 0.4f); - } - break; - } - case SPELLFAMILY_DEATHKNIGHT: - { - // Plague Strike - if (m_spellInfo->SpellFamilyFlags[0] & 0x1) - { - // Glyph of Plague Strike - if (AuraEffect const* aurEff = m_caster->GetAuraEffect(58657, EFFECT_0)) - AddPct(totalDamagePercentMod, aurEff->GetAmount()); break; } - // Blood Strike - if (m_spellInfo->SpellFamilyFlags[0] & 0x400000) - { - float disease_amt = m_spellInfo->Effects[EFFECT_2].CalcValue(); - //Death Knight T8 Melee 4P Bonus - if (AuraEffect *aurEff = m_caster->GetAuraEffectDummy(64736) ) - AddPct(disease_amt, aurEff->GetAmount()); - - AddPct(totalDamagePercentMod, disease_amt * unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) / 2.0f); - - // Glyph of Blood Strike - if (m_caster->GetAuraEffect(59332, EFFECT_0)) - if (unitTarget->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED)) - AddPct(totalDamagePercentMod, 20.0f); - break; - } - // Death Strike - if (m_spellInfo->SpellFamilyFlags[0] & 0x10) - { - // Glyph of Death Strike - if (AuraEffect const* aurEff = m_caster->GetAuraEffect(59336, EFFECT_0)) - if (uint32 runic = std::min(m_caster->GetPower(POWER_RUNIC_POWER), aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue())) - AddPct(totalDamagePercentMod, runic); - break; - } - // Obliterate (12.5% more damage per disease) - if (m_spellInfo->SpellFamilyFlags[1] & 0x20000) - { - bool consumeDiseases = true; - // Annihilation - if (AuraEffect const* aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2710, EFFECT_0)) - // Do not consume diseases if roll sucesses - if (roll_chance_i(aurEff->GetAmount())) - consumeDiseases = false; - - float disease_amt = m_spellInfo->Effects[EFFECT_2].CalcValue(); - //Death Knight T8 Melee 4P Bonus - if (AuraEffect *aurEff = m_caster->GetAuraEffectDummy(64736) ) - AddPct(disease_amt, aurEff->GetAmount()); - - AddPct(totalDamagePercentMod, disease_amt * unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), consumeDiseases) / 2.0f); - break; - } - // Blood-Caked Strike - Blood-Caked Blade - if (m_spellInfo->SpellIconID == 1736) - { - int32 weaponDamage = m_caster->CalculateDamage(m_attackType, false, true); - ApplyPct(weaponDamage, std::min(uint32(3), unitTarget->GetDiseasesByCaster(m_caster->GetGUID())) * 12.5f); - spell_bonus = weaponDamage; - break; - } - // Heart Strike - if (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) - { - float disease_amt = m_spellInfo->Effects[EFFECT_2].CalcValue(); - //Death Knight T8 Melee 4P Bonus - if (AuraEffect *aurEff = m_caster->GetAuraEffectDummy(64736) ) - AddPct(disease_amt, aurEff->GetAmount()); - - AddPct(totalDamagePercentMod, disease_amt * unitTarget->GetDiseasesByCaster(m_caster->GetGUID())); - break; - } - // Rune Strike - if (m_spellInfo->SpellFamilyFlags[1] & 0x20000000) - { - spell_bonus += int32(0.15f * m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); - } - - break; - } } bool normalized = false; @@ -3559,9 +3575,15 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) switch (m_attackType) { default: - case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; - case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break; - case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break; + case BASE_ATTACK: + unitMod = UNIT_MOD_DAMAGE_MAINHAND; + break; + case OFF_ATTACK: + unitMod = UNIT_MOD_DAMAGE_OFFHAND; + break; + case RANGED_ATTACK: + unitMod = UNIT_MOD_DAMAGE_RANGED; + break; } if (m_spellInfo->SchoolMask & SPELL_SCHOOL_MASK_NORMAL) @@ -3578,7 +3600,7 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) { if (Unit* owner = m_caster->GetOwner()) weaponDamage = owner->CalculateDamage(m_attackType, normalized, true); - } + } else weaponDamage = m_caster->CalculateDamage(m_attackType, normalized, true); @@ -3615,8 +3637,8 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) if (m_spellInfo->HasAttribute(SPELL_ATTR0_CU_SHARE_DAMAGE)) { uint32 count = 0; - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) - if (ihit->effectMask & (1<::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + if (ihit->effectMask & (1 << effIndex)) ++count; eff_damage /= count; // divide to all targets @@ -3677,10 +3699,10 @@ void Spell::EffectInterruptCast(SpellEffIndex effIndex) SpellInfo const* curSpellInfo = spell->m_spellInfo; // check if we can interrupt spell if ((spell->getState() == SPELL_STATE_CASTING - || (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastTime() > 0.0f)) - && curSpellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE - && ((i == CURRENT_GENERIC_SPELL && curSpellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT) - || (i == CURRENT_CHANNELED_SPELL && curSpellInfo->ChannelInterruptFlags & CHANNEL_INTERRUPT_FLAG_INTERRUPT))) + || (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastTime() > 0.0f)) + && curSpellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE + && ((i == CURRENT_GENERIC_SPELL && curSpellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT) + || (i == CURRENT_CHANNELED_SPELL && curSpellInfo->ChannelInterruptFlags & CHANNEL_INTERRUPT_FLAG_INTERRUPT))) { if (m_originalCaster) { @@ -3727,7 +3749,7 @@ void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) int32 duration = m_spellInfo->GetDuration(); - pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); + pGameObj->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effIndex, pGameObj); @@ -3738,14 +3760,14 @@ void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) if (pGameObj->GetGoType() == GAMEOBJECT_TYPE_FLAGDROP) if (Player* player = m_caster->ToPlayer()) if (Battleground* bg = player->GetBattleground()) - bg->SetDroppedFlagGUID(pGameObj->GetGUID(), player->GetTeamId() == TEAM_ALLIANCE ? TEAM_HORDE: TEAM_ALLIANCE); + bg->SetDroppedFlagGUID(pGameObj->GetGUID(), player->GetTeamId() == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE); if (uint32 linkedEntry = pGameObj->GetGOInfo()->GetLinkedGameObjectEntry()) { GameObject* linkedGO = sObjectMgr->IsGameObjectStaticTransport(linkedEntry) ? new StaticTransport() : new GameObject(); if (linkedGO->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, map, m_caster->GetPhaseMask(), x, y, z, target->GetOrientation(), G3D::Quat(), 100, GO_STATE_READY)) { - linkedGO->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); + linkedGO->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); linkedGO->SetSpellId(m_spellInfo->Id); // xinef: this is wrong @@ -3773,391 +3795,444 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - switch (m_spellInfo->Id) { - case 55693: // Remove Collapsing Cave Aura - if (!unitTarget) - return; - unitTarget->RemoveAurasDueToSpell(m_spellInfo->Effects[effIndex].CalcValue()); - break; - // Bending Shinbone - case 8856: + switch (m_spellInfo->Id) { - if (!itemTarget && m_caster->GetTypeId() != TYPEID_PLAYER) - return; - - uint32 spell_id = roll_chance_i(20) ? 8854 : 8855; - - m_caster->CastSpell(m_caster, spell_id, true, nullptr); - return; - } - // Brittle Armor - need remove one 24575 Brittle Armor aura - case 24590: - unitTarget->RemoveAuraFromStack(24575); - return; - // Mercurial Shield - need remove one 26464 Mercurial Shield aura - case 26465: - unitTarget->RemoveAuraFromStack(26464); - return; - // Shadow Flame (All script effects, not just end ones to prevent player from dodging the last triggered spell) - case 22539: - case 22972: - case 22975: - case 22976: - case 22977: - case 22978: - case 22979: - case 22980: - case 22981: - case 22982: - case 22983: - case 22984: - case 22985: - { - if (!unitTarget || !unitTarget->IsAlive()) - return; - - // Onyxia Scale Cloak - if (unitTarget->HasAura(22683)) - return; - - // Shadow Flame - m_caster->CastSpell(unitTarget, 22682, true); - return; - } - // Mirren's Drinking Hat - case 29830: - { - uint32 itemId = 23586; // Aerie Peak Pale Ale - switch (urand(0, 5)) - { - case 0: - case 1: - case 2: - itemId = 23584; - break; // Loch Modan Lager - case 3: - case 4: - itemId = 23585; - break; // Stouthammer Lite - } - DoCreateItem(effIndex, itemId); - break; - } - case 20589: // Escape artist - case 30918: // Improved Sprint - { - // Removes snares and roots. - unitTarget->RemoveMovementImpairingAuras(true); - break; - } - // Plant Warmaul Ogre Banner - case 32307: - if (Player* caster = m_caster->ToPlayer()) - { - caster->RewardPlayerAndGroupAtEvent(18388, unitTarget); - if (Creature* target = unitTarget->ToCreature()) + case 55693: // Remove Collapsing Cave Aura + if (!unitTarget) + return; + unitTarget->RemoveAurasDueToSpell(m_spellInfo->Effects[effIndex].CalcValue()); + break; + // Bending Shinbone + case 8856: { - target->setDeathState(CORPSE); - target->RemoveCorpse(); + if (!itemTarget && m_caster->GetTypeId() != TYPEID_PLAYER) + return; + + uint32 spell_id = roll_chance_i(20) ? 8854 : 8855; + + m_caster->CastSpell(m_caster, spell_id, true, nullptr); + return; } - } - break; - // SOTA defender teleport - case 54640: - { - if (Player* player = unitTarget->ToPlayer()) - if (player->GetBattleground() && player->GetBattleground()->GetBgTypeID(true) == BATTLEGROUND_SA) + // Brittle Armor - need remove one 24575 Brittle Armor aura + case 24590: + unitTarget->RemoveAuraFromStack(24575); + return; + // Mercurial Shield - need remove one 26464 Mercurial Shield aura + case 26465: + unitTarget->RemoveAuraFromStack(26464); + return; + // Shadow Flame (All script effects, not just end ones to prevent player from dodging the last triggered spell) + case 22539: + case 22972: + case 22975: + case 22976: + case 22977: + case 22978: + case 22979: + case 22980: + case 22981: + case 22982: + case 22983: + case 22984: + case 22985: { - if (GameObject* dportal = player->FindNearestGameObject(192819, 10.0f)) + if (!unitTarget || !unitTarget->IsAlive()) + return; + + // Onyxia Scale Cloak + if (unitTarget->HasAura(22683)) + return; + + // Shadow Flame + m_caster->CastSpell(unitTarget, 22682, true); + return; + } + // Mirren's Drinking Hat + case 29830: + { + uint32 itemId = 23586; // Aerie Peak Pale Ale + switch (urand(0, 5)) { - BattlegroundSA* bg = ((BattlegroundSA*)player->GetBattleground()); - bg->DefendersPortalTeleport(dportal, player); + case 0: + case 1: + case 2: + itemId = 23584; + break; // Loch Modan Lager + case 3: + case 4: + itemId = 23585; + break; // Stouthammer Lite + } + DoCreateItem(effIndex, itemId); + break; + } + case 20589: // Escape artist + case 30918: // Improved Sprint + { + // Removes snares and roots. + unitTarget->RemoveMovementImpairingAuras(true); + break; + } + // Plant Warmaul Ogre Banner + case 32307: + if (Player* caster = m_caster->ToPlayer()) + { + caster->RewardPlayerAndGroupAtEvent(18388, unitTarget); + if (Creature* target = unitTarget->ToCreature()) + { + target->setDeathState(CORPSE); + target->RemoveCorpse(); } } - return; - } - /*// Mug Transformation - case 41931: - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return; - - uint8 bag = 19; - uint8 slot = 0; - Item* item = nullptr; - - while (bag) // 256 = 0 due to var type - { - item = m_caster->ToPlayer()->GetItemByPos(bag, slot); - if (item && item->GetEntry() == 38587) - break; - - ++slot; - if (slot == 39) + break; + // SOTA defender teleport + case 54640: { - slot = 0; - ++bag; - } - } - if (bag) - { - if (m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount() == 1) m_caster->ToPlayer()->RemoveItem(bag, slot, true); - else m_caster->ToPlayer()->GetItemByPos(bag, slot)->SetCount(m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount()-1); - // Spell 42518 (Braufest - Gratisprobe des Braufest herstellen) - m_caster->CastSpell(m_caster, 42518, true); - return; - } - break; - }*/ - /* disabled for now, was being abused by idiots - // 5,000 Gold - case 46642: - { - if( !m_originalCaster || !unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) - return; - - unitTarget->ToPlayer()->ModifyMoney(5000 * GOLD); - - break; - }*/ - // Roll Dice - Decahedral Dwarven Dice - case 47770: - { - char buf[128]; - const char *gender = "his"; - if (m_caster->getGender() > 0) - gender = "her"; - sprintf(buf, "%s rubs %s [Decahedral Dwarven Dice] between %s hands and rolls. One %u and one %u.", m_caster->GetName().c_str(), gender, gender, urand(1, 10), urand(1, 10)); - m_caster->MonsterTextEmote(buf, nullptr); - break; - } - // Roll 'dem Bones - Worn Troll Dice - case 47776: - { - char buf[128]; - const char *gender = "his"; - if (m_caster->getGender() > 0) - gender = "her"; - sprintf(buf, "%s causually tosses %s [Worn Troll Dice]. One %u and one %u.", m_caster->GetName().c_str(), gender, urand(1, 6), urand(1, 6)); - m_caster->MonsterTextEmote(buf, nullptr); - break; - } - // Death Knight Initiate Visual - case 51519: - { - if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT) - return; - - uint32 iTmpSpellId = 0; - switch (unitTarget->GetDisplayId()) - { - case 25369: iTmpSpellId = 51552; break; // bloodelf female - case 25373: iTmpSpellId = 51551; break; // bloodelf male - case 25363: iTmpSpellId = 51542; break; // draenei female - case 25357: iTmpSpellId = 51541; break; // draenei male - case 25361: iTmpSpellId = 51537; break; // dwarf female - case 25356: iTmpSpellId = 51538; break; // dwarf male - case 25372: iTmpSpellId = 51550; break; // forsaken female - case 25367: iTmpSpellId = 51549; break; // forsaken male - case 25362: iTmpSpellId = 51540; break; // gnome female - case 25359: iTmpSpellId = 51539; break; // gnome male - case 25355: iTmpSpellId = 51534; break; // human female - case 25354: iTmpSpellId = 51520; break; // human male - case 25360: iTmpSpellId = 51536; break; // nightelf female - case 25358: iTmpSpellId = 51535; break; // nightelf male - case 25368: iTmpSpellId = 51544; break; // orc female - case 25364: iTmpSpellId = 51543; break; // orc male - case 25371: iTmpSpellId = 51548; break; // tauren female - case 25366: iTmpSpellId = 51547; break; // tauren male - case 25370: iTmpSpellId = 51545; break; // troll female - case 25365: iTmpSpellId = 51546; break; // troll male - default: return; - } - - unitTarget->CastSpell(unitTarget, iTmpSpellId, true); - Creature* npc = unitTarget->ToCreature(); - npc->LoadEquipment(); - return; - } - // Deathbolt from Thalgran Blightbringer - // reflected by Freya's Ward - // Retribution by Sevenfold Retribution - case 51854: - { - if (!unitTarget) - return; - if (unitTarget->HasAura(51845)) - unitTarget->CastSpell(m_caster, 51856, true); - else - m_caster->CastSpell(unitTarget, 51855, true); - break; - } - case 52173: // Coyote Spirit Despawn - case 60243: // Blood Parrot Despawn - if (unitTarget->GetTypeId() == TYPEID_UNIT && unitTarget->ToCreature()->IsSummon()) - unitTarget->ToTempSummon()->UnSummon(); - return; - case 57347: // Retrieving (Wintergrasp RP-GG pickup spell) - { - if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->GetTypeId() != TYPEID_PLAYER) - return; - - unitTarget->ToCreature()->DespawnOrUnsummon(); - - return; - } - case 57349: // Drop RP-GG (Wintergrasp RP-GG at death drop spell) - { - if (m_caster->GetTypeId() != TYPEID_PLAYER) - return; - - // Delete item from inventory at death - m_caster->ToPlayer()->DestroyItemCount(damage, 5, true); - - return; - } - case 58418: // Portal to Orgrimmar - case 58420: // Portal to Stormwind - { - if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER || effIndex != 0) - return; - - uint32 spellID = m_spellInfo->Effects[EFFECT_0].CalcValue(); - uint32 questID = m_spellInfo->Effects[EFFECT_1].CalcValue(); - - if (unitTarget->ToPlayer()->GetQuestStatus(questID) == QUEST_STATUS_COMPLETE) - unitTarget->CastSpell(unitTarget, spellID, true); - - return; - } - case 59317: // Teleporting - { - if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) - return; - - // return from top - if (unitTarget->ToPlayer()->GetAreaId() == 4637) - unitTarget->CastSpell(unitTarget, 59316, true); - // teleport atop - else - unitTarget->CastSpell(unitTarget, 59314, true); - - return; - } - case 60123: // Lightwell - { - if (m_caster->GetTypeId() != TYPEID_UNIT || !m_caster->ToCreature()->IsSummon()) - return; - - uint32 spell_heal; - - switch (m_caster->GetEntry()) - { - case 31897: spell_heal = 7001; break; - case 31896: spell_heal = 27873; break; - case 31895: spell_heal = 27874; break; - case 31894: spell_heal = 28276; break; - case 31893: spell_heal = 48084; break; - case 31883: spell_heal = 48085; break; - default: - sLog->outError("Unknown Lightwell spell caster %u", m_caster->GetEntry()); + if (Player* player = unitTarget->ToPlayer()) + if (player->GetBattleground() && player->GetBattleground()->GetBgTypeID(true) == BATTLEGROUND_SA) + { + if (GameObject* dportal = player->FindNearestGameObject(192819, 10.0f)) + { + BattlegroundSA* bg = ((BattlegroundSA*)player->GetBattleground()); + bg->DefendersPortalTeleport(dportal, player); + } + } return; - } - - // proc a spellcast - if (Aura* chargesAura = m_caster->GetAura(59907)) - { - m_caster->CastSpell(unitTarget, spell_heal, true, nullptr, nullptr, m_caster->ToTempSummon()->GetSummonerGUID()); - if (chargesAura->ModCharges(-1)) - m_caster->ToTempSummon()->UnSummon(); - } - - return; - } - // Stoneclaw Totem - case 55328: // Rank 1 - case 55329: // Rank 2 - case 55330: // Rank 3 - case 55332: // Rank 4 - case 55333: // Rank 5 - case 55335: // Rank 6 - case 55278: // Rank 7 - case 58589: // Rank 8 - case 58590: // Rank 9 - case 58591: // Rank 10 - { - int32 basepoints0 = damage; - // Cast Absorb on totems - for (uint8 slot = SUMMON_SLOT_TOTEM; slot < MAX_TOTEM_SLOT; ++slot) - { - if (!unitTarget->m_SummonSlot[slot]) - continue; - - Creature* totem = unitTarget->GetMap()->GetCreature(unitTarget->m_SummonSlot[slot]); - if (totem && totem->IsTotem()) - { - m_caster->CastCustomSpell(totem, 55277, &basepoints0, nullptr, nullptr, true); } - } - // Glyph of Stoneclaw Totem - if (AuraEffect* aur=unitTarget->GetAuraEffect(63298, 0)) + /*// Mug Transformation + case 41931: { - basepoints0 *= aur->GetAmount(); - m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, nullptr, nullptr, true); - } - break; - } - case 61263: // for item Intravenous Healing Potion (44698) - { - if( !m_caster || !unitTarget ) - return; + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return; - m_caster->CastSpell(m_caster, 61267, true); - m_caster->CastSpell(m_caster, 61268, true); - return; + uint8 bag = 19; + uint8 slot = 0; + Item* item = nullptr; + + while (bag) // 256 = 0 due to var type + { + item = m_caster->ToPlayer()->GetItemByPos(bag, slot); + if (item && item->GetEntry() == 38587) + break; + + ++slot; + if (slot == 39) + { + slot = 0; + ++bag; + } + } + if (bag) + { + if (m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount() == 1) m_caster->ToPlayer()->RemoveItem(bag, slot, true); + else m_caster->ToPlayer()->GetItemByPos(bag, slot)->SetCount(m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount()-1); + // Spell 42518 (Braufest - Gratisprobe des Braufest herstellen) + m_caster->CastSpell(m_caster, 42518, true); + return; + } + break; + }*/ + /* disabled for now, was being abused by idiots + // 5,000 Gold + case 46642: + { + if( !m_originalCaster || !unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) + return; + + unitTarget->ToPlayer()->ModifyMoney(5000 * GOLD); + + break; + }*/ + // Roll Dice - Decahedral Dwarven Dice + case 47770: + { + char buf[128]; + const char* gender = "his"; + if (m_caster->getGender() > 0) + gender = "her"; + sprintf(buf, "%s rubs %s [Decahedral Dwarven Dice] between %s hands and rolls. One %u and one %u.", m_caster->GetName().c_str(), gender, gender, urand(1, 10), urand(1, 10)); + m_caster->MonsterTextEmote(buf, nullptr); + break; + } + // Roll 'dem Bones - Worn Troll Dice + case 47776: + { + char buf[128]; + const char* gender = "his"; + if (m_caster->getGender() > 0) + gender = "her"; + sprintf(buf, "%s causually tosses %s [Worn Troll Dice]. One %u and one %u.", m_caster->GetName().c_str(), gender, urand(1, 6), urand(1, 6)); + m_caster->MonsterTextEmote(buf, nullptr); + break; + } + // Death Knight Initiate Visual + case 51519: + { + if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT) + return; + + uint32 iTmpSpellId = 0; + switch (unitTarget->GetDisplayId()) + { + case 25369: + iTmpSpellId = 51552; + break; // bloodelf female + case 25373: + iTmpSpellId = 51551; + break; // bloodelf male + case 25363: + iTmpSpellId = 51542; + break; // draenei female + case 25357: + iTmpSpellId = 51541; + break; // draenei male + case 25361: + iTmpSpellId = 51537; + break; // dwarf female + case 25356: + iTmpSpellId = 51538; + break; // dwarf male + case 25372: + iTmpSpellId = 51550; + break; // forsaken female + case 25367: + iTmpSpellId = 51549; + break; // forsaken male + case 25362: + iTmpSpellId = 51540; + break; // gnome female + case 25359: + iTmpSpellId = 51539; + break; // gnome male + case 25355: + iTmpSpellId = 51534; + break; // human female + case 25354: + iTmpSpellId = 51520; + break; // human male + case 25360: + iTmpSpellId = 51536; + break; // nightelf female + case 25358: + iTmpSpellId = 51535; + break; // nightelf male + case 25368: + iTmpSpellId = 51544; + break; // orc female + case 25364: + iTmpSpellId = 51543; + break; // orc male + case 25371: + iTmpSpellId = 51548; + break; // tauren female + case 25366: + iTmpSpellId = 51547; + break; // tauren male + case 25370: + iTmpSpellId = 51545; + break; // troll female + case 25365: + iTmpSpellId = 51546; + break; // troll male + default: + return; + } + + unitTarget->CastSpell(unitTarget, iTmpSpellId, true); + Creature* npc = unitTarget->ToCreature(); + npc->LoadEquipment(); + return; + } + // Deathbolt from Thalgran Blightbringer + // reflected by Freya's Ward + // Retribution by Sevenfold Retribution + case 51854: + { + if (!unitTarget) + return; + if (unitTarget->HasAura(51845)) + unitTarget->CastSpell(m_caster, 51856, true); + else + m_caster->CastSpell(unitTarget, 51855, true); + break; + } + case 52173: // Coyote Spirit Despawn + case 60243: // Blood Parrot Despawn + if (unitTarget->GetTypeId() == TYPEID_UNIT && unitTarget->ToCreature()->IsSummon()) + unitTarget->ToTempSummon()->UnSummon(); + return; + case 57347: // Retrieving (Wintergrasp RP-GG pickup spell) + { + if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->GetTypeId() != TYPEID_PLAYER) + return; + + unitTarget->ToCreature()->DespawnOrUnsummon(); + + return; + } + case 57349: // Drop RP-GG (Wintergrasp RP-GG at death drop spell) + { + if (m_caster->GetTypeId() != TYPEID_PLAYER) + return; + + // Delete item from inventory at death + m_caster->ToPlayer()->DestroyItemCount(damage, 5, true); + + return; + } + case 58418: // Portal to Orgrimmar + case 58420: // Portal to Stormwind + { + if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER || effIndex != 0) + return; + + uint32 spellID = m_spellInfo->Effects[EFFECT_0].CalcValue(); + uint32 questID = m_spellInfo->Effects[EFFECT_1].CalcValue(); + + if (unitTarget->ToPlayer()->GetQuestStatus(questID) == QUEST_STATUS_COMPLETE) + unitTarget->CastSpell(unitTarget, spellID, true); + + return; + } + case 59317: // Teleporting + { + if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) + return; + + // return from top + if (unitTarget->ToPlayer()->GetAreaId() == 4637) + unitTarget->CastSpell(unitTarget, 59316, true); + // teleport atop + else + unitTarget->CastSpell(unitTarget, 59314, true); + + return; + } + case 60123: // Lightwell + { + if (m_caster->GetTypeId() != TYPEID_UNIT || !m_caster->ToCreature()->IsSummon()) + return; + + uint32 spell_heal; + + switch (m_caster->GetEntry()) + { + case 31897: + spell_heal = 7001; + break; + case 31896: + spell_heal = 27873; + break; + case 31895: + spell_heal = 27874; + break; + case 31894: + spell_heal = 28276; + break; + case 31893: + spell_heal = 48084; + break; + case 31883: + spell_heal = 48085; + break; + default: + sLog->outError("Unknown Lightwell spell caster %u", m_caster->GetEntry()); + return; + } + + // proc a spellcast + if (Aura* chargesAura = m_caster->GetAura(59907)) + { + m_caster->CastSpell(unitTarget, spell_heal, true, nullptr, nullptr, m_caster->ToTempSummon()->GetSummonerGUID()); + if (chargesAura->ModCharges(-1)) + m_caster->ToTempSummon()->UnSummon(); + } + + return; + } + // Stoneclaw Totem + case 55328: // Rank 1 + case 55329: // Rank 2 + case 55330: // Rank 3 + case 55332: // Rank 4 + case 55333: // Rank 5 + case 55335: // Rank 6 + case 55278: // Rank 7 + case 58589: // Rank 8 + case 58590: // Rank 9 + case 58591: // Rank 10 + { + int32 basepoints0 = damage; + // Cast Absorb on totems + for (uint8 slot = SUMMON_SLOT_TOTEM; slot < MAX_TOTEM_SLOT; ++slot) + { + if (!unitTarget->m_SummonSlot[slot]) + continue; + + Creature* totem = unitTarget->GetMap()->GetCreature(unitTarget->m_SummonSlot[slot]); + if (totem && totem->IsTotem()) + { + m_caster->CastCustomSpell(totem, 55277, &basepoints0, nullptr, nullptr, true); + } + } + // Glyph of Stoneclaw Totem + if (AuraEffect* aur = unitTarget->GetAuraEffect(63298, 0)) + { + basepoints0 *= aur->GetAmount(); + m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, nullptr, nullptr, true); + } + break; + } + case 61263: // for item Intravenous Healing Potion (44698) + { + if( !m_caster || !unitTarget ) + return; + + m_caster->CastSpell(m_caster, 61267, true); + m_caster->CastSpell(m_caster, 61268, true); + return; + } } + break; } - break; - } case SPELLFAMILY_ROGUE: - { - switch( m_spellInfo->Id ) { - // Master of Subtlety - case 31666: + switch( m_spellInfo->Id ) { - if( !unitTarget ) - return; + // Master of Subtlety + case 31666: + { + if( !unitTarget ) + return; - Aura *mos = unitTarget->GetAura(31665); - if( mos ) - { - mos->SetMaxDuration(6000); - mos->SetDuration(6000, true); - } + Aura* mos = unitTarget->GetAura(31665); + if( mos ) + { + mos->SetMaxDuration(6000); + mos->SetDuration(6000, true); + } - break; - } - // Overkill - case 58428: - { - if( !unitTarget ) - return; - - Aura *overkill = unitTarget->GetAura(58427); - if( overkill ) - { - overkill->SetMaxDuration(20000); - overkill->SetDuration(20000, true); - } - - break; + break; + } + // Overkill + case 58428: + { + if( !unitTarget ) + return; + + Aura* overkill = unitTarget->GetAura(58427); + if( overkill ) + { + overkill->SetMaxDuration(20000); + overkill->SetDuration(20000, true); + } + + break; + } } + break; } - break; - } } // normal DB scripted effect @@ -4234,8 +4309,8 @@ void Spell::EffectSanctuary(SpellEffIndex /*effIndex*/) // Vanish allows to remove all threat and cast regular stealth so other spells can be used if (m_caster->GetTypeId() == TYPEID_PLAYER - && m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE - && (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_ROGUE_VANISH)) + && m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE + && (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_ROGUE_VANISH)) { m_caster->ToPlayer()->RemoveAurasByType(SPELL_AURA_MOD_ROOT); @@ -4254,9 +4329,9 @@ void Spell::EffectAddComboPoints(SpellEffIndex /*effIndex*/) return; if (m_spellInfo->Id == 14157 || // Ruthlessness and Netherblade set - m_spellInfo->Id == 70802) // xinef: mayhem, rogue t10p4 + m_spellInfo->Id == 70802) // xinef: mayhem, rogue t10p4 { - m_caster->m_movedByPlayer->ToPlayer()->SetComboPointGain(m_caster->m_movedByPlayer->ToPlayer()->GetComboPointGain()+damage); + m_caster->m_movedByPlayer->ToPlayer()->SetComboPointGain(m_caster->m_movedByPlayer->ToPlayer()->GetComboPointGain() + damage); return; } @@ -4299,20 +4374,20 @@ void Spell::EffectDuel(SpellEffIndex effIndex) Map* map = m_caster->GetMap(); if (!pGameObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), gameobject_id, - map, m_caster->GetPhaseMask(), - m_caster->GetPositionX()+(unitTarget->GetPositionX()-m_caster->GetPositionX())/2, - m_caster->GetPositionY()+(unitTarget->GetPositionY()-m_caster->GetPositionY())/2, - m_caster->GetPositionZ(), - m_caster->GetOrientation(), G3D::Quat(), 0, GO_STATE_READY)) + map, m_caster->GetPhaseMask(), + m_caster->GetPositionX() + (unitTarget->GetPositionX() - m_caster->GetPositionX()) / 2, + m_caster->GetPositionY() + (unitTarget->GetPositionY() - m_caster->GetPositionY()) / 2, + m_caster->GetPositionZ(), + m_caster->GetOrientation(), G3D::Quat(), 0, GO_STATE_READY)) { delete pGameObj; return; } pGameObj->SetUInt32Value(GAMEOBJECT_FACTION, m_caster->getFaction()); - pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel()+1); + pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel() + 1); int32 duration = m_spellInfo->GetDuration(); - pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); + pGameObj->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effIndex, pGameObj); @@ -4380,7 +4455,7 @@ void Spell::EffectStuck(SpellEffIndex /*effIndex*/) Item* hearthStone = target->GetItemByEntry(6948); if (!hearthStone || target->HasSpellCooldown(8690)) { - float o = rand_norm()*2*M_PI; + float o = rand_norm() * 2 * M_PI; Position pos = *target; target->MovePositionToFirstCollision(pos, 5.0f, o); target->NearTeleportTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), target->GetOrientation()); @@ -4388,7 +4463,7 @@ void Spell::EffectStuck(SpellEffIndex /*effIndex*/) } // xinef: we have hearthstone not on cooldown, just use it - target->CastSpell(target, 8690, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD)); + target->CastSpell(target, 8690, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD)); } void Spell::EffectSummonPlayer(SpellEffIndex /*effIndex*/) @@ -4410,10 +4485,10 @@ void Spell::EffectSummonPlayer(SpellEffIndex /*effIndex*/) unitTarget->ToPlayer()->SetSummonPoint(m_caster->GetMapId(), x, y, z); - WorldPacket data(SMSG_SUMMON_REQUEST, 8+4+4); + WorldPacket data(SMSG_SUMMON_REQUEST, 8 + 4 + 4); data << uint64(m_caster->GetGUID()); // summoner guid data << uint32(m_caster->GetZoneId()); // summoner zone - data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs + data << uint32(MAX_PLAYER_SUMMON_DELAY * IN_MILLISECONDS); // auto decline after msecs unitTarget->ToPlayer()->GetSession()->SendPacket(&data); } @@ -4453,11 +4528,21 @@ void Spell::EffectApplyGlyph(SpellEffIndex effIndex) switch (m_glyphIndex) { case 0: - case 1: minLevel = 15; break; - case 2: minLevel = 50; break; - case 3: minLevel = 30; break; - case 4: minLevel = 70; break; - case 5: minLevel = 80; break; + case 1: + minLevel = 15; + break; + case 2: + minLevel = 50; + break; + case 3: + minLevel = 30; + break; + case 4: + minLevel = 70; + break; + case 5: + minLevel = 80; + break; } if (minLevel && m_caster->getLevel() < minLevel) { @@ -4484,7 +4569,7 @@ void Spell::EffectApplyGlyph(SpellEffIndex effIndex) if (GlyphPropertiesEntry const* oldGlyphEntry = sGlyphPropertiesStore.LookupEntry(oldGlyph)) player->RemoveAurasDueToSpell(oldGlyphEntry->SpellId); - player->CastSpell(m_caster, glyphEntry->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK&~(TRIGGERED_IGNORE_SHAPESHIFT|TRIGGERED_IGNORE_CASTER_AURASTATE))); + player->CastSpell(m_caster, glyphEntry->SpellId, TriggerCastFlags(TRIGGERED_FULL_MASK & ~(TRIGGERED_IGNORE_SHAPESHIFT | TRIGGERED_IGNORE_CASTER_AURASTATE))); player->SetGlyph(m_glyphIndex, glyph, !player->GetSession()->PlayerLoading()); player->SendTalentsInfoData(false); } @@ -4515,13 +4600,13 @@ void Spell::EffectEnchantHeldItem(SpellEffIndex effIndex) uint32 enchant_id = m_spellInfo->Effects[effIndex].MiscValue; int32 duration = m_spellInfo->GetDuration(); //Try duration index first .. if (!duration) - duration = damage*IN_MILLISECONDS;//+1; //Base points after .. + duration = damage * IN_MILLISECONDS; //+1; //Base points after .. if (!duration) - duration = 10*IN_MILLISECONDS; //10 seconds for enchants which don't have listed duration + duration = 10 * IN_MILLISECONDS; //10 seconds for enchants which don't have listed duration // Xinef: Venomhide poison, no other spell uses this effect... if (m_spellInfo->Id == 14792) - duration = 5*MINUTE*IN_MILLISECONDS; + duration = 5 * MINUTE * IN_MILLISECONDS; SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) @@ -4637,11 +4722,20 @@ void Spell::EffectSummonObject(SpellEffIndex effIndex) uint8 slot = 0; switch (m_spellInfo->Effects[effIndex].Effect) { - case SPELL_EFFECT_SUMMON_OBJECT_SLOT1: slot = 0; break; - case SPELL_EFFECT_SUMMON_OBJECT_SLOT2: slot = 1; break; - case SPELL_EFFECT_SUMMON_OBJECT_SLOT3: slot = 2; break; - case SPELL_EFFECT_SUMMON_OBJECT_SLOT4: slot = 3; break; - default: return; + case SPELL_EFFECT_SUMMON_OBJECT_SLOT1: + slot = 0; + break; + case SPELL_EFFECT_SUMMON_OBJECT_SLOT2: + slot = 1; + break; + case SPELL_EFFECT_SUMMON_OBJECT_SLOT3: + slot = 2; + break; + case SPELL_EFFECT_SUMMON_OBJECT_SLOT4: + slot = 3; + break; + default: + return; } if (m_caster) @@ -4679,7 +4773,7 @@ void Spell::EffectSummonObject(SpellEffIndex effIndex) //pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel()); int32 duration = m_spellInfo->GetDuration(); - pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); + pGameObj->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); m_caster->AddGameObject(pGameObj); @@ -4823,7 +4917,7 @@ void Spell::EffectForceDeselect(SpellEffIndex /*effIndex*/) WorldPacket data(SMSG_CLEAR_TARGET, 8); data << uint64(m_caster->GetGUID()); - float dist = m_caster->GetVisibilityRange()+VISIBILITY_COMPENSATION; + float dist = m_caster->GetVisibilityRange() + VISIBILITY_COMPENSATION; acore::MessageDistDelivererToHostile notifier(m_caster, &data, dist); m_caster->VisitNearbyWorldObject(dist, notifier); @@ -4878,7 +4972,7 @@ void Spell::EffectForceDeselect(SpellEffIndex /*effIndex*/) } if (interrupt) - spell->m_targets.SetUnitTarget(images.at(urand(0, images.size()-1))); + spell->m_targets.SetUnitTarget(images.at(urand(0, images.size() - 1))); } } } @@ -4944,7 +5038,7 @@ void Spell::EffectSkinning(SpellEffIndex /*effIndex*/) creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); m_caster->ToPlayer()->SendLoot(creature->GetGUID(), LOOT_SKINNING); - int32 reqValue = targetLevel < 10 ? 0 : targetLevel < 20 ? (targetLevel-10)*10 : targetLevel*5; + int32 reqValue = targetLevel < 10 ? 0 : targetLevel < 20 ? (targetLevel - 10) * 10 : targetLevel * 5; int32 skillValue = m_caster->ToPlayer()->GetPureSkillValue(skill); @@ -4979,7 +5073,7 @@ void Spell::EffectCharge(SpellEffIndex /*effIndex*/) m_caster->GetFirstCollisionPosition(pos, dist, angle); } - m_caster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ+0.5f); + m_caster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ + 0.5f); } } @@ -5003,7 +5097,7 @@ void Spell::EffectChargeDest(SpellEffIndex /*effIndex*/) { Position pos; destTarget->GetPosition(&pos); - + if (!m_caster->IsWithinLOS(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ())) { float angle = m_caster->GetRelativeAngle(pos.GetPositionX(), pos.GetPositionY()); @@ -5022,7 +5116,7 @@ void Spell::EffectKnockBack(SpellEffIndex effIndex) if (!unitTarget) return; - + // Xinef: allow entry specific spells to skip those checks if (m_spellInfo->Effects[effIndex].TargetA.GetCheckType() != TARGET_CHECK_ENTRY && m_spellInfo->Effects[effIndex].TargetB.GetCheckType() != TARGET_CHECK_ENTRY) { @@ -5158,7 +5252,7 @@ void Spell::EffectPullTowards(SpellEffIndex effIndex) else //if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_PULL_TOWARDS) { // Xinef: Increase Z position a little bit, should protect from falling through textures - pos.Relocate(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()+1.0f, m_caster->GetOrientation()); + pos.Relocate(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ() + 1.0f, m_caster->GetOrientation()); } float speedXY = float(m_spellInfo->Effects[effIndex].MiscValue) * 0.1f; @@ -5223,7 +5317,7 @@ void Spell::EffectResurrectPet(SpellEffIndex /*effIndex*/) player->SummonPet(0, x, y, z, player->GetOrientation(), SUMMON_PET, 0, 0, (uint64)damage, PET_LOAD_SUMMON_DEAD_PET); return; } - + pet->SetPosition(x, y, z, player->GetOrientation()); pet->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE); @@ -5383,7 +5477,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) fz = m_caster->GetPositionZ(); } - Map *cMap = m_caster->GetMap(); + Map* cMap = m_caster->GetMap(); // if gameobject is summoning object, it should be spawned right on caster's position if (goinfo->type == GAMEOBJECT_TYPE_SUMMONING_RITUAL) m_caster->GetPosition(fx, fy, fz); @@ -5401,33 +5495,41 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) switch (goinfo->type) { case GAMEOBJECT_TYPE_FISHINGNODE: - { - m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, pGameObj->GetGUID()); - m_caster->AddGameObject(pGameObj); // will removed at spell cancel - - // end time of range when possible catch fish (FISHING_BOBBER_READY_TIME..GetDuration(m_spellInfo)) - // start time == fish-FISHING_BOBBER_READY_TIME (0..GetDuration(m_spellInfo)-FISHING_BOBBER_READY_TIME) - int32 lastSec = 0; - switch (urand(0, 3)) { - case 0: lastSec = 3; break; - case 1: lastSec = 7; break; - case 2: lastSec = 13; break; - case 3: lastSec = 17; break; - } + m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, pGameObj->GetGUID()); + m_caster->AddGameObject(pGameObj); // will removed at spell cancel - duration = duration - lastSec*IN_MILLISECONDS + FISHING_BOBBER_READY_TIME*IN_MILLISECONDS; - break; - } + // end time of range when possible catch fish (FISHING_BOBBER_READY_TIME..GetDuration(m_spellInfo)) + // start time == fish-FISHING_BOBBER_READY_TIME (0..GetDuration(m_spellInfo)-FISHING_BOBBER_READY_TIME) + int32 lastSec = 0; + switch (urand(0, 3)) + { + case 0: + lastSec = 3; + break; + case 1: + lastSec = 7; + break; + case 2: + lastSec = 13; + break; + case 3: + lastSec = 17; + break; + } + + duration = duration - lastSec * IN_MILLISECONDS + FISHING_BOBBER_READY_TIME * IN_MILLISECONDS; + break; + } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: - { - if (m_caster->GetTypeId() == TYPEID_PLAYER) { - pGameObj->AddUniqueUse(m_caster->ToPlayer()); - m_caster->AddGameObject(pGameObj); // will be removed at spell cancel + if (m_caster->GetTypeId() == TYPEID_PLAYER) + { + pGameObj->AddUniqueUse(m_caster->ToPlayer()); + m_caster->AddGameObject(pGameObj); // will be removed at spell cancel + } + break; } - break; - } case GAMEOBJECT_TYPE_DUEL_ARBITER: // 52991 m_caster->AddGameObject(pGameObj); break; @@ -5437,7 +5539,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) break; } - pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); + pGameObj->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); pGameObj->SetOwnerGUID(m_caster->GetGUID()); @@ -5459,7 +5561,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) GameObject* linkedGO = sObjectMgr->IsGameObjectStaticTransport(linkedEntry) ? new StaticTransport() : new GameObject(); if (linkedGO->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, cMap, m_caster->GetPhaseMask(), fx, fy, fz, m_caster->GetOrientation(), G3D::Quat(), 100, GO_STATE_READY)) { - linkedGO->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); + linkedGO->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); linkedGO->SetSpellId(m_spellInfo->Id); // xinef: this is wrong @@ -5594,7 +5696,7 @@ void Spell::EffectStealBeneficialBuff(SpellEffIndex effIndex) for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura* aura = itr->second; - AuraApplication * aurApp = aura->GetApplicationOfTarget(unitTarget->GetGUID()); + AuraApplication* aurApp = aura->GetApplicationOfTarget(unitTarget->GetGUID()); if (!aurApp) continue; @@ -5620,7 +5722,7 @@ void Spell::EffectStealBeneficialBuff(SpellEffIndex effIndex) // Ok if exist some buffs for dispel try dispel it uint32 failCount = 0; DispelList success_list; - WorldPacket dataFail(SMSG_DISPEL_FAILED, 8+8+4+4+damage*4); + WorldPacket dataFail(SMSG_DISPEL_FAILED, 8 + 8 + 4 + 4 + damage * 4); // dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && !steal_list.empty();) { @@ -5666,13 +5768,13 @@ void Spell::EffectStealBeneficialBuff(SpellEffIndex effIndex) if (success_list.empty()) return; - WorldPacket dataSuccess(SMSG_SPELLSTEALLOG, 8+8+4+1+4+damage*5); + WorldPacket dataSuccess(SMSG_SPELLSTEALLOG, 8 + 8 + 4 + 1 + 4 + damage * 5); dataSuccess.append(unitTarget->GetPackGUID()); // Victim GUID dataSuccess.append(m_caster->GetPackGUID()); // Caster GUID dataSuccess << uint32(m_spellInfo->Id); // dispel spell id dataSuccess << uint8(0); // not used dataSuccess << uint32(success_list.size()); // count - for (DispelList::iterator itr = success_list.begin(); itr!=success_list.end(); ++itr) + for (DispelList::iterator itr = success_list.begin(); itr != success_list.end(); ++itr) { dataSuccess << uint32(itr->first); // Spell Id dataSuccess << uint8(0); // 0 - steals !=0 transfers @@ -5783,10 +5885,10 @@ void Spell::EffectActivateRune(SpellEffIndex effIndex) for (uint32 l = 0; l < MAX_RUNES && count > 0; ++l) { // Check if both runes are on cd as that is the only time when this needs to come into effect - if ((player->GetRuneCooldown(l) && player->GetCurrentRune(l) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB)) && (player->GetRuneCooldown(l+1) && player->GetCurrentRune(l+1) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB))) + if ((player->GetRuneCooldown(l) && player->GetCurrentRune(l) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB)) && (player->GetRuneCooldown(l + 1) && player->GetCurrentRune(l + 1) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB))) { // Should always update the rune with the lowest cd - if (player->GetRuneCooldown(l) >= player->GetRuneCooldown(l+1)) + if (player->GetRuneCooldown(l) >= player->GetRuneCooldown(l + 1)) l++; player->SetRuneCooldown(l, 0); player->SetGracePeriod(l, player->IsInCombat()); // xinef: reset grace period @@ -5990,7 +6092,7 @@ void Spell::SummonGuardian(uint32 i, uint32 entry, SummonPropertiesEntry const* // xinef: if we have more than one guardian, change follow angle if (summon->HasUnitTypeMask(UNIT_MASK_MINION) && numGuardians > 1) - ((Minion*)summon)->SetFollowAngle(PET_FOLLOW_ANGLE + (count * M_PI / (numGuardians-1))); + ((Minion*)summon)->SetFollowAngle(PET_FOLLOW_ANGLE + (count * M_PI / (numGuardians - 1))); //else if (summon->HasUnitTypeMask(UNIT_MASK_MINION) && m_targets.HasDst()) // ((Minion*)summon)->SetFollowAngle(m_caster->GetAngle(summon)); @@ -6032,7 +6134,7 @@ void Spell::EffectRenamePet(SpellEffIndex /*effIndex*/) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || - !unitTarget->IsPet() || unitTarget->ToPet()->getPetType() != HUNTER_PET) + !unitTarget->IsPet() || unitTarget->ToPet()->getPetType() != HUNTER_PET) return; unitTarget->SetByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED); @@ -6078,7 +6180,7 @@ void Spell::EffectActivateSpec(SpellEffIndex /*effIndex*/) if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; - unitTarget->ToPlayer()->ActivateSpec(damage-1); // damage is 1 or 2, spec is 0 or 1 + unitTarget->ToPlayer()->ActivateSpec(damage - 1); // damage is 1 or 2, spec is 0 or 1 } void Spell::EffectPlaySound(SpellEffIndex effIndex) @@ -6233,7 +6335,7 @@ void Spell::EffectBind(SpellEffIndex effIndex) #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "EffectBind: New homebind X: %f, Y: %f, Z: %f, MapId: %u, AreaId: %u", - homeLoc.GetPositionX(), homeLoc.GetPositionY(), homeLoc.GetPositionZ(), homeLoc.GetMapId(), areaId); + homeLoc.GetPositionX(), homeLoc.GetPositionY(), homeLoc.GetPositionZ(), homeLoc.GetMapId(), areaId); #endif // zone update data.Initialize(SMSG_PLAYERBOUND, 8 + 4); @@ -6256,6 +6358,6 @@ void Spell::EffectSummonRaFFriend(SpellEffIndex /*effIndex*/) WorldPacket data(SMSG_SUMMON_REQUEST, 8 + 4 + 4); data << uint64(m_caster->GetGUID()); data << uint32(m_caster->GetZoneId()); - data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs + data << uint32(MAX_PLAYER_SUMMON_DELAY * IN_MILLISECONDS); // auto decline after msecs unitTarget->ToPlayer()->GetSession()->SendPacket(&data); } diff --git a/src/server/game/Spells/SpellInfo.cpp b/src/server/game/Spells/SpellInfo.cpp index 64bd88248..808b8599b 100644 --- a/src/server/game/Spells/SpellInfo.cpp +++ b/src/server/game/Spells/SpellInfo.cpp @@ -88,19 +88,19 @@ float SpellImplicitTargetInfo::CalcDirectionAngle() const case TARGET_DIR_BACK: return static_cast(M_PI); case TARGET_DIR_RIGHT: - return static_cast(-M_PI/2); + return static_cast(-M_PI / 2); case TARGET_DIR_LEFT: - return static_cast(M_PI/2); + return static_cast(M_PI / 2); case TARGET_DIR_FRONT_RIGHT: - return static_cast(-M_PI/4); + return static_cast(-M_PI / 4); case TARGET_DIR_BACK_RIGHT: - return static_cast(-3*M_PI/4); + return static_cast(-3 * M_PI / 4); case TARGET_DIR_BACK_LEFT: - return static_cast(3*M_PI/4); + return static_cast(3 * M_PI / 4); case TARGET_DIR_FRONT_LEFT: - return static_cast(M_PI/4); + return static_cast(M_PI / 4); case TARGET_DIR_RANDOM: - return float(rand_norm())*static_cast(2*M_PI); + return float(rand_norm()) * static_cast(2 * M_PI); default: return 0.0f; } @@ -258,7 +258,7 @@ SpellImplicitTargetInfo::StaticData SpellImplicitTargetInfo::_data[TOTAL_SPELL_ {TARGET_OBJECT_TYPE_UNIT, TARGET_REFERENCE_TYPE_CASTER, TARGET_SELECT_CATEGORY_NEARBY, TARGET_CHECK_RAID, TARGET_DIR_NONE}, // 58 TARGET_UNIT_NEARBY_RAID {TARGET_OBJECT_TYPE_UNIT, TARGET_REFERENCE_TYPE_CASTER, TARGET_SELECT_CATEGORY_CONE, TARGET_CHECK_ALLY, TARGET_DIR_FRONT}, // 59 TARGET_UNIT_CONE_ALLY {TARGET_OBJECT_TYPE_UNIT, TARGET_REFERENCE_TYPE_CASTER, TARGET_SELECT_CATEGORY_CONE, TARGET_CHECK_ENTRY, TARGET_DIR_FRONT}, // 60 TARGET_UNIT_CONE_ENTRY - {TARGET_OBJECT_TYPE_UNIT, TARGET_REFERENCE_TYPE_TARGET, TARGET_SELECT_CATEGORY_AREA, TARGET_CHECK_RAID_CLASS,TARGET_DIR_NONE}, // 61 TARGET_UNIT_TARGET_AREA_RAID_CLASS + {TARGET_OBJECT_TYPE_UNIT, TARGET_REFERENCE_TYPE_TARGET, TARGET_SELECT_CATEGORY_AREA, TARGET_CHECK_RAID_CLASS, TARGET_DIR_NONE}, // 61 TARGET_UNIT_TARGET_AREA_RAID_CLASS {TARGET_OBJECT_TYPE_NONE, TARGET_REFERENCE_TYPE_NONE, TARGET_SELECT_CATEGORY_NYI, TARGET_CHECK_DEFAULT, TARGET_DIR_NONE}, // 62 TARGET_UNK_62 {TARGET_OBJECT_TYPE_DEST, TARGET_REFERENCE_TYPE_TARGET, TARGET_SELECT_CATEGORY_DEFAULT, TARGET_CHECK_DEFAULT, TARGET_DIR_NONE}, // 63 TARGET_DEST_TARGET_ANY {TARGET_OBJECT_TYPE_DEST, TARGET_REFERENCE_TYPE_TARGET, TARGET_SELECT_CATEGORY_DEFAULT, TARGET_CHECK_DEFAULT, TARGET_DIR_FRONT}, // 64 TARGET_DEST_TARGET_FRONT @@ -365,11 +365,11 @@ bool SpellEffectInfo::IsTargetingArea() const bool SpellEffectInfo::IsAreaAuraEffect() const { if (Effect == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || - Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID || - Effect == SPELL_EFFECT_APPLY_AREA_AURA_FRIEND || - Effect == SPELL_EFFECT_APPLY_AREA_AURA_ENEMY || - Effect == SPELL_EFFECT_APPLY_AREA_AURA_PET || - Effect == SPELL_EFFECT_APPLY_AREA_AURA_OWNER) + Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID || + Effect == SPELL_EFFECT_APPLY_AREA_AURA_FRIEND || + Effect == SPELL_EFFECT_APPLY_AREA_AURA_ENEMY || + Effect == SPELL_EFFECT_APPLY_AREA_AURA_PET || + Effect == SPELL_EFFECT_APPLY_AREA_AURA_OWNER) return true; return false; } @@ -377,10 +377,10 @@ bool SpellEffectInfo::IsAreaAuraEffect() const bool SpellEffectInfo::IsFarUnitTargetEffect() const { return (Effect == SPELL_EFFECT_SUMMON_PLAYER) - || (Effect == SPELL_EFFECT_SUMMON_RAF_FRIEND) - || (Effect == SPELL_EFFECT_RESURRECT) - || (Effect == SPELL_EFFECT_RESURRECT_NEW) - /*|| (Effect == SPELL_EFFECT_SKIN_PLAYER_CORPSE) Xinef: This is not Far Unit Target Effect... what a bullshit*/; + || (Effect == SPELL_EFFECT_SUMMON_RAF_FRIEND) + || (Effect == SPELL_EFFECT_RESURRECT) + || (Effect == SPELL_EFFECT_RESURRECT_NEW) + /*|| (Effect == SPELL_EFFECT_SKIN_PLAYER_CORPSE) Xinef: This is not Far Unit Target Effect... what a bullshit*/; } bool SpellEffectInfo::IsFarDestTargetEffect() const @@ -417,13 +417,16 @@ int32 SpellEffectInfo::CalcValue(Unit const* caster, int32 const* bp, Unit const // roll in a range <1;EffectDieSides> as of patch 3.3.3 switch (randomPoints) { - case 0: break; - case 1: basePoints += 1; break; // range 1..1 + case 0: + break; + case 1: + basePoints += 1; + break; // range 1..1 default: // range can have positive (1..rand) and negative (rand..1) values, so order its for irand int32 randvalue = (randomPoints >= 1) - ? irand(1, randomPoints) - : irand(randomPoints, 1); + ? irand(1, randomPoints) + : irand(randomPoints, 1); basePoints += randvalue; break; @@ -438,14 +441,14 @@ int32 SpellEffectInfo::CalcValue(Unit const* caster, int32 const* bp, Unit const if (caster->m_movedByPlayer) if (uint8 comboPoints = caster->m_movedByPlayer->ToPlayer()->GetComboPoints()) if (float comboDamage = PointsPerComboPoint) - value += comboDamage* comboPoints; + value += comboDamage * comboPoints; value = caster->ApplyEffectModifiers(_spellInfo, _effIndex, value); // amount multiplication based on caster's level if (!caster->IsControlledByPlayer() && - _spellInfo->SpellLevel && _spellInfo->SpellLevel != caster->getLevel() && - !basePointsPerLevel && _spellInfo->HasAttribute(SPELL_ATTR0_LEVEL_DAMAGE_CALCULATION)) + _spellInfo->SpellLevel && _spellInfo->SpellLevel != caster->getLevel() && + !basePointsPerLevel && _spellInfo->HasAttribute(SPELL_ATTR0_LEVEL_DAMAGE_CALCULATION)) { bool canEffectScale = false; switch (Effect) @@ -891,17 +894,17 @@ bool SpellInfo::HasAreaAuraEffect() const bool SpellInfo::IsExplicitDiscovery() const { return ((Effects[0].Effect == SPELL_EFFECT_CREATE_RANDOM_ITEM - || Effects[0].Effect == SPELL_EFFECT_CREATE_ITEM_2) - && Effects[1].Effect == SPELL_EFFECT_SCRIPT_EFFECT) - || Id == 64323; + || Effects[0].Effect == SPELL_EFFECT_CREATE_ITEM_2) + && Effects[1].Effect == SPELL_EFFECT_SCRIPT_EFFECT) + || Id == 64323; } bool SpellInfo::IsLootCrafting() const { return (Effects[0].Effect == SPELL_EFFECT_CREATE_RANDOM_ITEM || - // different random cards from Inscription (121==Virtuoso Inking Set category) r without explicit item - (Effects[0].Effect == SPELL_EFFECT_CREATE_ITEM_2 && - ((TotemCategory[0] != 0 || (Totem[0] != 0 && SpellIconID == 1)) || Effects[0].ItemType == 0))); + // different random cards from Inscription (121==Virtuoso Inking Set category) r without explicit item + (Effects[0].Effect == SPELL_EFFECT_CREATE_ITEM_2 && + ((TotemCategory[0] != 0 || (Totem[0] != 0 && SpellIconID == 1)) || Effects[0].ItemType == 0))); } bool SpellInfo::IsQuestTame() const @@ -1108,7 +1111,7 @@ bool SpellInfo::ComputeIsStackableWithRanks() const case SPELLFAMILY_DRUID: // Druid form Spell if (Effects[i].Effect == SPELL_EFFECT_APPLY_AURA && - Effects[i].ApplyAuraName == SPELL_AURA_MOD_SHAPESHIFT) + Effects[i].ApplyAuraName == SPELL_AURA_MOD_SHAPESHIFT) return false; break; } @@ -1245,8 +1248,8 @@ bool SpellInfo::IsBreakingStealth() const bool SpellInfo::IsRangedWeaponSpell() const { return (SpellFamilyName == SPELLFAMILY_HUNTER && !(SpellFamilyFlags[1] & 0x10000000)) // for 53352, cannot find better way - || (EquippedItemSubClassMask & ITEM_SUBCLASS_MASK_WEAPON_RANGED) - || (Attributes & SPELL_ATTR0_REQ_AMMO); // Xinef: added + || (EquippedItemSubClassMask & ITEM_SUBCLASS_MASK_WEAPON_RANGED) + || (Attributes & SPELL_ATTR0_REQ_AMMO); // Xinef: added } bool SpellInfo::IsAutoRepeatRangedSpell() const @@ -1286,8 +1289,8 @@ bool SpellInfo::CanPierceImmuneAura(SpellInfo const* aura) const // these spells (Cyclone for example) can pierce all... if ((AttributesEx & SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE) - // ...but not these (Divine shield for example) // xinef: banish exception, banish can override banish to cancel itself - && !(aura && (aura->Mechanic == MECHANIC_IMMUNE_SHIELD || aura->Mechanic == MECHANIC_INVULNERABILITY || (aura->Mechanic == MECHANIC_BANISH && (Mechanic != MECHANIC_BANISH || !(AttributesEx2 & SPELL_ATTR2_CANT_TARGET_TAPPED)))))) + // ...but not these (Divine shield for example) // xinef: banish exception, banish can override banish to cancel itself + && !(aura && (aura->Mechanic == MECHANIC_IMMUNE_SHIELD || aura->Mechanic == MECHANIC_INVULNERABILITY || (aura->Mechanic == MECHANIC_BANISH && (Mechanic != MECHANIC_BANISH || !(AttributesEx2 & SPELL_ATTR2_CANT_TARGET_TAPPED)))))) return true; return false; @@ -1355,14 +1358,14 @@ bool SpellInfo::IsAuraExclusiveBySpecificWith(SpellInfo const* spellInfo) const return spellSpec1 == spellSpec2; case SPELL_SPECIFIC_FOOD: return spellSpec2 == SPELL_SPECIFIC_FOOD - || spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK; + || spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK; case SPELL_SPECIFIC_DRINK: return spellSpec2 == SPELL_SPECIFIC_DRINK - || spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK; + || spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK; case SPELL_SPECIFIC_FOOD_AND_DRINK: return spellSpec2 == SPELL_SPECIFIC_FOOD - || spellSpec2 == SPELL_SPECIFIC_DRINK - || spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK; + || spellSpec2 == SPELL_SPECIFIC_DRINK + || spellSpec2 == SPELL_SPECIFIC_FOOD_AND_DRINK; default: return false; } @@ -1392,7 +1395,7 @@ SpellCastResult SpellInfo::CheckShapeshift(uint32 form) const // talents that learn spells can have stance requirements that need ignore // (this requirement only for client-side stance show in talent description) if (GetTalentSpellCost(Id) > 0 && - (Effects[0].Effect == SPELL_EFFECT_LEARN_SPELL || Effects[1].Effect == SPELL_EFFECT_LEARN_SPELL || Effects[2].Effect == SPELL_EFFECT_LEARN_SPELL)) + (Effects[0].Effect == SPELL_EFFECT_LEARN_SPELL || Effects[1].Effect == SPELL_EFFECT_LEARN_SPELL || Effects[2].Effect == SPELL_EFFECT_LEARN_SPELL)) return SPELL_CAST_OK; uint32 stanceMask = (form ? 1 << (form - 1) : 0); @@ -1508,24 +1511,24 @@ SpellCastResult SpellInfo::CheckLocation(uint32 map_id, uint32 zone_id, uint32 a case 42792: // Recently Dropped Flag case 43681: // Inactive case 44535: // Spirit Heal (mana) - { - MapEntry const* mapEntry = sMapStore.LookupEntry(map_id); - if (!mapEntry) - return SPELL_FAILED_INCORRECT_AREA; + { + MapEntry const* mapEntry = sMapStore.LookupEntry(map_id); + if (!mapEntry) + return SPELL_FAILED_INCORRECT_AREA; - return zone_id == 4197 || (mapEntry->IsBattleground() && player && player->InBattleground()) ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; - } + return zone_id == 4197 || (mapEntry->IsBattleground() && player && player->InBattleground()) ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; + } case 32724: // Gold Team (Alliance) case 32725: // Green Team (Alliance) case 35774: // Gold Team (Horde) case 35775: // Green Team (Horde) - { - MapEntry const* mapEntry = sMapStore.LookupEntry(map_id); - if (!mapEntry) - return SPELL_FAILED_INCORRECT_AREA; + { + MapEntry const* mapEntry = sMapStore.LookupEntry(map_id); + if (!mapEntry) + return SPELL_FAILED_INCORRECT_AREA; - return mapEntry->IsBattleArena() && player && player->InBattleground() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; - } + return mapEntry->IsBattleArena() && player && player->InBattleground() ? SPELL_CAST_OK : SPELL_FAILED_REQUIRES_AREA; + } } // aura limitations @@ -1537,15 +1540,15 @@ SpellCastResult SpellInfo::CheckLocation(uint32 map_id, uint32 zone_id, uint32 a { case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED: case SPELL_AURA_FLY: - { - SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(Id); - for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) { - if (skillIter->second->skillId == SKILL_MOUNTS) - if (player && !player->canFlyInZone(map_id, zone_id)) - return SPELL_FAILED_INCORRECT_AREA; + SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(Id); + for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) + { + if (skillIter->second->skillId == SKILL_MOUNTS) + if (player && !player->canFlyInZone(map_id, zone_id)) + return SPELL_FAILED_INCORRECT_AREA; + } } - } } } return SPELL_CAST_OK; @@ -1633,9 +1636,9 @@ bool SpellInfo::IsStrongerAuraActive(Unit const* caster, Unit const* target) con basePoints = player->m_spellModTakingSpell->GetSpellValue()->EffectBasePoints[i]; int32 curValue = abs(Effects[i].CalcValue(caster, &basePoints)); - int32 auraValue = (sFlag & SPELL_GROUP_SPECIAL_FLAG_BASE_AMOUNT_CHECK) ? - abs((*iter)->GetSpellInfo()->Effects[(*iter)->GetEffIndex()].CalcValue((*iter)->GetCaster())) : - abs((*iter)->GetAmount()); + int32 auraValue = (sFlag & SPELL_GROUP_SPECIAL_FLAG_BASE_AMOUNT_CHECK) ? + abs((*iter)->GetSpellInfo()->Effects[(*iter)->GetEffIndex()].CalcValue((*iter)->GetCaster())) : + abs((*iter)->GetAmount()); // xinef: for same spells, divide amount by stack amount if (Id == (*iter)->GetId()) @@ -1674,7 +1677,7 @@ bool SpellInfo::IsAuraEffectEqual(SpellInfo const* otherSpellInfo) const { if (!otherSpellInfo->Effects[j].IsAura()) continue; - + if (Effects[i].ApplyAuraName != otherSpellInfo->Effects[j].ApplyAuraName || Effects[i].MiscValue != otherSpellInfo->Effects[j].MiscValue) continue; @@ -1695,9 +1698,9 @@ bool SpellInfo::IsAuraEffectEqual(SpellInfo const* otherSpellInfo) const ++auraCount; } - return matchCount*2 == auraCount; + return matchCount * 2 == auraCount; } - + bool SpellInfo::ValidateAttribute6SpellDamageMods(const Unit* caster, const AuraEffect* auraEffect, bool isDot) const { // Xinef: no attribute @@ -1709,8 +1712,8 @@ bool SpellInfo::ValidateAttribute6SpellDamageMods(const Unit* caster, const Aura if (Id == 70890 && auraEffect) { const SpellInfo* auraInfo = auraEffect->GetSpellInfo(); - return auraInfo->SpellIconID == 3086 || - (auraInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && (auraInfo->SpellFamilyFlags & flag96(8388608, 64, 16) || auraInfo->SpellIconID == 235 || auraInfo->SpellIconID == 154)); + return auraInfo->SpellIconID == 3086 || + (auraInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && (auraInfo->SpellFamilyFlags & flag96(8388608, 64, 16) || auraInfo->SpellIconID == 235 || auraInfo->SpellIconID == 154)); } // Xinef: Necrosis, no profits for done and taken else if (Id == 51460) @@ -1759,10 +1762,10 @@ SpellCastResult SpellInfo::CheckTarget(Unit const* caster, WorldObject const* ta if (AttributesCu & SPELL_ATTR0_CU_PICKPOCKET) { - if (unitTarget->GetTypeId() == TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; - else if ((unitTarget->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0) - return SPELL_FAILED_TARGET_NO_POCKETS; + if (unitTarget->GetTypeId() == TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; + else if ((unitTarget->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0) + return SPELL_FAILED_TARGET_NO_POCKETS; } // Not allow disarm unarmed player @@ -1798,14 +1801,14 @@ SpellCastResult SpellInfo::CheckTarget(Unit const* caster, WorldObject const* ta // corpseOwner and unit specific target checks if (AttributesEx3 & SPELL_ATTR3_ONLY_TARGET_PLAYERS && !unitTarget->ToPlayer()) - return SPELL_FAILED_TARGET_NOT_PLAYER; + return SPELL_FAILED_TARGET_NOT_PLAYER; if (!IsAllowingDeadTarget() && !unitTarget->IsAlive()) - return SPELL_FAILED_TARGETS_DEAD; + return SPELL_FAILED_TARGETS_DEAD; // check this flag only for implicit targets (chain and area), allow to explicitly target units for spells like Shield of Righteousness if (implicit && AttributesEx6 & SPELL_ATTR6_CANT_TARGET_CROWD_CONTROLLED && !unitTarget->CanFreeMove()) - return SPELL_FAILED_BAD_TARGETS; + return SPELL_FAILED_BAD_TARGETS; // checked in Unit::IsValidAttack/AssistTarget, shouldn't be checked for ENTRY targets //if (!(AttributesEx6 & SPELL_ATTR6_CAN_TARGET_UNTARGETABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) @@ -1887,10 +1890,10 @@ SpellCastResult SpellInfo::CheckExplicitTarget(Unit const* caster, WorldObject c if (caster->_IsValidAttackTarget(unitTarget, this)) return SPELL_CAST_OK; if (neededTargets & TARGET_FLAG_UNIT_ALLY - || (neededTargets & TARGET_FLAG_UNIT_PARTY && caster->IsInPartyWith(unitTarget)) - || (neededTargets & TARGET_FLAG_UNIT_RAID && caster->IsInRaidWith(unitTarget))) - if (caster->_IsValidAssistTarget(unitTarget, this)) - return SPELL_CAST_OK; + || (neededTargets & TARGET_FLAG_UNIT_PARTY && caster->IsInPartyWith(unitTarget)) + || (neededTargets & TARGET_FLAG_UNIT_RAID && caster->IsInRaidWith(unitTarget))) + if (caster->_IsValidAssistTarget(unitTarget, this)) + return SPELL_CAST_OK; if (neededTargets & TARGET_FLAG_UNIT_MINIPET) if (unitTarget->GetGUID() == caster->GetCritterGUID()) return SPELL_CAST_OK; @@ -1938,9 +1941,9 @@ uint32 SpellInfo::GetEffectMechanicMask(uint8 effIndex) const { uint32 mask = 0; if (Mechanic) - mask |= 1<< Mechanic; + mask |= 1 << Mechanic; if (Effects[effIndex].IsEffect() && Effects[effIndex].Mechanic) - mask |= 1<< Effects[effIndex].Mechanic; + mask |= 1 << Effects[effIndex].Mechanic; return mask; } @@ -1948,10 +1951,10 @@ uint32 SpellInfo::GetSpellMechanicMaskByEffectMask(uint32 effectMask) const { uint32 mask = 0; if (Mechanic) - mask |= 1<< Mechanic; + mask |= 1 << Mechanic; for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) if ((effectMask & (1 << i)) && Effects[i].Mechanic) - mask |= 1<< Effects[i].Mechanic; + mask |= 1 << Effects[i].Mechanic; return mask; } @@ -2004,24 +2007,26 @@ AuraStateType SpellInfo::LoadAuraState() const // Conflagrate aura state on Immolate and Shadowflame if (SpellFamilyName == SPELLFAMILY_WARLOCK && - // Immolate - ((SpellFamilyFlags[0] & 4) || - // Shadowflame - (SpellFamilyFlags[2] & 2))) + // Immolate + ((SpellFamilyFlags[0] & 4) || + // Shadowflame + (SpellFamilyFlags[2] & 2))) return AURA_STATE_CONFLAGRATE; // Faerie Fire (druid versions) if (SpellFamilyName == SPELLFAMILY_DRUID && SpellFamilyFlags[0] & 0x400) return AURA_STATE_FAERIE_FIRE; - + // Any Spells that prevent spells can be added here. uint32 StealthPreventionSpellList[] = { 9991, 35331, 9806, 35325 }; - + // Goes through each of the spells and identifies them as Stealth Prevention Spell. - for (uint32 i = 0; i < sizeof(StealthPreventionSpellList) / sizeof(uint32); i++) { - if (Id == StealthPreventionSpellList[i]) { + for (uint32 i = 0; i < sizeof(StealthPreventionSpellList) / sizeof(uint32); i++) + { + if (Id == StealthPreventionSpellList[i]) + { return AURA_STATE_FAERIE_FIRE; - } + } } // Sting (hunter's pet ability) @@ -2045,13 +2050,13 @@ AuraStateType SpellInfo::LoadAuraState() const return AURA_STATE_ENRAGE; // Bleeding aura state - if (GetAllEffectsMechanicMask() & 1<Id) + { + case 8118: // Strength + case 8099: // Stamina + case 8112: // Spirit + case 8096: // Intellect + case 8115: // Agility + case 8091: // Armor + return SPELL_SPECIFIC_SCROLL; } } - - if (food && drink) - return SPELL_SPECIFIC_FOOD_AND_DRINK; - else if (food) - return SPELL_SPECIFIC_FOOD; - else if (drink) - return SPELL_SPECIFIC_DRINK; + break; } - // scrolls effects - else - { - SpellInfo const* firstRankSpellInfo = GetFirstRankSpell(); - switch (firstRankSpellInfo->Id) - { - case 8118: // Strength - case 8099: // Stamina - case 8112: // Spirit - case 8096: // Intellect - case 8115: // Agility - case 8091: // Armor - return SPELL_SPECIFIC_SCROLL; - } - } - break; - } case SPELLFAMILY_MAGE: - { - // family flags 18(Molten), 25(Frost/Ice), 28(Mage) - if (SpellFamilyFlags[0] & 0x12040000) - return SPELL_SPECIFIC_MAGE_ARMOR; + { + // family flags 18(Molten), 25(Frost/Ice), 28(Mage) + if (SpellFamilyFlags[0] & 0x12040000) + return SPELL_SPECIFIC_MAGE_ARMOR; - // Arcane brillance and Arcane intelect (normal check fails because of flags difference) - if (SpellFamilyFlags[0] & 0x400) - return SPELL_SPECIFIC_MAGE_ARCANE_BRILLANCE; + // Arcane brillance and Arcane intelect (normal check fails because of flags difference) + if (SpellFamilyFlags[0] & 0x400) + return SPELL_SPECIFIC_MAGE_ARCANE_BRILLANCE; - if ((SpellFamilyFlags[0] & 0x1000000) && Effects[0].ApplyAuraName == SPELL_AURA_MOD_CONFUSE) - return SPELL_SPECIFIC_MAGE_POLYMORPH; + if ((SpellFamilyFlags[0] & 0x1000000) && Effects[0].ApplyAuraName == SPELL_AURA_MOD_CONFUSE) + return SPELL_SPECIFIC_MAGE_POLYMORPH; - break; - } + break; + } case SPELLFAMILY_WARLOCK: - { - // only warlock curses have this - if (Dispel == DISPEL_CURSE) - return SPELL_SPECIFIC_CURSE; + { + // only warlock curses have this + if (Dispel == DISPEL_CURSE) + return SPELL_SPECIFIC_CURSE; - // Warlock (Demon Armor | Demon Skin | Fel Armor) - if (SpellFamilyFlags[1] & 0x20000020 || SpellFamilyFlags[2] & 0x00000010) - return SPELL_SPECIFIC_WARLOCK_ARMOR; + // Warlock (Demon Armor | Demon Skin | Fel Armor) + if (SpellFamilyFlags[1] & 0x20000020 || SpellFamilyFlags[2] & 0x00000010) + return SPELL_SPECIFIC_WARLOCK_ARMOR; - //seed of corruption and corruption - if (SpellFamilyFlags[1] & 0x10 || SpellFamilyFlags[0] & 0x2) - return SPELL_SPECIFIC_WARLOCK_CORRUPTION; - break; - } + //seed of corruption and corruption + if (SpellFamilyFlags[1] & 0x10 || SpellFamilyFlags[0] & 0x2) + return SPELL_SPECIFIC_WARLOCK_CORRUPTION; + break; + } case SPELLFAMILY_PRIEST: - { - // Divine Spirit and Prayer of Spirit - if (SpellFamilyFlags[0] & 0x20) - return SPELL_SPECIFIC_PRIEST_DIVINE_SPIRIT; + { + // Divine Spirit and Prayer of Spirit + if (SpellFamilyFlags[0] & 0x20) + return SPELL_SPECIFIC_PRIEST_DIVINE_SPIRIT; - break; - } + break; + } case SPELLFAMILY_HUNTER: - { - // only hunter stings have this - if (Dispel == DISPEL_POISON) - return SPELL_SPECIFIC_STING; + { + // only hunter stings have this + if (Dispel == DISPEL_POISON) + return SPELL_SPECIFIC_STING; - // only hunter aspects have this (but not all aspects in hunter family) - if (SpellFamilyFlags.HasFlag(0x00380000, 0x00440000, 0x00001010)) - return SPELL_SPECIFIC_ASPECT; + // only hunter aspects have this (but not all aspects in hunter family) + if (SpellFamilyFlags.HasFlag(0x00380000, 0x00440000, 0x00001010)) + return SPELL_SPECIFIC_ASPECT; - break; - } + break; + } case SPELLFAMILY_PALADIN: - { - // Collection of all the seal family flags. No other paladin spell has any of those. - if (SpellFamilyFlags[1] & 0x26000C00 - || SpellFamilyFlags[0] & 0x0A000000) - return SPELL_SPECIFIC_SEAL; + { + // Collection of all the seal family flags. No other paladin spell has any of those. + if (SpellFamilyFlags[1] & 0x26000C00 + || SpellFamilyFlags[0] & 0x0A000000) + return SPELL_SPECIFIC_SEAL; - if (SpellFamilyFlags[0] & 0x00002190) - return SPELL_SPECIFIC_HAND; + if (SpellFamilyFlags[0] & 0x00002190) + return SPELL_SPECIFIC_HAND; - // Judgement of Wisdom, Judgement of Light, Judgement of Justice - if (Id == 20184 || Id == 20185 || Id == 20186) - return SPELL_SPECIFIC_JUDGEMENT; + // Judgement of Wisdom, Judgement of Light, Judgement of Justice + if (Id == 20184 || Id == 20185 || Id == 20186) + return SPELL_SPECIFIC_JUDGEMENT; - // only paladin auras have this (for palaldin class family) - if (SpellFamilyFlags[2] & 0x00000020) - return SPELL_SPECIFIC_AURA; + // only paladin auras have this (for palaldin class family) + if (SpellFamilyFlags[2] & 0x00000020) + return SPELL_SPECIFIC_AURA; - // Illidari Council Paladin (Gathios the Shatterer) - if (Id == 41459 || Id == 41469) - return SPELL_SPECIFIC_SEAL; + // Illidari Council Paladin (Gathios the Shatterer) + if (Id == 41459 || Id == 41469) + return SPELL_SPECIFIC_SEAL; - break; - } + break; + } case SPELLFAMILY_SHAMAN: - { - // family flags 10 (Lightning), 42 (Earth), 37 (Water), proc shield from T2 8 pieces bonus - if (SpellFamilyFlags[1] & 0x420 - || SpellFamilyFlags[0] & 0x00000400 - || Id == 23552) - return SPELL_SPECIFIC_ELEMENTAL_SHIELD; + { + // family flags 10 (Lightning), 42 (Earth), 37 (Water), proc shield from T2 8 pieces bonus + if (SpellFamilyFlags[1] & 0x420 + || SpellFamilyFlags[0] & 0x00000400 + || Id == 23552) + return SPELL_SPECIFIC_ELEMENTAL_SHIELD; - break; - } + break; + } case SPELLFAMILY_DEATHKNIGHT: if (Id == 48266 || Id == 48263 || Id == 48265) return SPELL_SPECIFIC_PRESENCE; @@ -2466,9 +2471,9 @@ SpellInfo const* SpellInfo::GetAuraRankForLevel(uint8 level) const for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (IsPositiveEffect(i) && - (Effects[i].Effect == SPELL_EFFECT_APPLY_AURA || - Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || - Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID)) + (Effects[i].Effect == SPELL_EFFECT_APPLY_AURA || + Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || + Effects[i].Effect == SPELL_EFFECT_APPLY_AREA_AURA_RAID)) { needRankSelection = true; break; @@ -2590,157 +2595,157 @@ bool SpellInfo::_IsPositiveEffect(uint8 effIndex, bool deep) const return false; case SPELL_EFFECT_SCHOOL_DAMAGE: - { - bool only = true; - for (int i = EFFECT_0; i <= EFFECT_2; ++i) { - if (Effects[effIndex].Effect > 0 && Effects[effIndex].Effect != SPELL_EFFECT_SCHOOL_DAMAGE) - only = false; - if (Effects[effIndex].Effect == SPELL_EFFECT_GAMEOBJECT_DAMAGE) + bool only = true; + for (int i = EFFECT_0; i <= EFFECT_2; ++i) + { + if (Effects[effIndex].Effect > 0 && Effects[effIndex].Effect != SPELL_EFFECT_SCHOOL_DAMAGE) + only = false; + if (Effects[effIndex].Effect == SPELL_EFFECT_GAMEOBJECT_DAMAGE) + return false; + } + // effects with school damage only cannot be positive... + if (only) return false; + break; } - // effects with school damage only cannot be positive... - if (only) - return false; - break; - } case SPELL_EFFECT_KNOCK_BACK: case SPELL_EFFECT_KNOCK_BACK_DEST: - { - for (int i = EFFECT_0; i <= EFFECT_2; ++i) - if (Effects[effIndex].Effect == SPELL_EFFECT_GAMEOBJECT_DAMAGE) - return false; - break; - } + { + for (int i = EFFECT_0; i <= EFFECT_2; ++i) + if (Effects[effIndex].Effect == SPELL_EFFECT_GAMEOBJECT_DAMAGE) + return false; + break; + } - // non-positive aura use + // non-positive aura use case SPELL_EFFECT_APPLY_AURA: case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: - { - switch (Effects[effIndex].ApplyAuraName) { - case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from bas point sign (negative -> negative) - case SPELL_AURA_MOD_STAT: - case SPELL_AURA_MOD_SKILL: - case SPELL_AURA_MOD_DODGE_PERCENT: - case SPELL_AURA_MOD_HEALING_PCT: - case SPELL_AURA_MOD_HEALING_DONE: - case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: - if (Effects[effIndex].CalcValue() < 0) - return false; - break; - case SPELL_AURA_MOD_DAMAGE_TAKEN: // dependent from bas point sign (positive -> negative) - if (Effects[effIndex].CalcValue() > 0) - return false; - break; - case SPELL_AURA_MOD_CRIT_PCT: - case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: - if (Effects[effIndex].CalcValue() > 0) - return true; // some expected positive spells have SPELL_ATTR1_NEGATIVE - break; - case SPELL_AURA_ADD_TARGET_TRIGGER: - return true; - case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE: - case SPELL_AURA_PERIODIC_TRIGGER_SPELL: - if (!deep) - { - if (SpellInfo const* spellTriggeredProto = sSpellMgr->GetSpellInfo(Effects[effIndex].TriggerSpell)) - { - // negative targets of main spell return early - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - { - if (!spellTriggeredProto->Effects[i].Effect) - continue; - // if non-positive trigger cast targeted to positive target this main cast is non-positive - // this will place this spell auras as debuffs - if (_IsPositiveTarget(spellTriggeredProto->Effects[i].TargetA.GetTarget(), spellTriggeredProto->Effects[i].TargetB.GetTarget()) && !spellTriggeredProto->_IsPositiveEffect(i, true)) - return false; - } - } - } - case SPELL_AURA_PROC_TRIGGER_SPELL: - // many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example) - break; - case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment. - if (effIndex == 0 && Effects[1].Effect == 0 && Effects[2].Effect == 0) - return false; // but all single stun aura spells is negative - break; - case SPELL_AURA_MOD_PACIFY_SILENCE: - if (Id == 24740) // Wisp Costume - return true; - return false; - case SPELL_AURA_MOD_ROOT: - case SPELL_AURA_MOD_SILENCE: - case SPELL_AURA_GHOST: - case SPELL_AURA_PERIODIC_LEECH: - case SPELL_AURA_MOD_STALKED: - case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: - case SPELL_AURA_PREVENT_RESURRECTION: - return false; - case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also. - // part of negative spell if casted at self (prevent cancel) - if (Effects[effIndex].TargetA.GetTarget() == TARGET_UNIT_CASTER) - return false; - break; - case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also - // part of positive spell if casted at self - if (Effects[effIndex].TargetA.GetTarget() != TARGET_UNIT_CASTER) - return false; - // but not this if this first effect (didn't find better check) - if (Attributes & SPELL_ATTR0_NEGATIVE_1 && effIndex == 0) - return false; - break; - case SPELL_AURA_MECHANIC_IMMUNITY: + switch (Effects[effIndex].ApplyAuraName) { - // non-positive immunities - switch (Effects[effIndex].MiscValue) - { - case MECHANIC_BANDAGE: - case MECHANIC_SHIELD: - case MECHANIC_MOUNT: - case MECHANIC_INVULNERABILITY: + case SPELL_AURA_MOD_DAMAGE_DONE: // dependent from bas point sign (negative -> negative) + case SPELL_AURA_MOD_STAT: + case SPELL_AURA_MOD_SKILL: + case SPELL_AURA_MOD_DODGE_PERCENT: + case SPELL_AURA_MOD_HEALING_PCT: + case SPELL_AURA_MOD_HEALING_DONE: + case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: + if (Effects[effIndex].CalcValue() < 0) return false; - default: - break; - } - break; - } - case SPELL_AURA_ADD_FLAT_MODIFIER: // mods - case SPELL_AURA_ADD_PCT_MODIFIER: - { - // non-positive mods - switch (Effects[effIndex].MiscValue) - { - case SPELLMOD_COST: // dependent from bas point sign (negative -> positive) - if (Effects[effIndex].CalcValue() > 0) + break; + case SPELL_AURA_MOD_DAMAGE_TAKEN: // dependent from bas point sign (positive -> negative) + if (Effects[effIndex].CalcValue() > 0) + return false; + break; + case SPELL_AURA_MOD_CRIT_PCT: + case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: + if (Effects[effIndex].CalcValue() > 0) + return true; // some expected positive spells have SPELL_ATTR1_NEGATIVE + break; + case SPELL_AURA_ADD_TARGET_TRIGGER: + return true; + case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE: + case SPELL_AURA_PERIODIC_TRIGGER_SPELL: + if (!deep) + { + if (SpellInfo const* spellTriggeredProto = sSpellMgr->GetSpellInfo(Effects[effIndex].TriggerSpell)) { - if (!deep) + // negative targets of main spell return early + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - bool negative = true; - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - { - if (i != effIndex) - if (_IsPositiveEffect(i, true)) - { - negative = false; - break; - } - } - if (negative) + if (!spellTriggeredProto->Effects[i].Effect) + continue; + // if non-positive trigger cast targeted to positive target this main cast is non-positive + // this will place this spell auras as debuffs + if (_IsPositiveTarget(spellTriggeredProto->Effects[i].TargetA.GetTarget(), spellTriggeredProto->Effects[i].TargetB.GetTarget()) && !spellTriggeredProto->_IsPositiveEffect(i, true)) return false; } } + } + case SPELL_AURA_PROC_TRIGGER_SPELL: + // many positive auras have negative triggered spells at damage for example and this not make it negative (it can be canceled for example) + break; + case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment. + if (effIndex == 0 && Effects[1].Effect == 0 && Effects[2].Effect == 0) + return false; // but all single stun aura spells is negative + break; + case SPELL_AURA_MOD_PACIFY_SILENCE: + if (Id == 24740) // Wisp Costume + return true; + return false; + case SPELL_AURA_MOD_ROOT: + case SPELL_AURA_MOD_SILENCE: + case SPELL_AURA_GHOST: + case SPELL_AURA_PERIODIC_LEECH: + case SPELL_AURA_MOD_STALKED: + case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: + case SPELL_AURA_PREVENT_RESURRECTION: + return false; + case SPELL_AURA_PERIODIC_DAMAGE: // used in positive spells also. + // part of negative spell if casted at self (prevent cancel) + if (Effects[effIndex].TargetA.GetTarget() == TARGET_UNIT_CASTER) + return false; + break; + case SPELL_AURA_MOD_DECREASE_SPEED: // used in positive spells also + // part of positive spell if casted at self + if (Effects[effIndex].TargetA.GetTarget() != TARGET_UNIT_CASTER) + return false; + // but not this if this first effect (didn't find better check) + if (Attributes & SPELL_ATTR0_NEGATIVE_1 && effIndex == 0) + return false; + break; + case SPELL_AURA_MECHANIC_IMMUNITY: + { + // non-positive immunities + switch (Effects[effIndex].MiscValue) + { + case MECHANIC_BANDAGE: + case MECHANIC_SHIELD: + case MECHANIC_MOUNT: + case MECHANIC_INVULNERABILITY: + return false; + default: + break; + } break; - default: + } + case SPELL_AURA_ADD_FLAT_MODIFIER: // mods + case SPELL_AURA_ADD_PCT_MODIFIER: + { + // non-positive mods + switch (Effects[effIndex].MiscValue) + { + case SPELLMOD_COST: // dependent from bas point sign (negative -> positive) + if (Effects[effIndex].CalcValue() > 0) + { + if (!deep) + { + bool negative = true; + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (i != effIndex) + if (_IsPositiveEffect(i, true)) + { + negative = false; + break; + } + } + if (negative) + return false; + } + } + break; + default: + break; + } break; - } - break; + } + default: + break; } - default: - break; + break; } - break; - } default: break; } diff --git a/src/server/game/Spells/SpellInfo.h b/src/server/game/Spells/SpellInfo.h index 589cc228d..6aece6da0 100644 --- a/src/server/game/Spells/SpellInfo.h +++ b/src/server/game/Spells/SpellInfo.h @@ -54,7 +54,7 @@ enum SpellCastTargetFlags TARGET_FLAG_UNIT_PASSENGER = 0x00100000, // guessed, used to validate target (if vehicle passenger) TARGET_FLAG_UNIT_MASK = TARGET_FLAG_UNIT | TARGET_FLAG_UNIT_RAID | TARGET_FLAG_UNIT_PARTY - | TARGET_FLAG_UNIT_ENEMY | TARGET_FLAG_UNIT_ALLY | TARGET_FLAG_UNIT_DEAD | TARGET_FLAG_UNIT_MINIPET | TARGET_FLAG_UNIT_PASSENGER, + | TARGET_FLAG_UNIT_ENEMY | TARGET_FLAG_UNIT_ALLY | TARGET_FLAG_UNIT_DEAD | TARGET_FLAG_UNIT_MINIPET | TARGET_FLAG_UNIT_PASSENGER, TARGET_FLAG_GAMEOBJECT_MASK = TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_GAMEOBJECT_ITEM, TARGET_FLAG_CORPSE_MASK = TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_CORPSE_ENEMY, TARGET_FLAG_ITEM_MASK = TARGET_FLAG_TRADE_ITEM | TARGET_FLAG_ITEM | TARGET_FLAG_GAMEOBJECT_ITEM, @@ -255,9 +255,9 @@ public: std::list* ImplicitTargetConditions; SpellEffectInfo() : _spellInfo(nullptr), _effIndex(0), Effect(0), ApplyAuraName(0), Amplitude(0), DieSides(0), - RealPointsPerLevel(0), BasePoints(0), PointsPerComboPoint(0), ValueMultiplier(0), DamageMultiplier(0), - BonusMultiplier(0), MiscValue(0), MiscValueB(0), Mechanic(MECHANIC_NONE), RadiusEntry(nullptr), ChainTarget(0), - ItemType(0), TriggerSpell(0), ImplicitTargetConditions(nullptr) {} + RealPointsPerLevel(0), BasePoints(0), PointsPerComboPoint(0), ValueMultiplier(0), DamageMultiplier(0), + BonusMultiplier(0), MiscValue(0), MiscValueB(0), Mechanic(MECHANIC_NONE), RadiusEntry(nullptr), ChainTarget(0), + ItemType(0), TriggerSpell(0), ImplicitTargetConditions(nullptr) {} SpellEffectInfo(SpellEntry const* spellEntry, SpellInfo const* spellInfo, uint8 effIndex); bool IsEffect() const; diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index a53a49a9e..5a717b05d 100644 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -61,145 +61,145 @@ DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellInfo const* spellproto, switch (spellproto->SpellFamilyName) { case SPELLFAMILY_GENERIC: - { - // Pet charge effects (Infernal Awakening, Demon Charge) - if (spellproto->SpellVisual[0] == 2816 && spellproto->SpellIconID == 15) - return DIMINISHING_CONTROLLED_STUN; - // Gnaw - else if (spellproto->Id == 47481) - return DIMINISHING_CONTROLLED_STUN; - // Screams of the Past - else if (spellproto->Id == 7074) - return DIMINISHING_NONE; - break; - } + { + // Pet charge effects (Infernal Awakening, Demon Charge) + if (spellproto->SpellVisual[0] == 2816 && spellproto->SpellIconID == 15) + return DIMINISHING_CONTROLLED_STUN; + // Gnaw + else if (spellproto->Id == 47481) + return DIMINISHING_CONTROLLED_STUN; + // Screams of the Past + else if (spellproto->Id == 7074) + return DIMINISHING_NONE; + break; + } // Event spells case SPELLFAMILY_UNK1: return DIMINISHING_NONE; case SPELLFAMILY_MAGE: - { - // Frostbite - if (spellproto->Id == 12494) - return DIMINISHING_ROOT; - // Shattered Barrier - else if (spellproto->Id == 55080) - return DIMINISHING_ROOT; - // Deep Freeze - else if (spellproto->SpellIconID == 2939 && spellproto->SpellVisual[0] == 9963) - return DIMINISHING_CONTROLLED_STUN; - // Frost Nova / Freeze (Water Elemental) - else if (spellproto->SpellIconID == 193) - return DIMINISHING_CONTROLLED_ROOT; - // Dragon's Breath - else if (spellproto->SpellFamilyFlags[0] & 0x800000) - return DIMINISHING_DRAGONS_BREATH; - break; - } + { + // Frostbite + if (spellproto->Id == 12494) + return DIMINISHING_ROOT; + // Shattered Barrier + else if (spellproto->Id == 55080) + return DIMINISHING_ROOT; + // Deep Freeze + else if (spellproto->SpellIconID == 2939 && spellproto->SpellVisual[0] == 9963) + return DIMINISHING_CONTROLLED_STUN; + // Frost Nova / Freeze (Water Elemental) + else if (spellproto->SpellIconID == 193) + return DIMINISHING_CONTROLLED_ROOT; + // Dragon's Breath + else if (spellproto->SpellFamilyFlags[0] & 0x800000) + return DIMINISHING_DRAGONS_BREATH; + break; + } case SPELLFAMILY_WARRIOR: - { - // Hamstring - limit duration to 10s in PvP - if (spellproto->SpellFamilyFlags[0] & 0x2) - return DIMINISHING_LIMITONLY; - // Improved Hamstring - else if (spellproto->Id == 23694) - return DIMINISHING_ROOT; - // Charge Stun (own diminishing) - else if (spellproto->SpellFamilyFlags[0] & 0x01000000) - return DIMINISHING_CHARGE; - break; - } + { + // Hamstring - limit duration to 10s in PvP + if (spellproto->SpellFamilyFlags[0] & 0x2) + return DIMINISHING_LIMITONLY; + // Improved Hamstring + else if (spellproto->Id == 23694) + return DIMINISHING_ROOT; + // Charge Stun (own diminishing) + else if (spellproto->SpellFamilyFlags[0] & 0x01000000) + return DIMINISHING_CHARGE; + break; + } case SPELLFAMILY_WARLOCK: - { - // Curses/etc - if ((spellproto->SpellFamilyFlags[0] & 0x80000000) || (spellproto->SpellFamilyFlags[1] & 0x200)) - return DIMINISHING_LIMITONLY; - // Seduction - else if (spellproto->SpellFamilyFlags[1] & 0x10000000) - return DIMINISHING_FEAR; - break; - } + { + // Curses/etc + if ((spellproto->SpellFamilyFlags[0] & 0x80000000) || (spellproto->SpellFamilyFlags[1] & 0x200)) + return DIMINISHING_LIMITONLY; + // Seduction + else if (spellproto->SpellFamilyFlags[1] & 0x10000000) + return DIMINISHING_FEAR; + break; + } case SPELLFAMILY_DRUID: - { - // Pounce - if (spellproto->SpellFamilyFlags[0] & 0x20000) - return DIMINISHING_OPENING_STUN; - // Cyclone - else if (spellproto->SpellFamilyFlags[1] & 0x20) - return DIMINISHING_CYCLONE; - // Entangling Roots - // Nature's Grasp - else if (spellproto->SpellFamilyFlags[0] & 0x00000200) - return DIMINISHING_CONTROLLED_ROOT; - // Faerie Fire - else if (spellproto->SpellFamilyFlags[0] & 0x400) - return DIMINISHING_LIMITONLY; - // Feral Charge Root Effect - else if (spellproto->Id == 45334) - return DIMINISHING_NONE; - break; - } + { + // Pounce + if (spellproto->SpellFamilyFlags[0] & 0x20000) + return DIMINISHING_OPENING_STUN; + // Cyclone + else if (spellproto->SpellFamilyFlags[1] & 0x20) + return DIMINISHING_CYCLONE; + // Entangling Roots + // Nature's Grasp + else if (spellproto->SpellFamilyFlags[0] & 0x00000200) + return DIMINISHING_CONTROLLED_ROOT; + // Faerie Fire + else if (spellproto->SpellFamilyFlags[0] & 0x400) + return DIMINISHING_LIMITONLY; + // Feral Charge Root Effect + else if (spellproto->Id == 45334) + return DIMINISHING_NONE; + break; + } case SPELLFAMILY_ROGUE: - { - // Gouge - if (spellproto->SpellFamilyFlags[0] & 0x8) - return DIMINISHING_DISORIENT; - // Blind - else if (spellproto->SpellFamilyFlags[0] & 0x1000000) - return DIMINISHING_FEAR; - // Cheap Shot - else if (spellproto->SpellFamilyFlags[0] & 0x400) - return DIMINISHING_OPENING_STUN; - // Crippling poison - Limit to 10 seconds in PvP (No SpellFamilyFlags) - else if (spellproto->SpellIconID == 163) - return DIMINISHING_LIMITONLY; - break; - } + { + // Gouge + if (spellproto->SpellFamilyFlags[0] & 0x8) + return DIMINISHING_DISORIENT; + // Blind + else if (spellproto->SpellFamilyFlags[0] & 0x1000000) + return DIMINISHING_FEAR; + // Cheap Shot + else if (spellproto->SpellFamilyFlags[0] & 0x400) + return DIMINISHING_OPENING_STUN; + // Crippling poison - Limit to 10 seconds in PvP (No SpellFamilyFlags) + else if (spellproto->SpellIconID == 163) + return DIMINISHING_LIMITONLY; + break; + } case SPELLFAMILY_HUNTER: - { - // Hunter's Mark - if ((spellproto->SpellFamilyFlags[0] & 0x400) && spellproto->SpellIconID == 538) - return DIMINISHING_LIMITONLY; - // Scatter Shot (own diminishing) - else if ((spellproto->SpellFamilyFlags[0] & 0x40000) && spellproto->SpellIconID == 132) - return DIMINISHING_SCATTER_SHOT; - // Entrapment (own diminishing) - else if (spellproto->SpellVisual[0] == 7484 && spellproto->SpellIconID == 20) - return DIMINISHING_ENTRAPMENT; - // Wyvern Sting mechanic is MECHANIC_SLEEP but the diminishing is DIMINISHING_DISORIENT - else if ((spellproto->SpellFamilyFlags[1] & 0x1000) && spellproto->SpellIconID == 1721) - return DIMINISHING_DISORIENT; - // Freezing Arrow - else if (spellproto->SpellFamilyFlags[0] & 0x8) - return DIMINISHING_DISORIENT; - break; - } + { + // Hunter's Mark + if ((spellproto->SpellFamilyFlags[0] & 0x400) && spellproto->SpellIconID == 538) + return DIMINISHING_LIMITONLY; + // Scatter Shot (own diminishing) + else if ((spellproto->SpellFamilyFlags[0] & 0x40000) && spellproto->SpellIconID == 132) + return DIMINISHING_SCATTER_SHOT; + // Entrapment (own diminishing) + else if (spellproto->SpellVisual[0] == 7484 && spellproto->SpellIconID == 20) + return DIMINISHING_ENTRAPMENT; + // Wyvern Sting mechanic is MECHANIC_SLEEP but the diminishing is DIMINISHING_DISORIENT + else if ((spellproto->SpellFamilyFlags[1] & 0x1000) && spellproto->SpellIconID == 1721) + return DIMINISHING_DISORIENT; + // Freezing Arrow + else if (spellproto->SpellFamilyFlags[0] & 0x8) + return DIMINISHING_DISORIENT; + break; + } case SPELLFAMILY_PALADIN: - { - // Judgement of Justice - limit duration to 10s in PvP - if (spellproto->SpellFamilyFlags[0] & 0x100000) - return DIMINISHING_LIMITONLY; - // Turn Evil - else if ((spellproto->SpellFamilyFlags[1] & 0x804000) && spellproto->SpellIconID == 309) - return DIMINISHING_FEAR; - break; - } + { + // Judgement of Justice - limit duration to 10s in PvP + if (spellproto->SpellFamilyFlags[0] & 0x100000) + return DIMINISHING_LIMITONLY; + // Turn Evil + else if ((spellproto->SpellFamilyFlags[1] & 0x804000) && spellproto->SpellIconID == 309) + return DIMINISHING_FEAR; + break; + } case SPELLFAMILY_SHAMAN: - { - // Storm, Earth and Fire - Earthgrab - if (spellproto->SpellFamilyFlags[2] & 0x4000) - return DIMINISHING_NONE; - break; - } + { + // Storm, Earth and Fire - Earthgrab + if (spellproto->SpellFamilyFlags[2] & 0x4000) + return DIMINISHING_NONE; + break; + } case SPELLFAMILY_DEATHKNIGHT: - { - // Hungering Cold (no flags) - if (spellproto->SpellIconID == 2797) - return DIMINISHING_DISORIENT; - // Mark of Blood - else if ((spellproto->SpellFamilyFlags[0] & 0x10000000) && spellproto->SpellIconID == 2285) - return DIMINISHING_LIMITONLY; - break; - } + { + // Hungering Cold (no flags) + if (spellproto->SpellIconID == 2797) + return DIMINISHING_DISORIENT; + // Mark of Blood + else if ((spellproto->SpellFamilyFlags[0] & 0x10000000) && spellproto->SpellIconID == 2285) + return DIMINISHING_LIMITONLY; + break; + } default: break; } @@ -272,45 +272,45 @@ int32 GetDiminishingReturnsLimitDuration(DiminishingGroup group, SpellInfo const switch (spellproto->SpellFamilyName) { case SPELLFAMILY_DRUID: - { - // Faerie Fire - limit to 40 seconds in PvP (3.1) - if (spellproto->SpellFamilyFlags[0] & 0x400) - return 40 * IN_MILLISECONDS; - break; - } + { + // Faerie Fire - limit to 40 seconds in PvP (3.1) + if (spellproto->SpellFamilyFlags[0] & 0x400) + return 40 * IN_MILLISECONDS; + break; + } case SPELLFAMILY_HUNTER: - { - // Wyvern Sting - if (spellproto->SpellFamilyFlags[1] & 0x1000) - return 6 * IN_MILLISECONDS; - // Hunter's Mark - if (spellproto->SpellFamilyFlags[0] & 0x400) - return 120 * IN_MILLISECONDS; - break; - } + { + // Wyvern Sting + if (spellproto->SpellFamilyFlags[1] & 0x1000) + return 6 * IN_MILLISECONDS; + // Hunter's Mark + if (spellproto->SpellFamilyFlags[0] & 0x400) + return 120 * IN_MILLISECONDS; + break; + } case SPELLFAMILY_PALADIN: - { - // Repentance - limit to 6 seconds in PvP - if (spellproto->SpellFamilyFlags[0] & 0x4) - return 6 * IN_MILLISECONDS; - break; - } + { + // Repentance - limit to 6 seconds in PvP + if (spellproto->SpellFamilyFlags[0] & 0x4) + return 6 * IN_MILLISECONDS; + break; + } case SPELLFAMILY_WARLOCK: - { - // Banish - limit to 6 seconds in PvP - if (spellproto->SpellFamilyFlags[1] & 0x8000000) - return 6 * IN_MILLISECONDS; - // Curse of Tongues - limit to 12 seconds in PvP - else if (spellproto->SpellFamilyFlags[2] & 0x800) - return 12 * IN_MILLISECONDS; - // Curse of Elements - limit to 120 seconds in PvP - else if (spellproto->SpellFamilyFlags[1] & 0x200) - return 120 * IN_MILLISECONDS; - // Curse of Exhaustion - else if (spellproto->SpellFamilyFlags[0] & 0x400000) - return 12 * IN_MILLISECONDS; - break; - } + { + // Banish - limit to 6 seconds in PvP + if (spellproto->SpellFamilyFlags[1] & 0x8000000) + return 6 * IN_MILLISECONDS; + // Curse of Tongues - limit to 12 seconds in PvP + else if (spellproto->SpellFamilyFlags[2] & 0x800) + return 12 * IN_MILLISECONDS; + // Curse of Elements - limit to 120 seconds in PvP + else if (spellproto->SpellFamilyFlags[1] & 0x200) + return 120 * IN_MILLISECONDS; + // Curse of Exhaustion + else if (spellproto->SpellFamilyFlags[0] & 0x400000) + return 12 * IN_MILLISECONDS; + break; + } default: break; } @@ -358,7 +358,7 @@ SpellMgr* SpellMgr::instance() } /// Some checks for spells, to prevent adding deprecated/broken spells for trainers, spell book, etc -bool SpellMgr::ComputeIsSpellValid(SpellInfo const *spellInfo, bool msg) +bool SpellMgr::ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg) { // not exist if (!spellInfo) @@ -377,40 +377,40 @@ bool SpellMgr::ComputeIsSpellValid(SpellInfo const *spellInfo, bool msg) // craft spell for crafting non-existed item (break client recipes list show) case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_ITEM_2: - { - if (spellInfo->Effects[i].ItemType == 0) { - // skip auto-loot crafting spells, its not need explicit item info (but have special fake items sometime) - if (!spellInfo->IsLootCrafting()) + if (spellInfo->Effects[i].ItemType == 0) + { + // skip auto-loot crafting spells, its not need explicit item info (but have special fake items sometime) + if (!spellInfo->IsLootCrafting()) + { + if (msg) + sLog->outErrorDb("Craft spell %u not have create item entry.", spellInfo->Id); + return false; + } + + } + // also possible IsLootCrafting case but fake item must exist anyway + else if (!sObjectMgr->GetItemTemplate(spellInfo->Effects[i].ItemType)) { if (msg) - sLog->outErrorDb("Craft spell %u not have create item entry.", spellInfo->Id); + sLog->outErrorDb("Craft spell %u create not-exist in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); return false; } + need_check_reagents = true; + break; } - // also possible IsLootCrafting case but fake item must exist anyway - else if (!sObjectMgr->GetItemTemplate(spellInfo->Effects[i].ItemType)) - { - if (msg) - sLog->outErrorDb("Craft spell %u create not-exist in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); - return false; - } - - need_check_reagents = true; - break; - } case SPELL_EFFECT_LEARN_SPELL: - { - SpellInfo const* spellInfo2 = sSpellMgr->GetSpellInfo(spellInfo->Effects[i].TriggerSpell); - if (!ComputeIsSpellValid(spellInfo2, msg)) { - if (msg) - sLog->outErrorDb("Spell %u learn to invalid spell %u, and then...", spellInfo->Id, spellInfo->Effects[i].TriggerSpell); - return false; + SpellInfo const* spellInfo2 = sSpellMgr->GetSpellInfo(spellInfo->Effects[i].TriggerSpell); + if (!ComputeIsSpellValid(spellInfo2, msg)) + { + if (msg) + sLog->outErrorDb("Spell %u learn to invalid spell %u, and then...", spellInfo->Id, spellInfo->Effects[i].TriggerSpell); + return false; + } + break; } - break; - } } } @@ -430,7 +430,7 @@ bool SpellMgr::ComputeIsSpellValid(SpellInfo const *spellInfo, bool msg) return true; } -bool SpellMgr::IsSpellValid(SpellInfo const *spellInfo) +bool SpellMgr::IsSpellValid(SpellInfo const* spellInfo) { if (!spellInfo) return false; @@ -827,7 +827,7 @@ bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellInfo const* spellProto, Spell if (procEvent_procEx == PROC_EX_NONE) { // No extra req, so can trigger only for hit/crit - spell has to be active - if ((procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) && active) + if ((procExtra & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) && active) return true; } else // Passive spells hits here only if resist/reflect/immune/evade @@ -844,7 +844,7 @@ bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellInfo const* spellProto, Spell if (procEvent_procEx & PROC_EX_EX_TRIGGER_ALWAYS) return true; // PROC_EX_NOT_ACTIVE_SPELL and PROC_EX_ONLY_ACTIVE_SPELL flags handle: if passed checks before - if ((procExtra & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) && ((procEvent_procEx & (AURA_SPELL_PROC_EX_MASK)) == 0)) + if ((procExtra & (PROC_EX_NORMAL_HIT | PROC_EX_CRITICAL_HIT)) && ((procEvent_procEx & (AURA_SPELL_PROC_EX_MASK)) == 0)) return true; } // Check Extra Requirement like (hit/crit/miss/resist/parry/dodge/block/immune/reflect/absorb and other) @@ -974,7 +974,7 @@ SkillLineAbilityMapBounds SpellMgr::GetSkillLineAbilityMapBounds(uint32 spell_id PetAura const* SpellMgr::GetPetAura(uint32 spell_id, uint8 eff) const { - SpellPetAuraMap::const_iterator itr = mSpellPetAuraMap.find((spell_id<<8) + eff); + SpellPetAuraMap::const_iterator itr = mSpellPetAuraMap.find((spell_id << 8) + eff); if (itr != mSpellPetAuraMap.end()) return &itr->second; else @@ -1072,93 +1072,93 @@ bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 switch (spellId) { case 58600: // No fly Zone - Dalaran - { - if (!player) - return false; + { + if (!player) + return false; - AreaTableEntry const* pArea = sAreaTableStore.LookupEntry(player->GetAreaId()); - if (!(pArea && pArea->flags & AREA_FLAG_NO_FLY_ZONE)) - return false; - if (!player->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !player->HasAuraType(SPELL_AURA_FLY)) - return false; - // Xinef: Underbelly elixir - if (player->GetPositionZ() < 637.0f && player->HasAuraType(SPELL_AURA_TRANSFORM)) - return false; - break; - } + AreaTableEntry const* pArea = sAreaTableStore.LookupEntry(player->GetAreaId()); + if (!(pArea && pArea->flags & AREA_FLAG_NO_FLY_ZONE)) + return false; + if (!player->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !player->HasAuraType(SPELL_AURA_FLY)) + return false; + // Xinef: Underbelly elixir + if (player->GetPositionZ() < 637.0f && player->HasAuraType(SPELL_AURA_TRANSFORM)) + return false; + break; + } case 58730: // No fly Zone - Wintergrasp - { - if (!player) - return false; + { + if (!player) + return false; - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()); - if (!Bf || Bf->CanFlyIn() || (!player->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !player->HasAuraType(SPELL_AURA_FLY))) - return false; - break; - } + Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()); + if (!Bf || Bf->CanFlyIn() || (!player->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !player->HasAuraType(SPELL_AURA_FLY))) + return false; + break; + } // xinef: northrend flying mounts // xinef: NE wisp and spectral gryphon case 55164: case 55173: - { - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()); - return !Bf || Bf->CanFlyIn(); - } + { + Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()); + return !Bf || Bf->CanFlyIn(); + } case 57940: // Essence of Wintergrasp OUTSIDE case 58045: // Essence of Wintergrasp INSIDE - { - if (!player) - return false; + { + if (!player) + return false; - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG); - if (!Bf || player->GetTeamId() != Bf->GetDefenderTeam() || Bf->IsWarTime()) - return false; - break; - } + Battlefield* Bf = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG); + if (!Bf || player->GetTeamId() != Bf->GetDefenderTeam() || Bf->IsWarTime()) + return false; + break; + } case 74411: // Battleground - Dampening - { - if (!player) - return false; + { + if (!player) + return false; - if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId())) - return bf->IsWarTime(); - break; - } + if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId())) + return bf->IsWarTime(); + break; + } case 68719: // Oil Refinery - Isle of Conquest. case 68720: // Quarry - Isle of Conquest. - { - if (!player) - return false; + { + if (!player) + return false; - Battleground* bg = player->GetBattleground(); - if (!bg || bg->GetBgTypeID(true) != BATTLEGROUND_IC) - return false; + Battleground* bg = player->GetBattleground(); + if (!bg || bg->GetBgTypeID(true) != BATTLEGROUND_IC) + return false; - uint8 nodeType = spellId == 68719 ? NODE_TYPE_REFINERY : NODE_TYPE_QUARRY; - uint8 nodeState = player->GetTeamId() == TEAM_ALLIANCE ? NODE_STATE_CONTROLLED_A : NODE_STATE_CONTROLLED_H; + uint8 nodeType = spellId == 68719 ? NODE_TYPE_REFINERY : NODE_TYPE_QUARRY; + uint8 nodeState = player->GetTeamId() == TEAM_ALLIANCE ? NODE_STATE_CONTROLLED_A : NODE_STATE_CONTROLLED_H; - return bg->ToBattlegroundIC()->GetNodeState(nodeType) == nodeState; - } + return bg->ToBattlegroundIC()->GetNodeState(nodeType) == nodeState; + } case 56618: // Horde Controls Factory Phase Shift case 56617: // Alliance Controls Factory Phase Shift - { - if (!player) - return false; + { + if (!player) + return false; - Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()); + Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId()); - if (!bf || bf->GetTypeId() != BATTLEFIELD_WG) - return false; + if (!bf || bf->GetTypeId() != BATTLEFIELD_WG) + return false; - // team that controls the workshop in the specified area - uint32 team = bf->GetData(newArea); + // team that controls the workshop in the specified area + uint32 team = bf->GetData(newArea); - if (team == TEAM_HORDE) - return spellId == 56618; - else if (team == TEAM_ALLIANCE) - return spellId == 56617; - break; - } + if (team == TEAM_HORDE) + return spellId == 56618; + else if (team == TEAM_ALLIANCE) + return spellId == 56617; + break; + } // Hellscream's Warsong case 73816: case 73818: @@ -1274,7 +1274,7 @@ void SpellMgr::LoadSpellRanks() do { - // spellid, rank + // spellid, rank std::list < std::pair < int32, int32 > > rankChain; int32 currentSpell = -1; int32 lastSpell = -1; @@ -1316,7 +1316,7 @@ void SpellMgr::LoadSpellRanks() int32 curRank = 0; bool valid = true; // check spells in chain - for (std::list >::iterator itr = rankChain.begin(); itr!= rankChain.end(); ++itr) + for (std::list >::iterator itr = rankChain.begin(); itr != rankChain.end(); ++itr) { SpellInfo const* spell = GetSpellInfo(itr->first); if (!spell) @@ -1356,8 +1356,7 @@ void SpellMgr::LoadSpellRanks() } else mSpellChains[addedSpell].next = GetSpellInfo(itr->first); - } - while (true); + } while (true); } while (!finished); sLog->outString(">> Loaded %u spell rank records in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); @@ -1508,7 +1507,7 @@ void SpellMgr::LoadSpellTargetPositions() continue; } - if (st.target_X==0 && st.target_Y==0 && st.target_Z==0) + if (st.target_X == 0 && st.target_Y == 0 && st.target_Z == 0) { sLog->outErrorDb("Spell (Id: %u, effIndex: %u) target coordinates not provided.", Spell_ID, effIndex); continue; @@ -1566,9 +1565,9 @@ void SpellMgr::LoadSpellTargetPositions() if (found) { if (!sSpellMgr->GetSpellTargetPosition(i)) -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_SPELLS_AURAS, "Spell (ID: %u) does not have record in `spell_target_position`", i); -#endif + #endif } }*/ @@ -1770,8 +1769,7 @@ void SpellMgr::LoadSpellProcEvents() } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u extra spell proc event conditions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -1908,8 +1906,7 @@ void SpellMgr::LoadSpellProcs() break; } ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u spell proc conditions and data in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -2080,7 +2077,7 @@ void SpellMgr::LoadSpellPetAuras() uint32 pet = fields[2].GetUInt32(); uint32 aura = fields[3].GetUInt32(); - SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find((spell<<8) + eff); + SpellPetAuraMap::iterator itr = mSpellPetAuraMap.find((spell << 8) + eff); if (itr != mSpellPetAuraMap.end()) itr->second.AddAura(pet, aura); else @@ -2092,8 +2089,8 @@ void SpellMgr::LoadSpellPetAuras() continue; } if (spellInfo->Effects[eff].Effect != SPELL_EFFECT_DUMMY && - (spellInfo->Effects[eff].Effect != SPELL_EFFECT_APPLY_AURA || - spellInfo->Effects[eff].ApplyAuraName != SPELL_AURA_DUMMY)) + (spellInfo->Effects[eff].Effect != SPELL_EFFECT_APPLY_AURA || + spellInfo->Effects[eff].ApplyAuraName != SPELL_AURA_DUMMY)) { sLog->outError("Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell); continue; @@ -2107,7 +2104,7 @@ void SpellMgr::LoadSpellPetAuras() } PetAura pa(pet, aura, spellInfo->Effects[eff].TargetA.GetTarget() == TARGET_UNIT_PET, spellInfo->Effects[eff].CalcValue()); - mSpellPetAuraMap[(spell<<8) + eff] = pa; + mSpellPetAuraMap[(spell << 8) + eff] = pa; } ++count; @@ -2126,7 +2123,7 @@ void SpellMgr::LoadEnchantCustomAttr() mEnchantCustomAttr.resize(size); for (uint32 i = 0; i < size; ++i) - mEnchantCustomAttr[i] = 0; + mEnchantCustomAttr[i] = 0; uint32 count = 0; for (uint32 i = 0; i < GetSpellInfoStoreSize(); ++i) @@ -2630,7 +2627,7 @@ void SpellMgr::LoadSpellAreas() if (sWorld->getIntConfig(CONFIG_ICC_BUFF_HORDE) > 0) { sLog->outString(">> Using ICC buff Horde: %u", sWorld->getIntConfig(CONFIG_ICC_BUFF_HORDE)); - SpellArea spellAreaICCBuffHorde = { sWorld->getIntConfig(CONFIG_ICC_BUFF_HORDE),ICC_AREA,0,0,0,ICC_RACEMASK_HORDE,Gender(2),64,11,1 }; + SpellArea spellAreaICCBuffHorde = { sWorld->getIntConfig(CONFIG_ICC_BUFF_HORDE), ICC_AREA, 0, 0, 0, ICC_RACEMASK_HORDE, Gender(2), 64, 11, 1 }; SpellArea const* saICCBuffHorde = &mSpellAreaMap.insert(SpellAreaMap::value_type(sWorld->getIntConfig(CONFIG_ICC_BUFF_HORDE), spellAreaICCBuffHorde))->second; mSpellAreaForAreaMap.insert(SpellAreaForAreaMap::value_type(ICC_AREA, saICCBuffHorde)); ++count; @@ -2641,7 +2638,7 @@ void SpellMgr::LoadSpellAreas() if (sWorld->getIntConfig(CONFIG_ICC_BUFF_ALLIANCE) > 0) { sLog->outString(">> Using ICC buff Alliance: %u", sWorld->getIntConfig(CONFIG_ICC_BUFF_ALLIANCE)); - SpellArea spellAreaICCBuffAlliance = { sWorld->getIntConfig(CONFIG_ICC_BUFF_ALLIANCE),ICC_AREA,0,0,0,ICC_RACEMASK_ALLIANCE,Gender(2),64,11,1 }; + SpellArea spellAreaICCBuffAlliance = { sWorld->getIntConfig(CONFIG_ICC_BUFF_ALLIANCE), ICC_AREA, 0, 0, 0, ICC_RACEMASK_ALLIANCE, Gender(2), 64, 11, 1 }; SpellArea const* saICCBuffAlliance = &mSpellAreaMap.insert(SpellAreaMap::value_type(sWorld->getIntConfig(CONFIG_ICC_BUFF_ALLIANCE), spellAreaICCBuffAlliance))->second; mSpellAreaForAreaMap.insert(SpellAreaForAreaMap::value_type(ICC_AREA, saICCBuffAlliance)); ++count; @@ -2726,7 +2723,7 @@ void SpellMgr::LoadSpellCustomAttr() uint32 spellId = fields[0].GetUInt32(); uint32 attributes = fields[1].GetUInt32(); - SpellInfo * spellInfo = _GetSpellInfo(spellId); + SpellInfo* spellInfo = _GetSpellInfo(spellId); if (!spellInfo) { sLog->outString("Table `spell_custom_attr` has wrong spell (spell_id: %u), ignored.", spellId); @@ -2781,7 +2778,7 @@ void SpellMgr::LoadSpellCustomAttr() for (uint8 k = 0; k < MAX_SPELL_EFFECTS; ++k) if (spellInfo->Effects[k].Effect == SPELL_EFFECT_LEARN_SPELL) if (const SpellInfo* learnSpell = GetSpellInfo(spellInfo->Effects[k].TriggerSpell)) - if (learnSpell->IsRanked() && !learnSpell->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE|SPELL_ATTR0_HIDDEN_CLIENTSIDE))) + if (learnSpell->IsRanked() && !learnSpell->HasAttribute(SpellAttr0(SPELL_ATTR0_PASSIVE | SPELL_ATTR0_HIDDEN_CLIENTSIDE))) mTalentSpellAdditionalSet.insert(learnSpell->Id); } @@ -2844,32 +2841,32 @@ void SpellMgr::LoadSpellCustomAttr() case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC: case SPELL_EFFECT_ENCHANT_HELD_ITEM: - { - // only enchanting profession enchantments procs can stack - if (IsPartOfSkillLine(SKILL_ENCHANTING, i)) { - uint32 enchantId = spellInfo->Effects[j].MiscValue; - SpellItemEnchantmentEntry const* enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId); - for (uint8 s = 0; s < MAX_SPELL_ITEM_ENCHANTMENT_EFFECTS; ++s) + // only enchanting profession enchantments procs can stack + if (IsPartOfSkillLine(SKILL_ENCHANTING, i)) { - if (enchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) - continue; + uint32 enchantId = spellInfo->Effects[j].MiscValue; + SpellItemEnchantmentEntry const* enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId); + for (uint8 s = 0; s < MAX_SPELL_ITEM_ENCHANTMENT_EFFECTS; ++s) + { + if (enchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) + continue; - SpellInfo* procInfo = (SpellInfo*)GetSpellInfo(enchant->spellid[s]); - if (!procInfo) - continue; + SpellInfo* procInfo = (SpellInfo*)GetSpellInfo(enchant->spellid[s]); + if (!procInfo) + continue; - // if proced directly from enchantment, not via proc aura - // NOTE: Enchant Weapon - Blade Ward also has proc aura spell and is proced directly - // however its not expected to stack so this check is good - if (procInfo->HasAura(SPELL_AURA_PROC_TRIGGER_SPELL)) - continue; + // if proced directly from enchantment, not via proc aura + // NOTE: Enchant Weapon - Blade Ward also has proc aura spell and is proced directly + // however its not expected to stack so this check is good + if (procInfo->HasAura(SPELL_AURA_PROC_TRIGGER_SPELL)) + continue; - procInfo->AttributesCu |= SPELL_ATTR0_CU_ENCHANT_PROC; + procInfo->AttributesCu |= SPELL_ATTR0_CU_ENCHANT_PROC; + } } + break; } - break; - } } } @@ -2899,23 +2896,23 @@ void SpellMgr::LoadSpellCustomAttr() case SPELL_EFFECT_APPLY_AREA_AURA_PET: case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: if (spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE || - spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE_PERCENT || - spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_DUMMY || - spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH || - spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_HEALTH_FUNNEL || - spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DUMMY) + spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE_PERCENT || + spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_DUMMY || + spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_LEECH || + spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_HEALTH_FUNNEL || + spellInfo->Effects[j].ApplyAuraName == SPELL_AURA_PERIODIC_DUMMY) continue; [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. default: if (spellInfo->Effects[j].CalcValue() || ((spellInfo->Effects[j].Effect == SPELL_EFFECT_INTERRUPT_CAST || spellInfo->HasAttribute(SPELL_ATTR0_CU_DONT_BREAK_STEALTH)) && !spellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY))) if (spellInfo->Id != 69649 && spellInfo->Id != 71056 && spellInfo->Id != 71057 && spellInfo->Id != 71058 && spellInfo->Id != 73061 && spellInfo->Id != 73062 && spellInfo->Id != 73063 && spellInfo->Id != 73064) // Sindragosa Frost Breath - if (spellInfo->SpellFamilyName != SPELLFAMILY_MAGE || !(spellInfo->SpellFamilyFlags[0] & 0x20)) // frostbolt - if (spellInfo->Id != 55095) // frost fever - if (spellInfo->SpellFamilyName != SPELLFAMILY_WARLOCK || !(spellInfo->SpellFamilyFlags[1] & 0x40000)) // Haunt - { - spellInfo->AttributesCu |= SPELL_ATTR0_CU_BINARY_SPELL; - break; - } + if (spellInfo->SpellFamilyName != SPELLFAMILY_MAGE || !(spellInfo->SpellFamilyFlags[0] & 0x20)) // frostbolt + if (spellInfo->Id != 55095) // frost fever + if (spellInfo->SpellFamilyName != SPELLFAMILY_WARLOCK || !(spellInfo->SpellFamilyFlags[1] & 0x40000)) // Haunt + { + spellInfo->AttributesCu |= SPELL_ATTR0_CU_BINARY_SPELL; + break; + } continue; } } @@ -3192,12 +3189,12 @@ void SpellMgr::LoadSpellCustomAttr() case 32684: case 57992: case 57993: - { - SpellEffectInfo info = spellInfo->Effects[EFFECT_0]; - spellInfo->Effects[EFFECT_0] = spellInfo->Effects[EFFECT_2]; - spellInfo->Effects[EFFECT_2] = info; - break; - } + { + SpellEffectInfo info = spellInfo->Effects[EFFECT_0]; + spellInfo->Effects[EFFECT_0] = spellInfo->Effects[EFFECT_2]; + spellInfo->Effects[EFFECT_2] = info; + break; + } // Xinef: Cooldown overwrites // Jotunheim Rapid-Fire Harpoon: Energy Reserve @@ -3354,3034 +3351,3154 @@ void SpellMgr::LoadDbcDataCorrections() case 36350: //They Must Burn Bomb Aura (self) spellInfo->EffectTriggerSpell[0] = 36325; // They Must Burn Bomb Drop (DND) break; - case 8494: // Mana Shield (rank 2) - // because of bug in dbc - spellInfo->procChance = 0; - break; - case 63320: // Glyph of Life Tap - // Entries were not updated after spell effect change, we have to do that manually :/ - spellInfo->AttributesEx3 |= SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED; - break; - case 31347: // Doom - case 41635: // Prayer of Mending - case 39365: // Thundering Storm - case 52124: // Sky Darkener Assault - case 42442: // Vengeance Landing Cannonfire - case 45863: // Cosmetic - Incinerate to Random Target - case 25425: // Shoot - case 45761: // Shoot - case 42611: // Shoot - case 61588: // Blazing Harpoon - case 36327: // Shoot Arcane Explosion Arrow - spellInfo->MaxAffectedTargets = 1; - break; - case 36384: // Skartax Purple Beam - spellInfo->MaxAffectedTargets = 2; - break; - case 37790: // Spread Shot - case 54172: // Divine Storm (heal) - case 66588: // Flaming Spear - case 54171: // Divine Storm - spellInfo->MaxAffectedTargets = 3; - break; - case 53385: // Divine Storm (Damage) - spellInfo->MaxAffectedTargets = 4; - break; - case 38296: // Spitfire Totem - spellInfo->MaxAffectedTargets = 5; - break; - case 40827: // Sinful Beam - case 40859: // Sinister Beam - case 40860: // Vile Beam - case 40861: // Wicked Beam - spellInfo->MaxAffectedTargets = 10; - break; - case 50312: // Unholy Frenzy - spellInfo->MaxAffectedTargets = 15; - break; - case 17941: // Shadow Trance - case 22008: // Netherwind Focus - case 31834: // Light's Grace - case 34754: // Clearcasting - case 34936: // Backlash - case 48108: // Hot Streak - case 51124: // Killing Machine - case 54741: // Firestarter - case 57761: // Fireball! - case 39805: // Lightning Overload - case 64823: // Item - Druid T8 Balance 4P Bonus - case 34477: // Misdirection - case 44401: // Missile Barrage - case 18820: // Insight - spellInfo->procCharges = 1; - break; - case 53390: // Tidal Wave - spellInfo->procCharges = 2; - break; - case 37408: // Oscillation Field - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - case 28200: // Ascendance (Talisman of Ascendance trinket) - spellInfo->procCharges = 6; - break; - case 51852: // The Eye of Acherus (no spawn in phase 2 in db) - spellInfo->EffectMiscValue[0] |= 1; - break; - case 51912: // Crafty's Ultra-Advanced Proto-Typical Shortening Blaster - spellInfo->EffectAmplitude[0] = 3000; - break; - case 29809: // Desecration Arm - 36 instead of 37 - typo? :/ - spellInfo->EffectRadiusIndex[0] = 37; - break; - case 42767: // Sic'em - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_NEARBY_ENTRY; - break; - // Master Shapeshifter: missing stance data for forms other than bear - bear version has correct data - // To prevent aura staying on target after talent unlearned - case 48420: - spellInfo->Stances = 1 << (FORM_CAT - 1); - break; - case 48421: - spellInfo->Stances = 1 << (FORM_MOONKIN - 1); - break; - case 48422: - spellInfo->Stances = 1 << (FORM_TREE - 1); - break; - case 51466: // Elemental Oath (Rank 1) - case 51470: // Elemental Oath (Rank 2) - spellInfo->Effect[EFFECT_1] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[EFFECT_1] = SPELL_AURA_ADD_FLAT_MODIFIER; - spellInfo->EffectMiscValue[EFFECT_1] = SPELLMOD_EFFECT2; - spellInfo->EffectSpellClassMask[EFFECT_1] = flag96(0x00000000, 0x00004000, 0x00000000); - break; - case 47569: // Improved Shadowform (Rank 1) - // with this spell atrribute aura can be stacked several times - spellInfo->Attributes &= ~SPELL_ATTR0_NOT_SHAPESHIFT; - break; - case 30421: // Nether Portal - Perseverence - spellInfo->EffectBasePoints[2] += 30000; - break; - case 16834: // Natural shapeshifter - case 16835: - spellInfo->DurationIndex = 21; - break; - case 51735: // Ebon Plague - case 51734: - case 51726: - spellInfo->SpellFamilyFlags[2] = 0x10; - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN; - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - case 41013: // Parasitic Shadowfiend Passive - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; // proc debuff, and summon infinite fiends - break; - case 27892: // To Anchor 1 - case 27928: // To Anchor 1 - case 27935: // To Anchor 1 - case 27915: // Anchor to Skulls - case 27931: // Anchor to Skulls - case 27937: // Anchor to Skulls - spellInfo->rangeIndex = 13; - break; - // target allys instead of enemies, target A is src_caster, spells with effect like that have ally target - // this is the only known exception, probably just wrong data - case 29214: // Wrath of the Plaguebringer - case 54836: // Wrath of the Plaguebringer - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ALLY; - spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_SRC_AREA_ALLY; - break; - case 57994: // Wind Shear - improper data for EFFECT_1 in 3.3.5 DBC, but is correct in 4.x - spellInfo->Effect[EFFECT_1] = SPELL_EFFECT_MODIFY_THREAT_PERCENT; - spellInfo->EffectBasePoints[EFFECT_1] = -6; // -5% - break; - case 63675: // Improved Devouring Plague - spellInfo->EffectBonusMultiplier[0] = 0; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - case 8145: // Tremor Totem (instant pulse) - case 6474: // Earthbind Totem (instant pulse) - spellInfo->AttributesEx5 |= SPELL_ATTR5_START_PERIODIC_AT_APPLY; - break; - case 53241: // Marked for Death (Rank 1) - case 53243: // Marked for Death (Rank 2) - case 53244: // Marked for Death (Rank 3) - case 53245: // Marked for Death (Rank 4) - case 53246: // Marked for Death (Rank 5) - spellInfo->EffectSpellClassMask[0] = flag96(423937, 276955137, 2049); - break; - case 70728: // Exploit Weakness - case 70840: // Devious Minds - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_PET; - break; - case 70893: // Culling The Herd - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_MASTER; - break; - case 54800: // Sigil of the Frozen Conscience - change class mask to custom extended flags of Icy Touch - // this is done because another spell also uses the same SpellFamilyFlags as Icy Touch - // SpellFamilyFlags[0] & 0x00000040 in SPELLFAMILY_DEATHKNIGHT is currently unused (3.3.5a) - // this needs research on modifier applying rules, does not seem to be in Attributes fields - spellInfo->EffectSpellClassMask[0] = flag96(0x00000040, 0x00000000, 0x00000000); - break; - case 64949: // Idol of the Flourishing Life - spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x00000000, 0x02000000, 0x00000000); - spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; - break; - case 34231: // Libram of the Lightbringer - case 60792: // Libram of Tolerance - case 64956: // Libram of the Resolute - spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x80000000, 0x00000000, 0x00000000); - spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; - break; - case 28851: // Libram of Light - case 28853: // Libram of Divinity - case 32403: // Blessed Book of Nagrand - spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x40000000, 0x00000000, 0x00000000); - spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; - break; - case 45602: // Ride Carpet - spellInfo->EffectBasePoints[EFFECT_0] = 0; // force seat 0, vehicle doesn't have the required seat flags for "no seat specified (-1)" - break; - case 64745: // Item - Death Knight T8 Tank 4P Bonus - case 64936: // Item - Warrior T8 Protection 4P Bonus - spellInfo->EffectBasePoints[EFFECT_0] = 100; // 100% chance of procc'ing, not -10% (chance calculated in PrepareTriggersExecutedOnHit) - break; - case 61719: // Easter Lay Noblegarden Egg Aura - Interrupt flags copied from aura which this aura is linked with - spellInfo->AuraInterruptFlags = AURA_INTERRUPT_FLAG_HITBYSPELL | AURA_INTERRUPT_FLAG_TAKE_DAMAGE; - break; - case 51640: // spell for item The Flag of Ownership (38578) - spellInfo->AttributesEx3 |= SPELL_ATTR3_ONLY_TARGET_PLAYERS; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; - spellInfo->MaxAffectedTargets = 1; - break; - case 34471: // The Beast Within - spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_CONFUSED | SPELL_ATTR5_USABLE_WHILE_FEARED | SPELL_ATTR5_USABLE_WHILE_STUNNED; - break; - case 40055: // Introspection - case 40165: // Introspection - case 40166: // Introspection - case 40167: // Introspection - spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; - break; - case 2378: // Minor Fortitude - spellInfo->manaCost = 0; - spellInfo->manaPerSecond = 0; - break; - case 24314: // Threatening Gaze - spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CAST | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_JUMP; - break; - - - ///////////////////////////////////////////// - /////////////////CLASS SPELLS//////////////// - ///////////////////////////////////////////// - - ///////////////////////////////// - ///// PALADIN - ///////////////////////////////// - // Heart of the Crusader - case 20335: - case 20336: - case 20337: - if (spellInfo->Id == 20335) - spellInfo->EffectTriggerSpell[0] = 21183; - else if (spellInfo->Id == 20336) - spellInfo->EffectTriggerSpell[0] = 54498; - else - spellInfo->EffectTriggerSpell[0] = 54499; - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; - break; - // Bleh, need to change FamilyFlags :/ (have the same as original aura - bad!) - case 63510: - spellInfo->SpellFamilyFlags[0] = 0; - spellInfo->SpellFamilyFlags[2] = 0x4000000; - break; - case 63514: - spellInfo->SpellFamilyFlags[0] = 0; - spellInfo->SpellFamilyFlags[2] = 0x2000000; - break; - case 63531: - spellInfo->SpellFamilyFlags[0] = 0; - spellInfo->SpellFamilyFlags[2] = 0x8000000; - break; - // And affecting spells - case 20138: - case 20139: - case 20140:// Improved Devotion Aura - spellInfo->EffectSpellClassMask[1][0] = 0; - spellInfo->EffectSpellClassMask[1][2] = 0x2000000; - break; - case 20254: - case 20255: - case 20256:// Improved concentration aura - spellInfo->EffectSpellClassMask[1][0] = 0; - spellInfo->EffectSpellClassMask[1][2] = 0x4000000; - spellInfo->EffectSpellClassMask[2][0] = 0; - spellInfo->EffectSpellClassMask[2][2] = 0x4000000; - break; - case 53379: - case 53484: - case 53648:// Swift Retribution - spellInfo->EffectSpellClassMask[0][0] = 0; - spellInfo->EffectSpellClassMask[0][2] = 0x8000000; - break; - case 31869:// Sanctified Retribution - spellInfo->EffectSpellClassMask[0][0] = 0; - spellInfo->EffectSpellClassMask[0][2] = 0x8000000; - break; - /* Judgements Facing -- SCEICCO: not sure this is offylike - case 20271: - case 53407: - case 53408: - spellInfo->FacingCasterFlags |= SPELL_FACING_FLAG_INFRONT; - break;*/ - // Seal of Light trigger - case 20167: - spellInfo->spellLevel = 0; - spellInfo->baseLevel = 0; - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - break; - // Light's Beacon, Beacon of Light - case 53651: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Hand of Reckoning - case 62124: - spellInfo->AttributesEx |= SPELL_ATTR1_CANT_BE_REDIRECTED; - break; - // Redemption - case 7328: - case 10322: - case 10324: - case 20772: - case 20773: - case 48949: - case 48950: - spellInfo->SpellFamilyName = SPELLFAMILY_PALADIN; - break; - // hack for seal of light and few spells, judgement consists of few single casts and each of them can proc - // some spell, base one has disabled proc flag but those dont have this flag - case 20184: - case 20185: - case 20186: - case 68055: - spellInfo->AttributesEx3 |= SPELL_ATTR3_CANT_TRIGGER_PROC; - break; - // Blessing of sanctuary stats - case 67480: - spellInfo->EffectMiscValue[0] = -1; - spellInfo->SpellFamilyName = SPELLFAMILY_UNK1; // allows stacking - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_DUMMY; // just a marker - break; - // Seal of Command trigger - case 20424: - spellInfo->AttributesEx3 &= ~SPELL_ATTR3_CANT_TRIGGER_PROC; - break; - // Glyph of Holy Light, Damage Class should be magic - case 54968: - // Beacon of Light heal, Damage Class should be magic - case 53652: - case 53654: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - break; - - - ///////////////////////////////// - ///// HUNTER - ///////////////////////////////// - // Furious Howl - case 64491: - case 64492: - case 64493: - case 64494: - case 64495: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_MASTER; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_MASTER; - break; - // Call of the Wild - case 53434: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_MASTER; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_MASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_CASTER; - break; - // Wild Hunt - case 62758: - case 62762: - spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; - spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_DUMMY; - break; - // Intervene - case 3411: - spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Roar of Sacrifice - case 53480: - spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_SPLIT_DAMAGE_PCT; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ALLY; - spellInfo->EffectDieSides[1] = 1; - spellInfo->EffectBasePoints[1] = 19; - spellInfo->EffectMiscValue[1] = 127; // all schools - break; - // Silencing Shot - case 34490: - case 41084: - case 42671: - spellInfo->speed = 0.0f; - break; - // Monstrous Bite - case 54680: - case 55495: - case 55496: - case 55497: - case 55498: - case 55499: - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_CASTER; - break; - // Hunter's Mark - case 1130: - case 14323: - case 14324: - case 14325: - case 53338: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - // Cobra Strikes - case 53257: - spellInfo->procCharges = 2; - spellInfo->StackAmount = 0; - break; - // Kill Command - case 34027: - spellInfo->procCharges = 0; - break; - // Kindred Spirits, damage aura - case 57458: - spellInfo->AttributesEx4 |= SPELL_ATTR4_UNK21; - break; - // Chimera Shot - Serpent trigger - case 53353: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - // Entrapment trigger - case 19185: - case 64803: - case 64804: - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[EFFECT_0] = TARGET_UNIT_DEST_AREA_ENEMY; - spellInfo->AttributesEx5 |= SPELL_ATTR5_SKIP_CHECKCAST_LOS_CHECK; - break; - // Improved Stings (Rank 2) - case 19465: - spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_CASTER; - break; - // Explosive Shot (trigger) - case 53352: - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - // Heart of the Phoenix (triggered) - case 54114: - spellInfo->AttributesEx &= ~SPELL_ATTR1_DISMISS_PET; - spellInfo->RecoveryTime = 8*60*IN_MILLISECONDS; // prev 600000 - break; - - - - ///////////////////////////////// - ///// ROGUE - ///////////////////////////////// - // Master of Subtlety - case 31221: - case 31222: - case 31223: - spellInfo->SpellFamilyName = SPELLFAMILY_ROGUE; - break; - // Master of Subtlety triggers - case 31666: - // Overkill - case 58428: - spellInfo->Effect[0] = SPELL_EFFECT_SCRIPT_EFFECT; - break; - // Honor Among Thieves - case 51698: - case 51700: - case 51701: - spellInfo->EffectTriggerSpell[0] = 51699; - break; - // Slice and Dice - case 5171: - case 6774: - // Distract - case 1725: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Envenom - case 32645: - case 32684: - case 57992: - case 57993: - spellInfo->Dispel = DISPEL_NONE; - break; - // Killing Spree (teleport) - case 57840: - spellInfo->rangeIndex = 6; // 100 yards - break; - // Killing Spree - case 51690: - spellInfo->AttributesEx |= SPELL_ATTR1_NOT_BREAK_STEALTH; - break; - - - ///////////////////////////////// - ///// DEATH KNIGHT - ///////////////////////////////// - // Blood Tap visual cd reset - case 47804: - spellInfo->Effect[2] = 0; - spellInfo->Effect[1] = 0; - spellInfo->runeCostID = 442; - break; - // Chains of Ice - case 45524: - spellInfo->Effect[EFFECT_2] = 0; - break; - // Impurity - case 49220: - case 49633: - case 49635: - case 49636: - case 49638: - spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - spellInfo->SpellFamilyName = SPELLFAMILY_DEATHKNIGHT; - break; - // Deadly Aggression (Deadly Gladiator's Death Knight Relic, item: 42620) - case 60549: - spellInfo->Effect[1] = 0; - break; - // Magic Suppression - case 49224: - case 49610: - case 49611: - spellInfo->procCharges = 0; - break; - // Wandering Plague - case 50526: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Dancing Rune Weapon - case 49028: - spellInfo->Effect[2] = 0; - spellInfo->procFlags |= PROC_FLAG_DONE_MELEE_AUTO_ATTACK; - break; - // Death and Decay - case 52212: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; - break; - // T9 blood plague crit bonus - case 67118: - spellInfo->Effect[1] = 0; - break; - // Pestilence - case 50842: - spellInfo->EffectImplicitTargetA[2] = TARGET_DEST_TARGET_ENEMY; - break; - // Horn of Winter, stacking issues - case 57330: - case 57623: - spellInfo->EffectImplicitTargetA[1] = 0; - break; - // Scourge Strike trigger - case 70890: - spellInfo->AttributesEx3 |= SPELL_ATTR3_CANT_TRIGGER_PROC; - break; - // Blood-caked Blade - Blood-caked Strike trigger - case 50463: - spellInfo->AttributesEx3 |= SPELL_ATTR3_CANT_TRIGGER_PROC; - break; - // Blood Gorged - ARP affect Death Strike and Rune Strike - case 61274: - case 61275: - case 61276: - case 61277: - case 61278: - spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x1400011, 0x20000000, 0x0); - break; - // Death Grip, remove main grip mechanic, leave only effect one - // Death Grip, should fix taunt on bosses and not break the pull protection at the same time (no aura provides immunity to grip mechanic) - case 49576: - case 49560: - spellInfo->Mechanic = 0; - break; - // Death Grip Jump Dest - case 57604: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - // Death Pact - case 48743: - spellInfo->AttributesEx &= ~SPELL_ATTR1_CANT_TARGET_SELF; - break; - // Raise Ally (trigger) - case 46619: - spellInfo->Attributes &= ~SPELL_ATTR0_CANT_CANCEL; - break; - // Frost Strike - case 49143: - case 51416: - case 51417: - case 51418: - case 51419: - case 55268: - spellInfo->AttributesEx3 |= SPELL_ATTR3_BLOCKABLE_SPELL; - break; - // Death Knight T10 Tank 2p Bonus - case 70650: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_ADD_PCT_MODIFIER; - break; - - - - ///////////////////////////////// - ///// SHAMAN - ///////////////////////////////// - // Lightning overload - case 45297: - case 45284: - spellInfo->CategoryRecoveryTime = 0; - spellInfo->RecoveryTime = 0; - spellInfo->AttributesEx6 |= SPELL_ATTR6_LIMIT_PCT_DAMAGE_MODS; - break; - // Improved Earth Shield - case 51560: - case 51561: - spellInfo->EffectMiscValue[1] = SPELLMOD_DAMAGE; - break; - // Tidal Force - case 55166: - case 55198: - spellInfo->DurationIndex = 18; - spellInfo->procCharges = 0; - break; - // Healing Stream Totem - case 52042: - spellInfo->spellLevel = 0; - spellInfo->baseLevel = 0; - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - break; - // Earth Shield - case 379: - spellInfo->spellLevel = 0; - spellInfo->baseLevel = 0; - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - // Stormstrike - case 17364: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Strength of Earth totem effect - case 8076: - case 8162: - case 8163: - case 10441: - case 25362: - case 25527: - case 57621: - case 58646: - spellInfo->EffectRadiusIndex[1] = spellInfo->EffectRadiusIndex[0]; - spellInfo->EffectRadiusIndex[2] = spellInfo->EffectRadiusIndex[0]; - break; - // Flametongue Totem effect - case 52109: - case 52110: - case 52111: - case 52112: - case 52113: - case 58651: - case 58654: - case 58655: - spellInfo->EffectImplicitTargetB[2] = spellInfo->EffectImplicitTargetB[1] = spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->EffectImplicitTargetA[2] = spellInfo->EffectImplicitTargetA[1] = spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - break; - // Sentry Totem - case 6495: - spellInfo->EffectRadiusIndex[0] = 0; - break; - // Bind Sight (PT) - case 6277: - spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_1; - spellInfo->Attributes |= SPELL_ATTR0_PASSIVE; - spellInfo->AttributesEx7 |= SPELL_ATTR7_REACTIVATE_AT_RESURRECT; // because it is passive, needs this to be properly removed at death in RemoveAllAurasOnDeath() - break; - // Ancestral Awakening Heal - case 52752: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - case 32182: // Heroism - spellInfo->excludeTargetAuraSpell = 57723; // Exhaustion - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - case 2825: // Bloodlust - spellInfo->excludeTargetAuraSpell = 57724; // Sated - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - - ///////////////////////////////// - ///// WARLOCK - ///////////////////////////////// - // Improved Succubus - case 18754: - case 18755: - case 18756: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - break; - // Unstable Affliction - case 31117: - spellInfo->PreventionType = SPELL_PREVENTION_TYPE_NONE; - break; - // Shadowflame - trigger - case 47960: // r1 - case 61291: // r2 - spellInfo->AttributesEx |= SPELL_ATTR1_CANT_BE_REDIRECTED; - break; - // Curse of Doom - summoned doomguard duration fix - case 18662: - spellInfo->DurationIndex = 6; - break; - // Glyph of Voidwalker - case 56247: - spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; - spellInfo->EffectMiscValue[EFFECT_0] = SPELLMOD_EFFECT1; - spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x8000000, 0, 0); - break; - // Everlasting Affliction - case 47201: - case 47202: - case 47203: - case 47204: - case 47205: - spellInfo->EffectSpellClassMask[1][0] |= 2; // add corruption to affected spells - break; - // Death's Embrace - case 47198: - case 47199: - case 47200: - spellInfo->EffectSpellClassMask[1][0] |= 0x4000; // include Drain Soul - break; - // Improved Demonic Tactics - case 54347: - case 54348: - case 54349: - spellInfo->Effect[EFFECT_1] = spellInfo->Effect[EFFECT_0]; - spellInfo->EffectApplyAuraName[EFFECT_1] = spellInfo->EffectApplyAuraName[EFFECT_0]; - spellInfo->EffectImplicitTargetA[EFFECT_1] = spellInfo->EffectImplicitTargetA[EFFECT_0]; - spellInfo->EffectMiscValue[EFFECT_0] = SPELLMOD_EFFECT1; - spellInfo->EffectMiscValue[EFFECT_1] = SPELLMOD_EFFECT2; - break; - // Rain of Fire (Doomguard) - case 42227: - spellInfo->speed = 0.0f; - break; - // Ritual Enslavement - case 22987: - spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_MOD_CHARM; - break; - - - ///////////////////////////////// - ///// MAGE - ///////////////////////////////// - // Combustion, make this passive - case 11129: - spellInfo->Dispel = DISPEL_NONE; - break; - // Magic Absorption (nigga stole my code) - case 29441: - case 29444: - spellInfo->spellLevel = 0; - break; - // Living Bomb - case 44461: - case 55361: - case 55362: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - spellInfo->AttributesEx4 |= SPELL_ATTR4_DAMAGE_DOESNT_BREAK_AURAS; - break; - // Evocation - case 12051: - spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; - break; - // MI Fireblast, WE Frostbolt, MI Frostbolt - case 59637: - case 31707: - case 72898: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - break; - // Blazing Speed - case 31641: - case 31642: - spellInfo->EffectTriggerSpell[0] = 31643; - break; - // Summon Water Elemental (permanent), treat it as pet - case 70908: - spellInfo->Effect[0] = SPELL_EFFECT_SUMMON_PET; - break; - // Burnout, trigger - case 44450: - spellInfo->Effect[0] = SPELL_EFFECT_POWER_BURN; - break; - // Mirror Image - Summon Spells - case 58831: - case 58833: - case 58834: - case 65047: - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_CASTER; - spellInfo->EffectRadiusIndex[EFFECT_0] = 0; - break; - // Initialize Images (Mirror Image) - case 58836: - spellInfo->EffectImplicitTargetA[EFFECT_1] = TARGET_UNIT_CASTER; - break; - // Arcane Blast, can't be dispelled - case 36032: - spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; - break; - // Chilled (frost armor, ice armor proc) - case 6136: - case 7321: - spellInfo->PreventionType = SPELL_PREVENTION_TYPE_NONE; - break; - // Mirror Image Frostbolt - case 59638: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->SpellFamilyName = SPELLFAMILY_MAGE; - spellInfo->SpellFamilyFlags = flag96(0x20, 0x0, 0x0); - break; - // Fingers of Frost - case 44544: - spellInfo->Dispel = DISPEL_NONE; - spellInfo->AttributesEx4 |= SPELL_ATTR4_NOT_STEALABLE; - spellInfo->EffectSpellClassMask[0] = flag96(685904631, 1151040, 32); // xinef: removed molten armor - break; - // Fingers of Frost visual buff - case 74396: - spellInfo->procCharges = 2; - spellInfo->StackAmount = 0; - break; - - - ///////////////////////////////// - ///// WARRIOR - ///////////////////////////////// - // Glyph of blocking - case 58375: - spellInfo->EffectTriggerSpell[0] = 58374; - break; - // Sweeping Strikes stance change - case 12328: - spellInfo->Attributes |= SPELL_ATTR0_NOT_SHAPESHIFT; - break; - // Damage Shield - case 59653: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->spellLevel = 0; - break; - // Strange shared cooldown - case 20230: // Retaliation - case 871: // Shield Wall - case 1719: // Recklessness - spellInfo->AttributesEx6 |= SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS; - break; - // Vigilance, fixes bug with empowered renew, single target aura - case 50720: - spellInfo->SpellFamilyName = SPELLFAMILY_WARRIOR; - break; - // Sunder Armor - trigger, remove spellfamilyflags because of glyph of sunder armor - case 58567: - spellInfo->SpellFamilyFlags = flag96(0x0, 0x0, 0x0); - break; - // Sunder Armor - Old Ranks - case 7405: - case 8380: - case 11596: - case 11597: - case 25225: - case 47467: - spellInfo->EffectTriggerSpell[EFFECT_0] = 11971; - spellInfo->Effect[EFFECT_0] = SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE; - break; - // Improved Spell Reflection - case 59725: - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_UNIT_CASTER_AREA_PARTY; - break; - - - - ///////////////////////////////// - ///// PRIEST - ///////////////////////////////// - // Shadow Weaving - case 15257: - case 15331: - case 15332: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; - break; - // Hymn of Hope - rewrite part of aura system or swap effects... - case 64904: - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT; - spellInfo->Effect[2] = spellInfo->Effect[0]; - spellInfo->Effect[0] = 0; - spellInfo->EffectDieSides[2] = spellInfo->EffectDieSides[0]; - spellInfo->EffectImplicitTargetA[2] = spellInfo->EffectImplicitTargetB[0]; - spellInfo->EffectRadiusIndex[2] = spellInfo->EffectRadiusIndex[0]; - spellInfo->EffectBasePoints[2] = spellInfo->EffectBasePoints[0]; - break; - // Divine Hymn - case 64844: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->spellLevel = 0; - break; - // Spiritual Healing affects prayer of mending - case 14898: case 15349: case 15354: case 15355: case 15356: - // Divine Providence affects prayer of mending - case 47562: case 47564: case 47565: case 47566: case 47567: - // Twin Disciplines affects prayer of mending - case 47586: case 47587: case 47588: case 52802: case 52803: - spellInfo->EffectSpellClassMask[0][1] |= 0x20; // prayer of mending - break; - // Power Infusion, hack to fix stacking with arcane power - case 10060: - spellInfo->Effect[EFFECT_2] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[EFFECT_2] = SPELL_AURA_ADD_PCT_MODIFIER; - spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_TARGET_ALLY; - break; - - - - ///////////////////////////////// - ///// DRUID - ///////////////////////////////// - // Lifebloom final bloom - case 33778: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->spellLevel = 0; - spellInfo->SpellFamilyFlags = flag96(0, 0x10, 0); - break; - // Clearcasting - case 16870: - spellInfo->DurationIndex = 31; // 8 secs - break; - // Owlkin Frenzy - case 48391: - spellInfo->Attributes |= SPELL_ATTR0_NOT_SHAPESHIFT; - break; - // Item T10 Restoration 4P Bonus - case 70691: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - // Faerie Fire, Faerie Fire (Feral) - case 770: - case 16857: - spellInfo->AttributesEx &= ~SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE; - break; - // Feral Charge - Cat - case 49376: - case 61138: - case 61132: - case 50259: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Glyph of Barkskin - case 63058: - spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE; - break; - - - ///////////////////////////////// - ///// MISC - ///////////////////////////////// - // Resurrection Sickness - case 15007: - spellInfo->SpellFamilyName = SPELLFAMILY_GENERIC; - break; - // Luck of the Draw - case 72221: - spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; - break; - case 3286: // Bind - spellInfo->Targets = 0; // neutral innkeepers not friendly? - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ANY; - break; - // remove creaturetargettype - case 2641: - case 23356: - spellInfo->TargetCreatureType = 0; - break; - case 34074: // Aspect of the Viper - spellInfo->Effect[2] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectImplicitTargetA[2] = 1; - spellInfo->EffectApplyAuraName[2] = SPELL_AURA_DUMMY; - break; - // Strength of Wrynn - case 60509: - spellInfo->EffectBasePoints[2] = 1500; - spellInfo->EffectBasePoints[1] = 150; - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_PERIODIC_HEAL; - break; - // Playback Speech - case 74209: - spellInfo->DurationIndex = 1; - break; - // Winterfin First Responder - case 48739: - spellInfo->EffectBasePoints[0] = 1; - spellInfo->EffectRealPointsPerLevel[0] = 0; - spellInfo->EffectDieSides[0] = 0; - spellInfo->EffectDamageMultiplier[0] = 0; - spellInfo->EffectBonusMultiplier[0] = 0; - break; - // Army of the Dead (trigger npc aura) - case 49099: - spellInfo->EffectAmplitude[0] = 15000; - break; - // Isle of Conquest - Teleport in, missing range - case 66551: - spellInfo->rangeIndex = 13; // 50000yd - break; - // A'dal's Song of Battle - case 39953: - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetA[EFFECT_1] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[EFFECT_0] = TARGET_UNIT_SRC_AREA_ALLY; - spellInfo->EffectImplicitTargetB[EFFECT_1] = TARGET_UNIT_SRC_AREA_ALLY; - spellInfo->EffectImplicitTargetB[EFFECT_2] = TARGET_UNIT_SRC_AREA_ALLY; - spellInfo->DurationIndex = 367; // 2 Hours - break; - // Wintergrasp spells - case 57607: // WintergraspCatapult - Spell Plague Barrel - EffectRadiusIndex - case 57619: // WintergraspDemolisher - Spell Hourl Boulder - EffectRadiusIndex - case 57610: // Cannon (Siege Turret) - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_25_YARDS; // SPELL_EFFECT_WMO_DAMAGE - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 51422: // WintergraspCannon - Spell Fire Cannon - EffectRadiusIndex - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; // SPELL_EFFECT_SCHOOL_DAMAGE - break; - case 54107: // WintergraspDemolisher - Spell Ram - EffectRadiusIndex - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_3_YARDS; // SPELL_EFFECT_KNOCK_BACK - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_3_YARDS; // SPELL_EFFECT_SCHOOL_DAMAGE - spellInfo->EffectRadiusIndex[2] = EFFECT_RADIUS_3_YARDS; // SPELL_EFFECT_WEAPON_DAMAGE - break; - case 51678: // WintergraspSiegeEngine - Spell Ram - EffectRadiusIndex - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; // SPELL_EFFECT_KNOCK_BACK - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_10_YARDS; // SPELL_EFFECT_SCHOOL_DAMAGE - spellInfo->EffectRadiusIndex[2] = EFFECT_RADIUS_20_YARDS; // SPELL_EFFECT_WEAPON_DAMAGE - break; - case 57606: // WintergraspCatapult - Spell Plague Barrell - Range - spellInfo->rangeIndex = 164; // "Catapult Range" - break; - case 50999: // Boulder (Demolisher) - spellInfo->EffectRadiusIndex[EFFECT_0] = 13; // 10yd - break; - case 50990: // Flame Breath (Catapult) - spellInfo->EffectRadiusIndex[EFFECT_0] = 19; // 18yd - break; - case 56103: // Jormungar Bite - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_UNIT_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[EFFECT_0] = 0; - break; - - ///////////////////////////////// - ///// Generic NPC Spells - ///////////////////////////////// - - // Throw Proximity Bomb - case 34095: - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[EFFECT_0] = 0; - break; - // DEATH KNIGHT SCARLET FIRE ARROW - case 53348: - // BALISTA - case 53117: - spellInfo->RecoveryTime = 5000; - spellInfo->CategoryRecoveryTime = 5000; - break; - // Teleport To Molten Core - case 25139: - spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; - break; - - - // /////////////////////////////////////////// - // ////////////////BOSS SPELLS//////////////// - // /////////////////////////////////////////// - ////////////////////////////////////////// - ////////// Vanilla Instances - ////////////////////////////////////////// - - // Shadowfang Keep - // Landen Stilwell Transform - case 31310: - spellInfo->Attributes |= SPELL_ATTR0_PASSIVE; - break; - - // Blackfathom Deeps - // Shadowstalker Stealth - case 5916: - spellInfo->EffectRealPointsPerLevel[EFFECT_0] = 5.0f; - break; - - // Maraudon - // Sneak - case 22766: - spellInfo->EffectRealPointsPerLevel[EFFECT_0] = 5.0f; - break; - - - ////////////////////////////////////////// - ////////// TBC Instances - ////////////////////////////////////////// - - // Shadow Labirynth - // Murmur's Touch - case 38794: - case 33711: - spellInfo->MaxAffectedTargets = 1; - spellInfo->EffectTriggerSpell[0] = 33760; - break; - - // The Arcatraz - // Negaton Field - case 36729: // Normal - case 38834: // Heroic - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Curse of the Doomsayer NORMAL - case 36173: - spellInfo->EffectTriggerSpell[0] = 36174; // Currently triggers heroic version... - break; - - // The Botanica - // Crystal Channel - case 34156: - spellInfo->rangeIndex = 35; // 35yd; - spellInfo->ChannelInterruptFlags |= AURA_INTERRUPT_FLAG_MOVE; - break; - - // Magtheridon's Lair - // Debris - case 36449: - spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; - break; - // Soul Channel - case 30531: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Debris Visual - case 30632: - spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_DYNOBJ_ALLY; - break; - - // Sunwell Plateu - // Activate Sunblade Protecto - case 46475: - case 46476: - spellInfo->rangeIndex = 14; // 60yd - break; - // Break Ice - case 46638: - spellInfo->AttributesEx3 &= ~SPELL_ATTR3_ONLY_TARGET_PLAYERS; // Obvious fail, it targets gameobject... - break; - // Sinister Reflection Clone - case 45785: - spellInfo->speed = 0.0f; - break; - // Armageddon - case 45909: - spellInfo->speed = 8.0f; - break; - - // Black Temple - // Spell Absorption - case 41034: - spellInfo->Effect[EFFECT_2] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[EFFECT_2] = SPELL_AURA_SCHOOL_ABSORB; - spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_CASTER; - spellInfo->EffectMiscValue[EFFECT_2] = SPELL_SCHOOL_MASK_MAGIC; - break; - // Shared Bonds - case 41363: - spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_1; - break; - // Deadly Poison - case 41485: - // Envenom - case 41487: - spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; - break; - // Parasitic Shadowfiend - case 41914: - spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Teleport Maiev - case 41221: - spellInfo->rangeIndex = 13; // 0-50000yd - break; - - // Serpentshrine Cavern - // Watery Grave Explosion - case 37852: - spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_STUNNED; - break; - - // Karazhan - // Amplify Damage - case 39095: - spellInfo->MaxAffectedTargets = 1; - break; - - // Magisters' Terrace - // Energy Feedback - case 44335: - spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; - break; - - /* - Raid: Battle for Mount Hyjal - Boss: Archimonde - */ - case 31984: // Spell doesn't need to ignore invulnerabilities - case 35354: - spellInfo->Attributes = SPELL_ATTR0_ABILITY; - break; - case 32111: // We only need the animation, no damage - spellInfo->CastingTimeIndex = 0; - break; - - ////////////////////////////////////////// - ////////// Vault of Archavon (VOA) - ////////////////////////////////////////// - // Flame Breath, catapult spell - case 50989: - spellInfo->Attributes &= ~SPELL_ATTR0_LEVEL_DAMAGE_CALCULATION; - break; - // Koralon, Flaming Cinder missing radius index - case 66690: - spellInfo->EffectRadiusIndex[0] = 12; //100yd - spellInfo->MaxAffectedTargets = 1; - break; - - ////////////////////////////////////////// - ////////// Naxxramas - ////////////////////////////////////////// - // Acid Volley - case 54714: - case 29325: - spellInfo->MaxAffectedTargets = 1; - break; - // Summon Plagued Warrior - case 29237: - spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; - spellInfo->Effect[1] = spellInfo->Effect[2] = 0; - break; - // Icebolt - case 28526: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - break; - // Infected Wound - case 29306: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Hopeless - case 29125: - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; - break; - // Jagged Knife - case 55550: - spellInfo->Attributes |= SPELL_ATTR0_REQ_AMMO; - break; - - ////////////////////////////////////////// - ////////// Gundrak - ////////////////////////////////////////// - // Moorabi - Transformation - case 55098: - spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; - break; - case 55521: // Poisoned Spear (Normal) - case 58967: // Poisoned Spear (Heroic) - case 55348: // Throw (Normal) - case 58966: // Throw (Heroic) - spellInfo->Attributes |= SPELL_ATTR0_REQ_AMMO; - break; - - ////////////////////////////////////////// - ////////// The Nexus: Nexus - ////////////////////////////////////////// - // Charged Chaotic rift aura, trigger - case 47737: - spellInfo->rangeIndex = 37; // 50yd - break; - - ////////////////////////////////////////// - ////////// AHN'KAHET: THE OLD KINGDOM - ////////////////////////////////////////// - // Vanish - case 55964: - spellInfo->Effect[1] = 0; - spellInfo->Effect[2] = 0; - break; - - ////////////////////////////////////////// - ////////// DRAK'THARON KEEP - ////////////////////////////////////////// - // Trollgore - Summon Drakkari Invader - case 49456: - case 49457: - case 49458: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DB; - break; - - ////////////////////////////////////////// - ////////// UTGARDE PINNACLE - ////////////////////////////////////////// - // Paralyse - case 48278: - // Awaken subboss - case 47669: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Flame Breath - case 47592: - spellInfo->EffectAmplitude[0] = 200; - break; - - ////////////////////////////////////////// - ////////// UTGARDE KEEP - ////////////////////////////////////////// - // Skarvald, Charge - case 43651: - spellInfo->rangeIndex = 13; // 0-50000yd - break; - // Ingvar the Plunderer, Woe Strike - case 42730: - spellInfo->EffectTriggerSpell[1] = 42739; - break; - case 59735: - spellInfo->EffectTriggerSpell[1] = 59736; - break; - // Ingvar the Plunderer, Ingvar transform - case 42796: - spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; - break; - case 42772: // Hurl Dagger (Normal) - case 59685: // Hurl Dagger (Heroic) - spellInfo->Attributes |= SPELL_ATTR0_REQ_AMMO; - break; - - ////////////////////////////////////////// - ////////// VIOLET HOLD - ////////////////////////////////////////// - // Control Crystal Activation - case 57804: - spellInfo->EffectImplicitTargetA[0] = 1; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Destroy Door Seal - case 58040: - spellInfo->ChannelInterruptFlags &= ~(AURA_INTERRUPT_FLAG_HITBYSPELL | AURA_INTERRUPT_FLAG_TAKE_DAMAGE); - break; - // Ichoron, Water Blast - case 54237: - case 59520: - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - - ////////////////////////////////////////// - ////////// AZJOL'NERUB - ////////////////////////////////////////// - - // Krik'thir - Mind Flay - case 52586: - case 59367: - spellInfo->ChannelInterruptFlags |= AURA_INTERRUPT_FLAG_MOVE; - break; - - ////////////////////////////////////////// - ////////// HALLS OF STONE - ////////////////////////////////////////// - // Glare of the Tribunal - case 50988: - case 59870: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Static Charge - case 50835: - case 59847: - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ALLY; - break; - - ////////////////////////////////////////// - ////////// OBSIDIAN SANCTUM - ////////////////////////////////////////// - // Lava Strike damage - case 57697: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - // Lava Strike trigger - case 57578: - spellInfo->MaxAffectedTargets = 1; - break; - // Gift of Twilight Shadow/Fire - case 57835: - case 58766: - spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_1; - break; - // Pyrobuffet - case 57557: - spellInfo->excludeTargetAuraSpell = 56911; - break; - - ////////////////////////////////////////// - ////////// EYE OF ETERNITY - ////////////////////////////////////////// - // Arcane Barrage - case 56397: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[1] = 0; - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[2] = 0; - break; - // Power Spark (ground +50% dmg aura) - case 55849: - // Arcane Overload (-50% dmg taken) - this is to prevent apply -> unapply -> apply ... dunno whether it's correct - case 56438: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Vortex (Control Vehicle) - case 56263: - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - // Haste (Nexus Lord, increase run speed of the disk) - case 57060: - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_VEHICLE; - break; - // Arcane Overload - case 56430: - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectTriggerSpell[0] = 56429; - [[fallthrough]]; - case 56429: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->EffectImplicitTargetA[1] = 0; - spellInfo->EffectImplicitTargetB[1] = 0; - spellInfo->EffectImplicitTargetA[2] = 0; - spellInfo->EffectImplicitTargetB[2] = 0; - break; - // Destroy Platform Event - case 59099: - spellInfo->EffectImplicitTargetA[1] = 22; - spellInfo->EffectImplicitTargetB[1] = 15; - spellInfo->EffectImplicitTargetA[2] = 22; - spellInfo->EffectImplicitTargetB[2] = 15; - break; - // Surge of Power (Phase 3) - case 57407: // N - case 60936: // H - spellInfo->MaxAffectedTargets = (i == 60936 ? 3 : 1); - spellInfo->InterruptFlags = 0; - spellInfo->EffectRadiusIndex[0] = 28; - spellInfo->AttributesEx4 |= SPELL_ATTR4_CAN_CAST_WHILE_CASTING; - spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - // Wyrmrest Drake - Life Burst - case 57143: - spellInfo->Effect[0] = 0; - spellInfo->EffectImplicitTargetA[0] = 0; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->EffectImplicitTargetA[1] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_SRC_AREA_ALLY; - spellInfo->EffectPointsPerComboPoint[1] = 2500; - spellInfo->EffectBasePoints[1] = 2499; - spellInfo->rangeIndex = 1; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - //Alexstrasza - Gift - case 61028: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - // Vortex (freeze anim) - case 55883: - spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; - break; - - ////////////////////////////////////////// - ////////// ULDUAR - ////////////////////////////////////////// - // Flame Leviathan - // Hurl Pyrite - case 62490: - spellInfo->Effect[EFFECT_1] = 0; - break; - - // Ulduar, Mimiron, Magnetic Core (summon) - case 64444: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_CASTER; - break; - // Ulduar, Mimiron, bomb bot explosion - case 63801: - spellInfo->EffectMiscValue[1] = 17286; - break; - // Ulduar, Mimiron, Summon Flames Initial - case 64563: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Ulduar, Mimiron, Flames (damage) - case 64566: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; - break; - - // Ulduar, Hodir, Starlight - case 62807: - spellInfo->EffectRadiusIndex[0] = 16; // 1yd - break; - - // Ulduar, General Vezax, Mark of the Faceless - case 63278: - spellInfo->Effect[0] = 0; - break; - - // XT-002 DECONSTRUCTOR - case 62834: // Boom (XT-002) - spellInfo->Effect[EFFECT_1] = 0; - break; - - // ASSEMBLY OF IRON - // Supercharge - case 61920: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - // Lightning Whirl - case 61916: - spellInfo->MaxAffectedTargets = 3; - break; - case 63482: - spellInfo->MaxAffectedTargets = 8; - break; - - // KOLOGARN - // Stone Grip, remove absorb aura - case 62056: - case 63985: - spellInfo->Effect[1] = 0; - break; - - // AURIAYA - // Sentinel Blast - case 64389: - case 64678: - spellInfo->Dispel = DISPEL_MAGIC; - break; - - // FREYA - // Potent Pheromones - case 62619: - spellInfo->AttributesEx |= SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY; - break; - // Healthy spore summon periodic - case 62566: - spellInfo->EffectAmplitude[0] = 2000; - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_TRIGGER_SPELL; - break; - // Brightleaf Essence trigger - case 62968: - spellInfo->Effect[1] = 0; // duplicate - break; - // Potent Pheromones - case 64321: - spellInfo->AttributesEx3 |= SPELL_ATTR3_ONLY_TARGET_PLAYERS; - spellInfo->AttributesEx |= SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY; - break; - - // THORIM - // charge obr stuff - case 62186: - spellInfo->EffectAmplitude[0] = 5000; // Duration 5 secs, amplitude 8 secs... - break; - // Charge Orb P2 - case 62976: - spellInfo->rangeIndex = 6; - spellInfo->DurationIndex = 28; - break; - // Sif's Blizzard - case 62576: - case 62602: - spellInfo->EffectRadiusIndex[0] = 14; // 8yd - spellInfo->EffectRadiusIndex[1] = 14; // 8yd - break; - - // YOGG-SARON - // Protective Gaze - case 64175: - spellInfo->RecoveryTime = 25000; - break; - // Shadow Beacon - case 64465: - spellInfo->EffectTriggerSpell[0] = 64467; // why do they need two script effects :/ (this one has visual effect) - break; - // Sanity - case 63050: - spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; - break; - // Shadow Nova - case 62714: - case 65209: - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - - // ALGALON - // Cosmic Smash (Algalon the Observer) - case 62293: - spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_CASTER; - break; - // Cosmic Smash (Algalon the Observer) - case 62311: - case 64596: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->EffectRadiusIndex[0] = 12; // 100yd - spellInfo->rangeIndex = 13; // 50000yd - break; - // Constellation Phase Effect - case 65509: - spellInfo->MaxAffectedTargets = 1; - break; - // Black Hole - case 62168: - case 65250: - case 62169: - spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; - break; - - // TRASH - // Ground Slam - case 62625: - spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; - break; - - ////////////////////////////////////////// - ////////// ONYXIA'S LAIR - ////////////////////////////////////////// - // Onyxia's Lair, Onyxia, Flame Breath (TriggerSpell = 0 and spamming errors in console) - case 18435: - spellInfo->Effect[1] = 0; - break; - // Onyxia's Lair, Onyxia, Create Onyxia Spawner - case 17647: - spellInfo->DurationIndex = 37; - break; - // Onyxia's Lair, Onyxia, Summon Onyxia Whelp - case 17646: - // Onyxia's Lair, Onyxia, Summon Lair Guard - case 68968: - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - spellInfo->rangeIndex = 13; - spellInfo->DurationIndex = 5; - break; - // Onyxia's Lair, Onyxia, Eruption: - case 17731: - case 69294: - spellInfo->Effect[1] = SPELL_EFFECT_DUMMY; - spellInfo->CastingTimeIndex = 3; - spellInfo->EffectRadiusIndex[1] = 19; // 18yd instead of 13yd to make sure all cracks erupt - break; - // Onyxia's Lair, Onyxia, Breath: - // TODO: fix it by IconId / SpellVisual - case 18576: case 18578: case 18579: case 18580: - case 18581: case 18582: case 18583: case 18609: case 18611: case 18612: case 18613: case 18614: - case 18615: case 18616: case 18584: case 18585: case 18586: case 18587: case 18588: case 18589: - case 18590: case 18591: case 18592: case 18593: case 18594: case 18595: case 18564: case 18565: - case 18566: case 18567: case 18568: case 18569: case 18570: case 18571: case 18572: case 18573: - case 18574: case 18575: case 18596: case 18597: case 18598: case 18599: case 18600: case 18601: - case 18602: case 18603: case 18604: case 18605: case 18606: case 18607: case 18617: case 18619: - case 18620: case 18621: case 18622: case 18623: case 18624: case 18625: case 18626: case 18627: - case 18628: case 18618: case 18351: case 18352: case 18353: case 18354: case 18355: case 18356: - case 18357: case 18358: case 18359: case 18360: case 18361: case 17086: case 17087: case 17088: - case 17089: case 17090: case 17091: case 17092: case 17093: case 17094: case 17095: case 17097: - case 22267: case 22268: case 21132: case 21133: case 21135: case 21136: case 21137: case 21138: - case 21139: - spellInfo->DurationIndex = 328; // 250ms - spellInfo->EffectImplicitTargetA[1] = 1; - if( spellInfo->Effect[1] ) - { + case 8494: // Mana Shield (rank 2) + // because of bug in dbc + spellInfo->procChance = 0; + break; + case 63320: // Glyph of Life Tap + // Entries were not updated after spell effect change, we have to do that manually :/ + spellInfo->AttributesEx3 |= SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED; + break; + case 31347: // Doom + case 41635: // Prayer of Mending + case 39365: // Thundering Storm + case 52124: // Sky Darkener Assault + case 42442: // Vengeance Landing Cannonfire + case 45863: // Cosmetic - Incinerate to Random Target + case 25425: // Shoot + case 45761: // Shoot + case 42611: // Shoot + case 61588: // Blazing Harpoon + case 36327: // Shoot Arcane Explosion Arrow + spellInfo->MaxAffectedTargets = 1; + break; + case 36384: // Skartax Purple Beam + spellInfo->MaxAffectedTargets = 2; + break; + case 37790: // Spread Shot + case 54172: // Divine Storm (heal) + case 66588: // Flaming Spear + case 54171: // Divine Storm + spellInfo->MaxAffectedTargets = 3; + break; + case 53385: // Divine Storm (Damage) + spellInfo->MaxAffectedTargets = 4; + break; + case 38296: // Spitfire Totem + spellInfo->MaxAffectedTargets = 5; + break; + case 40827: // Sinful Beam + case 40859: // Sinister Beam + case 40860: // Vile Beam + case 40861: // Wicked Beam + spellInfo->MaxAffectedTargets = 10; + break; + case 50312: // Unholy Frenzy + spellInfo->MaxAffectedTargets = 15; + break; + case 17941: // Shadow Trance + case 22008: // Netherwind Focus + case 31834: // Light's Grace + case 34754: // Clearcasting + case 34936: // Backlash + case 48108: // Hot Streak + case 51124: // Killing Machine + case 54741: // Firestarter + case 57761: // Fireball! + case 39805: // Lightning Overload + case 64823: // Item - Druid T8 Balance 4P Bonus + case 34477: // Misdirection + case 44401: // Missile Barrage + case 18820: // Insight + spellInfo->procCharges = 1; + break; + case 53390: // Tidal Wave + spellInfo->procCharges = 2; + break; + case 37408: // Oscillation Field + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + case 28200: // Ascendance (Talisman of Ascendance trinket) + spellInfo->procCharges = 6; + break; + case 51852: // The Eye of Acherus (no spawn in phase 2 in db) + spellInfo->EffectMiscValue[0] |= 1; + break; + case 51912: // Crafty's Ultra-Advanced Proto-Typical Shortening Blaster + spellInfo->EffectAmplitude[0] = 3000; + break; + case 29809: // Desecration Arm - 36 instead of 37 - typo? :/ + spellInfo->EffectRadiusIndex[0] = 37; + break; + case 42767: // Sic'em + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_NEARBY_ENTRY; + break; + // Master Shapeshifter: missing stance data for forms other than bear - bear version has correct data + // To prevent aura staying on target after talent unlearned + case 48420: + spellInfo->Stances = 1 << (FORM_CAT - 1); + break; + case 48421: + spellInfo->Stances = 1 << (FORM_MOONKIN - 1); + break; + case 48422: + spellInfo->Stances = 1 << (FORM_TREE - 1); + break; + case 51466: // Elemental Oath (Rank 1) + case 51470: // Elemental Oath (Rank 2) + spellInfo->Effect[EFFECT_1] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[EFFECT_1] = SPELL_AURA_ADD_FLAT_MODIFIER; + spellInfo->EffectMiscValue[EFFECT_1] = SPELLMOD_EFFECT2; + spellInfo->EffectSpellClassMask[EFFECT_1] = flag96(0x00000000, 0x00004000, 0x00000000); + break; + case 47569: // Improved Shadowform (Rank 1) + // with this spell atrribute aura can be stacked several times + spellInfo->Attributes &= ~SPELL_ATTR0_NOT_SHAPESHIFT; + break; + case 30421: // Nether Portal - Perseverence + spellInfo->EffectBasePoints[2] += 30000; + break; + case 16834: // Natural shapeshifter + case 16835: + spellInfo->DurationIndex = 21; + break; + case 51735: // Ebon Plague + case 51734: + case 51726: + spellInfo->SpellFamilyFlags[2] = 0x10; + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN; + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + case 41013: // Parasitic Shadowfiend Passive + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; // proc debuff, and summon infinite fiends + break; + case 27892: // To Anchor 1 + case 27928: // To Anchor 1 + case 27935: // To Anchor 1 + case 27915: // Anchor to Skulls + case 27931: // Anchor to Skulls + case 27937: // Anchor to Skulls + spellInfo->rangeIndex = 13; + break; + // target allys instead of enemies, target A is src_caster, spells with effect like that have ally target + // this is the only known exception, probably just wrong data + case 29214: // Wrath of the Plaguebringer + case 54836: // Wrath of the Plaguebringer + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ALLY; + spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_SRC_AREA_ALLY; + break; + case 57994: // Wind Shear - improper data for EFFECT_1 in 3.3.5 DBC, but is correct in 4.x + spellInfo->Effect[EFFECT_1] = SPELL_EFFECT_MODIFY_THREAT_PERCENT; + spellInfo->EffectBasePoints[EFFECT_1] = -6; // -5% + break; + case 63675: // Improved Devouring Plague + spellInfo->EffectBonusMultiplier[0] = 0; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + case 8145: // Tremor Totem (instant pulse) + case 6474: // Earthbind Totem (instant pulse) + spellInfo->AttributesEx5 |= SPELL_ATTR5_START_PERIODIC_AT_APPLY; + break; + case 53241: // Marked for Death (Rank 1) + case 53243: // Marked for Death (Rank 2) + case 53244: // Marked for Death (Rank 3) + case 53245: // Marked for Death (Rank 4) + case 53246: // Marked for Death (Rank 5) + spellInfo->EffectSpellClassMask[0] = flag96(423937, 276955137, 2049); + break; + case 70728: // Exploit Weakness + case 70840: // Devious Minds + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_PET; + break; + case 70893: // Culling The Herd + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_MASTER; + break; + case 54800: // Sigil of the Frozen Conscience - change class mask to custom extended flags of Icy Touch + // this is done because another spell also uses the same SpellFamilyFlags as Icy Touch + // SpellFamilyFlags[0] & 0x00000040 in SPELLFAMILY_DEATHKNIGHT is currently unused (3.3.5a) + // this needs research on modifier applying rules, does not seem to be in Attributes fields + spellInfo->EffectSpellClassMask[0] = flag96(0x00000040, 0x00000000, 0x00000000); + break; + case 64949: // Idol of the Flourishing Life + spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x00000000, 0x02000000, 0x00000000); + spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; + break; + case 34231: // Libram of the Lightbringer + case 60792: // Libram of Tolerance + case 64956: // Libram of the Resolute + spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x80000000, 0x00000000, 0x00000000); + spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; + break; + case 28851: // Libram of Light + case 28853: // Libram of Divinity + case 32403: // Blessed Book of Nagrand + spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x40000000, 0x00000000, 0x00000000); + spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; + break; + case 45602: // Ride Carpet + spellInfo->EffectBasePoints[EFFECT_0] = 0; // force seat 0, vehicle doesn't have the required seat flags for "no seat specified (-1)" + break; + case 64745: // Item - Death Knight T8 Tank 4P Bonus + case 64936: // Item - Warrior T8 Protection 4P Bonus + spellInfo->EffectBasePoints[EFFECT_0] = 100; // 100% chance of procc'ing, not -10% (chance calculated in PrepareTriggersExecutedOnHit) + break; + case 61719: // Easter Lay Noblegarden Egg Aura - Interrupt flags copied from aura which this aura is linked with + spellInfo->AuraInterruptFlags = AURA_INTERRUPT_FLAG_HITBYSPELL | AURA_INTERRUPT_FLAG_TAKE_DAMAGE; + break; + case 51640: // spell for item The Flag of Ownership (38578) + spellInfo->AttributesEx3 |= SPELL_ATTR3_ONLY_TARGET_PLAYERS; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; + spellInfo->MaxAffectedTargets = 1; + break; + case 34471: // The Beast Within + spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_CONFUSED | SPELL_ATTR5_USABLE_WHILE_FEARED | SPELL_ATTR5_USABLE_WHILE_STUNNED; + break; + case 40055: // Introspection + case 40165: // Introspection + case 40166: // Introspection + case 40167: // Introspection + spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; + break; + case 2378: // Minor Fortitude + spellInfo->manaCost = 0; + spellInfo->manaPerSecond = 0; + break; + case 24314: // Threatening Gaze + spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CAST | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_JUMP; + break; + + + ///////////////////////////////////////////// + /////////////////CLASS SPELLS//////////////// + ///////////////////////////////////////////// + + ///////////////////////////////// + ///// PALADIN + ///////////////////////////////// + // Heart of the Crusader + case 20335: + case 20336: + case 20337: + if (spellInfo->Id == 20335) + spellInfo->EffectTriggerSpell[0] = 21183; + else if (spellInfo->Id == 20336) + spellInfo->EffectTriggerSpell[0] = 54498; + else + spellInfo->EffectTriggerSpell[0] = 54499; + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; + break; + // Bleh, need to change FamilyFlags :/ (have the same as original aura - bad!) + case 63510: + spellInfo->SpellFamilyFlags[0] = 0; + spellInfo->SpellFamilyFlags[2] = 0x4000000; + break; + case 63514: + spellInfo->SpellFamilyFlags[0] = 0; + spellInfo->SpellFamilyFlags[2] = 0x2000000; + break; + case 63531: + spellInfo->SpellFamilyFlags[0] = 0; + spellInfo->SpellFamilyFlags[2] = 0x8000000; + break; + // And affecting spells + case 20138: + case 20139: + case 20140:// Improved Devotion Aura + spellInfo->EffectSpellClassMask[1][0] = 0; + spellInfo->EffectSpellClassMask[1][2] = 0x2000000; + break; + case 20254: + case 20255: + case 20256:// Improved concentration aura + spellInfo->EffectSpellClassMask[1][0] = 0; + spellInfo->EffectSpellClassMask[1][2] = 0x4000000; + spellInfo->EffectSpellClassMask[2][0] = 0; + spellInfo->EffectSpellClassMask[2][2] = 0x4000000; + break; + case 53379: + case 53484: + case 53648:// Swift Retribution + spellInfo->EffectSpellClassMask[0][0] = 0; + spellInfo->EffectSpellClassMask[0][2] = 0x8000000; + break; + case 31869:// Sanctified Retribution + spellInfo->EffectSpellClassMask[0][0] = 0; + spellInfo->EffectSpellClassMask[0][2] = 0x8000000; + break; + /* Judgements Facing -- SCEICCO: not sure this is offylike + case 20271: + case 53407: + case 53408: + spellInfo->FacingCasterFlags |= SPELL_FACING_FLAG_INFRONT; + break;*/ + // Seal of Light trigger + case 20167: + spellInfo->spellLevel = 0; + spellInfo->baseLevel = 0; + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + break; + // Light's Beacon, Beacon of Light + case 53651: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Hand of Reckoning + case 62124: + spellInfo->AttributesEx |= SPELL_ATTR1_CANT_BE_REDIRECTED; + break; + // Redemption + case 7328: + case 10322: + case 10324: + case 20772: + case 20773: + case 48949: + case 48950: + spellInfo->SpellFamilyName = SPELLFAMILY_PALADIN; + break; + // hack for seal of light and few spells, judgement consists of few single casts and each of them can proc + // some spell, base one has disabled proc flag but those dont have this flag + case 20184: + case 20185: + case 20186: + case 68055: + spellInfo->AttributesEx3 |= SPELL_ATTR3_CANT_TRIGGER_PROC; + break; + // Blessing of sanctuary stats + case 67480: + spellInfo->EffectMiscValue[0] = -1; + spellInfo->SpellFamilyName = SPELLFAMILY_UNK1; // allows stacking + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_DUMMY; // just a marker + break; + // Seal of Command trigger + case 20424: + spellInfo->AttributesEx3 &= ~SPELL_ATTR3_CANT_TRIGGER_PROC; + break; + // Glyph of Holy Light, Damage Class should be magic + case 54968: + // Beacon of Light heal, Damage Class should be magic + case 53652: + case 53654: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + break; + + + ///////////////////////////////// + ///// HUNTER + ///////////////////////////////// + // Furious Howl + case 64491: + case 64492: + case 64493: + case 64494: + case 64495: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_MASTER; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_MASTER; + break; + // Call of the Wild + case 53434: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_MASTER; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_MASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_CASTER; + break; + // Wild Hunt + case 62758: + case 62762: + spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_PERIODIC_TRIGGER_SPELL; - spellInfo->EffectAmplitude[1] = ((spellInfo->CastingTimeIndex == 170) ? 50 : 215); - } - break; - - ////////////////////////////////////////// - ////////// THE NEXUS: OCULUS - ////////////////////////////////////////// - // Oculus, Teleport to Coldarra DND - case 48760: - // Oculus, Teleport to Boss 1 DND - case 49305: - spellInfo->EffectImplicitTargetA[0] = 25; - spellInfo->EffectImplicitTargetB[0] = 17; - break; - // Oculus, Drake spell Stop Time - case 49838: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - spellInfo->excludeTargetAuraSpell = 51162; // exclude planar shift - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_150_YARDS; - break; - // Oculus, Varos Cloudstrider, Energize Cores - case 61407: - case 62136: - case 56251: - case 54069: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CONE_ENTRY; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - - ////////////////////////////////////////// - ////////// HALLS OF LIGHTNING - ////////////////////////////////////////// - // Halls of Lightning, Arc Weld - case 59086: - spellInfo->EffectImplicitTargetA[0] = 1; - break; - // Halls of Lightning, Arcing Burn - case 52671: - case 59834: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - - ////////////////////////////////////////// - ////////// TRIAL OF THE CHAMPION - ////////////////////////////////////////// - // Trial of the Champion, Death's Respite - case 68306: - spellInfo->EffectImplicitTargetA[0] = 25; - spellInfo->EffectImplicitTargetA[1] = 25; - break; - // Trial of the Champion, Eadric Achievement (The Faceroller) - case 68197: - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ALLY; - spellInfo->Attributes |= SPELL_ATTR0_CASTABLE_WHILE_DEAD; - break; - // Trial of the Champion, Earth Shield - case 67530: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; // will trigger 67537 - break; - // Trial of the Champion, Hammer of the Righteous - case 66867: - spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; - break; - // Trial of the Champion, Summon Risen Jaeren/Arelas - case 67705: - case 67715: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; - break; - // Trial of the Champion, Ghoul Explode - case 67751: - spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; - spellInfo->EffectRadiusIndex[0] = 12; - spellInfo->EffectImplicitTargetA[1] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_SRC_AREA_ENTRY; - spellInfo->EffectRadiusIndex[1] = 12; - spellInfo->EffectImplicitTargetA[2] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[2] = TARGET_UNIT_SRC_AREA_ENTRY; - spellInfo->EffectRadiusIndex[2] = 12; - break; - // Trial of the Champion, Desecration - case 67778: - case 67877: - spellInfo->EffectTriggerSpell[0] = 68766; - break; - - ////////////////////////////////////////// - ////////// TRIAL OF THE CRUSADER - ////////////////////////////////////////// - // Trial of the Crusader, Jaraxxus Intro spell - case 67888: - spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; - spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Trial of the Crusader, Lich King Intro spell - case 68193: - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; - break; - // Trial of the Crusader, Gormok, player vehicle spell, CUSTOM! (default jump to hand, not used) - case 66342: - spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_SET_VEHICLE_ID; - spellInfo->EffectMiscValue[0] = 496; - spellInfo->DurationIndex = 21; - spellInfo->rangeIndex = 13; - spellInfo->EffectImplicitTargetA[0] = 25; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->AuraInterruptFlags = AURA_INTERRUPT_FLAG_CHANGE_MAP; - break; - // Trial of the Crusader, Gormok, Fire Bomb - case 66313: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_TARGET_ANY; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[1] = TARGET_DEST_TARGET_ANY; - spellInfo->Effect[1] = 0; - [[fallthrough]]; - case 66317: - spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; - spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - case 66318: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->speed = 14.0f; - spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; - spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - case 66320: - case 67472: - case 67473: - case 67475: - spellInfo->EffectRadiusIndex[0] = 7; - spellInfo->EffectRadiusIndex[1] = 7; - break; - // Trial of the Crusader, Acidmaw & Dreadscale, Emerge - case 66947: - spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_STUNNED; - break; - // Trial of the Crusader, Jaraxxus, Curse of the Nether - case 66211: - spellInfo->excludeTargetAuraSpell = 66209; // exclude Touch of Jaraxxus - break; - // Trial of the Crusader, Jaraxxus, Summon Volcano - case 66258: - case 67901: - spellInfo->DurationIndex = 85; // summon for 18 seconds, 15 not enough - break; - // Trial of the Crusader, Jaraxxus, Spinning Pain Spike - case 66281: - spellInfo->EffectRadiusIndex[0] = 26; - break; - case 66287: - spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_TAUNT; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_NEARBY_ENTRY; - spellInfo->Effect[2] = SPELL_EFFECT_APPLY_AURA; - spellInfo->EffectApplyAuraName[2] = SPELL_AURA_MOD_STUN; - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_CASTER; - spellInfo->DurationIndex = 35; // 4 secs - break; - // Trial of the Crusader, Jaraxxus, Fel Fireball - case 66532: - case 66963: - case 66964: - case 66965: - spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; - break; - // tempfix, make Nether Power not stealable - case 66228: - case 67106: - case 67107: - case 67108: - spellInfo->AttributesEx4 |= SPELL_ATTR4_NOT_STEALABLE; - break; - // Trial of the Crusader, Faction Champions, Druid - Tranquality - case 66086: - case 67974: - case 67975: - case 67976: - spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AREA_AURA_FRIEND; - break; - // Trial of the Crusader, Faction Champions, Shaman - Earth Shield - case 66063: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; - spellInfo->EffectTriggerSpell[0] = 66064; - break; - // Trial of the Crusader, Faction Champions, Priest - Mana Burn - case 66100: - spellInfo->EffectBasePoints[0] = 5; - spellInfo->EffectDieSides[0] = 0; - break; - case 68026: - spellInfo->EffectBasePoints[0] = 8; - spellInfo->EffectDieSides[0] = 0; - break; - case 68027: - spellInfo->EffectBasePoints[0] = 6; - spellInfo->EffectDieSides[0] = 0; - break; - case 68028: - spellInfo->EffectBasePoints[0] = 10; - spellInfo->EffectDieSides[0] = 0; - break; - - // Trial of the Crusader, Twin Valkyr, Touch of Light/Darkness, Light/Dark Surge - case 65950: // light 0 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 65767: // light surge 0 - spellInfo->excludeTargetAuraSpell = 65686; - break; - case 67296: // light 1 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 67274: // light surge 1 - spellInfo->excludeTargetAuraSpell = 67222; - break; - case 67297: // light 2 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 67275: // light surge 2 - spellInfo->excludeTargetAuraSpell = 67223; - break; - case 67298: // light 3 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 67276: // light surge 3 - spellInfo->excludeTargetAuraSpell = 67224; - break; - case 66001: // dark 0 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 65769: // dark surge 0 - spellInfo->excludeTargetAuraSpell = 65684; - break; - case 67281: // dark 1 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 67265: // dark surge 1 - spellInfo->excludeTargetAuraSpell = 67176; - break; - case 67282: // dark 2 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 67266: // dark surge 2 - spellInfo->excludeTargetAuraSpell = 67177; - break; - case 67283: // dark 3 - //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - spellInfo->EffectImplicitTargetA[0] = 6; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. - case 67267: // dark surge 3 - spellInfo->excludeTargetAuraSpell = 67178; - break; - - // Trial of the Crusader, Twin Valkyr, Twin's Pact - case 65875: case 67303: case 67304: case 67305: case 65876: case 67306: case 67307: case 67308: - spellInfo->Effect[1] = 0; spellInfo->Effect[2] = 0; - break; - // Trial of the Crusader, Anub'arak, Emerge - case 65982: - spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_STUNNED; - break; - // Trial of the Crusader, Anub'arak, Penetrating Cold - case 66013: - case 67700: - case 68509: - case 68510: - spellInfo->EffectRadiusIndex[0] = 12; // 100yd - break; - // Trial of the Crusader, Anub'arak, Shadow Strike - case 66134: - spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; - spellInfo->Effect[0] = 0; - break; - // Trial of the Crusader, Anub'arak, Pursuing Spikes - case 65920: - case 65922: - case 65923: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; - //spellInfo->EffectTriggerSpell[0] = 0; - break; - // Trial of the Crusader, Anub'arak, Summon Scarab - case 66339: - spellInfo->DurationIndex = 35; - spellInfo->EffectImplicitTargetA[0] = 25; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Trial of the Crusader, Anub'arak, Achievements: The Traitor King - case 68186: // Anub'arak Scarab Achievement 10 - case 68515: // Anub'arak Scarab Achievement 25 - spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; - spellInfo->Attributes |= SPELL_ATTR0_CASTABLE_WHILE_DEAD; - break; - // Trial of the Crusader, Anub'arak, Spider Frenzy - case 66129: - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - - ////////////////////////////////////////// - ////////// THE FORGE OF SOULS - ////////////////////////////////////////// - // Soul Sickness (69131) - case 69131: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_TRIGGER_SPELL; - spellInfo->EffectAmplitude[0] = 8000; - spellInfo->EffectTriggerSpell[0] = 69133; - break; - // Phantom Blast (68982,70322) - case 68982: - case 70322: - spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; - break; - - ////////////////////////////////////////// - ////////// PIT OF SARON - ////////////////////////////////////////// - // Empowered Blizzard - case 70131: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - // Ice Lance Volley - case 70464: - spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; - spellInfo->EffectRadiusIndex[0] = 25; - break; - // Multi-Shot - case 70513: - // Shriek of the Highborne - case 59514: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CONE_ENTRY; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Icicle - case 69428: - case 69426: - spellInfo->InterruptFlags = 0; - spellInfo->AuraInterruptFlags = 0; - spellInfo->ChannelInterruptFlags = 0; - break; - // Jaina's Call - case 70525: - // Call of Sylvanas - case 70639: - spellInfo->Effect[0] = 0; - spellInfo->Effect[1] = 0; - spellInfo->EffectImplicitTargetA[2] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[2] = TARGET_UNIT_SRC_AREA_ENTRY; - spellInfo->EffectRadiusIndex[2] = 30; // 500yd - break; - // Frost Nova - case 68198: - spellInfo->rangeIndex = 13; - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - break; - // Blight - case 69604: - case 70286: - spellInfo->MaxAffectedTargets = 1; - spellInfo->AttributesEx3 |= (SPELL_ATTR3_IGNORE_HIT_RESULT | SPELL_ATTR3_ONLY_TARGET_PLAYERS); - break; - // Chilling Wave - case 68778: - case 70333: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Permafrost - case 68786: - case 70336: - spellInfo->AttributesEx3 |= (SPELL_ATTR3_IGNORE_HIT_RESULT | SPELL_ATTR3_ONLY_TARGET_PLAYERS); - spellInfo->Effect[2] = SPELL_EFFECT_DUMMY; - break; - // Pursuit: - case 68987: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[1] = 0; - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetB[2] = 0; - spellInfo->rangeIndex = 6; // 100yd - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - case 69029: - case 70850: - spellInfo->Effect[2] = 0; - break; - // Explosive Barrage: - case 69263: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_MOD_STUN; - break; - // Overlord's Brand: - case 69172: - spellInfo->procFlags = DONE_HIT_PROC_FLAG_MASK & ~PROC_FLAG_DONE_PERIODIC; - spellInfo->procChance = 100; - break; - // Icy Blast: - case 69232: - spellInfo->EffectTriggerSpell[1] = 69238; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - case 69233: - case 69646: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - case 69238: - case 69628: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_DYNOBJ_NONE; - spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[1] = TARGET_DEST_DYNOBJ_NONE; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - // Hoarfrost: - case 69246: - case 69245: - case 69645: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - // Devour Humanoid: - case 69503: - spellInfo->ChannelInterruptFlags |= 0; - spellInfo->AuraInterruptFlags = AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING; - break; - - ////////////////////////////////////////// - ////////// HALLS OF REFLECTION - ////////////////////////////////////////// - // Falric: Defiling Horror - case 72435: - case 72452: - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; - break; - // Frostsworn General - Throw Shield - case 69222: - case 73076: - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ENEMY; - break; - // Halls of Reflection Clone - case 69828: - spellInfo->Effect[1] = 0; - spellInfo->Effect[2] = 0; - break; - // Summon Ice Wall - case 69768: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - break; - case 69767: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_TARGET_ANY; - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ANY; - break; - // Essence of the Captured - case 73035: - case 70719: - spellInfo->rangeIndex = 13; - break; - // Achievement Check - case 72830: - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; - break; - - ////////////////////////////////////////// - ////////// ICECROWN CITADEL - ////////////////////////////////////////// - case 70781: // Light's Hammer Teleport - case 70856: // Oratory of the Damned Teleport - case 70857: // Rampart of Skulls Teleport - case 70858: // Deathbringer's Rise Teleport - case 70859: // Upper Spire Teleport - case 70860: // Frozen Throne Teleport - case 70861: // Sindragosa's Lair Teleport - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DB; // this target is for SPELL_EFFECT_TELEPORT_UNITS - spellInfo->EffectImplicitTargetB[1] = 0; - spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[2] = 0; - break; - case 70960: // Bone Flurry - case 71258: // Adrenaline Rush (Ymirjar Battle-Maiden) - spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_2; - break; - case 69055: // Saber Lash (Lord Marrowgar) - case 70814: // Saber Lash (Lord Marrowgar) - spellInfo->EffectRadiusIndex[0] = 8; // 5yd - break; - case 69065: // Impaled (Lord Marrowgar) - spellInfo->Effect[0] = 0; // remove stun so Dispersion can be used - break; - case 72701: // Cold Flame (Lord Marrowgar) - case 72702: // Cold Flame (Lord Marrowgar) - case 72703: // Cold Flame (Lord Marrowgar) - case 72704: // Cold Flame (Lord Marrowgar) - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[1] = 0; - spellInfo->DurationIndex = 9; // 30 secs instead of 12, need him for longer, but will stop his actions after 12 secs - break; - case 69138: // Coldflame (Lord Marrowgar) - spellInfo->Effect[0] = 0; - spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DEST; - spellInfo->DurationIndex = 9; // 30 secs instead of 12, need him for longer, but will stop his actions after 12 secs - break; - case 69146: case 70823: case 70824: case 70825: // Coldflame (Lord Marrowgar) - spellInfo->EffectRadiusIndex[0] = 15; // 3yd instead of 5yd - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; - break; - case 70897: // Dark Martyrdom (Lady Deathwhisper) - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; - break; - case 69075: // Bone Storm (Lord Marrowgar) - case 70834: // Bone Storm (Lord Marrowgar) - case 70835: // Bone Storm (Lord Marrowgar) - case 70836: // Bone Storm (Lord Marrowgar) - case 72378: // Blood Nova (Deathbringer Saurfang) - case 73058: // Blood Nova (Deathbringer Saurfang) - case 72769: // Scent of Blood (Deathbringer Saurfang) - case 72385: // Boiling Blood (Deathbringer Saurfang) - case 72441: // Boiling Blood (Deathbringer Saurfang) - case 72442: // Boiling Blood (Deathbringer Saurfang) - case 72443: // Boiling Blood (Deathbringer Saurfang) - case 71160: // Plague Stench (Stinky) - case 71161: // Plague Stench (Stinky) - case 71123: // Decimate (Stinky & Precious) - case 71464: // Divine Surge (Sister Svalna) - spellInfo->EffectRadiusIndex[0] = 12; // 100yd - break; - case 71169: // Shadow's Fate - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - case 72347: // Lock Players and Tap Chest - spellInfo->AttributesEx3 &= ~SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - case 73843: // Award Reputation - Boss Kill - case 73844: // Award Reputation - Boss Kill - case 73845: // Award Reputation - Boss Kill - case 73846: // Award Reputation - Boss Kill - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_50000_YARDS; - break; - case 72864: // Death Plague (Rotting Frost Giant) - spellInfo->excludeTargetAuraSpell = 0; - break; - case 69705: // Gunship Battle, spell Below Zero - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - case 72723: // Resistant Skin (Deathbringer Saurfang adds) - // this spell initially granted Shadow damage immunity, however it was removed but the data was left in client - spellInfo->Effect[2] = 0; - break; - case 72255: // Mark of the Fallen Champion (Deathbringer Saurfang) // Patch 3.3.2 (2010-01-02): Deathbringer Saurfang will no longer gain blood power from Mark of the Fallen Champion. - case 72444: // Mark of the Fallen Champion (Deathbringer Saurfang) // Xinef: prevented in script, effect needed for Prayer of Mending - case 72445: // Mark of the Fallen Champion (Deathbringer Saurfang) - case 72446: // Mark of the Fallen Champion (Deathbringer Saurfang) - spellInfo->AttributesEx3 &= ~SPELL_ATTR3_CANT_TRIGGER_PROC; - break; - case 70460: // Coldflame Jets (Traps after Saurfang) - spellInfo->DurationIndex = 1; // 10 seconds - break; - case 70461: // Coldflame Jets (Traps after Saurfang) - case 71289: // Dominate Mind (Lady Deathwhisper) - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - case 71906: // Severed Essence (Val'kyr Herald) - case 71942: // Severed Essence (Val'kyr Herald) - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY; - spellInfo->EffectImplicitTargetB[0] = 0; - spellInfo->Effect[1] = 0; - break; - case 71159: // Awaken Plagued Zombies (Precious) - case 71302: // Awaken Ymirjar Fallen (Ymirjar Deathbringer) - spellInfo->DurationIndex = 21; - break; - case 70981: // Blood Prince Council, Invocation of Blood - case 70982: // Blood Prince Council, Invocation of Blood - case 70952: // Blood Prince Council, Invocation of Blood - spellInfo->Effect[0] = 0; // clear share health aura - break; - case 71274: // Ymirjar Frostbinder, Frozen Orb - spellInfo->EffectImplicitTargetA[0] = 6; - break; - case 69783: // Ooze Flood (Rotface) - case 69797: - case 69799: - case 69802: - spellInfo->AttributesEx |= SPELL_ATTR1_CANT_TARGET_SELF; - break; - case 70530: // Volatile Ooze Beam Protection - spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; // blizzard typo, 65 instead of 6, aura itself is defined (dummy) - break; - case 70672: case 72455: case 72832: case 72833: // Professor Putricide, Gaseous Bloat (Orange Ooze Channel) -- copied attributes from Green Ooze Channel - spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - case 71412: // Green Ooze Summon (Professor Putricide) - case 71415: // Orange Ooze Summon (Professor Putricide) - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - break; - case 71621: case 72850: case 72851: case 72852: // Create Concoction (Professor Putricide) - case 71893: case 73120: case 73121: case 73122: // Guzzle Potions (Professor Putricide) - spellInfo->CastingTimeIndex = 15; // 4 sec - break; - case 72454: // Mutated Plague (Professor Putricide) - case 72464: // Mutated Plague (Professor Putricide) - case 72506: // Mutated Plague (Professor Putricide) - case 72507: // Mutated Plague (Professor Putricide) - spellInfo->AttributesEx4 |= SPELL_ATTR4_IGNORE_RESISTANCES; - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - case 70911: // Unbound Plague (Professor Putricide) (needs target selection script) - case 72854: // Unbound Plague (Professor Putricide) (needs target selection script) - case 72855: // Unbound Plague (Professor Putricide) (needs target selection script) - case 72856: // Unbound Plague (Professor Putricide) (needs target selection script) - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ENEMY; - break; - case 70402: // Mutated Transformation (Professor Putricide) - case 72511: // Mutated Transformation (Professor Putricide) - case 72512: // Mutated Transformation (Professor Putricide) - case 72513: // Mutated Transformation (Professor Putricide) - spellInfo->AttributesEx2 |= SPELL_ATTR2_CANT_CRIT; - break; - case 71708: // Empowered Flare (Blood Prince Council) - case 72785: // Empowered Flare (Blood Prince Council) - case 72786: // Empowered Flare (Blood Prince Council) - case 72787: // Empowered Flare (Blood Prince Council) - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - case 71518: // Unholy Infusion Quest Credit (Professor Putricide) - case 72934: // Blood Infusion Quest Credit (Blood-Queen Lana'thel) - case 72289: // Frost Infusion Quest Credit (Sindragosa) - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // another missing radius - break; - case 71266: // Swarming Shadows - case 72890: // Swarming Shadows - spellInfo->AreaGroupId = 0; // originally, these require area 4522, which is... outside of Icecrown Citadel - break; - case 71301: // Summon Dream Portal (Valithria Dreamwalker) - case 71977: // Summon Nightmare Portal (Valithria Dreamwalker) - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - case 70715: // Column of Frost (visual marker) - spellInfo->DurationIndex = 32; // 6 seconds (missing) - break; - case 71085: // Mana Void (periodic aura) - spellInfo->DurationIndex = 9; // 30 seconds (missing) - break; - case 70936: // Summon Suppressor (needs target selection script) - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - case 70602: // Corruption - spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; - break; - case 72706: // Achievement Check (Valithria Dreamwalker) - case 71357: // Order Whelp - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - break; - case 70598: // Sindragosa's Fury - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - case 71077: // Tail Smash (Sindragosa) - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_CASTER_BACK; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_DEST_AREA_ENEMY; - spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_CASTER_BACK; - spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_DEST_AREA_ENEMY; - break; - case 69846: // Frost Bomb - spellInfo->speed = 0.0f; // This spell's summon happens instantly - break; - case 70127: // Mystic Buffet (Sindragosa) - remove obsolete spell effect with no targets - case 72528: - case 72529: - case 72530: - spellInfo->Effect[1] = 0; - break; - case 70084: // Sindragosa, Frost Aura - case 71050: - case 71051: - case 71052: - spellInfo->Attributes &= ~SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; - break; - - case 71614: // Ice Lock - spellInfo->Mechanic = MECHANIC_STUN; - break; - case 70541: // Lich King, Infest - case 73779: - case 73780: - case 73781: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - case 70337: // Lich King, Necrotic Plague - case 73912: - case 73913: - case 73914: - case 70338: - case 73785: - case 73786: - case 73787: - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - case 69099: // Ice Pulse 10n - case 73776: // Ice Pulse 25n - case 73777: // Ice Pulse 10h - case 73778: // Ice Pulse 25h - spellInfo->AttributesEx2 |= SPELL_ATTR2_CANT_CRIT; - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; - break; - case 72350: // Fury of Frostmourne - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - case 72351: // Fury of Frostmourne - case 72431: // Jump (removes Fury of Frostmourne debuff) - case 72429: // Mass Resurrection - case 73159: // Play Movie - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - case 72376: // Raise Dead - spellInfo->MaxAffectedTargets = 4; - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - case 71809: // Jump - spellInfo->rangeIndex = 5; // 40yd - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; // 10yd - spellInfo->EffectMiscValue[0] = 190; - break; - case 72405: // Broken Frostmourne - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; // 200yd - break; - case 73540: // Summon Shadow Trap - spellInfo->DurationIndex = 3; // 60 seconds - break; - case 73530: // Shadow Trap (visual) - spellInfo->DurationIndex = 28; // 5 seconds - break; - case 73529: // Shadow Trap - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_10_YARDS; // 10yd - break; - case 74282: // Shadow Trap (searcher) - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_3_YARDS; // 3yd - break; - case 69198: // Raging Spirit Visual - spellInfo->rangeIndex = 13; // 50000yd - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; - break; - case 72762: // Defile - spellInfo->DurationIndex = 559; // 53 seconds - spellInfo->excludeCasterAuraSpell = 0; - spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; - spellInfo->AttributesEx6 |= (SPELL_ATTR6_CAN_TARGET_INVISIBLE | SPELL_ATTR6_CAN_TARGET_UNTARGETABLE); - break; - case 72743: // Defile - spellInfo->DurationIndex = 22; // 45 seconds - break; - case 72754: // Defile - case 73708: // Defile - case 73709: // Defile - case 73710: // Defile - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; // 200yd - break; - case 69030: // Val'kyr Target Search - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; // 200yd - spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; - break; - case 73654: // Harvest Souls - case 74295: // Harvest Souls - case 74296: // Harvest Souls - case 74297: // Harvest Souls - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_50000_YARDS; // 50000yd - spellInfo->EffectRadiusIndex[2] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - case 72595: // Restore Soul - case 73650: // Restore Soul - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - break; - case 75127: // Kill Frostmourne Players - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - case 73655: // Harvest Soul - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; - break; - case 74086: // Destroy Soul - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - break; - case 74302: // Summon Spirit Bomb - case 74342: // Summon Spirit Bomb - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - spellInfo->MaxAffectedTargets = 1; - break; - case 74341: // Summon Spirit Bomb - case 74343: // Summon Spirit Bomb - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd - spellInfo->MaxAffectedTargets = 3; - break; - case 73579: // Summon Spirit Bomb - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_25_YARDS; // 25yd - break; - case 73582: // Trigger Vile Spirit (Inside, Heroic) - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd - break; - // Scale Aura (used during Dominate Mind from Lady Deathwhisper) - case 73261: - spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; - break; - // Leap to a Random Location - case 70485: - spellInfo->rangeIndex = 6; // 100yd - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; - spellInfo->EffectMiscValue[0] = 100; - break; - // Empowered Blood - case 70227: - case 70232: - spellInfo->AreaGroupId = 2452; // Whole icc instead of Crimson Halls only, remove when area calculation is fixed - break; - - ////////////////////////////////////////// - ////////// RUBY SANCTUN - ////////////////////////////////////////// - // Repelling Wave - case 74509: - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_20_YARDS; - spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_20_YARDS; - break; - // Rallying Shout - case 75414: - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_20_YARDS; - break; - // Barrier Channel - case 76221: - spellInfo->ChannelInterruptFlags &= ~(AURA_INTERRUPT_FLAG_TURNING|AURA_INTERRUPT_FLAG_MOVE); - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_UNIT_NEARBY_ENTRY; - break; - // Intimidating Roar - case 74384: - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_100_YARDS; - spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_100_YARDS; - break; - // Fiery Combustion - case 74562: - // Soul Consumption - case 74792: - spellInfo->AttributesEx |= SPELL_ATTR1_CANT_BE_REDIRECTED; - break; - // Combustion - case 75883: - case 75884: - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_6_YARDS; - spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_6_YARDS; - break; - // Consumption - case 75875: - case 75876: - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_6_YARDS; - spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_6_YARDS; - spellInfo->EffectMechanic[EFFECT_0] = 0; - spellInfo->EffectMechanic[EFFECT_1] = MECHANIC_SNARE; - break; - // Soul Consumption - case 74799: - spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_12_YARDS; - break; - // Twilight Cutter - case 74769: - case 77844: - case 77845: - case 77846: - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_100_YARDS; - break; - // Twilight Mending - case 75509: - spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_100_YARDS; - spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_100_YARDS; - break; - // Meteor Strike - case 74637: - spellInfo->speed = 0; - break; - //Blazing Aura - case 75885: - case 75886: - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; - break; - //Meteor Strike - case 75952: - //Combustion Periodic - case 74629: - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; - break; + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_DUMMY; + break; + // Intervene + case 3411: + spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Roar of Sacrifice + case 53480: + spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_SPLIT_DAMAGE_PCT; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ALLY; + spellInfo->EffectDieSides[1] = 1; + spellInfo->EffectBasePoints[1] = 19; + spellInfo->EffectMiscValue[1] = 127; // all schools + break; + // Silencing Shot + case 34490: + case 41084: + case 42671: + spellInfo->speed = 0.0f; + break; + // Monstrous Bite + case 54680: + case 55495: + case 55496: + case 55497: + case 55498: + case 55499: + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_CASTER; + break; + // Hunter's Mark + case 1130: + case 14323: + case 14324: + case 14325: + case 53338: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + // Cobra Strikes + case 53257: + spellInfo->procCharges = 2; + spellInfo->StackAmount = 0; + break; + // Kill Command + case 34027: + spellInfo->procCharges = 0; + break; + // Kindred Spirits, damage aura + case 57458: + spellInfo->AttributesEx4 |= SPELL_ATTR4_UNK21; + break; + // Chimera Shot - Serpent trigger + case 53353: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + // Entrapment trigger + case 19185: + case 64803: + case 64804: + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[EFFECT_0] = TARGET_UNIT_DEST_AREA_ENEMY; + spellInfo->AttributesEx5 |= SPELL_ATTR5_SKIP_CHECKCAST_LOS_CHECK; + break; + // Improved Stings (Rank 2) + case 19465: + spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_CASTER; + break; + // Explosive Shot (trigger) + case 53352: + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + // Heart of the Phoenix (triggered) + case 54114: + spellInfo->AttributesEx &= ~SPELL_ATTR1_DISMISS_PET; + spellInfo->RecoveryTime = 8 * 60 * IN_MILLISECONDS; // prev 600000 + break; - // /////////////////////////////////////////// - // ////////////////QUESTS///////////////////// - // /////////////////////////////////////////// - // Going Bearback (12851) - case 54897: - spellInfo->Effect[1] = SPELL_EFFECT_DUMMY; - spellInfo->EffectRadiusIndex[1] = spellInfo->EffectRadiusIndex[0]; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_DEST_AREA_ENTRY; - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_CAN_CAST_WHILE_CASTING; - break; - // Still At It (12644) - case 51931: - case 51932: - case 51933: - spellInfo->EffectImplicitTargetA[0] = 38; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Rallying the Troops (12070) - case 47394: - spellInfo->excludeTargetAuraSpell = 47394; - break; - // A Tangled Skein (12555) - case 51165: - case 51173: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // A Cloudlet of Classy Cologne (24635) - case 69563: - // A Perfect Puff of Perfume (24629) - case 69445: - // Bonbon Blitz (24636) - case 69489: - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_CASTER; - break; - // Control (9595) - case 30790: - spellInfo->EffectMiscValue[1] = 0; - break; - // Reclusive Runemaster (12150) - case 48028: - spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; - break; - // Mastery of - case 65147: - spellInfo->Category = 1244; - spellInfo->CategoryRecoveryTime = 1500; - break; - // Weakness to Lightning (11896) - case 46432: - spellInfo->AttributesEx3 &= ~SPELL_ATTR3_DEATH_PERSISTENT; - break; - // Wrangle Some Aether Rays! (11065) - case 40856: - spellInfo->DurationIndex = 27; // 3000ms - break; - // The Black Knight's Orders (13663) - case 63163: - spellInfo->EffectBasePoints[0] = 52390; - break; - // The Warp Rifts (10278) - case 34888: - spellInfo->DurationIndex = 5; // 300 secs - break; - // The Smallest Creatures (10720) - case 38544: - spellInfo->EffectMiscValueB[0] = 427; - spellInfo->EffectImplicitTargetA[0] = 1; - spellInfo->Effect[1] = 0; - break; - // Ridding the red rocket - case 49177: - spellInfo->EffectBasePoints[0] = 1; // corrects seat id (points - 1 = seatId) - break; - // The Iron Colossus (13007) - case 56513: - case 56524: - spellInfo->RecoveryTime = (spellInfo->Id == 56524 ? 6000 : 2000); - break; - // Kaw the Mammoth Destroyer (11879) - case 46260: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - // That's Abominable (13264)(13276)(13288)(13289) - case 59565: - spellInfo->EffectMiscValueB[0] = 1721; // controlable guardian - break; - // Investigate the Blue Recluse (1920) - // Investigate the Alchemist Shop (1960) - case 9095: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; - spellInfo->EffectRadiusIndex[0] = 13; - break; - // Dragonmaw Race: All parts - case 40890: // Oldie's Rotten Pumpkin - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectTriggerSpell[0] = 40905; - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - case 40909: // Trope's Slime Cannon - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectTriggerSpell[0] = 40905; - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - case 40894: // Corlok's Skull Barrage - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectTriggerSpell[0] = 40900; - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - case 40928: // Ichman's Blazing Fireball - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectTriggerSpell[0] = 40929; - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - case 40930: // Mulverick's Great Balls of Lightning - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectTriggerSpell[0] = 40931; - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - case 40945: // Sky Shatter - spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; - spellInfo->EffectTriggerSpell[0] = 41064; - spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - break; - // Gauging the Resonant Frequency (10594) - case 37390: - spellInfo->EffectMiscValueB[0] = 181; - break; - // Where in the World is Hemet Nesingwary? (12521) - case 50860: - spellInfo->EffectBasePoints[0] = 50860; - break; - case 50861: - spellInfo->EffectBasePoints[0] = 0; - break; - // Krolmir, Hammer of Storms (13010) - case 56606: - case 56541: - spellInfo->EffectBasePoints[0] = 1; - break; - // Blightbeasts be Damned! (12072) - case 47424: - spellInfo->AuraInterruptFlags &= ~AURA_INTERRUPT_FLAG_NOT_ABOVEWATER; - break; - // Leading the Charge (13380), All Infra-Green bomber quests - case 59059: - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_CAN_CAST_WHILE_CASTING; - break; - // Dark Horizon (12664), Reunited (12663) - case 52190: - spellInfo->EffectBasePoints[EFFECT_0] = 52391-1; - break; - // The Sum is Greater than the Parts (13043) - Chained Grip - case 60540: - spellInfo->EffectMiscValue[EFFECT_0] = 300; - break; - // Not a Bug (13342) - case 60531: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; - break; - // Frankly, It Makes No Sense... (10672) - case 37851: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Honor Challenge (12939) - case 21855: - spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; - break; - // Convocation at Zol'Heb (12730) - case 52956: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_DEST_AREA_ENTRY; - break; - // Mangletooth Quests (http://www.wowhead.com/npc=3430) - case 7764: - case 10767: - case 16610: - case 16612: - case 16618: - case 17013: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - spellInfo->AttributesEx5 |= SPELL_ATTR5_SKIP_CHECKCAST_LOS_CHECK; - break; - //Crushing the Crown - case 71024: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DYNOBJ_NONE; - break; - // Battle for the Undercity - case 59892: // Cyclone fall - spellInfo->Effect[EFFECT_0] = SPELL_EFFECT_APPLY_AREA_AURA_FRIEND; - spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; - spellInfo->AttributesEx &= ~SPELL_ATTR0_CANT_CANCEL; - spellInfo->AttributesEx3 |= SPELL_ATTR3_ONLY_TARGET_PLAYERS; - break; - // /////////////////////////////////////////// - // ////////////////ITEMS////////////////////// - // /////////////////////////////////////////// - // enchant Lightweave Embroidery - case 55637: - spellInfo->EffectMiscValue[1] = 126; - break; - // Magic Broom - case 47977: - spellInfo->Effect[0] = 0; - spellInfo->Effect[1] = 0; - break; - // Titanium Seal of Dalaran, Toss your luck - case 60476: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; - break; - // Mind Amplification Dish, change charm aura - case 26740: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_MOD_CHARM; - break; - // Persistent Shield (fixes idiocity) - case 26467: - spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE; - spellInfo->EffectTriggerSpell[0] = 26470; - break; - // Deadly Swiftness - case 31255: - spellInfo->EffectTriggerSpell[0] = 22588; - break; - // Black Magic enchant - case 59630: - spellInfo->Attributes |= SPELL_ATTR0_PASSIVE; - break; - // Precious's Ribbon - case 72968: - spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; - break; - // Item - Bauble of True Blood 10m - // Item - Bauble of True Blood 25m - case 71646: - case 71607: - // Item - Althor's Abacus trigger 10m - // Item - Althor's Abacus trigger 25m - case 71610: - case 71641: - spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; - spellInfo->spellLevel = 0; - break; - // Drain Life - Bryntroll Normal / Heroic - case 71838: - case 71839: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CANT_CRIT; - spellInfo->AttributesEx4 |= SPELL_ATTR4_IGNORE_RESISTANCES; - break; - // Alchemist's Stone - case 17619: - spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; - break; - // Gnomish Death Ray - case 13278: - case 13280: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY; - break; - // Stormchops - case 43730: - spellInfo->EffectImplicitTargetA[1] = 1; - spellInfo->EffectImplicitTargetB[1] = 0; - break; - // Savory Deviate Delight (transformations), allow to mount while transformed - case 8219: - case 8220: - case 8221: - case 8222: - spellInfo->Attributes &= ~SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; - break; - // Clamlette Magnifique - case 72623: // drink triggered spell - spellInfo->EffectBasePoints[EFFECT_0] = spellInfo->EffectBasePoints[EFFECT_1]; - break; - // Compact Harvest Reaper - case 4078: - spellInfo->DurationIndex = 6; // 10 minutes - break; - // Dragon Kite, Tuskarr Kite - Kite String - case 45192: - spellInfo->rangeIndex = 6; // 100yd - break; - // Frigid Frostling, Infrigidate - case 74960: - spellInfo->EffectRadiusIndex[EFFECT_0] = 9; // 20yd - break; + ///////////////////////////////// + ///// ROGUE + ///////////////////////////////// + // Master of Subtlety + case 31221: + case 31222: + case 31223: + spellInfo->SpellFamilyName = SPELLFAMILY_ROGUE; + break; + // Master of Subtlety triggers + case 31666: + // Overkill + case 58428: + spellInfo->Effect[0] = SPELL_EFFECT_SCRIPT_EFFECT; + break; + // Honor Among Thieves + case 51698: + case 51700: + case 51701: + spellInfo->EffectTriggerSpell[0] = 51699; + break; + // Slice and Dice + case 5171: + case 6774: + // Distract + case 1725: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Envenom + case 32645: + case 32684: + case 57992: + case 57993: + spellInfo->Dispel = DISPEL_NONE; + break; + // Killing Spree (teleport) + case 57840: + spellInfo->rangeIndex = 6; // 100 yards + break; + // Killing Spree + case 51690: + spellInfo->AttributesEx |= SPELL_ATTR1_NOT_BREAK_STEALTH; + break; - // /////////////////////////////////////////// - // ////////////////EVENTS///////////////////// - // /////////////////////////////////////////// + ///////////////////////////////// + ///// DEATH KNIGHT + ///////////////////////////////// + // Blood Tap visual cd reset + case 47804: + spellInfo->Effect[2] = 0; + spellInfo->Effect[1] = 0; + spellInfo->runeCostID = 442; + break; + // Chains of Ice + case 45524: + spellInfo->Effect[EFFECT_2] = 0; + break; + // Impurity + case 49220: + case 49633: + case 49635: + case 49636: + case 49638: + spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + spellInfo->SpellFamilyName = SPELLFAMILY_DEATHKNIGHT; + break; + // Deadly Aggression (Deadly Gladiator's Death Knight Relic, item: 42620) + case 60549: + spellInfo->Effect[1] = 0; + break; + // Magic Suppression + case 49224: + case 49610: + case 49611: + spellInfo->procCharges = 0; + break; + // Wandering Plague + case 50526: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Dancing Rune Weapon + case 49028: + spellInfo->Effect[2] = 0; + spellInfo->procFlags |= PROC_FLAG_DONE_MELEE_AUTO_ATTACK; + break; + // Death and Decay + case 52212: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; + break; + // T9 blood plague crit bonus + case 67118: + spellInfo->Effect[1] = 0; + break; + // Pestilence + case 50842: + spellInfo->EffectImplicitTargetA[2] = TARGET_DEST_TARGET_ENEMY; + break; + // Horn of Winter, stacking issues + case 57330: + case 57623: + spellInfo->EffectImplicitTargetA[1] = 0; + break; + // Scourge Strike trigger + case 70890: + spellInfo->AttributesEx3 |= SPELL_ATTR3_CANT_TRIGGER_PROC; + break; + // Blood-caked Blade - Blood-caked Strike trigger + case 50463: + spellInfo->AttributesEx3 |= SPELL_ATTR3_CANT_TRIGGER_PROC; + break; + // Blood Gorged - ARP affect Death Strike and Rune Strike + case 61274: + case 61275: + case 61276: + case 61277: + case 61278: + spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x1400011, 0x20000000, 0x0); + break; + // Death Grip, remove main grip mechanic, leave only effect one + // Death Grip, should fix taunt on bosses and not break the pull protection at the same time (no aura provides immunity to grip mechanic) + case 49576: + case 49560: + spellInfo->Mechanic = 0; + break; + // Death Grip Jump Dest + case 57604: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + // Death Pact + case 48743: + spellInfo->AttributesEx &= ~SPELL_ATTR1_CANT_TARGET_SELF; + break; + // Raise Ally (trigger) + case 46619: + spellInfo->Attributes &= ~SPELL_ATTR0_CANT_CANCEL; + break; + // Frost Strike + case 49143: + case 51416: + case 51417: + case 51418: + case 51419: + case 55268: + spellInfo->AttributesEx3 |= SPELL_ATTR3_BLOCKABLE_SPELL; + break; + // Death Knight T10 Tank 2p Bonus + case 70650: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_ADD_PCT_MODIFIER; + break; - ////////////////////////////////////////// - ////////// BREWFEST - ////////////////////////////////////////// - // Apple Trap - case 43450: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_SRC_AREA_ENEMY; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_CASTER; - spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; - break; - // Dark Iron Attack - spawn mole machine - case 43563: - spellInfo->Effect[2] = 0; // summon GO's manually - break; - // Throw Mug visual - case 42300: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; - break; - // Dark Iron knockback Aura - case 42299: - spellInfo->EffectApplyAuraName[1] = SPELL_AURA_DUMMY; - spellInfo->EffectMiscValue[0] = 100; - spellInfo->EffectBasePoints[0] = 79; - break; - // Chug and Chuck! - case 42436: - spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; - spellInfo->MaxAffectedTargets = 0; - spellInfo->excludeCasterAuraSpell = 42299; - break; - // Catch the Wild Wolpertinger! - case 41621: - spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; - break; - // Brewfest quests - case 47134: - case 51798: - spellInfo->Effect[0] = 0; - break; - // The Heart of The Storms (12998) - case 43528: - spellInfo->DurationIndex = 18; - spellInfo->EffectImplicitTargetA[0] = 25; - break; - ////////////////////////////////////////// - ////////// Hallow's End - ////////////////////////////////////////// - // Water splash - case 42348: - spellInfo->Effect[0] = 0; - break; - // Summon Lantersn - case 44255: - case 44231: - spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; - spellInfo->EffectImplicitTargetB[0] = 0; - break; - // Throw Head Back - case 42401: - spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_NEARBY_ENTRY; - break; - ////////////////////////////////////////// - ////////// Pilgrim's Bounty - ////////////////////////////////////////// - // Various food - case 65418: - spellInfo->EffectTriggerSpell[2] = 65410; - break; - case 65422: - spellInfo->EffectTriggerSpell[2] = 65414; - break; - case 65419: - spellInfo->EffectTriggerSpell[2] = 65416; - break; - case 65420: - spellInfo->EffectTriggerSpell[2] = 65412; - break; - case 65421: - spellInfo->EffectTriggerSpell[2] = 65415; - break; + ///////////////////////////////// + ///// SHAMAN + ///////////////////////////////// + // Lightning overload + case 45297: + case 45284: + spellInfo->CategoryRecoveryTime = 0; + spellInfo->RecoveryTime = 0; + spellInfo->AttributesEx6 |= SPELL_ATTR6_LIMIT_PCT_DAMAGE_MODS; + break; + // Improved Earth Shield + case 51560: + case 51561: + spellInfo->EffectMiscValue[1] = SPELLMOD_DAMAGE; + break; + // Tidal Force + case 55166: + case 55198: + spellInfo->DurationIndex = 18; + spellInfo->procCharges = 0; + break; + // Healing Stream Totem + case 52042: + spellInfo->spellLevel = 0; + spellInfo->baseLevel = 0; + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + break; + // Earth Shield + case 379: + spellInfo->spellLevel = 0; + spellInfo->baseLevel = 0; + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + // Stormstrike + case 17364: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Strength of Earth totem effect + case 8076: + case 8162: + case 8163: + case 10441: + case 25362: + case 25527: + case 57621: + case 58646: + spellInfo->EffectRadiusIndex[1] = spellInfo->EffectRadiusIndex[0]; + spellInfo->EffectRadiusIndex[2] = spellInfo->EffectRadiusIndex[0]; + break; + // Flametongue Totem effect + case 52109: + case 52110: + case 52111: + case 52112: + case 52113: + case 58651: + case 58654: + case 58655: + spellInfo->EffectImplicitTargetB[2] = spellInfo->EffectImplicitTargetB[1] = spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->EffectImplicitTargetA[2] = spellInfo->EffectImplicitTargetA[1] = spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + break; + // Sentry Totem + case 6495: + spellInfo->EffectRadiusIndex[0] = 0; + break; + // Bind Sight (PT) + case 6277: + spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_1; + spellInfo->Attributes |= SPELL_ATTR0_PASSIVE; + spellInfo->AttributesEx7 |= SPELL_ATTR7_REACTIVATE_AT_RESURRECT; // because it is passive, needs this to be properly removed at death in RemoveAllAurasOnDeath() + break; + // Ancestral Awakening Heal + case 52752: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + case 32182: // Heroism + spellInfo->excludeTargetAuraSpell = 57723; // Exhaustion + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + case 2825: // Bloodlust + spellInfo->excludeTargetAuraSpell = 57724; // Sated + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; - ////////////////////////////////////////// - ////////// Midsummer - ////////////////////////////////////////// - // Stamp Out Bonfire - case 45437: - spellInfo->Effect[1] = SPELL_EFFECT_DUMMY; - spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_NEARBY_ENTRY; - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - // Light Bonfire (DND) - case 29831: - spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; - break; - ////////////////////////////////////////// - ////////// Misc Events - ////////////////////////////////////////// - // Infernal - case 33240: - spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_TARGET_ANY; - spellInfo->EffectImplicitTargetA[EFFECT_1] = TARGET_UNIT_TARGET_ANY; - spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_TARGET_ANY; - break; - // Check for SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER - case 47476: // Deathknight - Strangulate - case 15487: // Priest - Silence - case 5211: // Druid - Bash - R1 - case 6798: // Druid - Bash - R2 - case 8983: // Druid - Bash - R3 - spellInfo->AttributesEx7 |= SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER; - break; + ///////////////////////////////// + ///// WARLOCK + ///////////////////////////////// + // Improved Succubus + case 18754: + case 18755: + case 18756: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + break; + // Unstable Affliction + case 31117: + spellInfo->PreventionType = SPELL_PREVENTION_TYPE_NONE; + break; + // Shadowflame - trigger + case 47960: // r1 + case 61291: // r2 + spellInfo->AttributesEx |= SPELL_ATTR1_CANT_BE_REDIRECTED; + break; + // Curse of Doom - summoned doomguard duration fix + case 18662: + spellInfo->DurationIndex = 6; + break; + // Glyph of Voidwalker + case 56247: + spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_ADD_FLAT_MODIFIER; + spellInfo->EffectMiscValue[EFFECT_0] = SPELLMOD_EFFECT1; + spellInfo->EffectSpellClassMask[EFFECT_0] = flag96(0x8000000, 0, 0); + break; + // Everlasting Affliction + case 47201: + case 47202: + case 47203: + case 47204: + case 47205: + spellInfo->EffectSpellClassMask[1][0] |= 2; // add corruption to affected spells + break; + // Death's Embrace + case 47198: + case 47199: + case 47200: + spellInfo->EffectSpellClassMask[1][0] |= 0x4000; // include Drain Soul + break; + // Improved Demonic Tactics + case 54347: + case 54348: + case 54349: + spellInfo->Effect[EFFECT_1] = spellInfo->Effect[EFFECT_0]; + spellInfo->EffectApplyAuraName[EFFECT_1] = spellInfo->EffectApplyAuraName[EFFECT_0]; + spellInfo->EffectImplicitTargetA[EFFECT_1] = spellInfo->EffectImplicitTargetA[EFFECT_0]; + spellInfo->EffectMiscValue[EFFECT_0] = SPELLMOD_EFFECT1; + spellInfo->EffectMiscValue[EFFECT_1] = SPELLMOD_EFFECT2; + break; + // Rain of Fire (Doomguard) + case 42227: + spellInfo->speed = 0.0f; + break; + // Ritual Enslavement + case 22987: + spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_MOD_CHARM; + break; + + + ///////////////////////////////// + ///// MAGE + ///////////////////////////////// + // Combustion, make this passive + case 11129: + spellInfo->Dispel = DISPEL_NONE; + break; + // Magic Absorption (nigga stole my code) + case 29441: + case 29444: + spellInfo->spellLevel = 0; + break; + // Living Bomb + case 44461: + case 55361: + case 55362: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + spellInfo->AttributesEx4 |= SPELL_ATTR4_DAMAGE_DOESNT_BREAK_AURAS; + break; + // Evocation + case 12051: + spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; + break; + // MI Fireblast, WE Frostbolt, MI Frostbolt + case 59637: + case 31707: + case 72898: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + break; + // Blazing Speed + case 31641: + case 31642: + spellInfo->EffectTriggerSpell[0] = 31643; + break; + // Summon Water Elemental (permanent), treat it as pet + case 70908: + spellInfo->Effect[0] = SPELL_EFFECT_SUMMON_PET; + break; + // Burnout, trigger + case 44450: + spellInfo->Effect[0] = SPELL_EFFECT_POWER_BURN; + break; + // Mirror Image - Summon Spells + case 58831: + case 58833: + case 58834: + case 65047: + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_CASTER; + spellInfo->EffectRadiusIndex[EFFECT_0] = 0; + break; + // Initialize Images (Mirror Image) + case 58836: + spellInfo->EffectImplicitTargetA[EFFECT_1] = TARGET_UNIT_CASTER; + break; + // Arcane Blast, can't be dispelled + case 36032: + spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; + break; + // Chilled (frost armor, ice armor proc) + case 6136: + case 7321: + spellInfo->PreventionType = SPELL_PREVENTION_TYPE_NONE; + break; + // Mirror Image Frostbolt + case 59638: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->SpellFamilyName = SPELLFAMILY_MAGE; + spellInfo->SpellFamilyFlags = flag96(0x20, 0x0, 0x0); + break; + // Fingers of Frost + case 44544: + spellInfo->Dispel = DISPEL_NONE; + spellInfo->AttributesEx4 |= SPELL_ATTR4_NOT_STEALABLE; + spellInfo->EffectSpellClassMask[0] = flag96(685904631, 1151040, 32); // xinef: removed molten armor + break; + // Fingers of Frost visual buff + case 74396: + spellInfo->procCharges = 2; + spellInfo->StackAmount = 0; + break; + + + ///////////////////////////////// + ///// WARRIOR + ///////////////////////////////// + // Glyph of blocking + case 58375: + spellInfo->EffectTriggerSpell[0] = 58374; + break; + // Sweeping Strikes stance change + case 12328: + spellInfo->Attributes |= SPELL_ATTR0_NOT_SHAPESHIFT; + break; + // Damage Shield + case 59653: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->spellLevel = 0; + break; + // Strange shared cooldown + case 20230: // Retaliation + case 871: // Shield Wall + case 1719: // Recklessness + spellInfo->AttributesEx6 |= SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS; + break; + // Vigilance, fixes bug with empowered renew, single target aura + case 50720: + spellInfo->SpellFamilyName = SPELLFAMILY_WARRIOR; + break; + // Sunder Armor - trigger, remove spellfamilyflags because of glyph of sunder armor + case 58567: + spellInfo->SpellFamilyFlags = flag96(0x0, 0x0, 0x0); + break; + // Sunder Armor - Old Ranks + case 7405: + case 8380: + case 11596: + case 11597: + case 25225: + case 47467: + spellInfo->EffectTriggerSpell[EFFECT_0] = 11971; + spellInfo->Effect[EFFECT_0] = SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE; + break; + // Improved Spell Reflection + case 59725: + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_UNIT_CASTER_AREA_PARTY; + break; + + + + ///////////////////////////////// + ///// PRIEST + ///////////////////////////////// + // Shadow Weaving + case 15257: + case 15331: + case 15332: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; + break; + // Hymn of Hope - rewrite part of aura system or swap effects... + case 64904: + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT; + spellInfo->Effect[2] = spellInfo->Effect[0]; + spellInfo->Effect[0] = 0; + spellInfo->EffectDieSides[2] = spellInfo->EffectDieSides[0]; + spellInfo->EffectImplicitTargetA[2] = spellInfo->EffectImplicitTargetB[0]; + spellInfo->EffectRadiusIndex[2] = spellInfo->EffectRadiusIndex[0]; + spellInfo->EffectBasePoints[2] = spellInfo->EffectBasePoints[0]; + break; + // Divine Hymn + case 64844: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->spellLevel = 0; + break; + // Spiritual Healing affects prayer of mending + case 14898: + case 15349: + case 15354: + case 15355: + case 15356: + // Divine Providence affects prayer of mending + case 47562: + case 47564: + case 47565: + case 47566: + case 47567: + // Twin Disciplines affects prayer of mending + case 47586: + case 47587: + case 47588: + case 52802: + case 52803: + spellInfo->EffectSpellClassMask[0][1] |= 0x20; // prayer of mending + break; + // Power Infusion, hack to fix stacking with arcane power + case 10060: + spellInfo->Effect[EFFECT_2] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[EFFECT_2] = SPELL_AURA_ADD_PCT_MODIFIER; + spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_TARGET_ALLY; + break; + + + + ///////////////////////////////// + ///// DRUID + ///////////////////////////////// + // Lifebloom final bloom + case 33778: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->spellLevel = 0; + spellInfo->SpellFamilyFlags = flag96(0, 0x10, 0); + break; + // Clearcasting + case 16870: + spellInfo->DurationIndex = 31; // 8 secs + break; + // Owlkin Frenzy + case 48391: + spellInfo->Attributes |= SPELL_ATTR0_NOT_SHAPESHIFT; + break; + // Item T10 Restoration 4P Bonus + case 70691: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + // Faerie Fire, Faerie Fire (Feral) + case 770: + case 16857: + spellInfo->AttributesEx &= ~SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE; + break; + // Feral Charge - Cat + case 49376: + case 61138: + case 61132: + case 50259: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Glyph of Barkskin + case 63058: + spellInfo->EffectApplyAuraName[EFFECT_0] = SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE; + break; + + + ///////////////////////////////// + ///// MISC + ///////////////////////////////// + // Resurrection Sickness + case 15007: + spellInfo->SpellFamilyName = SPELLFAMILY_GENERIC; + break; + // Luck of the Draw + case 72221: + spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; + break; + case 3286: // Bind + spellInfo->Targets = 0; // neutral innkeepers not friendly? + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ANY; + break; + // remove creaturetargettype + case 2641: + case 23356: + spellInfo->TargetCreatureType = 0; + break; + case 34074: // Aspect of the Viper + spellInfo->Effect[2] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectImplicitTargetA[2] = 1; + spellInfo->EffectApplyAuraName[2] = SPELL_AURA_DUMMY; + break; + // Strength of Wrynn + case 60509: + spellInfo->EffectBasePoints[2] = 1500; + spellInfo->EffectBasePoints[1] = 150; + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_PERIODIC_HEAL; + break; + // Playback Speech + case 74209: + spellInfo->DurationIndex = 1; + break; + // Winterfin First Responder + case 48739: + spellInfo->EffectBasePoints[0] = 1; + spellInfo->EffectRealPointsPerLevel[0] = 0; + spellInfo->EffectDieSides[0] = 0; + spellInfo->EffectDamageMultiplier[0] = 0; + spellInfo->EffectBonusMultiplier[0] = 0; + break; + // Army of the Dead (trigger npc aura) + case 49099: + spellInfo->EffectAmplitude[0] = 15000; + break; + // Isle of Conquest - Teleport in, missing range + case 66551: + spellInfo->rangeIndex = 13; // 50000yd + break; + // A'dal's Song of Battle + case 39953: + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetA[EFFECT_1] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[EFFECT_0] = TARGET_UNIT_SRC_AREA_ALLY; + spellInfo->EffectImplicitTargetB[EFFECT_1] = TARGET_UNIT_SRC_AREA_ALLY; + spellInfo->EffectImplicitTargetB[EFFECT_2] = TARGET_UNIT_SRC_AREA_ALLY; + spellInfo->DurationIndex = 367; // 2 Hours + break; + // Wintergrasp spells + case 57607: // WintergraspCatapult - Spell Plague Barrel - EffectRadiusIndex + case 57619: // WintergraspDemolisher - Spell Hourl Boulder - EffectRadiusIndex + case 57610: // Cannon (Siege Turret) + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_25_YARDS; // SPELL_EFFECT_WMO_DAMAGE + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 51422: // WintergraspCannon - Spell Fire Cannon - EffectRadiusIndex + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; // SPELL_EFFECT_SCHOOL_DAMAGE + break; + case 54107: // WintergraspDemolisher - Spell Ram - EffectRadiusIndex + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_3_YARDS; // SPELL_EFFECT_KNOCK_BACK + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_3_YARDS; // SPELL_EFFECT_SCHOOL_DAMAGE + spellInfo->EffectRadiusIndex[2] = EFFECT_RADIUS_3_YARDS; // SPELL_EFFECT_WEAPON_DAMAGE + break; + case 51678: // WintergraspSiegeEngine - Spell Ram - EffectRadiusIndex + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; // SPELL_EFFECT_KNOCK_BACK + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_10_YARDS; // SPELL_EFFECT_SCHOOL_DAMAGE + spellInfo->EffectRadiusIndex[2] = EFFECT_RADIUS_20_YARDS; // SPELL_EFFECT_WEAPON_DAMAGE + break; + case 57606: // WintergraspCatapult - Spell Plague Barrell - Range + spellInfo->rangeIndex = 164; // "Catapult Range" + break; + case 50999: // Boulder (Demolisher) + spellInfo->EffectRadiusIndex[EFFECT_0] = 13; // 10yd + break; + case 50990: // Flame Breath (Catapult) + spellInfo->EffectRadiusIndex[EFFECT_0] = 19; // 18yd + break; + case 56103: // Jormungar Bite + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_UNIT_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[EFFECT_0] = 0; + break; + + ///////////////////////////////// + ///// Generic NPC Spells + ///////////////////////////////// + + // Throw Proximity Bomb + case 34095: + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[EFFECT_0] = 0; + break; + // DEATH KNIGHT SCARLET FIRE ARROW + case 53348: + // BALISTA + case 53117: + spellInfo->RecoveryTime = 5000; + spellInfo->CategoryRecoveryTime = 5000; + break; + // Teleport To Molten Core + case 25139: + spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; + break; + + + // /////////////////////////////////////////// + // ////////////////BOSS SPELLS//////////////// + // /////////////////////////////////////////// + ////////////////////////////////////////// + ////////// Vanilla Instances + ////////////////////////////////////////// + + // Shadowfang Keep + // Landen Stilwell Transform + case 31310: + spellInfo->Attributes |= SPELL_ATTR0_PASSIVE; + break; + + // Blackfathom Deeps + // Shadowstalker Stealth + case 5916: + spellInfo->EffectRealPointsPerLevel[EFFECT_0] = 5.0f; + break; + + // Maraudon + // Sneak + case 22766: + spellInfo->EffectRealPointsPerLevel[EFFECT_0] = 5.0f; + break; + + + ////////////////////////////////////////// + ////////// TBC Instances + ////////////////////////////////////////// + + // Shadow Labirynth + // Murmur's Touch + case 38794: + case 33711: + spellInfo->MaxAffectedTargets = 1; + spellInfo->EffectTriggerSpell[0] = 33760; + break; + + // The Arcatraz + // Negaton Field + case 36729: // Normal + case 38834: // Heroic + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Curse of the Doomsayer NORMAL + case 36173: + spellInfo->EffectTriggerSpell[0] = 36174; // Currently triggers heroic version... + break; + + // The Botanica + // Crystal Channel + case 34156: + spellInfo->rangeIndex = 35; // 35yd; + spellInfo->ChannelInterruptFlags |= AURA_INTERRUPT_FLAG_MOVE; + break; + + // Magtheridon's Lair + // Debris + case 36449: + spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; + break; + // Soul Channel + case 30531: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Debris Visual + case 30632: + spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_DYNOBJ_ALLY; + break; + + // Sunwell Plateu + // Activate Sunblade Protecto + case 46475: + case 46476: + spellInfo->rangeIndex = 14; // 60yd + break; + // Break Ice + case 46638: + spellInfo->AttributesEx3 &= ~SPELL_ATTR3_ONLY_TARGET_PLAYERS; // Obvious fail, it targets gameobject... + break; + // Sinister Reflection Clone + case 45785: + spellInfo->speed = 0.0f; + break; + // Armageddon + case 45909: + spellInfo->speed = 8.0f; + break; + + // Black Temple + // Spell Absorption + case 41034: + spellInfo->Effect[EFFECT_2] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[EFFECT_2] = SPELL_AURA_SCHOOL_ABSORB; + spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_CASTER; + spellInfo->EffectMiscValue[EFFECT_2] = SPELL_SCHOOL_MASK_MAGIC; + break; + // Shared Bonds + case 41363: + spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_1; + break; + // Deadly Poison + case 41485: + // Envenom + case 41487: + spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; + break; + // Parasitic Shadowfiend + case 41914: + spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Teleport Maiev + case 41221: + spellInfo->rangeIndex = 13; // 0-50000yd + break; + + // Serpentshrine Cavern + // Watery Grave Explosion + case 37852: + spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_STUNNED; + break; + + // Karazhan + // Amplify Damage + case 39095: + spellInfo->MaxAffectedTargets = 1; + break; + + // Magisters' Terrace + // Energy Feedback + case 44335: + spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; + break; + + /* + Raid: Battle for Mount Hyjal + Boss: Archimonde + */ + case 31984: // Spell doesn't need to ignore invulnerabilities + case 35354: + spellInfo->Attributes = SPELL_ATTR0_ABILITY; + break; + case 32111: // We only need the animation, no damage + spellInfo->CastingTimeIndex = 0; + break; + + ////////////////////////////////////////// + ////////// Vault of Archavon (VOA) + ////////////////////////////////////////// + // Flame Breath, catapult spell + case 50989: + spellInfo->Attributes &= ~SPELL_ATTR0_LEVEL_DAMAGE_CALCULATION; + break; + // Koralon, Flaming Cinder missing radius index + case 66690: + spellInfo->EffectRadiusIndex[0] = 12; //100yd + spellInfo->MaxAffectedTargets = 1; + break; + + ////////////////////////////////////////// + ////////// Naxxramas + ////////////////////////////////////////// + // Acid Volley + case 54714: + case 29325: + spellInfo->MaxAffectedTargets = 1; + break; + // Summon Plagued Warrior + case 29237: + spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; + spellInfo->Effect[1] = spellInfo->Effect[2] = 0; + break; + // Icebolt + case 28526: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + break; + // Infected Wound + case 29306: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Hopeless + case 29125: + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; + break; + // Jagged Knife + case 55550: + spellInfo->Attributes |= SPELL_ATTR0_REQ_AMMO; + break; + + ////////////////////////////////////////// + ////////// Gundrak + ////////////////////////////////////////// + // Moorabi - Transformation + case 55098: + spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; + break; + case 55521: // Poisoned Spear (Normal) + case 58967: // Poisoned Spear (Heroic) + case 55348: // Throw (Normal) + case 58966: // Throw (Heroic) + spellInfo->Attributes |= SPELL_ATTR0_REQ_AMMO; + break; + + ////////////////////////////////////////// + ////////// The Nexus: Nexus + ////////////////////////////////////////// + // Charged Chaotic rift aura, trigger + case 47737: + spellInfo->rangeIndex = 37; // 50yd + break; + + ////////////////////////////////////////// + ////////// AHN'KAHET: THE OLD KINGDOM + ////////////////////////////////////////// + // Vanish + case 55964: + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + break; + + ////////////////////////////////////////// + ////////// DRAK'THARON KEEP + ////////////////////////////////////////// + // Trollgore - Summon Drakkari Invader + case 49456: + case 49457: + case 49458: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DB; + break; + + ////////////////////////////////////////// + ////////// UTGARDE PINNACLE + ////////////////////////////////////////// + // Paralyse + case 48278: + // Awaken subboss + case 47669: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Flame Breath + case 47592: + spellInfo->EffectAmplitude[0] = 200; + break; + + ////////////////////////////////////////// + ////////// UTGARDE KEEP + ////////////////////////////////////////// + // Skarvald, Charge + case 43651: + spellInfo->rangeIndex = 13; // 0-50000yd + break; + // Ingvar the Plunderer, Woe Strike + case 42730: + spellInfo->EffectTriggerSpell[1] = 42739; + break; + case 59735: + spellInfo->EffectTriggerSpell[1] = 59736; + break; + // Ingvar the Plunderer, Ingvar transform + case 42796: + spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; + break; + case 42772: // Hurl Dagger (Normal) + case 59685: // Hurl Dagger (Heroic) + spellInfo->Attributes |= SPELL_ATTR0_REQ_AMMO; + break; + + ////////////////////////////////////////// + ////////// VIOLET HOLD + ////////////////////////////////////////// + // Control Crystal Activation + case 57804: + spellInfo->EffectImplicitTargetA[0] = 1; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Destroy Door Seal + case 58040: + spellInfo->ChannelInterruptFlags &= ~(AURA_INTERRUPT_FLAG_HITBYSPELL | AURA_INTERRUPT_FLAG_TAKE_DAMAGE); + break; + // Ichoron, Water Blast + case 54237: + case 59520: + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + + ////////////////////////////////////////// + ////////// AZJOL'NERUB + ////////////////////////////////////////// + + // Krik'thir - Mind Flay + case 52586: + case 59367: + spellInfo->ChannelInterruptFlags |= AURA_INTERRUPT_FLAG_MOVE; + break; + + ////////////////////////////////////////// + ////////// HALLS OF STONE + ////////////////////////////////////////// + // Glare of the Tribunal + case 50988: + case 59870: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Static Charge + case 50835: + case 59847: + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ALLY; + break; + + ////////////////////////////////////////// + ////////// OBSIDIAN SANCTUM + ////////////////////////////////////////// + // Lava Strike damage + case 57697: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + // Lava Strike trigger + case 57578: + spellInfo->MaxAffectedTargets = 1; + break; + // Gift of Twilight Shadow/Fire + case 57835: + case 58766: + spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_1; + break; + // Pyrobuffet + case 57557: + spellInfo->excludeTargetAuraSpell = 56911; + break; + + ////////////////////////////////////////// + ////////// EYE OF ETERNITY + ////////////////////////////////////////// + // Arcane Barrage + case 56397: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[1] = 0; + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[2] = 0; + break; + // Power Spark (ground +50% dmg aura) + case 55849: + // Arcane Overload (-50% dmg taken) - this is to prevent apply -> unapply -> apply ... dunno whether it's correct + case 56438: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Vortex (Control Vehicle) + case 56263: + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + // Haste (Nexus Lord, increase run speed of the disk) + case 57060: + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_VEHICLE; + break; + // Arcane Overload + case 56430: + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectTriggerSpell[0] = 56429; + [[fallthrough]]; + case 56429: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->EffectImplicitTargetA[1] = 0; + spellInfo->EffectImplicitTargetB[1] = 0; + spellInfo->EffectImplicitTargetA[2] = 0; + spellInfo->EffectImplicitTargetB[2] = 0; + break; + // Destroy Platform Event + case 59099: + spellInfo->EffectImplicitTargetA[1] = 22; + spellInfo->EffectImplicitTargetB[1] = 15; + spellInfo->EffectImplicitTargetA[2] = 22; + spellInfo->EffectImplicitTargetB[2] = 15; + break; + // Surge of Power (Phase 3) + case 57407: // N + case 60936: // H + spellInfo->MaxAffectedTargets = (i == 60936 ? 3 : 1); + spellInfo->InterruptFlags = 0; + spellInfo->EffectRadiusIndex[0] = 28; + spellInfo->AttributesEx4 |= SPELL_ATTR4_CAN_CAST_WHILE_CASTING; + spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + // Wyrmrest Drake - Life Burst + case 57143: + spellInfo->Effect[0] = 0; + spellInfo->EffectImplicitTargetA[0] = 0; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->EffectImplicitTargetA[1] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_SRC_AREA_ALLY; + spellInfo->EffectPointsPerComboPoint[1] = 2500; + spellInfo->EffectBasePoints[1] = 2499; + spellInfo->rangeIndex = 1; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + //Alexstrasza - Gift + case 61028: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + // Vortex (freeze anim) + case 55883: + spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; + break; + + ////////////////////////////////////////// + ////////// ULDUAR + ////////////////////////////////////////// + // Flame Leviathan + // Hurl Pyrite + case 62490: + spellInfo->Effect[EFFECT_1] = 0; + break; + + // Ulduar, Mimiron, Magnetic Core (summon) + case 64444: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_CASTER; + break; + // Ulduar, Mimiron, bomb bot explosion + case 63801: + spellInfo->EffectMiscValue[1] = 17286; + break; + // Ulduar, Mimiron, Summon Flames Initial + case 64563: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Ulduar, Mimiron, Flames (damage) + case 64566: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; + break; + + // Ulduar, Hodir, Starlight + case 62807: + spellInfo->EffectRadiusIndex[0] = 16; // 1yd + break; + + // Ulduar, General Vezax, Mark of the Faceless + case 63278: + spellInfo->Effect[0] = 0; + break; + + // XT-002 DECONSTRUCTOR + case 62834: // Boom (XT-002) + spellInfo->Effect[EFFECT_1] = 0; + break; + + // ASSEMBLY OF IRON + // Supercharge + case 61920: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + // Lightning Whirl + case 61916: + spellInfo->MaxAffectedTargets = 3; + break; + case 63482: + spellInfo->MaxAffectedTargets = 8; + break; + + // KOLOGARN + // Stone Grip, remove absorb aura + case 62056: + case 63985: + spellInfo->Effect[1] = 0; + break; + + // AURIAYA + // Sentinel Blast + case 64389: + case 64678: + spellInfo->Dispel = DISPEL_MAGIC; + break; + + // FREYA + // Potent Pheromones + case 62619: + spellInfo->AttributesEx |= SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY; + break; + // Healthy spore summon periodic + case 62566: + spellInfo->EffectAmplitude[0] = 2000; + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_TRIGGER_SPELL; + break; + // Brightleaf Essence trigger + case 62968: + spellInfo->Effect[1] = 0; // duplicate + break; + // Potent Pheromones + case 64321: + spellInfo->AttributesEx3 |= SPELL_ATTR3_ONLY_TARGET_PLAYERS; + spellInfo->AttributesEx |= SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY; + break; + + // THORIM + // charge obr stuff + case 62186: + spellInfo->EffectAmplitude[0] = 5000; // Duration 5 secs, amplitude 8 secs... + break; + // Charge Orb P2 + case 62976: + spellInfo->rangeIndex = 6; + spellInfo->DurationIndex = 28; + break; + // Sif's Blizzard + case 62576: + case 62602: + spellInfo->EffectRadiusIndex[0] = 14; // 8yd + spellInfo->EffectRadiusIndex[1] = 14; // 8yd + break; + + // YOGG-SARON + // Protective Gaze + case 64175: + spellInfo->RecoveryTime = 25000; + break; + // Shadow Beacon + case 64465: + spellInfo->EffectTriggerSpell[0] = 64467; // why do they need two script effects :/ (this one has visual effect) + break; + // Sanity + case 63050: + spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; + break; + // Shadow Nova + case 62714: + case 65209: + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + + // ALGALON + // Cosmic Smash (Algalon the Observer) + case 62293: + spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_CASTER; + break; + // Cosmic Smash (Algalon the Observer) + case 62311: + case 64596: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->EffectRadiusIndex[0] = 12; // 100yd + spellInfo->rangeIndex = 13; // 50000yd + break; + // Constellation Phase Effect + case 65509: + spellInfo->MaxAffectedTargets = 1; + break; + // Black Hole + case 62168: + case 65250: + case 62169: + spellInfo->Attributes |= SPELL_ATTR0_NEGATIVE_1; + break; + + // TRASH + // Ground Slam + case 62625: + spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; + break; + + ////////////////////////////////////////// + ////////// ONYXIA'S LAIR + ////////////////////////////////////////// + // Onyxia's Lair, Onyxia, Flame Breath (TriggerSpell = 0 and spamming errors in console) + case 18435: + spellInfo->Effect[1] = 0; + break; + // Onyxia's Lair, Onyxia, Create Onyxia Spawner + case 17647: + spellInfo->DurationIndex = 37; + break; + // Onyxia's Lair, Onyxia, Summon Onyxia Whelp + case 17646: + // Onyxia's Lair, Onyxia, Summon Lair Guard + case 68968: + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + spellInfo->rangeIndex = 13; + spellInfo->DurationIndex = 5; + break; + // Onyxia's Lair, Onyxia, Eruption: + case 17731: + case 69294: + spellInfo->Effect[1] = SPELL_EFFECT_DUMMY; + spellInfo->CastingTimeIndex = 3; + spellInfo->EffectRadiusIndex[1] = 19; // 18yd instead of 13yd to make sure all cracks erupt + break; + // Onyxia's Lair, Onyxia, Breath: + // TODO: fix it by IconId / SpellVisual + case 18576: + case 18578: + case 18579: + case 18580: + case 18581: + case 18582: + case 18583: + case 18609: + case 18611: + case 18612: + case 18613: + case 18614: + case 18615: + case 18616: + case 18584: + case 18585: + case 18586: + case 18587: + case 18588: + case 18589: + case 18590: + case 18591: + case 18592: + case 18593: + case 18594: + case 18595: + case 18564: + case 18565: + case 18566: + case 18567: + case 18568: + case 18569: + case 18570: + case 18571: + case 18572: + case 18573: + case 18574: + case 18575: + case 18596: + case 18597: + case 18598: + case 18599: + case 18600: + case 18601: + case 18602: + case 18603: + case 18604: + case 18605: + case 18606: + case 18607: + case 18617: + case 18619: + case 18620: + case 18621: + case 18622: + case 18623: + case 18624: + case 18625: + case 18626: + case 18627: + case 18628: + case 18618: + case 18351: + case 18352: + case 18353: + case 18354: + case 18355: + case 18356: + case 18357: + case 18358: + case 18359: + case 18360: + case 18361: + case 17086: + case 17087: + case 17088: + case 17089: + case 17090: + case 17091: + case 17092: + case 17093: + case 17094: + case 17095: + case 17097: + case 22267: + case 22268: + case 21132: + case 21133: + case 21135: + case 21136: + case 21137: + case 21138: + case 21139: + spellInfo->DurationIndex = 328; // 250ms + spellInfo->EffectImplicitTargetA[1] = 1; + if( spellInfo->Effect[1] ) + { + spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_PERIODIC_TRIGGER_SPELL; + spellInfo->EffectAmplitude[1] = ((spellInfo->CastingTimeIndex == 170) ? 50 : 215); + } + break; + + ////////////////////////////////////////// + ////////// THE NEXUS: OCULUS + ////////////////////////////////////////// + // Oculus, Teleport to Coldarra DND + case 48760: + // Oculus, Teleport to Boss 1 DND + case 49305: + spellInfo->EffectImplicitTargetA[0] = 25; + spellInfo->EffectImplicitTargetB[0] = 17; + break; + // Oculus, Drake spell Stop Time + case 49838: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + spellInfo->excludeTargetAuraSpell = 51162; // exclude planar shift + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_150_YARDS; + break; + // Oculus, Varos Cloudstrider, Energize Cores + case 61407: + case 62136: + case 56251: + case 54069: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CONE_ENTRY; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + + ////////////////////////////////////////// + ////////// HALLS OF LIGHTNING + ////////////////////////////////////////// + // Halls of Lightning, Arc Weld + case 59086: + spellInfo->EffectImplicitTargetA[0] = 1; + break; + // Halls of Lightning, Arcing Burn + case 52671: + case 59834: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + + ////////////////////////////////////////// + ////////// TRIAL OF THE CHAMPION + ////////////////////////////////////////// + // Trial of the Champion, Death's Respite + case 68306: + spellInfo->EffectImplicitTargetA[0] = 25; + spellInfo->EffectImplicitTargetA[1] = 25; + break; + // Trial of the Champion, Eadric Achievement (The Faceroller) + case 68197: + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ALLY; + spellInfo->Attributes |= SPELL_ATTR0_CASTABLE_WHILE_DEAD; + break; + // Trial of the Champion, Earth Shield + case 67530: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; // will trigger 67537 + break; + // Trial of the Champion, Hammer of the Righteous + case 66867: + spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; + break; + // Trial of the Champion, Summon Risen Jaeren/Arelas + case 67705: + case 67715: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; + break; + // Trial of the Champion, Ghoul Explode + case 67751: + spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; + spellInfo->EffectRadiusIndex[0] = 12; + spellInfo->EffectImplicitTargetA[1] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_SRC_AREA_ENTRY; + spellInfo->EffectRadiusIndex[1] = 12; + spellInfo->EffectImplicitTargetA[2] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[2] = TARGET_UNIT_SRC_AREA_ENTRY; + spellInfo->EffectRadiusIndex[2] = 12; + break; + // Trial of the Champion, Desecration + case 67778: + case 67877: + spellInfo->EffectTriggerSpell[0] = 68766; + break; + + ////////////////////////////////////////// + ////////// TRIAL OF THE CRUSADER + ////////////////////////////////////////// + // Trial of the Crusader, Jaraxxus Intro spell + case 67888: + spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; + spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Trial of the Crusader, Lich King Intro spell + case 68193: + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; + break; + // Trial of the Crusader, Gormok, player vehicle spell, CUSTOM! (default jump to hand, not used) + case 66342: + spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_SET_VEHICLE_ID; + spellInfo->EffectMiscValue[0] = 496; + spellInfo->DurationIndex = 21; + spellInfo->rangeIndex = 13; + spellInfo->EffectImplicitTargetA[0] = 25; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->AuraInterruptFlags = AURA_INTERRUPT_FLAG_CHANGE_MAP; + break; + // Trial of the Crusader, Gormok, Fire Bomb + case 66313: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_TARGET_ANY; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[1] = TARGET_DEST_TARGET_ANY; + spellInfo->Effect[1] = 0; + [[fallthrough]]; + case 66317: + spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; + spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + case 66318: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->speed = 14.0f; + spellInfo->Attributes |= SPELL_ATTR0_STOP_ATTACK_TARGET; + spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + case 66320: + case 67472: + case 67473: + case 67475: + spellInfo->EffectRadiusIndex[0] = 7; + spellInfo->EffectRadiusIndex[1] = 7; + break; + // Trial of the Crusader, Acidmaw & Dreadscale, Emerge + case 66947: + spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_STUNNED; + break; + // Trial of the Crusader, Jaraxxus, Curse of the Nether + case 66211: + spellInfo->excludeTargetAuraSpell = 66209; // exclude Touch of Jaraxxus + break; + // Trial of the Crusader, Jaraxxus, Summon Volcano + case 66258: + case 67901: + spellInfo->DurationIndex = 85; // summon for 18 seconds, 15 not enough + break; + // Trial of the Crusader, Jaraxxus, Spinning Pain Spike + case 66281: + spellInfo->EffectRadiusIndex[0] = 26; + break; + case 66287: + spellInfo->Effect[1] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_MOD_TAUNT; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_NEARBY_ENTRY; + spellInfo->Effect[2] = SPELL_EFFECT_APPLY_AURA; + spellInfo->EffectApplyAuraName[2] = SPELL_AURA_MOD_STUN; + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_CASTER; + spellInfo->DurationIndex = 35; // 4 secs + break; + // Trial of the Crusader, Jaraxxus, Fel Fireball + case 66532: + case 66963: + case 66964: + case 66965: + spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; + break; + // tempfix, make Nether Power not stealable + case 66228: + case 67106: + case 67107: + case 67108: + spellInfo->AttributesEx4 |= SPELL_ATTR4_NOT_STEALABLE; + break; + // Trial of the Crusader, Faction Champions, Druid - Tranquality + case 66086: + case 67974: + case 67975: + case 67976: + spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AREA_AURA_FRIEND; + break; + // Trial of the Crusader, Faction Champions, Shaman - Earth Shield + case 66063: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL; + spellInfo->EffectTriggerSpell[0] = 66064; + break; + // Trial of the Crusader, Faction Champions, Priest - Mana Burn + case 66100: + spellInfo->EffectBasePoints[0] = 5; + spellInfo->EffectDieSides[0] = 0; + break; + case 68026: + spellInfo->EffectBasePoints[0] = 8; + spellInfo->EffectDieSides[0] = 0; + break; + case 68027: + spellInfo->EffectBasePoints[0] = 6; + spellInfo->EffectDieSides[0] = 0; + break; + case 68028: + spellInfo->EffectBasePoints[0] = 10; + spellInfo->EffectDieSides[0] = 0; + break; + + // Trial of the Crusader, Twin Valkyr, Touch of Light/Darkness, Light/Dark Surge + case 65950: // light 0 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 65767: // light surge 0 + spellInfo->excludeTargetAuraSpell = 65686; + break; + case 67296: // light 1 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 67274: // light surge 1 + spellInfo->excludeTargetAuraSpell = 67222; + break; + case 67297: // light 2 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 67275: // light surge 2 + spellInfo->excludeTargetAuraSpell = 67223; + break; + case 67298: // light 3 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 67276: // light surge 3 + spellInfo->excludeTargetAuraSpell = 67224; + break; + case 66001: // dark 0 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 65769: // dark surge 0 + spellInfo->excludeTargetAuraSpell = 65684; + break; + case 67281: // dark 1 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 67265: // dark surge 1 + spellInfo->excludeTargetAuraSpell = 67176; + break; + case 67282: // dark 2 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 67266: // dark surge 2 + spellInfo->excludeTargetAuraSpell = 67177; + break; + case 67283: // dark 3 + //spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + spellInfo->EffectImplicitTargetA[0] = 6; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + [[fallthrough]]; // TODO: Not sure whether the fallthrough was a mistake (forgetting a break) or intended. This should be double-checked. + case 67267: // dark surge 3 + spellInfo->excludeTargetAuraSpell = 67178; + break; + + // Trial of the Crusader, Twin Valkyr, Twin's Pact + case 65875: + case 67303: + case 67304: + case 67305: + case 65876: + case 67306: + case 67307: + case 67308: + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + break; + // Trial of the Crusader, Anub'arak, Emerge + case 65982: + spellInfo->AttributesEx5 |= SPELL_ATTR5_USABLE_WHILE_STUNNED; + break; + // Trial of the Crusader, Anub'arak, Penetrating Cold + case 66013: + case 67700: + case 68509: + case 68510: + spellInfo->EffectRadiusIndex[0] = 12; // 100yd + break; + // Trial of the Crusader, Anub'arak, Shadow Strike + case 66134: + spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; + spellInfo->Effect[0] = 0; + break; + // Trial of the Crusader, Anub'arak, Pursuing Spikes + case 65920: + case 65922: + case 65923: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_DUMMY; + //spellInfo->EffectTriggerSpell[0] = 0; + break; + // Trial of the Crusader, Anub'arak, Summon Scarab + case 66339: + spellInfo->DurationIndex = 35; + spellInfo->EffectImplicitTargetA[0] = 25; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Trial of the Crusader, Anub'arak, Achievements: The Traitor King + case 68186: // Anub'arak Scarab Achievement 10 + case 68515: // Anub'arak Scarab Achievement 25 + spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; + spellInfo->Attributes |= SPELL_ATTR0_CASTABLE_WHILE_DEAD; + break; + // Trial of the Crusader, Anub'arak, Spider Frenzy + case 66129: + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + + ////////////////////////////////////////// + ////////// THE FORGE OF SOULS + ////////////////////////////////////////// + // Soul Sickness (69131) + case 69131: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PERIODIC_TRIGGER_SPELL; + spellInfo->EffectAmplitude[0] = 8000; + spellInfo->EffectTriggerSpell[0] = 69133; + break; + // Phantom Blast (68982,70322) + case 68982: + case 70322: + spellInfo->InterruptFlags |= SPELL_INTERRUPT_FLAG_INTERRUPT; + break; + + ////////////////////////////////////////// + ////////// PIT OF SARON + ////////////////////////////////////////// + // Empowered Blizzard + case 70131: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + // Ice Lance Volley + case 70464: + spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; + spellInfo->EffectRadiusIndex[0] = 25; + break; + // Multi-Shot + case 70513: + // Shriek of the Highborne + case 59514: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CONE_ENTRY; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Icicle + case 69428: + case 69426: + spellInfo->InterruptFlags = 0; + spellInfo->AuraInterruptFlags = 0; + spellInfo->ChannelInterruptFlags = 0; + break; + // Jaina's Call + case 70525: + // Call of Sylvanas + case 70639: + spellInfo->Effect[0] = 0; + spellInfo->Effect[1] = 0; + spellInfo->EffectImplicitTargetA[2] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[2] = TARGET_UNIT_SRC_AREA_ENTRY; + spellInfo->EffectRadiusIndex[2] = 30; // 500yd + break; + // Frost Nova + case 68198: + spellInfo->rangeIndex = 13; + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + break; + // Blight + case 69604: + case 70286: + spellInfo->MaxAffectedTargets = 1; + spellInfo->AttributesEx3 |= (SPELL_ATTR3_IGNORE_HIT_RESULT | SPELL_ATTR3_ONLY_TARGET_PLAYERS); + break; + // Chilling Wave + case 68778: + case 70333: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Permafrost + case 68786: + case 70336: + spellInfo->AttributesEx3 |= (SPELL_ATTR3_IGNORE_HIT_RESULT | SPELL_ATTR3_ONLY_TARGET_PLAYERS); + spellInfo->Effect[2] = SPELL_EFFECT_DUMMY; + break; + // Pursuit: + case 68987: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[1] = 0; + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetB[2] = 0; + spellInfo->rangeIndex = 6; // 100yd + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + case 69029: + case 70850: + spellInfo->Effect[2] = 0; + break; + // Explosive Barrage: + case 69263: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_MOD_STUN; + break; + // Overlord's Brand: + case 69172: + spellInfo->procFlags = DONE_HIT_PROC_FLAG_MASK & ~PROC_FLAG_DONE_PERIODIC; + spellInfo->procChance = 100; + break; + // Icy Blast: + case 69232: + spellInfo->EffectTriggerSpell[1] = 69238; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + case 69233: + case 69646: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + case 69238: + case 69628: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[0] = TARGET_DEST_DYNOBJ_NONE; + spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[1] = TARGET_DEST_DYNOBJ_NONE; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + // Hoarfrost: + case 69246: + case 69245: + case 69645: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + // Devour Humanoid: + case 69503: + spellInfo->ChannelInterruptFlags |= 0; + spellInfo->AuraInterruptFlags = AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING; + break; + + ////////////////////////////////////////// + ////////// HALLS OF REFLECTION + ////////////////////////////////////////// + // Falric: Defiling Horror + case 72435: + case 72452: + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; + break; + // Frostsworn General - Throw Shield + case 69222: + case 73076: + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ENEMY; + break; + // Halls of Reflection Clone + case 69828: + spellInfo->Effect[1] = 0; + spellInfo->Effect[2] = 0; + break; + // Summon Ice Wall + case 69768: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + break; + case 69767: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_TARGET_ANY; + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ANY; + break; + // Essence of the Captured + case 73035: + case 70719: + spellInfo->rangeIndex = 13; + break; + // Achievement Check + case 72830: + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; + break; + + ////////////////////////////////////////// + ////////// ICECROWN CITADEL + ////////////////////////////////////////// + case 70781: // Light's Hammer Teleport + case 70856: // Oratory of the Damned Teleport + case 70857: // Rampart of Skulls Teleport + case 70858: // Deathbringer's Rise Teleport + case 70859: // Upper Spire Teleport + case 70860: // Frozen Throne Teleport + case 70861: // Sindragosa's Lair Teleport + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DB; // this target is for SPELL_EFFECT_TELEPORT_UNITS + spellInfo->EffectImplicitTargetB[1] = 0; + spellInfo->EffectImplicitTargetA[2] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[2] = 0; + break; + case 70960: // Bone Flurry + case 71258: // Adrenaline Rush (Ymirjar Battle-Maiden) + spellInfo->AttributesEx &= ~SPELL_ATTR1_CHANNELED_2; + break; + case 69055: // Saber Lash (Lord Marrowgar) + case 70814: // Saber Lash (Lord Marrowgar) + spellInfo->EffectRadiusIndex[0] = 8; // 5yd + break; + case 69065: // Impaled (Lord Marrowgar) + spellInfo->Effect[0] = 0; // remove stun so Dispersion can be used + break; + case 72701: // Cold Flame (Lord Marrowgar) + case 72702: // Cold Flame (Lord Marrowgar) + case 72703: // Cold Flame (Lord Marrowgar) + case 72704: // Cold Flame (Lord Marrowgar) + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[1] = 0; + spellInfo->DurationIndex = 9; // 30 secs instead of 12, need him for longer, but will stop his actions after 12 secs + break; + case 69138: // Coldflame (Lord Marrowgar) + spellInfo->Effect[0] = 0; + spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_DEST; + spellInfo->DurationIndex = 9; // 30 secs instead of 12, need him for longer, but will stop his actions after 12 secs + break; + case 69146: + case 70823: + case 70824: + case 70825: // Coldflame (Lord Marrowgar) + spellInfo->EffectRadiusIndex[0] = 15; // 3yd instead of 5yd + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; + break; + case 70897: // Dark Martyrdom (Lady Deathwhisper) + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; + break; + case 69075: // Bone Storm (Lord Marrowgar) + case 70834: // Bone Storm (Lord Marrowgar) + case 70835: // Bone Storm (Lord Marrowgar) + case 70836: // Bone Storm (Lord Marrowgar) + case 72378: // Blood Nova (Deathbringer Saurfang) + case 73058: // Blood Nova (Deathbringer Saurfang) + case 72769: // Scent of Blood (Deathbringer Saurfang) + case 72385: // Boiling Blood (Deathbringer Saurfang) + case 72441: // Boiling Blood (Deathbringer Saurfang) + case 72442: // Boiling Blood (Deathbringer Saurfang) + case 72443: // Boiling Blood (Deathbringer Saurfang) + case 71160: // Plague Stench (Stinky) + case 71161: // Plague Stench (Stinky) + case 71123: // Decimate (Stinky & Precious) + case 71464: // Divine Surge (Sister Svalna) + spellInfo->EffectRadiusIndex[0] = 12; // 100yd + break; + case 71169: // Shadow's Fate + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + case 72347: // Lock Players and Tap Chest + spellInfo->AttributesEx3 &= ~SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + case 73843: // Award Reputation - Boss Kill + case 73844: // Award Reputation - Boss Kill + case 73845: // Award Reputation - Boss Kill + case 73846: // Award Reputation - Boss Kill + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_50000_YARDS; + break; + case 72864: // Death Plague (Rotting Frost Giant) + spellInfo->excludeTargetAuraSpell = 0; + break; + case 69705: // Gunship Battle, spell Below Zero + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + case 72723: // Resistant Skin (Deathbringer Saurfang adds) + // this spell initially granted Shadow damage immunity, however it was removed but the data was left in client + spellInfo->Effect[2] = 0; + break; + case 72255: // Mark of the Fallen Champion (Deathbringer Saurfang) // Patch 3.3.2 (2010-01-02): Deathbringer Saurfang will no longer gain blood power from Mark of the Fallen Champion. + case 72444: // Mark of the Fallen Champion (Deathbringer Saurfang) // Xinef: prevented in script, effect needed for Prayer of Mending + case 72445: // Mark of the Fallen Champion (Deathbringer Saurfang) + case 72446: // Mark of the Fallen Champion (Deathbringer Saurfang) + spellInfo->AttributesEx3 &= ~SPELL_ATTR3_CANT_TRIGGER_PROC; + break; + case 70460: // Coldflame Jets (Traps after Saurfang) + spellInfo->DurationIndex = 1; // 10 seconds + break; + case 70461: // Coldflame Jets (Traps after Saurfang) + case 71289: // Dominate Mind (Lady Deathwhisper) + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + case 71906: // Severed Essence (Val'kyr Herald) + case 71942: // Severed Essence (Val'kyr Herald) + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY; + spellInfo->EffectImplicitTargetB[0] = 0; + spellInfo->Effect[1] = 0; + break; + case 71159: // Awaken Plagued Zombies (Precious) + case 71302: // Awaken Ymirjar Fallen (Ymirjar Deathbringer) + spellInfo->DurationIndex = 21; + break; + case 70981: // Blood Prince Council, Invocation of Blood + case 70982: // Blood Prince Council, Invocation of Blood + case 70952: // Blood Prince Council, Invocation of Blood + spellInfo->Effect[0] = 0; // clear share health aura + break; + case 71274: // Ymirjar Frostbinder, Frozen Orb + spellInfo->EffectImplicitTargetA[0] = 6; + break; + case 69783: // Ooze Flood (Rotface) + case 69797: + case 69799: + case 69802: + spellInfo->AttributesEx |= SPELL_ATTR1_CANT_TARGET_SELF; + break; + case 70530: // Volatile Ooze Beam Protection + spellInfo->Effect[0] = SPELL_EFFECT_APPLY_AURA; // blizzard typo, 65 instead of 6, aura itself is defined (dummy) + break; + case 70672: + case 72455: + case 72832: + case 72833: // Professor Putricide, Gaseous Bloat (Orange Ooze Channel) -- copied attributes from Green Ooze Channel + spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + case 71412: // Green Ooze Summon (Professor Putricide) + case 71415: // Orange Ooze Summon (Professor Putricide) + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + break; + case 71621: + case 72850: + case 72851: + case 72852: // Create Concoction (Professor Putricide) + case 71893: + case 73120: + case 73121: + case 73122: // Guzzle Potions (Professor Putricide) + spellInfo->CastingTimeIndex = 15; // 4 sec + break; + case 72454: // Mutated Plague (Professor Putricide) + case 72464: // Mutated Plague (Professor Putricide) + case 72506: // Mutated Plague (Professor Putricide) + case 72507: // Mutated Plague (Professor Putricide) + spellInfo->AttributesEx4 |= SPELL_ATTR4_IGNORE_RESISTANCES; + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + case 70911: // Unbound Plague (Professor Putricide) (needs target selection script) + case 72854: // Unbound Plague (Professor Putricide) (needs target selection script) + case 72855: // Unbound Plague (Professor Putricide) (needs target selection script) + case 72856: // Unbound Plague (Professor Putricide) (needs target selection script) + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ENEMY; + break; + case 70402: // Mutated Transformation (Professor Putricide) + case 72511: // Mutated Transformation (Professor Putricide) + case 72512: // Mutated Transformation (Professor Putricide) + case 72513: // Mutated Transformation (Professor Putricide) + spellInfo->AttributesEx2 |= SPELL_ATTR2_CANT_CRIT; + break; + case 71708: // Empowered Flare (Blood Prince Council) + case 72785: // Empowered Flare (Blood Prince Council) + case 72786: // Empowered Flare (Blood Prince Council) + case 72787: // Empowered Flare (Blood Prince Council) + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + case 71518: // Unholy Infusion Quest Credit (Professor Putricide) + case 72934: // Blood Infusion Quest Credit (Blood-Queen Lana'thel) + case 72289: // Frost Infusion Quest Credit (Sindragosa) + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // another missing radius + break; + case 71266: // Swarming Shadows + case 72890: // Swarming Shadows + spellInfo->AreaGroupId = 0; // originally, these require area 4522, which is... outside of Icecrown Citadel + break; + case 71301: // Summon Dream Portal (Valithria Dreamwalker) + case 71977: // Summon Nightmare Portal (Valithria Dreamwalker) + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + case 70715: // Column of Frost (visual marker) + spellInfo->DurationIndex = 32; // 6 seconds (missing) + break; + case 71085: // Mana Void (periodic aura) + spellInfo->DurationIndex = 9; // 30 seconds (missing) + break; + case 70936: // Summon Suppressor (needs target selection script) + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + case 70602: // Corruption + spellInfo->AttributesEx3 |= SPELL_ATTR3_STACK_FOR_DIFF_CASTERS; + break; + case 72706: // Achievement Check (Valithria Dreamwalker) + case 71357: // Order Whelp + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + break; + case 70598: // Sindragosa's Fury + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + case 71077: // Tail Smash (Sindragosa) + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_CASTER_BACK; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_DEST_AREA_ENEMY; + spellInfo->EffectImplicitTargetA[1] = TARGET_DEST_CASTER_BACK; + spellInfo->EffectImplicitTargetB[1] = TARGET_UNIT_DEST_AREA_ENEMY; + break; + case 69846: // Frost Bomb + spellInfo->speed = 0.0f; // This spell's summon happens instantly + break; + case 70127: // Mystic Buffet (Sindragosa) - remove obsolete spell effect with no targets + case 72528: + case 72529: + case 72530: + spellInfo->Effect[1] = 0; + break; + case 70084: // Sindragosa, Frost Aura + case 71050: + case 71051: + case 71052: + spellInfo->Attributes &= ~SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; + break; + + case 71614: // Ice Lock + spellInfo->Mechanic = MECHANIC_STUN; + break; + case 70541: // Lich King, Infest + case 73779: + case 73780: + case 73781: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + case 70337: // Lich King, Necrotic Plague + case 73912: + case 73913: + case 73914: + case 70338: + case 73785: + case 73786: + case 73787: + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + case 69099: // Ice Pulse 10n + case 73776: // Ice Pulse 25n + case 73777: // Ice Pulse 10h + case 73778: // Ice Pulse 25h + spellInfo->AttributesEx2 |= SPELL_ATTR2_CANT_CRIT; + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; + break; + case 72350: // Fury of Frostmourne + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + case 72351: // Fury of Frostmourne + case 72431: // Jump (removes Fury of Frostmourne debuff) + case 72429: // Mass Resurrection + case 73159: // Play Movie + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + case 72376: // Raise Dead + spellInfo->MaxAffectedTargets = 4; + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + case 71809: // Jump + spellInfo->rangeIndex = 5; // 40yd + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; // 10yd + spellInfo->EffectMiscValue[0] = 190; + break; + case 72405: // Broken Frostmourne + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; // 200yd + break; + case 73540: // Summon Shadow Trap + spellInfo->DurationIndex = 3; // 60 seconds + break; + case 73530: // Shadow Trap (visual) + spellInfo->DurationIndex = 28; // 5 seconds + break; + case 73529: // Shadow Trap + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_10_YARDS; // 10yd + break; + case 74282: // Shadow Trap (searcher) + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_3_YARDS; // 3yd + break; + case 69198: // Raging Spirit Visual + spellInfo->rangeIndex = 13; // 50000yd + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->AttributesEx3 |= SPELL_ATTR3_IGNORE_HIT_RESULT; + break; + case 72762: // Defile + spellInfo->DurationIndex = 559; // 53 seconds + spellInfo->excludeCasterAuraSpell = 0; + spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; + spellInfo->AttributesEx6 |= (SPELL_ATTR6_CAN_TARGET_INVISIBLE | SPELL_ATTR6_CAN_TARGET_UNTARGETABLE); + break; + case 72743: // Defile + spellInfo->DurationIndex = 22; // 45 seconds + break; + case 72754: // Defile + case 73708: // Defile + case 73709: // Defile + case 73710: // Defile + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; // 200yd + break; + case 69030: // Val'kyr Target Search + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_200_YARDS; // 200yd + spellInfo->Attributes |= SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; + break; + case 73654: // Harvest Souls + case 74295: // Harvest Souls + case 74296: // Harvest Souls + case 74297: // Harvest Souls + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + spellInfo->EffectRadiusIndex[1] = EFFECT_RADIUS_50000_YARDS; // 50000yd + spellInfo->EffectRadiusIndex[2] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + case 72595: // Restore Soul + case 73650: // Restore Soul + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + break; + case 75127: // Kill Frostmourne Players + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + case 73655: // Harvest Soul + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_DONE_BONUS; + break; + case 74086: // Destroy Soul + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + break; + case 74302: // Summon Spirit Bomb + case 74342: // Summon Spirit Bomb + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + spellInfo->MaxAffectedTargets = 1; + break; + case 74341: // Summon Spirit Bomb + case 74343: // Summon Spirit Bomb + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_200_YARDS; // 200yd + spellInfo->MaxAffectedTargets = 3; + break; + case 73579: // Summon Spirit Bomb + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_25_YARDS; // 25yd + break; + case 73582: // Trigger Vile Spirit (Inside, Heroic) + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_50000_YARDS; // 50000yd + break; + // Scale Aura (used during Dominate Mind from Lady Deathwhisper) + case 73261: + spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CHANGE_MAP; + break; + // Leap to a Random Location + case 70485: + spellInfo->rangeIndex = 6; // 100yd + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; + spellInfo->EffectMiscValue[0] = 100; + break; + // Empowered Blood + case 70227: + case 70232: + spellInfo->AreaGroupId = 2452; // Whole icc instead of Crimson Halls only, remove when area calculation is fixed + break; + + ////////////////////////////////////////// + ////////// RUBY SANCTUN + ////////////////////////////////////////// + // Repelling Wave + case 74509: + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_20_YARDS; + spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_20_YARDS; + break; + // Rallying Shout + case 75414: + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_20_YARDS; + break; + // Barrier Channel + case 76221: + spellInfo->ChannelInterruptFlags &= ~(AURA_INTERRUPT_FLAG_TURNING | AURA_INTERRUPT_FLAG_MOVE); + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_UNIT_NEARBY_ENTRY; + break; + // Intimidating Roar + case 74384: + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_100_YARDS; + spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_100_YARDS; + break; + // Fiery Combustion + case 74562: + // Soul Consumption + case 74792: + spellInfo->AttributesEx |= SPELL_ATTR1_CANT_BE_REDIRECTED; + break; + // Combustion + case 75883: + case 75884: + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_6_YARDS; + spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_6_YARDS; + break; + // Consumption + case 75875: + case 75876: + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_6_YARDS; + spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_6_YARDS; + spellInfo->EffectMechanic[EFFECT_0] = 0; + spellInfo->EffectMechanic[EFFECT_1] = MECHANIC_SNARE; + break; + // Soul Consumption + case 74799: + spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_12_YARDS; + break; + // Twilight Cutter + case 74769: + case 77844: + case 77845: + case 77846: + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_100_YARDS; + break; + // Twilight Mending + case 75509: + spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->EffectRadiusIndex[EFFECT_0] = EFFECT_RADIUS_100_YARDS; + spellInfo->EffectRadiusIndex[EFFECT_1] = EFFECT_RADIUS_100_YARDS; + break; + // Meteor Strike + case 74637: + spellInfo->speed = 0; + break; + //Blazing Aura + case 75885: + case 75886: + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; + break; + //Meteor Strike + case 75952: + //Combustion Periodic + case 74629: + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_IGNORE_RESISTANCES; + break; + + + // /////////////////////////////////////////// + // ////////////////QUESTS///////////////////// + // /////////////////////////////////////////// + // Going Bearback (12851) + case 54897: + spellInfo->Effect[1] = SPELL_EFFECT_DUMMY; + spellInfo->EffectRadiusIndex[1] = spellInfo->EffectRadiusIndex[0]; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_DEST_AREA_ENTRY; + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_CAN_CAST_WHILE_CASTING; + break; + // Still At It (12644) + case 51931: + case 51932: + case 51933: + spellInfo->EffectImplicitTargetA[0] = 38; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Rallying the Troops (12070) + case 47394: + spellInfo->excludeTargetAuraSpell = 47394; + break; + // A Tangled Skein (12555) + case 51165: + case 51173: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // A Cloudlet of Classy Cologne (24635) + case 69563: + // A Perfect Puff of Perfume (24629) + case 69445: + // Bonbon Blitz (24636) + case 69489: + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_CASTER; + break; + // Control (9595) + case 30790: + spellInfo->EffectMiscValue[1] = 0; + break; + // Reclusive Runemaster (12150) + case 48028: + spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENEMY; + break; + // Mastery of + case 65147: + spellInfo->Category = 1244; + spellInfo->CategoryRecoveryTime = 1500; + break; + // Weakness to Lightning (11896) + case 46432: + spellInfo->AttributesEx3 &= ~SPELL_ATTR3_DEATH_PERSISTENT; + break; + // Wrangle Some Aether Rays! (11065) + case 40856: + spellInfo->DurationIndex = 27; // 3000ms + break; + // The Black Knight's Orders (13663) + case 63163: + spellInfo->EffectBasePoints[0] = 52390; + break; + // The Warp Rifts (10278) + case 34888: + spellInfo->DurationIndex = 5; // 300 secs + break; + // The Smallest Creatures (10720) + case 38544: + spellInfo->EffectMiscValueB[0] = 427; + spellInfo->EffectImplicitTargetA[0] = 1; + spellInfo->Effect[1] = 0; + break; + // Ridding the red rocket + case 49177: + spellInfo->EffectBasePoints[0] = 1; // corrects seat id (points - 1 = seatId) + break; + // The Iron Colossus (13007) + case 56513: + case 56524: + spellInfo->RecoveryTime = (spellInfo->Id == 56524 ? 6000 : 2000); + break; + // Kaw the Mammoth Destroyer (11879) + case 46260: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + // That's Abominable (13264)(13276)(13288)(13289) + case 59565: + spellInfo->EffectMiscValueB[0] = 1721; // controlable guardian + break; + // Investigate the Blue Recluse (1920) + // Investigate the Alchemist Shop (1960) + case 9095: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_DUMMY; + spellInfo->EffectRadiusIndex[0] = 13; + break; + // Dragonmaw Race: All parts + case 40890: // Oldie's Rotten Pumpkin + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectTriggerSpell[0] = 40905; + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + case 40909: // Trope's Slime Cannon + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectTriggerSpell[0] = 40905; + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + case 40894: // Corlok's Skull Barrage + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectTriggerSpell[0] = 40900; + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + case 40928: // Ichman's Blazing Fireball + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectTriggerSpell[0] = 40929; + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + case 40930: // Mulverick's Great Balls of Lightning + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectTriggerSpell[0] = 40931; + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + case 40945: // Sky Shatter + spellInfo->Targets |= TARGET_FLAG_DEST_LOCATION; + spellInfo->EffectTriggerSpell[0] = 41064; + spellInfo->Effect[0] = SPELL_EFFECT_TRIGGER_MISSILE; + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + break; + // Gauging the Resonant Frequency (10594) + case 37390: + spellInfo->EffectMiscValueB[0] = 181; + break; + // Where in the World is Hemet Nesingwary? (12521) + case 50860: + spellInfo->EffectBasePoints[0] = 50860; + break; + case 50861: + spellInfo->EffectBasePoints[0] = 0; + break; + // Krolmir, Hammer of Storms (13010) + case 56606: + case 56541: + spellInfo->EffectBasePoints[0] = 1; + break; + // Blightbeasts be Damned! (12072) + case 47424: + spellInfo->AuraInterruptFlags &= ~AURA_INTERRUPT_FLAG_NOT_ABOVEWATER; + break; + // Leading the Charge (13380), All Infra-Green bomber quests + case 59059: + spellInfo->AttributesEx4 &= ~SPELL_ATTR4_CAN_CAST_WHILE_CASTING; + break; + // Dark Horizon (12664), Reunited (12663) + case 52190: + spellInfo->EffectBasePoints[EFFECT_0] = 52391 - 1; + break; + // The Sum is Greater than the Parts (13043) - Chained Grip + case 60540: + spellInfo->EffectMiscValue[EFFECT_0] = 300; + break; + // Not a Bug (13342) + case 60531: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_DEAD; + break; + // Frankly, It Makes No Sense... (10672) + case 37851: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Honor Challenge (12939) + case 21855: + spellInfo->AttributesEx3 |= SPELL_ATTR3_NO_INITIAL_AGGRO; + break; + // Convocation at Zol'Heb (12730) + case 52956: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_DEST_AREA_ENTRY; + break; + // Mangletooth Quests (http://www.wowhead.com/npc=3430) + case 7764: + case 10767: + case 16610: + case 16612: + case 16618: + case 17013: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + spellInfo->AttributesEx5 |= SPELL_ATTR5_SKIP_CHECKCAST_LOS_CHECK; + break; + //Crushing the Crown + case 71024: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DYNOBJ_NONE; + break; + // Battle for the Undercity + case 59892: // Cyclone fall + spellInfo->Effect[EFFECT_0] = SPELL_EFFECT_APPLY_AREA_AURA_FRIEND; + spellInfo->EffectRadiusIndex[0] = EFFECT_RADIUS_10_YARDS; + spellInfo->AttributesEx &= ~SPELL_ATTR0_CANT_CANCEL; + spellInfo->AttributesEx3 |= SPELL_ATTR3_ONLY_TARGET_PLAYERS; + break; + + // /////////////////////////////////////////// + // ////////////////ITEMS////////////////////// + // /////////////////////////////////////////// + // enchant Lightweave Embroidery + case 55637: + spellInfo->EffectMiscValue[1] = 126; + break; + // Magic Broom + case 47977: + spellInfo->Effect[0] = 0; + spellInfo->Effect[1] = 0; + break; + // Titanium Seal of Dalaran, Toss your luck + case 60476: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_CASTER; + break; + // Mind Amplification Dish, change charm aura + case 26740: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_MOD_CHARM; + break; + // Persistent Shield (fixes idiocity) + case 26467: + spellInfo->EffectApplyAuraName[0] = SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE; + spellInfo->EffectTriggerSpell[0] = 26470; + break; + // Deadly Swiftness + case 31255: + spellInfo->EffectTriggerSpell[0] = 22588; + break; + // Black Magic enchant + case 59630: + spellInfo->Attributes |= SPELL_ATTR0_PASSIVE; + break; + // Precious's Ribbon + case 72968: + spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; + break; + // Item - Bauble of True Blood 10m + // Item - Bauble of True Blood 25m + case 71646: + case 71607: + // Item - Althor's Abacus trigger 10m + // Item - Althor's Abacus trigger 25m + case 71610: + case 71641: + spellInfo->DmgClass = SPELL_DAMAGE_CLASS_MAGIC; + spellInfo->spellLevel = 0; + break; + // Drain Life - Bryntroll Normal / Heroic + case 71838: + case 71839: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CANT_CRIT; + spellInfo->AttributesEx4 |= SPELL_ATTR4_IGNORE_RESISTANCES; + break; + // Alchemist's Stone + case 17619: + spellInfo->AttributesEx3 |= SPELL_ATTR3_DEATH_PERSISTENT; + break; + // Gnomish Death Ray + case 13278: + case 13280: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ENEMY; + break; + // Stormchops + case 43730: + spellInfo->EffectImplicitTargetA[1] = 1; + spellInfo->EffectImplicitTargetB[1] = 0; + break; + // Savory Deviate Delight (transformations), allow to mount while transformed + case 8219: + case 8220: + case 8221: + case 8222: + spellInfo->Attributes &= ~SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY; + break; + // Clamlette Magnifique + case 72623: // drink triggered spell + spellInfo->EffectBasePoints[EFFECT_0] = spellInfo->EffectBasePoints[EFFECT_1]; + break; + // Compact Harvest Reaper + case 4078: + spellInfo->DurationIndex = 6; // 10 minutes + break; + // Dragon Kite, Tuskarr Kite - Kite String + case 45192: + spellInfo->rangeIndex = 6; // 100yd + break; + // Frigid Frostling, Infrigidate + case 74960: + spellInfo->EffectRadiusIndex[EFFECT_0] = 9; // 20yd + break; + + + // /////////////////////////////////////////// + // ////////////////EVENTS///////////////////// + // /////////////////////////////////////////// + + ////////////////////////////////////////// + ////////// BREWFEST + ////////////////////////////////////////// + // Apple Trap + case 43450: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_SRC_AREA_ENEMY; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_CASTER; + spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; + break; + // Dark Iron Attack - spawn mole machine + case 43563: + spellInfo->Effect[2] = 0; // summon GO's manually + break; + // Throw Mug visual + case 42300: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_TARGET_ANY; + break; + // Dark Iron knockback Aura + case 42299: + spellInfo->EffectApplyAuraName[1] = SPELL_AURA_DUMMY; + spellInfo->EffectMiscValue[0] = 100; + spellInfo->EffectBasePoints[0] = 79; + break; + // Chug and Chuck! + case 42436: + spellInfo->EffectImplicitTargetA[0] = TARGET_SRC_CASTER; + spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_SRC_AREA_ENTRY; + spellInfo->MaxAffectedTargets = 0; + spellInfo->excludeCasterAuraSpell = 42299; + break; + // Catch the Wild Wolpertinger! + case 41621: + spellInfo->Effect[0] = SPELL_EFFECT_DUMMY; + break; + // Brewfest quests + case 47134: + case 51798: + spellInfo->Effect[0] = 0; + break; + // The Heart of The Storms (12998) + case 43528: + spellInfo->DurationIndex = 18; + spellInfo->EffectImplicitTargetA[0] = 25; + break; + + ////////////////////////////////////////// + ////////// Hallow's End + ////////////////////////////////////////// + // Water splash + case 42348: + spellInfo->Effect[0] = 0; + break; + // Summon Lantersn + case 44255: + case 44231: + spellInfo->EffectImplicitTargetA[0] = TARGET_DEST_DEST; + spellInfo->EffectImplicitTargetB[0] = 0; + break; + // Throw Head Back + case 42401: + spellInfo->EffectImplicitTargetA[0] = TARGET_UNIT_NEARBY_ENTRY; + break; + + ////////////////////////////////////////// + ////////// Pilgrim's Bounty + ////////////////////////////////////////// + // Various food + case 65418: + spellInfo->EffectTriggerSpell[2] = 65410; + break; + case 65422: + spellInfo->EffectTriggerSpell[2] = 65414; + break; + case 65419: + spellInfo->EffectTriggerSpell[2] = 65416; + break; + case 65420: + spellInfo->EffectTriggerSpell[2] = 65412; + break; + case 65421: + spellInfo->EffectTriggerSpell[2] = 65415; + break; + + ////////////////////////////////////////// + ////////// Midsummer + ////////////////////////////////////////// + // Stamp Out Bonfire + case 45437: + spellInfo->Effect[1] = SPELL_EFFECT_DUMMY; + spellInfo->EffectImplicitTargetA[1] = TARGET_UNIT_NEARBY_ENTRY; + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + // Light Bonfire (DND) + case 29831: + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + break; + ////////////////////////////////////////// + ////////// Misc Events + ////////////////////////////////////////// + // Infernal + case 33240: + spellInfo->EffectImplicitTargetA[EFFECT_0] = TARGET_DEST_TARGET_ANY; + spellInfo->EffectImplicitTargetA[EFFECT_1] = TARGET_UNIT_TARGET_ANY; + spellInfo->EffectImplicitTargetA[EFFECT_2] = TARGET_UNIT_TARGET_ANY; + break; + // Check for SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER + case 47476: // Deathknight - Strangulate + case 15487: // Priest - Silence + case 5211: // Druid - Bash - R1 + case 6798: // Druid - Bash - R2 + case 8983: // Druid - Bash - R3 + spellInfo->AttributesEx7 |= SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER; + break; } switch (spellInfo->SpellFamilyName) diff --git a/src/server/game/Spells/SpellMgr.h b/src/server/game/Spells/SpellMgr.h index c02f6ce19..12d77b405 100644 --- a/src/server/game/Spells/SpellMgr.h +++ b/src/server/game/Spells/SpellMgr.h @@ -134,37 +134,37 @@ enum ProcFlags // flag masks AUTO_ATTACK_PROC_FLAG_MASK = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK - | PROC_FLAG_DONE_RANGED_AUTO_ATTACK | PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK, + | PROC_FLAG_DONE_RANGED_AUTO_ATTACK | PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK, MELEE_PROC_FLAG_MASK = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK - | PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS - | PROC_FLAG_DONE_MAINHAND_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK, + | PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS + | PROC_FLAG_DONE_MAINHAND_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK, RANGED_PROC_FLAG_MASK = PROC_FLAG_DONE_RANGED_AUTO_ATTACK | PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK - | PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS, + | PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS, SPELL_PROC_FLAG_MASK = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS - | PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS - | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS - | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG - | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS - | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG, + | PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS + | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS + | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG + | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS + | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG, SPELL_CAST_PROC_FLAG_MASK = SPELL_PROC_FLAG_MASK | PROC_FLAG_DONE_TRAP_ACTIVATION | RANGED_PROC_FLAG_MASK, PERIODIC_PROC_FLAG_MASK = PROC_FLAG_DONE_PERIODIC | PROC_FLAG_TAKEN_PERIODIC, DONE_HIT_PROC_FLAG_MASK = PROC_FLAG_DONE_MELEE_AUTO_ATTACK | PROC_FLAG_DONE_RANGED_AUTO_ATTACK - | PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS | PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS - | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG - | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG - | PROC_FLAG_DONE_PERIODIC | PROC_FLAG_DONE_MAINHAND_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK, + | PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS | PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS + | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG + | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG + | PROC_FLAG_DONE_PERIODIC | PROC_FLAG_DONE_MAINHAND_ATTACK | PROC_FLAG_DONE_OFFHAND_ATTACK, TAKEN_HIT_PROC_FLAG_MASK = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK | PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK - | PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS - | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG - | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG - | PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_TAKEN_DAMAGE, + | PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS | PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS + | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG + | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG + | PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_TAKEN_DAMAGE, REQ_SPELL_PHASE_PROC_FLAG_MASK = SPELL_PROC_FLAG_MASK & DONE_HIT_PROC_FLAG_MASK, }; @@ -318,9 +318,9 @@ enum SpellGroupSpecialFlags SPELL_GROUP_SPECIAL_FLAG_ELIXIR_GUARDIAN = 0x002, SPELL_GROUP_SPECIAL_FLAG_ELIXIR_UNSTABLE = 0x004, SPELL_GROUP_SPECIAL_FLAG_ELIXIR_SHATTRATH = 0x008, - SPELL_GROUP_SPECIAL_FLAG_STACK_EXCLUSIVE_MAX= 0x00F, + SPELL_GROUP_SPECIAL_FLAG_STACK_EXCLUSIVE_MAX = 0x00F, SPELL_GROUP_SPECIAL_FLAG_FORCED_STRONGEST = 0x010, // xinef: specially helpful flag if some spells have different auras, but only one should be present - SPELL_GROUP_SPECIAL_FLAG_SKIP_STRONGER_CHECK= 0x020, + SPELL_GROUP_SPECIAL_FLAG_SKIP_STRONGER_CHECK = 0x020, SPELL_GROUP_SPECIAL_FLAG_BASE_AMOUNT_CHECK = 0x040, SPELL_GROUP_SPECIAL_FLAG_PRIORITY1 = 0x100, SPELL_GROUP_SPECIAL_FLAG_PRIORITY2 = 0x200, @@ -440,51 +440,51 @@ enum EffectRadiusIndex // Spell pet auras class PetAura { - private: - typedef std::unordered_map PetAuraMap; +private: + typedef std::unordered_map PetAuraMap; - public: - PetAura() : removeOnChangePet(false), damage(0) - { - auras.clear(); - } +public: + PetAura() : removeOnChangePet(false), damage(0) + { + auras.clear(); + } - PetAura(uint32 petEntry, uint32 aura, bool _removeOnChangePet, int _damage) : + PetAura(uint32 petEntry, uint32 aura, bool _removeOnChangePet, int _damage) : removeOnChangePet(_removeOnChangePet), damage(_damage) - { - auras[petEntry] = aura; - } + { + auras[petEntry] = aura; + } - uint32 GetAura(uint32 petEntry) const - { - PetAuraMap::const_iterator itr = auras.find(petEntry); - if (itr != auras.end()) - return itr->second; - PetAuraMap::const_iterator itr2 = auras.find(0); - if (itr2 != auras.end()) - return itr2->second; - return 0; - } + uint32 GetAura(uint32 petEntry) const + { + PetAuraMap::const_iterator itr = auras.find(petEntry); + if (itr != auras.end()) + return itr->second; + PetAuraMap::const_iterator itr2 = auras.find(0); + if (itr2 != auras.end()) + return itr2->second; + return 0; + } - void AddAura(uint32 petEntry, uint32 aura) - { - auras[petEntry] = aura; - } + void AddAura(uint32 petEntry, uint32 aura) + { + auras[petEntry] = aura; + } - bool IsRemovedOnChangePet() const - { - return removeOnChangePet; - } + bool IsRemovedOnChangePet() const + { + return removeOnChangePet; + } - int32 GetDamage() const - { - return damage; - } + int32 GetDamage() const + { + return damage; + } - private: - PetAuraMap auras; - bool removeOnChangePet; - int32 damage; +private: + PetAuraMap auras; + bool removeOnChangePet; + int32 damage; }; typedef std::map SpellPetAuraMap; @@ -601,159 +601,159 @@ typedef std::set TalentAdditionalSet; class SpellMgr { // Constructors - private: - SpellMgr(); - ~SpellMgr(); +private: + SpellMgr(); + ~SpellMgr(); // Accessors (const or static functions) - public: - static SpellMgr* instance(); +public: + static SpellMgr* instance(); - // Spell correctness for client using - static bool ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg = true); - static bool IsSpellValid(SpellInfo const* spellInfo); - static bool CheckSpellValid(SpellInfo const* spellInfo, uint32 spellId, bool isTalent); + // Spell correctness for client using + static bool ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg = true); + static bool IsSpellValid(SpellInfo const* spellInfo); + static bool CheckSpellValid(SpellInfo const* spellInfo, uint32 spellId, bool isTalent); - // Spell difficulty - uint32 GetSpellDifficultyId(uint32 spellId) const; - void SetSpellDifficultyId(uint32 spellId, uint32 id); - uint32 GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) const; - SpellInfo const* GetSpellForDifficultyFromSpell(SpellInfo const* spell, Unit const* caster) const; + // Spell difficulty + uint32 GetSpellDifficultyId(uint32 spellId) const; + void SetSpellDifficultyId(uint32 spellId, uint32 id); + uint32 GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) const; + SpellInfo const* GetSpellForDifficultyFromSpell(SpellInfo const* spell, Unit const* caster) const; - // Spell Ranks table - SpellChainNode const* GetSpellChainNode(uint32 spell_id) const; - uint32 GetFirstSpellInChain(uint32 spell_id) const; - uint32 GetLastSpellInChain(uint32 spell_id) const; - uint32 GetNextSpellInChain(uint32 spell_id) const; - uint32 GetPrevSpellInChain(uint32 spell_id) const; - uint8 GetSpellRank(uint32 spell_id) const; - // not strict check returns provided spell if rank not avalible - uint32 GetSpellWithRank(uint32 spell_id, uint32 rank, bool strict = false) const; + // Spell Ranks table + SpellChainNode const* GetSpellChainNode(uint32 spell_id) const; + uint32 GetFirstSpellInChain(uint32 spell_id) const; + uint32 GetLastSpellInChain(uint32 spell_id) const; + uint32 GetNextSpellInChain(uint32 spell_id) const; + uint32 GetPrevSpellInChain(uint32 spell_id) const; + uint8 GetSpellRank(uint32 spell_id) const; + // not strict check returns provided spell if rank not avalible + uint32 GetSpellWithRank(uint32 spell_id, uint32 rank, bool strict = false) const; - // Spell Required table - SpellRequiredMapBounds GetSpellsRequiredForSpellBounds(uint32 spell_id) const; - SpellsRequiringSpellMapBounds GetSpellsRequiringSpellBounds(uint32 spell_id) const; - bool IsSpellRequiringSpell(uint32 spellid, uint32 req_spellid) const; + // Spell Required table + SpellRequiredMapBounds GetSpellsRequiredForSpellBounds(uint32 spell_id) const; + SpellsRequiringSpellMapBounds GetSpellsRequiringSpellBounds(uint32 spell_id) const; + bool IsSpellRequiringSpell(uint32 spellid, uint32 req_spellid) const; - // Spell learning - SpellLearnSkillNode const* GetSpellLearnSkill(uint32 spell_id) const; + // Spell learning + SpellLearnSkillNode const* GetSpellLearnSkill(uint32 spell_id) const; - // Spell target coordinates - SpellTargetPosition const* GetSpellTargetPosition(uint32 spell_id, SpellEffIndex effIndex) const; + // Spell target coordinates + SpellTargetPosition const* GetSpellTargetPosition(uint32 spell_id, SpellEffIndex effIndex) const; - // Spell Groups - uint32 GetSpellGroup(uint32 spellid) const; - SpellGroupSpecialFlags GetSpellGroupSpecialFlags(uint32 spell_id) const; - SpellGroupStackFlags GetGroupStackFlags(uint32 groupid) const; - SpellGroupStackFlags CheckSpellGroupStackRules(SpellInfo const* spellInfo1, SpellInfo const* spellInfo2, bool remove, bool areaAura) const; - void GetSetOfSpellsInSpellGroupWithFlag(uint32 group_id, SpellGroupSpecialFlags flag, std::set& availableElixirs) const; + // Spell Groups + uint32 GetSpellGroup(uint32 spellid) const; + SpellGroupSpecialFlags GetSpellGroupSpecialFlags(uint32 spell_id) const; + SpellGroupStackFlags GetGroupStackFlags(uint32 groupid) const; + SpellGroupStackFlags CheckSpellGroupStackRules(SpellInfo const* spellInfo1, SpellInfo const* spellInfo2, bool remove, bool areaAura) const; + void GetSetOfSpellsInSpellGroupWithFlag(uint32 group_id, SpellGroupSpecialFlags flag, std::set& availableElixirs) const; - // Spell proc event table - SpellProcEventEntry const* GetSpellProcEvent(uint32 spellId) const; - bool IsSpellProcEventCanTriggeredBy(SpellInfo const* spellProto, SpellProcEventEntry const* spellProcEvent, uint32 EventProcFlag, SpellInfo const* procSpell, uint32 procFlags, uint32 procExtra, bool active) const; + // Spell proc event table + SpellProcEventEntry const* GetSpellProcEvent(uint32 spellId) const; + bool IsSpellProcEventCanTriggeredBy(SpellInfo const* spellProto, SpellProcEventEntry const* spellProcEvent, uint32 EventProcFlag, SpellInfo const* procSpell, uint32 procFlags, uint32 procExtra, bool active) const; - // Spell proc table - SpellProcEntry const* GetSpellProcEntry(uint32 spellId) const; - bool CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const; + // Spell proc table + SpellProcEntry const* GetSpellProcEntry(uint32 spellId) const; + bool CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const; - // Spell bonus data table - SpellBonusEntry const* GetSpellBonusData(uint32 spellId) const; + // Spell bonus data table + SpellBonusEntry const* GetSpellBonusData(uint32 spellId) const; - // Spell threat table - SpellThreatEntry const* GetSpellThreatEntry(uint32 spellID) const; + // Spell threat table + SpellThreatEntry const* GetSpellThreatEntry(uint32 spellID) const; - // Spell mixology table - float GetSpellMixologyBonus(uint32 spellId) const; + // Spell mixology table + float GetSpellMixologyBonus(uint32 spellId) const; - SkillLineAbilityMapBounds GetSkillLineAbilityMapBounds(uint32 spell_id) const; + SkillLineAbilityMapBounds GetSkillLineAbilityMapBounds(uint32 spell_id) const; - PetAura const* GetPetAura(uint32 spell_id, uint8 eff) const; + PetAura const* GetPetAura(uint32 spell_id, uint8 eff) const; - SpellEnchantProcEntry const* GetSpellEnchantProcEvent(uint32 enchId) const; - bool IsArenaAllowedEnchancment(uint32 ench_id) const; + SpellEnchantProcEntry const* GetSpellEnchantProcEvent(uint32 enchId) const; + bool IsArenaAllowedEnchancment(uint32 ench_id) const; - const std::vector *GetSpellLinked(int32 spell_id) const; + const std::vector* GetSpellLinked(int32 spell_id) const; - PetLevelupSpellSet const* GetPetLevelupSpellList(uint32 petFamily) const; - PetDefaultSpellsEntry const* GetPetDefaultSpellsEntry(int32 id) const; + PetLevelupSpellSet const* GetPetLevelupSpellList(uint32 petFamily) const; + PetDefaultSpellsEntry const* GetPetDefaultSpellsEntry(int32 id) const; - // Spell area - SpellAreaMapBounds GetSpellAreaMapBounds(uint32 spell_id) const; - SpellAreaForQuestMapBounds GetSpellAreaForQuestMapBounds(uint32 quest_id) const; - SpellAreaForQuestMapBounds GetSpellAreaForQuestEndMapBounds(uint32 quest_id) const; - SpellAreaForAuraMapBounds GetSpellAreaForAuraMapBounds(uint32 spell_id) const; - SpellAreaForAreaMapBounds GetSpellAreaForAreaMapBounds(uint32 area_id) const; + // Spell area + SpellAreaMapBounds GetSpellAreaMapBounds(uint32 spell_id) const; + SpellAreaForQuestMapBounds GetSpellAreaForQuestMapBounds(uint32 quest_id) const; + SpellAreaForQuestMapBounds GetSpellAreaForQuestEndMapBounds(uint32 quest_id) const; + SpellAreaForAuraMapBounds GetSpellAreaForAuraMapBounds(uint32 spell_id) const; + SpellAreaForAreaMapBounds GetSpellAreaForAreaMapBounds(uint32 area_id) const; - // SpellInfo object management - SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } - uint32 GetSpellInfoStoreSize() const { return mSpellInfoMap.size(); } + // SpellInfo object management + SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } + uint32 GetSpellInfoStoreSize() const { return mSpellInfoMap.size(); } - // Talent Additional Set - bool IsAdditionalTalentSpell(uint32 spellId) const; + // Talent Additional Set + bool IsAdditionalTalentSpell(uint32 spellId) const; - private: - SpellInfo* _GetSpellInfo(uint32 spellId) { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } +private: + SpellInfo* _GetSpellInfo(uint32 spellId) { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } // Modifiers - public: +public: - // Loading data at server startup - void UnloadSpellInfoChains(); - void LoadSpellTalentRanks(); - void LoadSpellRanks(); - void LoadSpellRequired(); - void LoadSpellLearnSkills(); - void LoadSpellTargetPositions(); - void LoadSpellGroups(); - void LoadSpellGroupStackRules(); - void LoadSpellProcEvents(); - void LoadSpellProcs(); - void LoadSpellBonusess(); - void LoadSpellThreats(); - void LoadSpellMixology(); - void LoadSkillLineAbilityMap(); - void LoadSpellPetAuras(); - void LoadEnchantCustomAttr(); - void LoadSpellEnchantProcData(); - void LoadSpellLinked(); - void LoadPetLevelupSpellMap(); - void LoadPetDefaultSpells(); - void LoadSpellAreas(); - void LoadSpellInfoStore(); - void UnloadSpellInfoStore(); - void UnloadSpellInfoImplicitTargetConditionLists(); - void LoadSpellCustomAttr(); - void LoadDbcDataCorrections(); - void LoadSpellSpecificAndAuraState(); + // Loading data at server startup + void UnloadSpellInfoChains(); + void LoadSpellTalentRanks(); + void LoadSpellRanks(); + void LoadSpellRequired(); + void LoadSpellLearnSkills(); + void LoadSpellTargetPositions(); + void LoadSpellGroups(); + void LoadSpellGroupStackRules(); + void LoadSpellProcEvents(); + void LoadSpellProcs(); + void LoadSpellBonusess(); + void LoadSpellThreats(); + void LoadSpellMixology(); + void LoadSkillLineAbilityMap(); + void LoadSpellPetAuras(); + void LoadEnchantCustomAttr(); + void LoadSpellEnchantProcData(); + void LoadSpellLinked(); + void LoadPetLevelupSpellMap(); + void LoadPetDefaultSpells(); + void LoadSpellAreas(); + void LoadSpellInfoStore(); + void UnloadSpellInfoStore(); + void UnloadSpellInfoImplicitTargetConditionLists(); + void LoadSpellCustomAttr(); + void LoadDbcDataCorrections(); + void LoadSpellSpecificAndAuraState(); - private: - SpellDifficultySearcherMap mSpellDifficultySearcherMap; - SpellChainMap mSpellChains; - SpellsRequiringSpellMap mSpellsReqSpell; - SpellRequiredMap mSpellReq; - SpellLearnSkillMap mSpellLearnSkills; - SpellTargetPositionMap mSpellTargetPositions; - SpellGroupMap mSpellGroupMap; - SpellGroupStackMap mSpellGroupStackMap; - SpellProcEventMap mSpellProcEventMap; - SpellProcMap mSpellProcMap; - SpellBonusMap mSpellBonusMap; - SpellThreatMap mSpellThreatMap; - SpellMixologyMap mSpellMixologyMap; - SpellPetAuraMap mSpellPetAuraMap; - SpellLinkedMap mSpellLinkedMap; - SpellEnchantProcEventMap mSpellEnchantProcEventMap; - EnchantCustomAttribute mEnchantCustomAttr; - SpellAreaMap mSpellAreaMap; - SpellAreaForQuestMap mSpellAreaForQuestMap; - SpellAreaForQuestMap mSpellAreaForQuestEndMap; - SpellAreaForAuraMap mSpellAreaForAuraMap; - SpellAreaForAreaMap mSpellAreaForAreaMap; - SkillLineAbilityMap mSkillLineAbilityMap; - PetLevelupSpellMap mPetLevelupSpellMap; - PetDefaultSpellsMap mPetDefaultSpellsMap; // only spells not listed in related mPetLevelupSpellMap entry - SpellInfoMap mSpellInfoMap; - TalentAdditionalSet mTalentSpellAdditionalSet; +private: + SpellDifficultySearcherMap mSpellDifficultySearcherMap; + SpellChainMap mSpellChains; + SpellsRequiringSpellMap mSpellsReqSpell; + SpellRequiredMap mSpellReq; + SpellLearnSkillMap mSpellLearnSkills; + SpellTargetPositionMap mSpellTargetPositions; + SpellGroupMap mSpellGroupMap; + SpellGroupStackMap mSpellGroupStackMap; + SpellProcEventMap mSpellProcEventMap; + SpellProcMap mSpellProcMap; + SpellBonusMap mSpellBonusMap; + SpellThreatMap mSpellThreatMap; + SpellMixologyMap mSpellMixologyMap; + SpellPetAuraMap mSpellPetAuraMap; + SpellLinkedMap mSpellLinkedMap; + SpellEnchantProcEventMap mSpellEnchantProcEventMap; + EnchantCustomAttribute mEnchantCustomAttr; + SpellAreaMap mSpellAreaMap; + SpellAreaForQuestMap mSpellAreaForQuestMap; + SpellAreaForQuestMap mSpellAreaForQuestEndMap; + SpellAreaForAuraMap mSpellAreaForAuraMap; + SpellAreaForAreaMap mSpellAreaForAreaMap; + SkillLineAbilityMap mSkillLineAbilityMap; + PetLevelupSpellMap mPetLevelupSpellMap; + PetDefaultSpellsMap mPetDefaultSpellsMap; // only spells not listed in related mPetLevelupSpellMap entry + SpellInfoMap mSpellInfoMap; + TalentAdditionalSet mTalentSpellAdditionalSet; }; #define sSpellMgr SpellMgr::instance() diff --git a/src/server/game/Spells/SpellScript.cpp b/src/server/game/Spells/SpellScript.cpp index a855a087f..94d3c8041 100644 --- a/src/server/game/Spells/SpellScript.cpp +++ b/src/server/game/Spells/SpellScript.cpp @@ -63,20 +63,20 @@ uint8 _SpellScript::EffectHook::GetAffectedEffectsMask(SpellInfo const* spellEnt if ((effIndex == EFFECT_FIRST_FOUND) && mask) return mask; if (CheckEffect(spellEntry, i)) - mask |= (uint8)1<Effects[effIndex].TargetA.GetTarget() != targetType && - spellEntry->Effects[effIndex].TargetB.GetTarget() != targetType) + spellEntry->Effects[effIndex].TargetB.GetTarget() != targetType) return false; SpellImplicitTargetInfo targetInfo(targetType); @@ -368,12 +368,12 @@ bool SpellScript::IsInEffectHook() const Unit* SpellScript::GetCaster() { - return m_spell->GetCaster(); + return m_spell->GetCaster(); } Unit* SpellScript::GetOriginalCaster() { - return m_spell->GetOriginalCaster(); + return m_spell->GetOriginalCaster(); } SpellInfo const* SpellScript::GetSpellInfo() @@ -756,7 +756,7 @@ bool AuraScript::EffectBase::CheckEffect(SpellInfo const* spellEntry, uint8 effI std::string AuraScript::EffectBase::ToString() { - return "Index: " + EffIndexToString() + " AuraName: " +_SpellScript::EffectAuraNameCheck::ToString(); + return "Index: " + EffIndexToString() + " AuraName: " + _SpellScript::EffectAuraNameCheck::ToString(); } AuraScript::EffectPeriodicHandler::EffectPeriodicHandler(AuraEffectPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) diff --git a/src/server/game/Spells/SpellScript.h b/src/server/game/Spells/SpellScript.h index 76e51dfd8..bb94c5df5 100644 --- a/src/server/game/Spells/SpellScript.h +++ b/src/server/game/Spells/SpellScript.h @@ -45,71 +45,71 @@ class _SpellScript { // internal use classes & functions // DO NOT THESE IN SCRIPTS - protected: - virtual bool _Validate(SpellInfo const* entry); +protected: + virtual bool _Validate(SpellInfo const* entry); +public: + _SpellScript() : m_currentScriptState(SPELL_SCRIPT_STATE_NONE), m_scriptName(nullptr), m_scriptSpellId(0) {} + virtual ~_SpellScript() {} + virtual void _Register(); + virtual void _Unload(); + virtual void _Init(std::string const* scriptname, uint32 spellId); + std::string const* _GetScriptName() const; + +protected: + class EffectHook + { public: - _SpellScript() : m_currentScriptState(SPELL_SCRIPT_STATE_NONE), m_scriptName(nullptr), m_scriptSpellId(0) {} - virtual ~_SpellScript() {} - virtual void _Register(); - virtual void _Unload(); - virtual void _Init(std::string const* scriptname, uint32 spellId); - std::string const* _GetScriptName() const; + EffectHook(uint8 _effIndex); + virtual ~EffectHook() { } + uint8 GetAffectedEffectsMask(SpellInfo const* spellEntry); + bool IsEffectAffected(SpellInfo const* spellEntry, uint8 effIndex); + virtual bool CheckEffect(SpellInfo const* spellEntry, uint8 effIndex) = 0; + std::string EffIndexToString(); protected: - class EffectHook - { - public: - EffectHook(uint8 _effIndex); - virtual ~EffectHook() { } + uint8 effIndex; + }; - uint8 GetAffectedEffectsMask(SpellInfo const* spellEntry); - bool IsEffectAffected(SpellInfo const* spellEntry, uint8 effIndex); - virtual bool CheckEffect(SpellInfo const* spellEntry, uint8 effIndex) = 0; - std::string EffIndexToString(); - protected: - uint8 effIndex; - }; - - class EffectNameCheck - { - public: - EffectNameCheck(uint16 _effName) { effName = _effName; } - bool Check(SpellInfo const* spellEntry, uint8 effIndex); - std::string ToString(); - private: - uint16 effName; - }; - - class EffectAuraNameCheck - { - public: - EffectAuraNameCheck(uint16 _effAurName) { effAurName = _effAurName; } - bool Check(SpellInfo const* spellEntry, uint8 effIndex); - std::string ToString(); - private: - uint16 effAurName; - }; - - uint8 m_currentScriptState; - std::string const* m_scriptName; - uint32 m_scriptSpellId; + class EffectNameCheck + { public: - // - // SpellScript/AuraScript interface base - // these functions are safe to override, see notes below for usage instructions - // - // Function in which handler functions are registered, must be implemented in script - virtual void Register() = 0; - // Function called on server startup, if returns false script won't be used in core - // use for: dbc/template data presence/correctness checks - virtual bool Validate(SpellInfo const* /*spellEntry*/) { return true; } - // Function called when script is created, if returns false script will be unloaded afterwards - // use for: initializing local script variables (DO NOT USE CONSTRUCTOR FOR THIS PURPOSE!) - virtual bool Load() { return true; } - // Function called when script is destroyed - // use for: deallocating memory allocated by script - virtual void Unload() {} + EffectNameCheck(uint16 _effName) { effName = _effName; } + bool Check(SpellInfo const* spellEntry, uint8 effIndex); + std::string ToString(); + private: + uint16 effName; + }; + + class EffectAuraNameCheck + { + public: + EffectAuraNameCheck(uint16 _effAurName) { effAurName = _effAurName; } + bool Check(SpellInfo const* spellEntry, uint8 effIndex); + std::string ToString(); + private: + uint16 effAurName; + }; + + uint8 m_currentScriptState; + std::string const* m_scriptName; + uint32 m_scriptSpellId; +public: + // + // SpellScript/AuraScript interface base + // these functions are safe to override, see notes below for usage instructions + // + // Function in which handler functions are registered, must be implemented in script + virtual void Register() = 0; + // Function called on server startup, if returns false script won't be used in core + // use for: dbc/template data presence/correctness checks + virtual bool Validate(SpellInfo const* /*spellEntry*/) { return true; } + // Function called when script is created, if returns false script will be unloaded afterwards + // use for: initializing local script variables (DO NOT USE CONSTRUCTOR FOR THIS PURPOSE!) + virtual bool Load() { return true; } + // Function called when script is destroyed + // use for: deallocating memory allocated by script + virtual void Unload() {} }; // SpellScript interface - enum used for runtime checks of script function calls @@ -141,8 +141,8 @@ class SpellScript : public _SpellScript { // internal use classes & functions // DO NOT THESE IN SCRIPTS - public: - #define SPELLSCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) \ +public: +#define SPELLSCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) \ typedef SpellCastResult(CLASSNAME::*SpellCheckCastFnType)(); \ typedef void(CLASSNAME::*SpellEffectFnType)(SpellEffIndex); \ typedef void(CLASSNAME::*SpellHitFnType)(); \ @@ -151,87 +151,87 @@ class SpellScript : public _SpellScript typedef void(CLASSNAME::*SpellObjectTargetSelectFnType)(WorldObject*&); \ typedef void(CLASSNAME::*SpellDestinationTargetSelectFnType)(SpellDestination&); - SPELLSCRIPT_FUNCTION_TYPE_DEFINES(SpellScript) + SPELLSCRIPT_FUNCTION_TYPE_DEFINES(SpellScript) - class CastHandler - { - public: - CastHandler(SpellCastFnType _pCastHandlerScript); - void Call(SpellScript* spellScript); - private: - SpellCastFnType pCastHandlerScript; - }; + class CastHandler + { + public: + CastHandler(SpellCastFnType _pCastHandlerScript); + void Call(SpellScript* spellScript); + private: + SpellCastFnType pCastHandlerScript; + }; - class CheckCastHandler - { - public: - CheckCastHandler(SpellCheckCastFnType checkCastHandlerScript); - SpellCastResult Call(SpellScript* spellScript); - private: - SpellCheckCastFnType _checkCastHandlerScript; - }; + class CheckCastHandler + { + public: + CheckCastHandler(SpellCheckCastFnType checkCastHandlerScript); + SpellCastResult Call(SpellScript* spellScript); + private: + SpellCheckCastFnType _checkCastHandlerScript; + }; - class EffectHandler : public _SpellScript::EffectNameCheck, public _SpellScript::EffectHook - { - public: - EffectHandler(SpellEffectFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); - std::string ToString(); - bool CheckEffect(SpellInfo const* spellEntry, uint8 effIndex); - void Call(SpellScript* spellScript, SpellEffIndex effIndex); - private: - SpellEffectFnType pEffectHandlerScript; - }; + class EffectHandler : public _SpellScript::EffectNameCheck, public _SpellScript::EffectHook + { + public: + EffectHandler(SpellEffectFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); + std::string ToString(); + bool CheckEffect(SpellInfo const* spellEntry, uint8 effIndex); + void Call(SpellScript* spellScript, SpellEffIndex effIndex); + private: + SpellEffectFnType pEffectHandlerScript; + }; - class HitHandler - { - public: - HitHandler(SpellHitFnType _pHitHandlerScript); - void Call(SpellScript* spellScript); - private: - SpellHitFnType pHitHandlerScript; - }; + class HitHandler + { + public: + HitHandler(SpellHitFnType _pHitHandlerScript); + void Call(SpellScript* spellScript); + private: + SpellHitFnType pHitHandlerScript; + }; - class TargetHook : public _SpellScript::EffectHook - { - public: - TargetHook(uint8 _effectIndex, uint16 _targetType, bool _area, bool _dest); - bool CheckEffect(SpellInfo const* spellInfo, uint8 effIndex); - std::string ToString(); - uint16 GetTarget() const { return targetType; } - protected: - uint16 targetType; - bool area; - bool dest; - }; + class TargetHook : public _SpellScript::EffectHook + { + public: + TargetHook(uint8 _effectIndex, uint16 _targetType, bool _area, bool _dest); + bool CheckEffect(SpellInfo const* spellInfo, uint8 effIndex); + std::string ToString(); + uint16 GetTarget() const { return targetType; } + protected: + uint16 targetType; + bool area; + bool dest; + }; - class ObjectAreaTargetSelectHandler : public TargetHook - { - public: - ObjectAreaTargetSelectHandler(SpellObjectAreaTargetSelectFnType _pObjectAreaTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); - void Call(SpellScript* spellScript, std::list& targets); - private: - SpellObjectAreaTargetSelectFnType pObjectAreaTargetSelectHandlerScript; - }; + class ObjectAreaTargetSelectHandler : public TargetHook + { + public: + ObjectAreaTargetSelectHandler(SpellObjectAreaTargetSelectFnType _pObjectAreaTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); + void Call(SpellScript* spellScript, std::list& targets); + private: + SpellObjectAreaTargetSelectFnType pObjectAreaTargetSelectHandlerScript; + }; - class ObjectTargetSelectHandler : public TargetHook - { - public: - ObjectTargetSelectHandler(SpellObjectTargetSelectFnType _pObjectTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); - void Call(SpellScript* spellScript, WorldObject*& target); - private: - SpellObjectTargetSelectFnType pObjectTargetSelectHandlerScript; - }; + class ObjectTargetSelectHandler : public TargetHook + { + public: + ObjectTargetSelectHandler(SpellObjectTargetSelectFnType _pObjectTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); + void Call(SpellScript* spellScript, WorldObject*& target); + private: + SpellObjectTargetSelectFnType pObjectTargetSelectHandlerScript; + }; - class DestinationTargetSelectHandler : public TargetHook - { - public: - DestinationTargetSelectHandler(SpellDestinationTargetSelectFnType _DestinationTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); - void Call(SpellScript* spellScript, SpellDestination& target); - private: - SpellDestinationTargetSelectFnType DestinationTargetSelectHandlerScript; - }; + class DestinationTargetSelectHandler : public TargetHook + { + public: + DestinationTargetSelectHandler(SpellDestinationTargetSelectFnType _DestinationTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); + void Call(SpellScript* spellScript, SpellDestination& target); + private: + SpellDestinationTargetSelectFnType DestinationTargetSelectHandlerScript; + }; - #define SPELLSCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) \ +#define SPELLSCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) \ class CastHandlerFunction : public SpellScript::CastHandler { public: CastHandlerFunction(SpellCastFnType _pCastHandlerScript) : SpellScript::CastHandler((SpellScript::SpellCastFnType)_pCastHandlerScript) {} }; \ class CheckCastHandlerFunction : public SpellScript::CheckCastHandler { public: CheckCastHandlerFunction(SpellCheckCastFnType _checkCastHandlerScript) : SpellScript::CheckCastHandler((SpellScript::SpellCheckCastFnType)_checkCastHandlerScript) {} }; \ class EffectHandlerFunction : public SpellScript::EffectHandler { public: EffectHandlerFunction(SpellEffectFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : SpellScript::EffectHandler((SpellScript::SpellEffectFnType)_pEffectHandlerScript, _effIndex, _effName) {} }; \ @@ -240,185 +240,185 @@ class SpellScript : public _SpellScript class ObjectTargetSelectHandlerFunction : public SpellScript::ObjectTargetSelectHandler { public: ObjectTargetSelectHandlerFunction(SpellObjectTargetSelectFnType _pObjectTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType) : SpellScript::ObjectTargetSelectHandler((SpellScript::SpellObjectTargetSelectFnType)_pObjectTargetSelectHandlerScript, _effIndex, _targetType) { } }; \ class DestinationTargetSelectHandlerFunction : public SpellScript::DestinationTargetSelectHandler { public: DestinationTargetSelectHandlerFunction(SpellDestinationTargetSelectFnType _DestinationTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType) : SpellScript::DestinationTargetSelectHandler((SpellScript::SpellDestinationTargetSelectFnType)_DestinationTargetSelectHandlerScript, _effIndex, _targetType) { } }; - #define PrepareSpellScript(CLASSNAME) SPELLSCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) SPELLSCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) - public: - bool _Validate(SpellInfo const* entry); - bool _Load(Spell* spell); - void _InitHit(); - bool _IsEffectPrevented(SpellEffIndex effIndex) { return m_hitPreventEffectMask & (1< BeforeCast; - // example: OnCast += SpellCastFn(class::function); - HookList OnCast; - // example: AfterCast += SpellCastFn(class::function); - HookList AfterCast; - #define SpellCastFn(F) CastHandlerFunction(&F) +#define PrepareSpellScript(CLASSNAME) SPELLSCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) SPELLSCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) +public: + bool _Validate(SpellInfo const* entry); + bool _Load(Spell* spell); + void _InitHit(); + bool _IsEffectPrevented(SpellEffIndex effIndex) { return m_hitPreventEffectMask & (1 << effIndex); } + bool _IsDefaultEffectPrevented(SpellEffIndex effIndex) { return m_hitPreventDefaultEffectMask & (1 << effIndex); } + void _PrepareScriptCall(SpellScriptHookType hookType); + void _FinishScriptCall(); + bool IsInCheckCastHook() const; + bool IsInTargetHook() const; + bool IsInHitPhase() const; + bool IsInEffectHook() const; +private: + Spell* m_spell; + uint8 m_hitPreventEffectMask; + uint8 m_hitPreventDefaultEffectMask; +public: + // + // SpellScript interface + // hooks to which you can attach your functions + // + // example: BeforeCast += SpellCastFn(class::function); + HookList BeforeCast; + // example: OnCast += SpellCastFn(class::function); + HookList OnCast; + // example: AfterCast += SpellCastFn(class::function); + HookList AfterCast; +#define SpellCastFn(F) CastHandlerFunction(&F) - // example: OnCheckCast += SpellCheckCastFn(); - // where function is SpellCastResult function() - HookList OnCheckCast; - #define SpellCheckCastFn(F) CheckCastHandlerFunction(&F) + // example: OnCheckCast += SpellCheckCastFn(); + // where function is SpellCastResult function() + HookList OnCheckCast; +#define SpellCheckCastFn(F) CheckCastHandlerFunction(&F) - // example: OnEffect**** += SpellEffectFn(class::function, EffectIndexSpecifier, EffectNameSpecifier); - // where function is void function(SpellEffIndex effIndex) - HookList OnEffectLaunch; - HookList OnEffectLaunchTarget; - HookList OnEffectHit; - HookList OnEffectHitTarget; - #define SpellEffectFn(F, I, N) EffectHandlerFunction(&F, I, N) + // example: OnEffect**** += SpellEffectFn(class::function, EffectIndexSpecifier, EffectNameSpecifier); + // where function is void function(SpellEffIndex effIndex) + HookList OnEffectLaunch; + HookList OnEffectLaunchTarget; + HookList OnEffectHit; + HookList OnEffectHitTarget; +#define SpellEffectFn(F, I, N) EffectHandlerFunction(&F, I, N) - // example: BeforeHit += SpellHitFn(class::function); - HookList BeforeHit; - // example: OnHit += SpellHitFn(class::function); - HookList OnHit; - // example: AfterHit += SpellHitFn(class::function); - HookList AfterHit; - // where function is: void function() - #define SpellHitFn(F) HitHandlerFunction(&F) + // example: BeforeHit += SpellHitFn(class::function); + HookList BeforeHit; + // example: OnHit += SpellHitFn(class::function); + HookList OnHit; + // example: AfterHit += SpellHitFn(class::function); + HookList AfterHit; + // where function is: void function() +#define SpellHitFn(F) HitHandlerFunction(&F) - // example: OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(class::function, EffectIndexSpecifier, TargetsNameSpecifier); - // where function is void function(std::list& targets) - HookList OnObjectAreaTargetSelect; - #define SpellObjectAreaTargetSelectFn(F, I, N) ObjectAreaTargetSelectHandlerFunction(&F, I, N) + // example: OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(class::function, EffectIndexSpecifier, TargetsNameSpecifier); + // where function is void function(std::list& targets) + HookList OnObjectAreaTargetSelect; +#define SpellObjectAreaTargetSelectFn(F, I, N) ObjectAreaTargetSelectHandlerFunction(&F, I, N) - // example: OnObjectTargetSelect += SpellObjectTargetSelectFn(class::function, EffectIndexSpecifier, TargetsNameSpecifier); - // where function is void function(WorldObject*& target) - HookList OnObjectTargetSelect; - #define SpellObjectTargetSelectFn(F, I, N) ObjectTargetSelectHandlerFunction(&F, I, N) + // example: OnObjectTargetSelect += SpellObjectTargetSelectFn(class::function, EffectIndexSpecifier, TargetsNameSpecifier); + // where function is void function(WorldObject*& target) + HookList OnObjectTargetSelect; +#define SpellObjectTargetSelectFn(F, I, N) ObjectTargetSelectHandlerFunction(&F, I, N) - // example: OnDestinationTargetSelect += SpellDestinationTargetSelectFn(class::function, EffectIndexSpecifier, TargetsNameSpecifier); - // where function is void function(SpellDestination& target) - HookList OnDestinationTargetSelect; - #define SpellDestinationTargetSelectFn(F, I, N) DestinationTargetSelectHandlerFunction(&F, I, N) + // example: OnDestinationTargetSelect += SpellDestinationTargetSelectFn(class::function, EffectIndexSpecifier, TargetsNameSpecifier); + // where function is void function(SpellDestination& target) + HookList OnDestinationTargetSelect; +#define SpellDestinationTargetSelectFn(F, I, N) DestinationTargetSelectHandlerFunction(&F, I, N) - // hooks are executed in following order, at specified event of spell: - // 1. BeforeCast - executed when spell preparation is finished (when cast bar becomes full) before cast is handled - // 2. OnCheckCast - allows to override result of CheckCast function - // 3a. OnObjectAreaTargetSelect - executed just before adding selected targets to final target list (for area targets) - // 3b. OnObjectTargetSelect - executed just before adding selected target to final target list (for single unit targets) - // 3c. OnDestinationTargetSelect - executed just before adding selected target to final target list (for destination targets) - // 4. OnCast - executed just before spell is launched (creates missile) or executed - // 5. AfterCast - executed after spell missile is launched and immediate spell actions are done - // 6. OnEffectLaunch - executed just before specified effect handler call - when spell missile is launched - // 7. OnEffectLaunchTarget - executed just before specified effect handler call - when spell missile is launched - called for each target from spell target map - // 8. OnEffectHit - executed just before specified effect handler call - when spell missile hits dest - // 9. BeforeHit - executed just before spell hits a target - called for each target from spell target map - // 10. OnEffectHitTarget - executed just before specified effect handler call - called for each target from spell target map - // 11. OnHit - executed just before spell deals damage and procs auras - when spell hits target - called for each target from spell target map - // 12. AfterHit - executed just after spell finishes all it's jobs for target - called for each target from spell target map + // hooks are executed in following order, at specified event of spell: + // 1. BeforeCast - executed when spell preparation is finished (when cast bar becomes full) before cast is handled + // 2. OnCheckCast - allows to override result of CheckCast function + // 3a. OnObjectAreaTargetSelect - executed just before adding selected targets to final target list (for area targets) + // 3b. OnObjectTargetSelect - executed just before adding selected target to final target list (for single unit targets) + // 3c. OnDestinationTargetSelect - executed just before adding selected target to final target list (for destination targets) + // 4. OnCast - executed just before spell is launched (creates missile) or executed + // 5. AfterCast - executed after spell missile is launched and immediate spell actions are done + // 6. OnEffectLaunch - executed just before specified effect handler call - when spell missile is launched + // 7. OnEffectLaunchTarget - executed just before specified effect handler call - when spell missile is launched - called for each target from spell target map + // 8. OnEffectHit - executed just before specified effect handler call - when spell missile hits dest + // 9. BeforeHit - executed just before spell hits a target - called for each target from spell target map + // 10. OnEffectHitTarget - executed just before specified effect handler call - called for each target from spell target map + // 11. OnHit - executed just before spell deals damage and procs auras - when spell hits target - called for each target from spell target map + // 12. AfterHit - executed just after spell finishes all it's jobs for target - called for each target from spell target map - // - // methods allowing interaction with Spell object - // - // methods useable during all spell handling phases - Unit* GetCaster(); - Unit* GetOriginalCaster(); - SpellInfo const* GetSpellInfo(); - SpellValue const* GetSpellValue(); + // + // methods allowing interaction with Spell object + // + // methods useable during all spell handling phases + Unit* GetCaster(); + Unit* GetOriginalCaster(); + SpellInfo const* GetSpellInfo(); + SpellValue const* GetSpellValue(); - // methods useable after spell is prepared - // accessors to the explicit targets of the spell - // explicit target - target selected by caster (player, game client, or script - DoCast(explicitTarget, ...), required for spell to be cast - // examples: - // -shadowstep - explicit target is the unit you want to go behind of - // -chain heal - explicit target is the unit to be healed first - // -holy nova/arcane explosion - explicit target = NULL because target you are selecting doesn't affect how spell targets are selected - // you can determine if spell requires explicit targets by dbc columns: - // - Targets - mask of explicit target types - // - ImplicitTargetXX set to TARGET_XXX_TARGET_YYY, _TARGET_ here means that explicit target is used by the effect, so spell needs one too + // methods useable after spell is prepared + // accessors to the explicit targets of the spell + // explicit target - target selected by caster (player, game client, or script - DoCast(explicitTarget, ...), required for spell to be cast + // examples: + // -shadowstep - explicit target is the unit you want to go behind of + // -chain heal - explicit target is the unit to be healed first + // -holy nova/arcane explosion - explicit target = NULL because target you are selecting doesn't affect how spell targets are selected + // you can determine if spell requires explicit targets by dbc columns: + // - Targets - mask of explicit target types + // - ImplicitTargetXX set to TARGET_XXX_TARGET_YYY, _TARGET_ here means that explicit target is used by the effect, so spell needs one too - // returns: WorldLocation which was selected as a spell destination or NULL - WorldLocation const* GetExplTargetDest(); + // returns: WorldLocation which was selected as a spell destination or NULL + WorldLocation const* GetExplTargetDest(); - void SetExplTargetDest(WorldLocation& loc); + void SetExplTargetDest(WorldLocation& loc); - // returns: WorldObject which was selected as an explicit spell target or NULL if there's no target - WorldObject* GetExplTargetWorldObject(); + // returns: WorldObject which was selected as an explicit spell target or NULL if there's no target + WorldObject* GetExplTargetWorldObject(); - // returns: Unit which was selected as an explicit spell target or NULL if there's no target - Unit* GetExplTargetUnit(); + // returns: Unit which was selected as an explicit spell target or NULL if there's no target + Unit* GetExplTargetUnit(); - // returns: GameObject which was selected as an explicit spell target or NULL if there's no target - GameObject* GetExplTargetGObj(); + // returns: GameObject which was selected as an explicit spell target or NULL if there's no target + GameObject* GetExplTargetGObj(); - // returns: Item which was selected as an explicit spell target or NULL if there's no target - Item* GetExplTargetItem(); + // returns: Item which was selected as an explicit spell target or NULL if there's no target + Item* GetExplTargetItem(); - // methods useable only during spell hit on target, or during spell launch on target: - // returns: target of current effect if it was Unit otherwise NULL - Unit* GetHitUnit(); - // returns: target of current effect if it was Creature otherwise NULL - Creature* GetHitCreature(); - // returns: target of current effect if it was Player otherwise NULL - Player* GetHitPlayer(); - // returns: target of current effect if it was Item otherwise NULL - Item* GetHitItem(); - // returns: target of current effect if it was GameObject otherwise NULL - GameObject* GetHitGObj(); - // returns: destination of current effect - WorldLocation* GetHitDest(); - // setter/getter for for damage done by spell to target of spell hit - // returns damage calculated before hit, and real dmg done after hit - int32 GetHitDamage(); - void SetHitDamage(int32 damage); - void PreventHitDamage() { SetHitDamage(0); } - // setter/getter for for heal done by spell to target of spell hit - // returns healing calculated before hit, and real dmg done after hit - int32 GetHitHeal(); - void SetHitHeal(int32 heal); - void PreventHitHeal() { SetHitHeal(0); } - Spell* GetSpell() { return m_spell; } - // returns current spell hit target aura - Aura* GetHitAura(); - // prevents applying aura on current spell hit target - void PreventHitAura(); + // methods useable only during spell hit on target, or during spell launch on target: + // returns: target of current effect if it was Unit otherwise NULL + Unit* GetHitUnit(); + // returns: target of current effect if it was Creature otherwise NULL + Creature* GetHitCreature(); + // returns: target of current effect if it was Player otherwise NULL + Player* GetHitPlayer(); + // returns: target of current effect if it was Item otherwise NULL + Item* GetHitItem(); + // returns: target of current effect if it was GameObject otherwise NULL + GameObject* GetHitGObj(); + // returns: destination of current effect + WorldLocation* GetHitDest(); + // setter/getter for for damage done by spell to target of spell hit + // returns damage calculated before hit, and real dmg done after hit + int32 GetHitDamage(); + void SetHitDamage(int32 damage); + void PreventHitDamage() { SetHitDamage(0); } + // setter/getter for for heal done by spell to target of spell hit + // returns healing calculated before hit, and real dmg done after hit + int32 GetHitHeal(); + void SetHitHeal(int32 heal); + void PreventHitHeal() { SetHitHeal(0); } + Spell* GetSpell() { return m_spell; } + // returns current spell hit target aura + Aura* GetHitAura(); + // prevents applying aura on current spell hit target + void PreventHitAura(); - // prevents effect execution on current spell hit target - // including other effect/hit scripts - // will not work on aura/damage/heal - // will not work if effects were already handled - void PreventHitEffect(SpellEffIndex effIndex); + // prevents effect execution on current spell hit target + // including other effect/hit scripts + // will not work on aura/damage/heal + // will not work if effects were already handled + void PreventHitEffect(SpellEffIndex effIndex); - // prevents default effect execution on current spell hit target - // will not work on aura/damage/heal effects - // will not work if effects were already handled - void PreventHitDefaultEffect(SpellEffIndex effIndex); + // prevents default effect execution on current spell hit target + // will not work on aura/damage/heal effects + // will not work if effects were already handled + void PreventHitDefaultEffect(SpellEffIndex effIndex); - // method avalible only in EffectHandler method - int32 GetEffectValue() const; - void SetEffectValue(int32 value); + // method avalible only in EffectHandler method + int32 GetEffectValue() const; + void SetEffectValue(int32 value); - // returns: cast item if present. - Item* GetCastItem(); + // returns: cast item if present. + Item* GetCastItem(); - // Creates item. Calls Spell::DoCreateItem method. - void CreateItem(uint32 effIndex, uint32 itemId); + // Creates item. Calls Spell::DoCreateItem method. + void CreateItem(uint32 effIndex, uint32 itemId); - // Returns SpellInfo from the spell that triggered the current one - SpellInfo const* GetTriggeringSpell(); + // Returns SpellInfo from the spell that triggered the current one + SpellInfo const* GetTriggeringSpell(); - // finishes spellcast prematurely with selected error message - void FinishCast(SpellCastResult result); + // finishes spellcast prematurely with selected error message + void FinishCast(SpellCastResult result); - void Cancel(); // pussywizard + void Cancel(); // pussywizard - void SetCustomCastResultMessage(SpellCustomErrors result); + void SetCustomCastResultMessage(SpellCustomErrors result); }; // AuraScript interface - enum used for runtime checks of script function calls @@ -460,9 +460,9 @@ class AuraScript : public _SpellScript { // internal use classes & functions // DO NOT THESE IN SCRIPTS - public: +public: - #define AURASCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) \ +#define AURASCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) \ typedef bool(CLASSNAME::*AuraCheckAreaTargetFnType)(Unit* target); \ typedef void(CLASSNAME::*AuraDispelFnType)(DispelInfo* dispelInfo); \ typedef void(CLASSNAME::*AuraEffectApplicationModeFnType)(AuraEffect const*, AuraEffectHandleModes); \ @@ -477,130 +477,130 @@ class AuraScript : public _SpellScript typedef void(CLASSNAME::*AuraProcFnType)(ProcEventInfo&); \ typedef void(CLASSNAME::*AuraEffectProcFnType)(AuraEffect const*, ProcEventInfo&); \ - AURASCRIPT_FUNCTION_TYPE_DEFINES(AuraScript) + AURASCRIPT_FUNCTION_TYPE_DEFINES(AuraScript) - class CheckAreaTargetHandler - { - public: - CheckAreaTargetHandler(AuraCheckAreaTargetFnType pHandlerScript); - bool Call(AuraScript* auraScript, Unit* target); - private: - AuraCheckAreaTargetFnType pHandlerScript; - }; - class AuraDispelHandler - { - public: - AuraDispelHandler(AuraDispelFnType pHandlerScript); - void Call(AuraScript* auraScript, DispelInfo* dispelInfo); - private: - AuraDispelFnType pHandlerScript; - }; - class EffectBase : public _SpellScript::EffectAuraNameCheck, public _SpellScript::EffectHook - { - public: - EffectBase(uint8 _effIndex, uint16 _effName); - std::string ToString(); - bool CheckEffect(SpellInfo const* spellEntry, uint8 effIndex); - }; - class EffectPeriodicHandler : public EffectBase - { - public: - EffectPeriodicHandler(AuraEffectPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); - void Call(AuraScript* auraScript, AuraEffect const* _aurEff); - private: - AuraEffectPeriodicFnType pEffectHandlerScript; - }; - class EffectUpdatePeriodicHandler : public EffectBase - { - public: - EffectUpdatePeriodicHandler(AuraEffectUpdatePeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); - void Call(AuraScript* auraScript, AuraEffect* aurEff); - private: - AuraEffectUpdatePeriodicFnType pEffectHandlerScript; - }; - class EffectCalcAmountHandler : public EffectBase - { - public: - EffectCalcAmountHandler(AuraEffectCalcAmountFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); - void Call(AuraScript* auraScript, AuraEffect const* aurEff, int32 & amount, bool & canBeRecalculated); - private: - AuraEffectCalcAmountFnType pEffectHandlerScript; - }; - class EffectCalcPeriodicHandler : public EffectBase - { - public: - EffectCalcPeriodicHandler(AuraEffectCalcPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); - void Call(AuraScript* auraScript, AuraEffect const* aurEff, bool & isPeriodic, int32 & periodicTimer); - private: - AuraEffectCalcPeriodicFnType pEffectHandlerScript; - }; - class EffectCalcSpellModHandler : public EffectBase - { - public: - EffectCalcSpellModHandler(AuraEffectCalcSpellModFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); - void Call(AuraScript* auraScript, AuraEffect const* aurEff, SpellModifier* & spellMod); - private: - AuraEffectCalcSpellModFnType pEffectHandlerScript; - }; - class EffectApplyHandler : public EffectBase - { - public: - EffectApplyHandler(AuraEffectApplicationModeFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName, AuraEffectHandleModes _mode); - void Call(AuraScript* auraScript, AuraEffect const* _aurEff, AuraEffectHandleModes _mode); - private: - AuraEffectApplicationModeFnType pEffectHandlerScript; - AuraEffectHandleModes mode; - }; - class EffectAbsorbHandler : public EffectBase - { - public: - EffectAbsorbHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex); - void Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & absorbAmount); - private: - AuraEffectAbsorbFnType pEffectHandlerScript; - }; - class EffectManaShieldHandler : public EffectBase - { - public: - EffectManaShieldHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex); - void Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & absorbAmount); - private: - AuraEffectAbsorbFnType pEffectHandlerScript; - }; - class EffectSplitHandler : public EffectBase - { - public: - EffectSplitHandler(AuraEffectSplitFnType _pEffectHandlerScript, uint8 _effIndex); - void Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & splitAmount); - private: - AuraEffectSplitFnType pEffectHandlerScript; - }; - class CheckProcHandler - { - public: - CheckProcHandler(AuraCheckProcFnType handlerScript); - bool Call(AuraScript* auraScript, ProcEventInfo& eventInfo); - private: - AuraCheckProcFnType _HandlerScript; - }; - class AuraProcHandler - { - public: - AuraProcHandler(AuraProcFnType handlerScript); - void Call(AuraScript* auraScript, ProcEventInfo& eventInfo); - private: - AuraProcFnType _HandlerScript; - }; - class EffectProcHandler : public EffectBase - { - public: - EffectProcHandler(AuraEffectProcFnType effectHandlerScript, uint8 effIndex, uint16 effName); - void Call(AuraScript* auraScript, AuraEffect const* aurEff, ProcEventInfo& eventInfo); - private: - AuraEffectProcFnType _EffectHandlerScript; - }; + class CheckAreaTargetHandler + { + public: + CheckAreaTargetHandler(AuraCheckAreaTargetFnType pHandlerScript); + bool Call(AuraScript* auraScript, Unit* target); + private: + AuraCheckAreaTargetFnType pHandlerScript; + }; + class AuraDispelHandler + { + public: + AuraDispelHandler(AuraDispelFnType pHandlerScript); + void Call(AuraScript* auraScript, DispelInfo* dispelInfo); + private: + AuraDispelFnType pHandlerScript; + }; + class EffectBase : public _SpellScript::EffectAuraNameCheck, public _SpellScript::EffectHook + { + public: + EffectBase(uint8 _effIndex, uint16 _effName); + std::string ToString(); + bool CheckEffect(SpellInfo const* spellEntry, uint8 effIndex); + }; + class EffectPeriodicHandler : public EffectBase + { + public: + EffectPeriodicHandler(AuraEffectPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); + void Call(AuraScript* auraScript, AuraEffect const* _aurEff); + private: + AuraEffectPeriodicFnType pEffectHandlerScript; + }; + class EffectUpdatePeriodicHandler : public EffectBase + { + public: + EffectUpdatePeriodicHandler(AuraEffectUpdatePeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); + void Call(AuraScript* auraScript, AuraEffect* aurEff); + private: + AuraEffectUpdatePeriodicFnType pEffectHandlerScript; + }; + class EffectCalcAmountHandler : public EffectBase + { + public: + EffectCalcAmountHandler(AuraEffectCalcAmountFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); + void Call(AuraScript* auraScript, AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated); + private: + AuraEffectCalcAmountFnType pEffectHandlerScript; + }; + class EffectCalcPeriodicHandler : public EffectBase + { + public: + EffectCalcPeriodicHandler(AuraEffectCalcPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); + void Call(AuraScript* auraScript, AuraEffect const* aurEff, bool& isPeriodic, int32& periodicTimer); + private: + AuraEffectCalcPeriodicFnType pEffectHandlerScript; + }; + class EffectCalcSpellModHandler : public EffectBase + { + public: + EffectCalcSpellModHandler(AuraEffectCalcSpellModFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); + void Call(AuraScript* auraScript, AuraEffect const* aurEff, SpellModifier*& spellMod); + private: + AuraEffectCalcSpellModFnType pEffectHandlerScript; + }; + class EffectApplyHandler : public EffectBase + { + public: + EffectApplyHandler(AuraEffectApplicationModeFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName, AuraEffectHandleModes _mode); + void Call(AuraScript* auraScript, AuraEffect const* _aurEff, AuraEffectHandleModes _mode); + private: + AuraEffectApplicationModeFnType pEffectHandlerScript; + AuraEffectHandleModes mode; + }; + class EffectAbsorbHandler : public EffectBase + { + public: + EffectAbsorbHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex); + void Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); + private: + AuraEffectAbsorbFnType pEffectHandlerScript; + }; + class EffectManaShieldHandler : public EffectBase + { + public: + EffectManaShieldHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex); + void Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); + private: + AuraEffectAbsorbFnType pEffectHandlerScript; + }; + class EffectSplitHandler : public EffectBase + { + public: + EffectSplitHandler(AuraEffectSplitFnType _pEffectHandlerScript, uint8 _effIndex); + void Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& splitAmount); + private: + AuraEffectSplitFnType pEffectHandlerScript; + }; + class CheckProcHandler + { + public: + CheckProcHandler(AuraCheckProcFnType handlerScript); + bool Call(AuraScript* auraScript, ProcEventInfo& eventInfo); + private: + AuraCheckProcFnType _HandlerScript; + }; + class AuraProcHandler + { + public: + AuraProcHandler(AuraProcFnType handlerScript); + void Call(AuraScript* auraScript, ProcEventInfo& eventInfo); + private: + AuraProcFnType _HandlerScript; + }; + class EffectProcHandler : public EffectBase + { + public: + EffectProcHandler(AuraEffectProcFnType effectHandlerScript, uint8 effIndex, uint16 effName); + void Call(AuraScript* auraScript, AuraEffect const* aurEff, ProcEventInfo& eventInfo); + private: + AuraEffectProcFnType _EffectHandlerScript; + }; - #define AURASCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) \ +#define AURASCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) \ class CheckAreaTargetFunction : public AuraScript::CheckAreaTargetHandler { public: CheckAreaTargetFunction(AuraCheckAreaTargetFnType _pHandlerScript) : AuraScript::CheckAreaTargetHandler((AuraScript::AuraCheckAreaTargetFnType)_pHandlerScript) {} }; \ class AuraDispelFunction : public AuraScript::AuraDispelHandler { public: AuraDispelFunction(AuraDispelFnType _pHandlerScript) : AuraScript::AuraDispelHandler((AuraScript::AuraDispelFnType)_pHandlerScript) {} }; \ class EffectPeriodicHandlerFunction : public AuraScript::EffectPeriodicHandler { public: EffectPeriodicHandlerFunction(AuraEffectPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : AuraScript::EffectPeriodicHandler((AuraScript::AuraEffectPeriodicFnType)_pEffectHandlerScript, _effIndex, _effName) {} }; \ @@ -616,245 +616,245 @@ class AuraScript : public _SpellScript class AuraProcHandlerFunction : public AuraScript::AuraProcHandler { public: AuraProcHandlerFunction(AuraProcFnType handlerScript) : AuraScript::AuraProcHandler((AuraScript::AuraProcFnType)handlerScript) {} }; \ class EffectProcHandlerFunction : public AuraScript::EffectProcHandler { public: EffectProcHandlerFunction(AuraEffectProcFnType effectHandlerScript, uint8 effIndex, uint16 effName) : AuraScript::EffectProcHandler((AuraScript::AuraEffectProcFnType)effectHandlerScript, effIndex, effName) {} }; \ - #define PrepareAuraScript(CLASSNAME) AURASCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) AURASCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) +#define PrepareAuraScript(CLASSNAME) AURASCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) AURASCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) +public: + AuraScript() : _SpellScript(), m_aura(nullptr), m_auraApplication(nullptr), m_defaultActionPrevented(false) + {} + bool _Validate(SpellInfo const* entry); + bool _Load(Aura* aura); + void _PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp = nullptr); + void _FinishScriptCall(); + bool _IsDefaultActionPrevented(); +private: + Aura* m_aura; + AuraApplication const* m_auraApplication; + bool m_defaultActionPrevented; + + class ScriptStateStore + { public: - AuraScript() : _SpellScript(), m_aura(nullptr), m_auraApplication(nullptr), m_defaultActionPrevented(false) + AuraApplication const* _auraApplication; + uint8 _currentScriptState; + bool _defaultActionPrevented; + ScriptStateStore(uint8 currentScriptState, AuraApplication const* auraApplication, bool defaultActionPrevented) + : _auraApplication(auraApplication), _currentScriptState(currentScriptState), _defaultActionPrevented(defaultActionPrevented) {} - bool _Validate(SpellInfo const* entry); - bool _Load(Aura* aura); - void _PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp = nullptr); - void _FinishScriptCall(); - bool _IsDefaultActionPrevented(); - private: - Aura* m_aura; - AuraApplication const* m_auraApplication; - bool m_defaultActionPrevented; + }; + typedef std::stack ScriptStateStack; + ScriptStateStack m_scriptStates; - class ScriptStateStore - { - public: - AuraApplication const* _auraApplication; - uint8 _currentScriptState; - bool _defaultActionPrevented; - ScriptStateStore(uint8 currentScriptState, AuraApplication const* auraApplication, bool defaultActionPrevented) - : _auraApplication(auraApplication), _currentScriptState(currentScriptState), _defaultActionPrevented(defaultActionPrevented) - {} - }; - typedef std::stack ScriptStateStack; - ScriptStateStack m_scriptStates; +public: + // + // AuraScript interface + // hooks to which you can attach your functions + // + // executed when area aura checks if it can be applied on target + // example: OnEffectApply += AuraEffectApplyFn(class::function); + // where function is: bool function (Unit* target); + HookList DoCheckAreaTarget; +#define AuraCheckAreaTargetFn(F) CheckAreaTargetFunction(&F) - public: - // - // AuraScript interface - // hooks to which you can attach your functions - // - // executed when area aura checks if it can be applied on target - // example: OnEffectApply += AuraEffectApplyFn(class::function); - // where function is: bool function (Unit* target); - HookList DoCheckAreaTarget; - #define AuraCheckAreaTargetFn(F) CheckAreaTargetFunction(&F) + // executed when aura is dispelled by a unit + // example: OnDispel += AuraDispelFn(class::function); + // where function is: void function (DispelInfo* dispelInfo); + HookList OnDispel; + // executed after aura is dispelled by a unit + // example: AfterDispel += AuraDispelFn(class::function); + // where function is: void function (DispelInfo* dispelInfo); + HookList AfterDispel; +#define AuraDispelFn(F) AuraDispelFunction(&F) - // executed when aura is dispelled by a unit - // example: OnDispel += AuraDispelFn(class::function); - // where function is: void function (DispelInfo* dispelInfo); - HookList OnDispel; - // executed after aura is dispelled by a unit - // example: AfterDispel += AuraDispelFn(class::function); - // where function is: void function (DispelInfo* dispelInfo); - HookList AfterDispel; - #define AuraDispelFn(F) AuraDispelFunction(&F) + // executed when aura effect is applied with specified mode to target + // should be used when when effect handler preventing/replacing is needed, do not use this hook for triggering spellcasts/removing auras etc - may be unsafe + // example: OnEffectApply += AuraEffectApplyFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); + // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); + HookList OnEffectApply; + // executed after aura effect is applied with specified mode to target + // example: AfterEffectApply += AuraEffectApplyFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); + // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); + HookList AfterEffectApply; +#define AuraEffectApplyFn(F, I, N, M) EffectApplyHandlerFunction(&F, I, N, M) - // executed when aura effect is applied with specified mode to target - // should be used when when effect handler preventing/replacing is needed, do not use this hook for triggering spellcasts/removing auras etc - may be unsafe - // example: OnEffectApply += AuraEffectApplyFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); - // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); - HookList OnEffectApply; - // executed after aura effect is applied with specified mode to target - // example: AfterEffectApply += AuraEffectApplyFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); - // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); - HookList AfterEffectApply; - #define AuraEffectApplyFn(F, I, N, M) EffectApplyHandlerFunction(&F, I, N, M) + // executed after aura effect is removed with specified mode from target + // should be used when when effect handler preventing/replacing is needed, do not use this hook for triggering spellcasts/removing auras etc - may be unsafe + // example: OnEffectRemove += AuraEffectRemoveFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); + // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); + HookList OnEffectRemove; + // executed when aura effect is removed with specified mode from target + // example: AfterEffectRemove += AuraEffectRemoveFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); + // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); + HookList AfterEffectRemove; +#define AuraEffectRemoveFn(F, I, N, M) EffectApplyHandlerFunction(&F, I, N, M) - // executed after aura effect is removed with specified mode from target - // should be used when when effect handler preventing/replacing is needed, do not use this hook for triggering spellcasts/removing auras etc - may be unsafe - // example: OnEffectRemove += AuraEffectRemoveFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); - // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); - HookList OnEffectRemove; - // executed when aura effect is removed with specified mode from target - // example: AfterEffectRemove += AuraEffectRemoveFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier, AuraEffectHandleModes); - // where function is: void function (AuraEffect const* aurEff, AuraEffectHandleModes mode); - HookList AfterEffectRemove; - #define AuraEffectRemoveFn(F, I, N, M) EffectApplyHandlerFunction(&F, I, N, M) + // executed when periodic aura effect ticks on target + // example: OnEffectPeriodic += AuraEffectPeriodicFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect const* aurEff); + HookList OnEffectPeriodic; +#define AuraEffectPeriodicFn(F, I, N) EffectPeriodicHandlerFunction(&F, I, N) - // executed when periodic aura effect ticks on target - // example: OnEffectPeriodic += AuraEffectPeriodicFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect const* aurEff); - HookList OnEffectPeriodic; - #define AuraEffectPeriodicFn(F, I, N) EffectPeriodicHandlerFunction(&F, I, N) + // executed when periodic aura effect is updated + // example: OnEffectUpdatePeriodic += AuraEffectUpdatePeriodicFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect* aurEff); + HookList OnEffectUpdatePeriodic; +#define AuraEffectUpdatePeriodicFn(F, I, N) EffectUpdatePeriodicHandlerFunction(&F, I, N) - // executed when periodic aura effect is updated - // example: OnEffectUpdatePeriodic += AuraEffectUpdatePeriodicFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect* aurEff); - HookList OnEffectUpdatePeriodic; - #define AuraEffectUpdatePeriodicFn(F, I, N) EffectUpdatePeriodicHandlerFunction(&F, I, N) + // executed when aura effect calculates amount + // example: DoEffectCalcAmount += AuraEffectCalcAmounFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect* aurEff, int32& amount, bool& canBeRecalculated); + HookList DoEffectCalcAmount; +#define AuraEffectCalcAmountFn(F, I, N) EffectCalcAmountHandlerFunction(&F, I, N) - // executed when aura effect calculates amount - // example: DoEffectCalcAmount += AuraEffectCalcAmounFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect* aurEff, int32& amount, bool& canBeRecalculated); - HookList DoEffectCalcAmount; - #define AuraEffectCalcAmountFn(F, I, N) EffectCalcAmountHandlerFunction(&F, I, N) + // executed when aura effect calculates periodic data + // example: DoEffectCalcPeriodic += AuraEffectCalcPeriodicFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect const* aurEff, bool& isPeriodic, int32& amplitude); + HookList DoEffectCalcPeriodic; +#define AuraEffectCalcPeriodicFn(F, I, N) EffectCalcPeriodicHandlerFunction(&F, I, N) - // executed when aura effect calculates periodic data - // example: DoEffectCalcPeriodic += AuraEffectCalcPeriodicFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect const* aurEff, bool& isPeriodic, int32& amplitude); - HookList DoEffectCalcPeriodic; - #define AuraEffectCalcPeriodicFn(F, I, N) EffectCalcPeriodicHandlerFunction(&F, I, N) + // executed when aura effect calculates spellmod + // example: DoEffectCalcSpellMod += AuraEffectCalcSpellModFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect const* aurEff, SpellModifier*& spellMod); + HookList DoEffectCalcSpellMod; +#define AuraEffectCalcSpellModFn(F, I, N) EffectCalcSpellModHandlerFunction(&F, I, N) - // executed when aura effect calculates spellmod - // example: DoEffectCalcSpellMod += AuraEffectCalcSpellModFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect const* aurEff, SpellModifier*& spellMod); - HookList DoEffectCalcSpellMod; - #define AuraEffectCalcSpellModFn(F, I, N) EffectCalcSpellModHandlerFunction(&F, I, N) + // executed when absorb aura effect is going to reduce damage + // example: OnEffectAbsorb += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); + // where function is: void function (AuraEffect const* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); + HookList OnEffectAbsorb; +#define AuraEffectAbsorbFn(F, I) EffectAbsorbFunction(&F, I) - // executed when absorb aura effect is going to reduce damage - // example: OnEffectAbsorb += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); - // where function is: void function (AuraEffect const* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); - HookList OnEffectAbsorb; - #define AuraEffectAbsorbFn(F, I) EffectAbsorbFunction(&F, I) + // executed after absorb aura effect reduced damage to target - absorbAmount is real amount absorbed by aura + // example: AfterEffectAbsorb += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); + // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); + HookList AfterEffectAbsorb; - // executed after absorb aura effect reduced damage to target - absorbAmount is real amount absorbed by aura - // example: AfterEffectAbsorb += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); - // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); - HookList AfterEffectAbsorb; + // executed when mana shield aura effect is going to reduce damage + // example: OnEffectManaShield += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); + // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); + HookList OnEffectManaShield; +#define AuraEffectManaShieldFn(F, I) EffectManaShieldFunction(&F, I) - // executed when mana shield aura effect is going to reduce damage - // example: OnEffectManaShield += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); - // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); - HookList OnEffectManaShield; - #define AuraEffectManaShieldFn(F, I) EffectManaShieldFunction(&F, I) + // executed after mana shield aura effect reduced damage to target - absorbAmount is real amount absorbed by aura + // example: AfterEffectManaShield += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); + // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); + HookList AfterEffectManaShield; - // executed after mana shield aura effect reduced damage to target - absorbAmount is real amount absorbed by aura - // example: AfterEffectManaShield += AuraEffectAbsorbFn(class::function, EffectIndexSpecifier); - // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount); - HookList AfterEffectManaShield; + // executed when the caster of some spell with split dmg aura gets damaged through it + // example: OnEffectSplit += AuraEffectSplitFn(class::function, EffectIndexSpecifier); + // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& splitAmount); + HookList OnEffectSplit; +#define AuraEffectSplitFn(F, I) EffectSplitFunction(&F, I) - // executed when the caster of some spell with split dmg aura gets damaged through it - // example: OnEffectSplit += AuraEffectSplitFn(class::function, EffectIndexSpecifier); - // where function is: void function (AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& splitAmount); - HookList OnEffectSplit; - #define AuraEffectSplitFn(F, I) EffectSplitFunction(&F, I) + // executed when aura checks if it can proc + // example: DoCheckProc += AuraCheckProcFn(class::function); + // where function is: bool function (ProcEventInfo& eventInfo); + HookList DoCheckProc; +#define AuraCheckProcFn(F) CheckProcHandlerFunction(&F) - // executed when aura checks if it can proc - // example: DoCheckProc += AuraCheckProcFn(class::function); - // where function is: bool function (ProcEventInfo& eventInfo); - HookList DoCheckProc; - #define AuraCheckProcFn(F) CheckProcHandlerFunction(&F) + // executed before aura procs (possibility to prevent charge drop/cooldown) + // example: DoPrepareProc += AuraProcFn(class::function); + // where function is: void function (ProcEventInfo& eventInfo); + HookList DoPrepareProc; + // executed when aura procs + // example: OnProc += AuraProcFn(class::function); + // where function is: void function (ProcEventInfo& eventInfo); + HookList OnProc; + // executed after aura proced + // example: AfterProc += AuraProcFn(class::function); + // where function is: void function (ProcEventInfo& eventInfo); + HookList AfterProc; +#define AuraProcFn(F) AuraProcHandlerFunction(&F) - // executed before aura procs (possibility to prevent charge drop/cooldown) - // example: DoPrepareProc += AuraProcFn(class::function); - // where function is: void function (ProcEventInfo& eventInfo); - HookList DoPrepareProc; - // executed when aura procs - // example: OnProc += AuraProcFn(class::function); - // where function is: void function (ProcEventInfo& eventInfo); - HookList OnProc; - // executed after aura proced - // example: AfterProc += AuraProcFn(class::function); - // where function is: void function (ProcEventInfo& eventInfo); - HookList AfterProc; - #define AuraProcFn(F) AuraProcHandlerFunction(&F) + // executed when aura effect procs + // example: OnEffectProc += AuraEffectProcFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect const* aurEff, ProcEventInfo& procInfo); + HookList OnEffectProc; + // executed after aura effect proced + // example: AfterEffectProc += AuraEffectProcFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); + // where function is: void function (AuraEffect const* aurEff, ProcEventInfo& procInfo); + HookList AfterEffectProc; +#define AuraEffectProcFn(F, I, N) EffectProcHandlerFunction(&F, I, N) - // executed when aura effect procs - // example: OnEffectProc += AuraEffectProcFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect const* aurEff, ProcEventInfo& procInfo); - HookList OnEffectProc; - // executed after aura effect proced - // example: AfterEffectProc += AuraEffectProcFn(class::function, EffectIndexSpecifier, EffectAuraNameSpecifier); - // where function is: void function (AuraEffect const* aurEff, ProcEventInfo& procInfo); - HookList AfterEffectProc; - #define AuraEffectProcFn(F, I, N) EffectProcHandlerFunction(&F, I, N) + // AuraScript interface - hook/effect execution manipulators - // AuraScript interface - hook/effect execution manipulators + // prevents default action of a hook from being executed (works only while called in a hook which default action can be prevented) + void PreventDefaultAction(); - // prevents default action of a hook from being executed (works only while called in a hook which default action can be prevented) - void PreventDefaultAction(); + // AuraScript interface - functions which are redirecting to Aura class - // AuraScript interface - functions which are redirecting to Aura class + // returns proto of the spell + SpellInfo const* GetSpellInfo() const; + // returns spellid of the spell + uint32 GetId() const; - // returns proto of the spell - SpellInfo const* GetSpellInfo() const; - // returns spellid of the spell - uint32 GetId() const; + // returns guid of object which casted the aura (m_originalCaster of the Spell class) + uint64 GetCasterGUID() const; + // returns unit which casted the aura or NULL if not avalible (caster logged out for example) + Unit* GetCaster() const; + // returns object on which aura was casted, target for non-area auras, area aura source for area auras + WorldObject* GetOwner() const; + // returns owner if it's unit or unit derived object, NULL otherwise (only for persistent area auras NULL is returned) + Unit* GetUnitOwner() const; + // returns owner if it's dynobj, NULL otherwise + DynamicObject* GetDynobjOwner() const; - // returns guid of object which casted the aura (m_originalCaster of the Spell class) - uint64 GetCasterGUID() const; - // returns unit which casted the aura or NULL if not avalible (caster logged out for example) - Unit* GetCaster() const; - // returns object on which aura was casted, target for non-area auras, area aura source for area auras - WorldObject* GetOwner() const; - // returns owner if it's unit or unit derived object, NULL otherwise (only for persistent area auras NULL is returned) - Unit* GetUnitOwner() const; - // returns owner if it's dynobj, NULL otherwise - DynamicObject* GetDynobjOwner() const; + // removes aura with remove mode (see AuraRemoveMode enum) + void Remove(uint32 removeMode = 0); + // returns aura object of script + Aura* GetAura() const; - // removes aura with remove mode (see AuraRemoveMode enum) - void Remove(uint32 removeMode = 0); - // returns aura object of script - Aura* GetAura() const; + // returns type of the aura, may be dynobj owned aura or unit owned aura + AuraObjectType GetType() const; - // returns type of the aura, may be dynobj owned aura or unit owned aura - AuraObjectType GetType() const; + // aura duration manipulation - when duration goes to 0 aura is removed + int32 GetDuration() const; + void SetDuration(int32 duration, bool withMods = false); + // sets duration to maxduration + void RefreshDuration(); + time_t GetApplyTime() const; + int32 GetMaxDuration() const; + void SetMaxDuration(int32 duration); + int32 CalcMaxDuration() const; + // expired - duration just went to 0 + bool IsExpired() const; + // permament - has infinite duration + bool IsPermanent() const; - // aura duration manipulation - when duration goes to 0 aura is removed - int32 GetDuration() const; - void SetDuration(int32 duration, bool withMods = false); - // sets duration to maxduration - void RefreshDuration(); - time_t GetApplyTime() const; - int32 GetMaxDuration() const; - void SetMaxDuration(int32 duration); - int32 CalcMaxDuration() const; - // expired - duration just went to 0 - bool IsExpired() const; - // permament - has infinite duration - bool IsPermanent() const; + // charges manipulation - 0 - not charged aura + uint8 GetCharges() const; + void SetCharges(uint8 charges); + uint8 CalcMaxCharges() const; + bool ModCharges(int8 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + // returns true if last charge dropped + bool DropCharge(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - // charges manipulation - 0 - not charged aura - uint8 GetCharges() const; - void SetCharges(uint8 charges); - uint8 CalcMaxCharges() const; - bool ModCharges(int8 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - // returns true if last charge dropped - bool DropCharge(AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + // stack amount manipulation + uint8 GetStackAmount() const; + void SetStackAmount(uint8 num); + bool ModStackAmount(int32 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - // stack amount manipulation - uint8 GetStackAmount() const; - void SetStackAmount(uint8 num); - bool ModStackAmount(int32 num, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); + // passive - "working in background", not saved, not removed by immunities, not seen by player + bool IsPassive() const; + // death persistent - not removed on death + bool IsDeathPersistent() const; - // passive - "working in background", not saved, not removed by immunities, not seen by player - bool IsPassive() const; - // death persistent - not removed on death - bool IsDeathPersistent() const; + // check if aura has effect of given effindex + bool HasEffect(uint8 effIndex) const; + // returns aura effect of given effect index or NULL + AuraEffect* GetEffect(uint8 effIndex) const; - // check if aura has effect of given effindex - bool HasEffect(uint8 effIndex) const; - // returns aura effect of given effect index or NULL - AuraEffect* GetEffect(uint8 effIndex) const; + // check if aura has effect of given aura type + bool HasEffectType(AuraType type) const; - // check if aura has effect of given aura type - bool HasEffectType(AuraType type) const; + // AuraScript interface - functions which are redirecting to AuraApplication class + // Do not call these in hooks in which AuraApplication is not avalible, otherwise result will differ from expected (the functions will return nullptr) - // AuraScript interface - functions which are redirecting to AuraApplication class - // Do not call these in hooks in which AuraApplication is not avalible, otherwise result will differ from expected (the functions will return nullptr) - - // returns currently processed target of an aura - // Return value does not need to be NULL-checked, the only situation this will (always) - // return NULL is when the call happens in an unsupported hook, in other cases, it is always valid - Unit* GetTarget() const; - // returns AuraApplication object of currently processed target - AuraApplication const* GetTargetApplication() const; + // returns currently processed target of an aura + // Return value does not need to be NULL-checked, the only situation this will (always) + // return NULL is when the call happens in an unsupported hook, in other cases, it is always valid + Unit* GetTarget() const; + // returns AuraApplication object of currently processed target + AuraApplication const* GetTargetApplication() const; }; // diff --git a/src/server/game/Texts/CreatureTextMgr.cpp b/src/server/game/Texts/CreatureTextMgr.cpp index 4a53844e5..8f3651aa1 100644 --- a/src/server/game/Texts/CreatureTextMgr.cpp +++ b/src/server/game/Texts/CreatureTextMgr.cpp @@ -16,51 +16,51 @@ class CreatureTextBuilder { - public: - CreatureTextBuilder(WorldObject* obj, uint8 gender, ChatMsg msgtype, uint8 textGroup, uint32 id, uint32 language, WorldObject const* target) - : _source(obj), _gender(gender), _msgType(msgtype), _textGroup(textGroup), _textId(id), _language(language), _target(target) - { - } +public: + CreatureTextBuilder(WorldObject* obj, uint8 gender, ChatMsg msgtype, uint8 textGroup, uint32 id, uint32 language, WorldObject const* target) + : _source(obj), _gender(gender), _msgType(msgtype), _textGroup(textGroup), _textId(id), _language(language), _target(target) + { + } - size_t operator()(WorldPacket* data, LocaleConstant locale) const - { - std::string const& text = sCreatureTextMgr->GetLocalizedChatString(_source->GetEntry(), _gender, _textGroup, _textId, locale); + size_t operator()(WorldPacket* data, LocaleConstant locale) const + { + std::string const& text = sCreatureTextMgr->GetLocalizedChatString(_source->GetEntry(), _gender, _textGroup, _textId, locale); - return ChatHandler::BuildChatPacket(*data, _msgType, Language(_language), _source, _target, text, 0, "", locale); - } + return ChatHandler::BuildChatPacket(*data, _msgType, Language(_language), _source, _target, text, 0, "", locale); + } - WorldObject* _source; - uint8 _gender; - ChatMsg _msgType; - uint8 _textGroup; - uint32 _textId; - uint32 _language; - WorldObject const* _target; + WorldObject* _source; + uint8 _gender; + ChatMsg _msgType; + uint8 _textGroup; + uint32 _textId; + uint32 _language; + WorldObject const* _target; }; class PlayerTextBuilder { - public: - PlayerTextBuilder(WorldObject* obj, WorldObject* speaker, uint8 gender, ChatMsg msgtype, uint8 textGroup, uint32 id, uint32 language, WorldObject const* target) - : _source(obj), _talker(speaker), _gender(gender), _msgType(msgtype), _textGroup(textGroup), _textId(id), _language(language), _target(target) - { - } +public: + PlayerTextBuilder(WorldObject* obj, WorldObject* speaker, uint8 gender, ChatMsg msgtype, uint8 textGroup, uint32 id, uint32 language, WorldObject const* target) + : _source(obj), _talker(speaker), _gender(gender), _msgType(msgtype), _textGroup(textGroup), _textId(id), _language(language), _target(target) + { + } - size_t operator()(WorldPacket* data, LocaleConstant locale) const - { - std::string const& text = sCreatureTextMgr->GetLocalizedChatString(_source->GetEntry(), _gender, _textGroup, _textId, locale); + size_t operator()(WorldPacket* data, LocaleConstant locale) const + { + std::string const& text = sCreatureTextMgr->GetLocalizedChatString(_source->GetEntry(), _gender, _textGroup, _textId, locale); - return ChatHandler::BuildChatPacket(*data, _msgType, Language(_language), _talker, _target, text, 0, "", locale); - } + return ChatHandler::BuildChatPacket(*data, _msgType, Language(_language), _talker, _target, text, 0, "", locale); + } - WorldObject* _source; - WorldObject* _talker; - uint8 _gender; - ChatMsg _msgType; - uint8 _textGroup; - uint32 _textId; - uint32 _language; - WorldObject const* _target; + WorldObject* _source; + WorldObject* _talker; + uint8 _gender; + ChatMsg _msgType; + uint8 _textGroup; + uint32 _textId; + uint32 _language; + WorldObject const* _target; }; CreatureTextMgr* CreatureTextMgr::instance() @@ -108,7 +108,8 @@ void CreatureTextMgr::LoadCreatureTexts() if (temp.sound) { - if (!sSoundEntriesStore.LookupEntry(temp.sound)){ + if (!sSoundEntriesStore.LookupEntry(temp.sound)) + { sLog->outErrorDb("CreatureTextMgr: Entry %u, Group %u in table `creature_texts` has Sound %u but sound does not exist.", temp.entry, temp.group, temp.sound); temp.sound = 0; } @@ -336,17 +337,17 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, { case CHAT_MSG_MONSTER_WHISPER: case CHAT_MSG_RAID_BOSS_WHISPER: - { - if (range == TEXT_RANGE_NORMAL)//ignores team and gmOnly { - if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) - return; + if (range == TEXT_RANGE_NORMAL)//ignores team and gmOnly + { + if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) + return; - whisperTarget->ToPlayer()->GetSession()->SendPacket(data); - return; + whisperTarget->ToPlayer()->GetSession()->SendPacket(data); + return; + } + break; } - break; - } default: break; } @@ -354,40 +355,40 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, switch (range) { case TEXT_RANGE_AREA: - { - uint32 areaId = source->GetAreaId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetAreaId() == areaId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); - return; - } + { + uint32 areaId = source->GetAreaId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetAreaId() == areaId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) + itr->GetSource()->GetSession()->SendPacket(data); + return; + } case TEXT_RANGE_ZONE: - { - uint32 zoneId = source->GetZoneId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetZoneId() == zoneId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); - return; - } + { + uint32 zoneId = source->GetZoneId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetZoneId() == zoneId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) + itr->GetSource()->GetSession()->SendPacket(data); + return; + } case TEXT_RANGE_MAP: - { - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if ((teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); - return; - } + { + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if ((teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) + itr->GetSource()->GetSession()->SendPacket(data); + return; + } case TEXT_RANGE_WORLD: - { - SessionMap const& smap = sWorld->GetAllSessions(); - for (SessionMap::const_iterator itr = smap.begin(); itr != smap.end(); ++itr) - if (Player* player = itr->second->GetPlayer()) - if ((teamId == TEAM_NEUTRAL || player->GetTeamId() == teamId) && (!gmOnly || player->IsGameMaster())) - player->GetSession()->SendPacket(data); - return; - } + { + SessionMap const& smap = sWorld->GetAllSessions(); + for (SessionMap::const_iterator itr = smap.begin(); itr != smap.end(); ++itr) + if (Player* player = itr->second->GetPlayer()) + if ((teamId == TEAM_NEUTRAL || player->GetTeamId() == teamId) && (!gmOnly || player->IsGameMaster())) + player->GetSession()->SendPacket(data); + return; + } case TEXT_RANGE_NORMAL: default: break; diff --git a/src/server/game/Texts/CreatureTextMgr.h b/src/server/game/Texts/CreatureTextMgr.h index ed0f81015..e9d44db89 100644 --- a/src/server/game/Texts/CreatureTextMgr.h +++ b/src/server/game/Texts/CreatureTextMgr.h @@ -74,34 +74,34 @@ class CreatureTextMgr { CreatureTextMgr() { } - public: - static CreatureTextMgr* instance(); +public: + static CreatureTextMgr* instance(); - ~CreatureTextMgr() { } - void LoadCreatureTexts(); - void LoadCreatureTextLocales(); - CreatureTextMap const& GetTextMap() const { return mTextMap; } + ~CreatureTextMgr() { } + void LoadCreatureTexts(); + void LoadCreatureTextLocales(); + CreatureTextMap const& GetTextMap() const { return mTextMap; } - void SendSound(Creature* source, uint32 sound, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, TeamId teamId, bool gmOnly); - void SendEmote(Unit* source, uint32 emote); + void SendSound(Creature* source, uint32 sound, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, TeamId teamId, bool gmOnly); + void SendEmote(Unit* source, uint32 emote); - //if sent, returns the 'duration' of the text else 0 if error - uint32 SendChat(Creature* source, uint8 textGroup, WorldObject const* whisperTarget = NULL, ChatMsg msgType = CHAT_MSG_ADDON, Language language = LANG_ADDON, CreatureTextRange range = TEXT_RANGE_NORMAL, uint32 sound = 0, TeamId teamId = TEAM_NEUTRAL, bool gmOnly = false, Player* srcPlr = nullptr); - bool TextExist(uint32 sourceEntry, uint8 textGroup); - std::string GetLocalizedChatString(uint32 entry, uint8 gender, uint8 textGroup, uint32 id, LocaleConstant locale) const; + //if sent, returns the 'duration' of the text else 0 if error + uint32 SendChat(Creature* source, uint8 textGroup, WorldObject const* whisperTarget = NULL, ChatMsg msgType = CHAT_MSG_ADDON, Language language = LANG_ADDON, CreatureTextRange range = TEXT_RANGE_NORMAL, uint32 sound = 0, TeamId teamId = TEAM_NEUTRAL, bool gmOnly = false, Player* srcPlr = nullptr); + bool TextExist(uint32 sourceEntry, uint8 textGroup); + std::string GetLocalizedChatString(uint32 entry, uint8 gender, uint8 textGroup, uint32 id, LocaleConstant locale) const; - template void SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget = NULL, CreatureTextRange range = TEXT_RANGE_NORMAL, TeamId teamId = TEAM_NEUTRAL, bool gmOnly = false) const; + template void SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget = NULL, CreatureTextRange range = TEXT_RANGE_NORMAL, TeamId teamId = TEAM_NEUTRAL, bool gmOnly = false) const; - private: - CreatureTextRepeatIds GetRepeatGroup(Creature* source, uint8 textGroup); - void SetRepeatId(Creature* source, uint8 textGroup, uint8 id); +private: + CreatureTextRepeatIds GetRepeatGroup(Creature* source, uint8 textGroup); + void SetRepeatId(Creature* source, uint8 textGroup, uint8 id); - void SendNonChatPacket(WorldObject* source, WorldPacket* data, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, TeamId teamId, bool gmOnly) const; - float GetRangeForChatType(ChatMsg msgType) const; + void SendNonChatPacket(WorldObject* source, WorldPacket* data, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, TeamId teamId, bool gmOnly) const; + float GetRangeForChatType(ChatMsg msgType) const; - CreatureTextMap mTextMap; - CreatureTextRepeatMap mTextRepeatMap; - LocaleCreatureTextMap mLocaleTextMap; + CreatureTextMap mTextMap; + CreatureTextRepeatMap mTextRepeatMap; + LocaleCreatureTextMap mLocaleTextMap; }; #define sCreatureTextMgr CreatureTextMgr::instance() @@ -109,60 +109,60 @@ class CreatureTextMgr template class CreatureTextLocalizer { - public: - CreatureTextLocalizer(Builder const& builder, ChatMsg msgType) : _builder(builder), _msgType(msgType) +public: + CreatureTextLocalizer(Builder const& builder, ChatMsg msgType) : _builder(builder), _msgType(msgType) + { + _packetCache.resize(TOTAL_LOCALES, nullptr); + } + + ~CreatureTextLocalizer() + { + for (size_t i = 0; i < _packetCache.size(); ++i) { - _packetCache.resize(TOTAL_LOCALES, nullptr); + if (_packetCache[i]) + delete _packetCache[i]->first; + delete _packetCache[i]; + } + } + + void operator()(Player* player) + { + LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); + WorldPacket* messageTemplate; + size_t whisperGUIDpos; + + // create if not cached yet + if (!_packetCache[loc_idx]) + { + messageTemplate = new WorldPacket(); + whisperGUIDpos = _builder(messageTemplate, loc_idx); + ASSERT(messageTemplate->GetOpcode() != MSG_NULL_ACTION); + _packetCache[loc_idx] = new std::pair(messageTemplate, whisperGUIDpos); + } + else + { + messageTemplate = _packetCache[loc_idx]->first; + whisperGUIDpos = _packetCache[loc_idx]->second; } - ~CreatureTextLocalizer() + WorldPacket data(*messageTemplate); + switch (_msgType) { - for (size_t i = 0; i < _packetCache.size(); ++i) - { - if (_packetCache[i]) - delete _packetCache[i]->first; - delete _packetCache[i]; - } + case CHAT_MSG_MONSTER_WHISPER: + case CHAT_MSG_RAID_BOSS_WHISPER: + data.put(whisperGUIDpos, player->GetGUID()); + break; + default: + break; } - void operator()(Player* player) - { - LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); - WorldPacket* messageTemplate; - size_t whisperGUIDpos; + player->SendDirectMessage(&data); + } - // create if not cached yet - if (!_packetCache[loc_idx]) - { - messageTemplate = new WorldPacket(); - whisperGUIDpos = _builder(messageTemplate, loc_idx); - ASSERT(messageTemplate->GetOpcode() != MSG_NULL_ACTION); - _packetCache[loc_idx] = new std::pair(messageTemplate, whisperGUIDpos); - } - else - { - messageTemplate = _packetCache[loc_idx]->first; - whisperGUIDpos = _packetCache[loc_idx]->second; - } - - WorldPacket data(*messageTemplate); - switch (_msgType) - { - case CHAT_MSG_MONSTER_WHISPER: - case CHAT_MSG_RAID_BOSS_WHISPER: - data.put(whisperGUIDpos, player->GetGUID()); - break; - default: - break; - } - - player->SendDirectMessage(&data); - } - - private: - std::vector* > _packetCache; - Builder const& _builder; - ChatMsg _msgType; +private: + std::vector* > _packetCache; + Builder const& _builder; + ChatMsg _msgType; }; template @@ -177,17 +177,17 @@ void CreatureTextMgr::SendChatPacket(WorldObject* source, Builder const& builder { case CHAT_MSG_MONSTER_WHISPER: case CHAT_MSG_RAID_BOSS_WHISPER: - { - if (range == TEXT_RANGE_NORMAL) //ignores team and gmOnly { - if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) - return; + if (range == TEXT_RANGE_NORMAL) //ignores team and gmOnly + { + if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) + return; - localizer(const_cast(whisperTarget->ToPlayer())); - return; + localizer(const_cast(whisperTarget->ToPlayer())); + return; + } + break; } - break; - } default: break; } @@ -195,40 +195,40 @@ void CreatureTextMgr::SendChatPacket(WorldObject* source, Builder const& builder switch (range) { case TEXT_RANGE_AREA: - { - uint32 areaId = source->GetAreaId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetAreaId() == areaId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } + { + uint32 areaId = source->GetAreaId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetAreaId() == areaId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } case TEXT_RANGE_ZONE: - { - uint32 zoneId = source->GetZoneId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetZoneId() == zoneId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } + { + uint32 zoneId = source->GetZoneId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetZoneId() == zoneId && (teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } case TEXT_RANGE_MAP: - { - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if ((teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } + { + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if ((teamId == TEAM_NEUTRAL || itr->GetSource()->GetTeamId() == teamId) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } case TEXT_RANGE_WORLD: - { - SessionMap const& smap = sWorld->GetAllSessions(); - for (SessionMap::const_iterator itr = smap.begin(); itr != smap.end(); ++itr) - if (Player* player = itr->second->GetPlayer()) - if ((teamId == TEAM_NEUTRAL || player->GetTeamId() == teamId) && (!gmOnly || player->IsGameMaster())) - localizer(player); - return; - } + { + SessionMap const& smap = sWorld->GetAllSessions(); + for (SessionMap::const_iterator itr = smap.begin(); itr != smap.end(); ++itr) + if (Player* player = itr->second->GetPlayer()) + if ((teamId == TEAM_NEUTRAL || player->GetTeamId() == teamId) && (!gmOnly || player->IsGameMaster())) + localizer(player); + return; + } case TEXT_RANGE_NORMAL: default: break; diff --git a/src/server/game/Tickets/TicketMgr.cpp b/src/server/game/Tickets/TicketMgr.cpp index 5c02404ff..9a42ddabb 100644 --- a/src/server/game/Tickets/TicketMgr.cpp +++ b/src/server/game/Tickets/TicketMgr.cpp @@ -21,8 +21,8 @@ inline float GetAge(uint64 t) { return float(time(nullptr) - t) / DAY; } /////////////////////////////////////////////////////////////////////////////////////////////////// // GM ticket GmTicket::GmTicket() : _id(0), _playerGuid(0), _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _posZ(0), _mapId(0), _createTime(0), _lastModifiedTime(0), - _closedBy(0), _resolvedBy(0), _assignedTo(0), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), - _needResponse(false), _needMoreHelp(false) { } + _closedBy(0), _resolvedBy(0), _assignedTo(0), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), + _needResponse(false), _needMoreHelp(false) { } GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _createTime(time(nullptr)), _lastModifiedTime(time(nullptr)), _closedBy(0), _resolvedBy(0), _assignedTo(0), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needMoreHelp(false) { @@ -191,8 +191,12 @@ void GmTicket::SetUnassigned() _assignedTo = 0; switch (_escalatedStatus) { - case TICKET_ASSIGNED: _escalatedStatus = TICKET_UNASSIGNED; break; - case TICKET_ESCALATED_ASSIGNED: _escalatedStatus = TICKET_IN_ESCALATION_QUEUE; break; + case TICKET_ASSIGNED: + _escalatedStatus = TICKET_UNASSIGNED; + break; + case TICKET_ESCALATED_ASSIGNED: + _escalatedStatus = TICKET_IN_ESCALATION_QUEUE; + break; case TICKET_UNASSIGNED: case TICKET_IN_ESCALATION_QUEUE: default: diff --git a/src/server/game/Tickets/TicketMgr.h b/src/server/game/Tickets/TicketMgr.h index 91a55b687..1760206fd 100644 --- a/src/server/game/Tickets/TicketMgr.h +++ b/src/server/game/Tickets/TicketMgr.h @@ -178,7 +178,7 @@ private: public: static TicketMgr* instance(); - + void LoadTickets(); void LoadSurveys(); diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.cpp b/src/server/game/Tools/CharacterDatabaseCleaner.cpp index d0a9bf96e..116d27513 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.cpp +++ b/src/server/game/Tools/CharacterDatabaseCleaner.cpp @@ -84,8 +84,7 @@ void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table ss << id; } - } - while (result->NextRow()); + } while (result->NextRow()); if (found) { diff --git a/src/server/game/Tools/PlayerDump.cpp b/src/server/game/Tools/PlayerDump.cpp index e33c6d7e8..5cf2500e8 100644 --- a/src/server/game/Tools/PlayerDump.cpp +++ b/src/server/game/Tools/PlayerDump.cpp @@ -51,9 +51,10 @@ static DumpTable dumpTables[DUMP_TABLE_COUNT] = }; // Low level functions -static bool findtoknth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e) +static bool findtoknth(std::string& str, int n, std::string::size_type& s, std::string::size_type& e) { - int i; s = e = 0; + int i; + s = e = 0; std::string::size_type size = str.size(); for (i = 1; s < size && i < n; s++) if (str[s] == ' ') ++i; if (i < n) @@ -64,89 +65,89 @@ static bool findtoknth(std::string &str, int n, std::string::size_type &s, std:: return e != std::string::npos; } -std::string gettoknth(std::string &str, int n) +std::string gettoknth(std::string& str, int n) { std::string::size_type s = 0, e = 0; if (!findtoknth(str, n, s, e)) return ""; - return str.substr(s, e-s); + return str.substr(s, e - s); } -bool findnth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e) +bool findnth(std::string& str, int n, std::string::size_type& s, std::string::size_type& e) { - s = str.find("VALUES ('")+9; + s = str.find("VALUES ('") + 9; if (s == std::string::npos) return false; do { e = str.find('\'', s); if (e == std::string::npos) return false; - } while (str[e-1] == '\\'); + } while (str[e - 1] == '\\'); for (int i = 1; i < n; ++i) { do { - s = e+4; + s = e + 4; e = str.find('\'', s); if (e == std::string::npos) return false; - } while (str[e-1] == '\\'); + } while (str[e - 1] == '\\'); } return true; } -std::string gettablename(std::string &str) +std::string gettablename(std::string& str) { std::string::size_type s = 13; std::string::size_type e = str.find(_TABLE_SIM_, s); if (e == std::string::npos) return ""; - return str.substr(s, e-s); + return str.substr(s, e - s); } -bool changenth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false) +bool changenth(std::string& str, int n, const char* with, bool insert = false, bool nonzero = false) { std::string::size_type s, e; if (!findnth(str, n, s, e)) return false; - if (nonzero && str.substr(s, e-s) == "0") + if (nonzero && str.substr(s, e - s) == "0") return true; // not an error if (!insert) - str.replace(s, e-s, with); + str.replace(s, e - s, with); else str.insert(s, with); return true; } -std::string getnth(std::string &str, int n) +std::string getnth(std::string& str, int n) { std::string::size_type s, e; if (!findnth(str, n, s, e)) return ""; - return str.substr(s, e-s); + return str.substr(s, e - s); } -bool changetoknth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false) +bool changetoknth(std::string& str, int n, const char* with, bool insert = false, bool nonzero = false) { std::string::size_type s = 0, e = 0; if (!findtoknth(str, n, s, e)) return false; - if (nonzero && str.substr(s, e-s) == "0") + if (nonzero && str.substr(s, e - s) == "0") return true; // not an error if (!insert) - str.replace(s, e-s, with); + str.replace(s, e - s, with); else str.insert(s, with); return true; } -uint32 registerNewGuid(uint32 oldGuid, std::map &guidMap, uint32 hiGuid) +uint32 registerNewGuid(uint32 oldGuid, std::map& guidMap, uint32 hiGuid) { std::map::const_iterator itr = guidMap.find(oldGuid); if (itr != guidMap.end()) @@ -157,7 +158,7 @@ uint32 registerNewGuid(uint32 oldGuid, std::map &guidMap, uint32 return newguid; } -bool changeGuid(std::string &str, int n, std::map &guidMap, uint32 hiGuid, bool nonzero = false) +bool changeGuid(std::string& str, int n, std::map& guidMap, uint32 hiGuid, bool nonzero = false) { char chritem[20]; uint32 oldGuid = atoi(getnth(str, n).c_str()); @@ -170,7 +171,7 @@ bool changeGuid(std::string &str, int n, std::map &guidMap, uint return changenth(str, n, chritem, false, nonzero); } -bool changetokGuid(std::string &str, int n, std::map &guidMap, uint32 hiGuid, bool nonzero = false) +bool changetokGuid(std::string& str, int n, std::map& guidMap, uint32 hiGuid, bool nonzero = false) { char chritem[20]; uint32 oldGuid = atoi(gettoknth(str, n).c_str()); @@ -187,7 +188,7 @@ std::string CreateDumpString(char const* tableName, QueryResult result) { if (!tableName || !result) return ""; std::ostringstream ss; - ss << "INSERT INTO "<< _TABLE_SIM_ << tableName << _TABLE_SIM_ << " VALUES ("; + ss << "INSERT INTO " << _TABLE_SIM_ << tableName << _TABLE_SIM_ << " VALUES ("; Field* fields = result->Fetch(); for (uint32 i = 0; i < result->GetFieldCount(); ++i) { @@ -251,20 +252,38 @@ void StoreGUID(QueryResult result, uint32 data, uint32 field, std::set& } // Writing - High-level functions -bool PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type) +bool PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const* tableFrom, char const* tableTo, DumpTableType type) { GUIDs const* guids = nullptr; char const* fieldname = nullptr; switch (type) { - case DTT_ITEM: fieldname = "guid"; guids = &items; break; - case DTT_ITEM_GIFT: fieldname = "item_guid"; guids = &items; break; - case DTT_PET: fieldname = "owner"; break; - case DTT_PET_TABLE: fieldname = "guid"; guids = &pets; break; - case DTT_MAIL: fieldname = "receiver"; break; - case DTT_MAIL_ITEM: fieldname = "mail_id"; guids = &mails; break; - default: fieldname = "guid"; break; + case DTT_ITEM: + fieldname = "guid"; + guids = &items; + break; + case DTT_ITEM_GIFT: + fieldname = "item_guid"; + guids = &items; + break; + case DTT_PET: + fieldname = "owner"; + break; + case DTT_PET_TABLE: + fieldname = "guid"; + guids = &pets; + break; + case DTT_MAIL: + fieldname = "receiver"; + break; + case DTT_MAIL_ITEM: + fieldname = "mail_id"; + guids = &mails; + break; + default: + fieldname = "guid"; + break; } // for guid set stop if set is empty @@ -307,28 +326,26 @@ bool PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tabl StoreGUID(result, 1, items); // item guid collection (mail_items.item_guid) break; case DTT_CHARACTER: - { - if (result->GetFieldCount() <= 74) // avoid crashes on next check - sLog->outCrash("PlayerDumpWriter::DumpTable - Trying to access non-existing or wrong positioned field (`deleteInfos_Account`) in `characters` table."); + { + if (result->GetFieldCount() <= 74) // avoid crashes on next check + sLog->outCrash("PlayerDumpWriter::DumpTable - Trying to access non-existing or wrong positioned field (`deleteInfos_Account`) in `characters` table."); - if (result->Fetch()[74].GetUInt32()) // characters.deleteInfos_Account - if filled error - return false; - break; - } + if (result->Fetch()[74].GetUInt32()) // characters.deleteInfos_Account - if filled error + return false; + break; + } default: break; } dump += CreateDumpString(tableTo, result); dump += "\n"; - } - while (result->NextRow()); - } - while (guids && guids_itr != guids->end()); // not set case iterate single time, set case iterate for all guids + } while (result->NextRow()); + } while (guids && guids_itr != guids->end()); // not set case iterate single time, set case iterate for all guids return true; } -bool PlayerDumpWriter::GetDump(uint32 guid, std::string &dump) +bool PlayerDumpWriter::GetDump(uint32 guid, std::string& dump) { dump = ""; @@ -373,7 +390,7 @@ DumpReturn PlayerDumpWriter::WriteDump(const std::string& file, uint32 guid) // Reading - High-level functions #define ROLLBACK(DR) {fclose(fin); return (DR);} -void fixNULLfields(std::string &line) +void fixNULLfields(std::string& line) { std::string nullString("'NULL'"); size_t pos = line.find(nullString); @@ -457,7 +474,8 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s ROLLBACK(DUMP_FILE_BROKEN); } - std::string line; line.assign(buf); + std::string line; + line.assign(buf); // skip empty strings size_t nw_pos = line.find_first_not_of(" \t\n\r\7"); @@ -466,8 +484,8 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s // skip logfile-side dump start notice, the important notes and dump end notices if ((line.substr(nw_pos, 16) == "== START DUMP ==") || - (line.substr(nw_pos, 15) == "IMPORTANT NOTE:") || - (line.substr(nw_pos, 14) == "== END DUMP ==")) + (line.substr(nw_pos, 15) == "IMPORTANT NOTE:") || + (line.substr(nw_pos, 14) == "== END DUMP ==")) continue; // add required_ check @@ -510,147 +528,147 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s switch (type) { case DTT_CHARACTER: - { - if (!changenth(line, 1, newguid)) // characters.guid update - ROLLBACK(DUMP_FILE_BROKEN); - - if (!changenth(line, 2, chraccount)) // characters.account update - ROLLBACK(DUMP_FILE_BROKEN); - - race = uint8(atol(getnth(line, 4).c_str())); - playerClass = uint8(atol(getnth(line, 5).c_str())); - gender = uint8(atol(getnth(line, 6).c_str())); - level = uint8(atol(getnth(line, 7).c_str())); - if (name == "") { - // check if the original name already exists - name = getnth(line, 3); + if (!changenth(line, 1, newguid)) // characters.guid update + ROLLBACK(DUMP_FILE_BROKEN); - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); - stmt->setString(0, name); - PreparedQueryResult result = CharacterDatabase.Query(stmt); + if (!changenth(line, 2, chraccount)) // characters.account update + ROLLBACK(DUMP_FILE_BROKEN); - if (result) - if (!changenth(line, 38, "1")) // characters.at_login set to "rename on login" - ROLLBACK(DUMP_FILE_BROKEN); + race = uint8(atol(getnth(line, 4).c_str())); + playerClass = uint8(atol(getnth(line, 5).c_str())); + gender = uint8(atol(getnth(line, 6).c_str())); + level = uint8(atol(getnth(line, 7).c_str())); + if (name == "") + { + // check if the original name already exists + name = getnth(line, 3); + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); + stmt->setString(0, name); + PreparedQueryResult result = CharacterDatabase.Query(stmt); + + if (result) + if (!changenth(line, 38, "1")) // characters.at_login set to "rename on login" + ROLLBACK(DUMP_FILE_BROKEN); + } + else if (!changenth(line, 3, name.c_str())) // characters.name + ROLLBACK(DUMP_FILE_BROKEN); + + const char null[5] = "NULL"; + if (!changenth(line, 75, null)) // characters.deleteInfos_Account + ROLLBACK(DUMP_FILE_BROKEN); + if (!changenth(line, 76, null)) // characters.deleteInfos_Name + ROLLBACK(DUMP_FILE_BROKEN); + if (!changenth(line, 77, null)) // characters.deleteDate + ROLLBACK(DUMP_FILE_BROKEN); + break; } - else if (!changenth(line, 3, name.c_str())) // characters.name - ROLLBACK(DUMP_FILE_BROKEN); - - const char null[5] = "NULL"; - if (!changenth(line, 75, null)) // characters.deleteInfos_Account - ROLLBACK(DUMP_FILE_BROKEN); - if (!changenth(line, 76, null)) // characters.deleteInfos_Name - ROLLBACK(DUMP_FILE_BROKEN); - if (!changenth(line, 77, null)) // characters.deleteDate - ROLLBACK(DUMP_FILE_BROKEN); - break; - } case DTT_CHAR_TABLE: - { - if (!changenth(line, 1, newguid)) // character_*.guid update - ROLLBACK(DUMP_FILE_BROKEN); - break; - } + { + if (!changenth(line, 1, newguid)) // character_*.guid update + ROLLBACK(DUMP_FILE_BROKEN); + break; + } case DTT_EQSET_TABLE: - { - if (!changenth(line, 1, newguid)) - ROLLBACK(DUMP_FILE_BROKEN); // character_equipmentsets.guid + { + if (!changenth(line, 1, newguid)) + ROLLBACK(DUMP_FILE_BROKEN); // character_equipmentsets.guid - char newSetGuid[24]; - snprintf(newSetGuid, 24, UI64FMTD, sObjectMgr->GenerateEquipmentSetGuid()); - if (!changenth(line, 2, newSetGuid)) - ROLLBACK(DUMP_FILE_BROKEN); // character_equipmentsets.setguid - break; - } + char newSetGuid[24]; + snprintf(newSetGuid, 24, UI64FMTD, sObjectMgr->GenerateEquipmentSetGuid()); + if (!changenth(line, 2, newSetGuid)) + ROLLBACK(DUMP_FILE_BROKEN); // character_equipmentsets.setguid + break; + } case DTT_INVENTORY: - { - if (!changenth(line, 1, newguid)) // character_inventory.guid update - ROLLBACK(DUMP_FILE_BROKEN); + { + if (!changenth(line, 1, newguid)) // character_inventory.guid update + ROLLBACK(DUMP_FILE_BROKEN); - if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid, true)) - ROLLBACK(DUMP_FILE_BROKEN); // character_inventory.bag update - if (!changeGuid(line, 4, items, sObjectMgr->_hiItemGuid)) - ROLLBACK(DUMP_FILE_BROKEN); // character_inventory.item update - break; - } + if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid, true)) + ROLLBACK(DUMP_FILE_BROKEN); // character_inventory.bag update + if (!changeGuid(line, 4, items, sObjectMgr->_hiItemGuid)) + ROLLBACK(DUMP_FILE_BROKEN); // character_inventory.item update + break; + } case DTT_MAIL: // mail - { - if (!changeGuid(line, 1, mails, sObjectMgr->_mailId)) - ROLLBACK(DUMP_FILE_BROKEN); // mail.id update - if (!changenth(line, 6, newguid)) // mail.receiver update - ROLLBACK(DUMP_FILE_BROKEN); - break; - } + { + if (!changeGuid(line, 1, mails, sObjectMgr->_mailId)) + ROLLBACK(DUMP_FILE_BROKEN); // mail.id update + if (!changenth(line, 6, newguid)) // mail.receiver update + ROLLBACK(DUMP_FILE_BROKEN); + break; + } case DTT_MAIL_ITEM: // mail_items - { - if (!changeGuid(line, 1, mails, sObjectMgr->_mailId)) - ROLLBACK(DUMP_FILE_BROKEN); // mail_items.id - if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid)) - ROLLBACK(DUMP_FILE_BROKEN); // mail_items.item_guid - if (!changenth(line, 3, newguid)) // mail_items.receiver - ROLLBACK(DUMP_FILE_BROKEN); - break; - } + { + if (!changeGuid(line, 1, mails, sObjectMgr->_mailId)) + ROLLBACK(DUMP_FILE_BROKEN); // mail_items.id + if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid)) + ROLLBACK(DUMP_FILE_BROKEN); // mail_items.item_guid + if (!changenth(line, 3, newguid)) // mail_items.receiver + ROLLBACK(DUMP_FILE_BROKEN); + break; + } case DTT_ITEM: - { - // item, owner, data field:item, owner guid - if (!changeGuid(line, 1, items, sObjectMgr->_hiItemGuid)) - ROLLBACK(DUMP_FILE_BROKEN); // item_instance.guid update - if (!changenth(line, 3, newguid)) // item_instance.owner_guid update - ROLLBACK(DUMP_FILE_BROKEN); - break; - } + { + // item, owner, data field:item, owner guid + if (!changeGuid(line, 1, items, sObjectMgr->_hiItemGuid)) + ROLLBACK(DUMP_FILE_BROKEN); // item_instance.guid update + if (!changenth(line, 3, newguid)) // item_instance.owner_guid update + ROLLBACK(DUMP_FILE_BROKEN); + break; + } case DTT_ITEM_GIFT: - { - if (!changenth(line, 1, newguid)) // character_gifts.guid update - ROLLBACK(DUMP_FILE_BROKEN); - if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid)) - ROLLBACK(DUMP_FILE_BROKEN); // character_gifts.item_guid update - break; - } + { + if (!changenth(line, 1, newguid)) // character_gifts.guid update + ROLLBACK(DUMP_FILE_BROKEN); + if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid)) + ROLLBACK(DUMP_FILE_BROKEN); // character_gifts.item_guid update + break; + } case DTT_PET: - { - //store a map of old pet id to new inserted pet id for use by type 5 tables - snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); - if (*lastpetid == '\0') - snprintf(lastpetid, 20, "%s", currpetid); - if (strcmp(lastpetid, currpetid) != 0) { - snprintf(newpetid, 20, "%d", sObjectMgr->GeneratePetNumber()); - snprintf(lastpetid, 20, "%s", currpetid); + //store a map of old pet id to new inserted pet id for use by type 5 tables + snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); + if (*lastpetid == '\0') + snprintf(lastpetid, 20, "%s", currpetid); + if (strcmp(lastpetid, currpetid) != 0) + { + snprintf(newpetid, 20, "%d", sObjectMgr->GeneratePetNumber()); + snprintf(lastpetid, 20, "%s", currpetid); + } + + std::map :: const_iterator petids_iter = petids.find(atoi(currpetid)); + + if (petids_iter == petids.end()) + { + petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid))); + } + + if (!changenth(line, 1, newpetid)) // character_pet.id update + ROLLBACK(DUMP_FILE_BROKEN); + if (!changenth(line, 3, newguid)) // character_pet.owner update + ROLLBACK(DUMP_FILE_BROKEN); + + break; } - - std::map :: const_iterator petids_iter = petids.find(atoi(currpetid)); - - if (petids_iter == petids.end()) - { - petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid))); - } - - if (!changenth(line, 1, newpetid)) // character_pet.id update - ROLLBACK(DUMP_FILE_BROKEN); - if (!changenth(line, 3, newguid)) // character_pet.owner update - ROLLBACK(DUMP_FILE_BROKEN); - - break; - } case DTT_PET_TABLE: // pet_aura, pet_spell, pet_spell_cooldown - { - snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); + { + snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); - // lookup currpetid and match to new inserted pet id - std::map :: const_iterator petids_iter = petids.find(atoi(currpetid)); - if (petids_iter == petids.end()) // couldn't find new inserted id - ROLLBACK(DUMP_FILE_BROKEN); + // lookup currpetid and match to new inserted pet id + std::map :: const_iterator petids_iter = petids.find(atoi(currpetid)); + if (petids_iter == petids.end()) // couldn't find new inserted id + ROLLBACK(DUMP_FILE_BROKEN); - snprintf(newpetid, 20, "%d", petids_iter->second); + snprintf(newpetid, 20, "%d", petids_iter->second); - if (!changenth(line, 1, newpetid)) - ROLLBACK(DUMP_FILE_BROKEN); + if (!changenth(line, 1, newpetid)) + ROLLBACK(DUMP_FILE_BROKEN); - break; - } + break; + } default: sLog->outError("Unknown dump table type: %u", type); break; diff --git a/src/server/game/Tools/PlayerDump.h b/src/server/game/Tools/PlayerDump.h index 7f370bbdf..7c9989be1 100644 --- a/src/server/game/Tools/PlayerDump.h +++ b/src/server/game/Tools/PlayerDump.h @@ -16,22 +16,22 @@ enum DumpTableType DTT_CHARACTER, // // characters DTT_CHAR_TABLE, // // character_achievement, character_achievement_progress, - // character_action, character_aura, character_homebind, - // character_queststatus, character_queststatus_rewarded, character_reputation, - // character_spell, character_spell_cooldown, character_ticket, character_talent + // character_action, character_aura, character_homebind, + // character_queststatus, character_queststatus_rewarded, character_reputation, + // character_spell, character_spell_cooldown, character_ticket, character_talent DTT_EQSET_TABLE, // <- guid // character_equipmentsets DTT_INVENTORY, // -> item guids collection // character_inventory DTT_MAIL, // -> mail ids collection // mail - // -> item_text + // -> item_text DTT_MAIL_ITEM, // <- mail ids // mail_items - // -> item guids collection + // -> item guids collection DTT_ITEM, // <- item guids // item_instance - // -> item_text + // -> item_text DTT_ITEM_GIFT, // <- item guids // character_gifts @@ -51,35 +51,35 @@ enum DumpReturn class PlayerDump { - protected: - PlayerDump() {} +protected: + PlayerDump() {} }; class PlayerDumpWriter : public PlayerDump { - public: - PlayerDumpWriter() {} +public: + PlayerDumpWriter() {} - bool GetDump(uint32 guid, std::string& dump); - DumpReturn WriteDump(std::string const& file, uint32 guid); - private: - typedef std::set GUIDs; + bool GetDump(uint32 guid, std::string& dump); + DumpReturn WriteDump(std::string const& file, uint32 guid); +private: + typedef std::set GUIDs; - bool DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type); - std::string GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr); - std::string GenerateWhereStr(char const* field, uint32 guid); + bool DumpTable(std::string& dump, uint32 guid, char const* tableFrom, char const* tableTo, DumpTableType type); + std::string GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr); + std::string GenerateWhereStr(char const* field, uint32 guid); - GUIDs pets; - GUIDs mails; - GUIDs items; + GUIDs pets; + GUIDs mails; + GUIDs items; }; class PlayerDumpReader : public PlayerDump { - public: - PlayerDumpReader() {} +public: + PlayerDumpReader() {} - DumpReturn LoadDump(std::string const& file, uint32 account, std::string name, uint32 guid); + DumpReturn LoadDump(std::string const& file, uint32 account, std::string name, uint32 guid); }; #endif diff --git a/src/server/game/Warden/Warden.cpp b/src/server/game/Warden/Warden.cpp index 14386ec2d..40f20da38 100644 --- a/src/server/game/Warden/Warden.cpp +++ b/src/server/game/Warden/Warden.cpp @@ -20,8 +20,8 @@ #include "BanManager.h" Warden::Warden() : _session(nullptr), _inputCrypto(16), _outputCrypto(16), _checkTimer(10000/*10 sec*/), _clientResponseTimer(0), - _dataSent(false), _previousTimestamp(0), _module(nullptr), _initialized(false) -{ + _dataSent(false), _previousTimestamp(0), _module(nullptr), _initialized(false) +{ memset(_inputKey, 0, sizeof(_inputKey)); memset(_outputKey, 0, sizeof(_outputKey)); memset(_seed, 0, sizeof(_seed)); @@ -144,7 +144,8 @@ bool Warden::IsValidCheckSum(uint32 checksum, const uint8* data, const uint16 le } } -struct keyData { +struct keyData +{ union { struct @@ -184,56 +185,115 @@ std::string Warden::Penalty(WardenCheck* check /*= NULL*/, uint16 checkFailed /* if (checkFailed) switch (checkFailed) { - case 47: banReason += " (FrameXML Signature Check)"; break; - case 51: banReason += " (Lua DoString)"; break; - case 59: banReason += " (Lua Protection Patch)"; break; - case 72: banReason += " (Movement State related)"; break; - case 118: banReason += " (Wall Climb)"; break; - case 121: banReason += " (No Fall Damage Patch)"; break; - case 193: banReason += " (Follow Unit Check)"; break; - case 209: banReason += " (WoWEmuHacker Injection)"; longBan = true; break; - case 237: banReason += " (AddChatMessage)"; break; - case 246: banReason += " (Language Patch)"; break; - case 260: banReason += " (Jump Momentum)"; break; - case 288: banReason += " (Language Patch)"; break; - case 308: banReason += " (SendChatMessage)"; break; - case 312: banReason += " (Jump Physics)"; break; - case 314: banReason += " (GetCharacterInfo)"; break; - case 329: banReason += " (Wall Climb)"; break; - case 343: banReason += " (Login Password Pointer)"; break; - case 349: banReason += " (Language Patch)"; break; - case 712: banReason += " (WS2_32.Send)"; break; - case 780: banReason += " (Lua Protection Remover)"; break; - case 781: banReason += " (Walk on Water Patch)"; break; - case 782: banReason += " (Collision M2 Special)"; longBan = true; break; - case 783: banReason += " (Collision M2 Regular)"; longBan = true; break; - case 784: banReason += " (Collision WMD)"; longBan = true; break; - case 785: banReason += " (Multi-Jump Patch)"; break; - case 786: banReason += " (WPE PRO)"; longBan = true; break; - case 787: banReason += " (rEdoX Packet Editor)"; break; + case 47: + banReason += " (FrameXML Signature Check)"; + break; + case 51: + banReason += " (Lua DoString)"; + break; + case 59: + banReason += " (Lua Protection Patch)"; + break; + case 72: + banReason += " (Movement State related)"; + break; + case 118: + banReason += " (Wall Climb)"; + break; + case 121: + banReason += " (No Fall Damage Patch)"; + break; + case 193: + banReason += " (Follow Unit Check)"; + break; + case 209: + banReason += " (WoWEmuHacker Injection)"; + longBan = true; + break; + case 237: + banReason += " (AddChatMessage)"; + break; + case 246: + banReason += " (Language Patch)"; + break; + case 260: + banReason += " (Jump Momentum)"; + break; + case 288: + banReason += " (Language Patch)"; + break; + case 308: + banReason += " (SendChatMessage)"; + break; + case 312: + banReason += " (Jump Physics)"; + break; + case 314: + banReason += " (GetCharacterInfo)"; + break; + case 329: + banReason += " (Wall Climb)"; + break; + case 343: + banReason += " (Login Password Pointer)"; + break; + case 349: + banReason += " (Language Patch)"; + break; + case 712: + banReason += " (WS2_32.Send)"; + break; + case 780: + banReason += " (Lua Protection Remover)"; + break; + case 781: + banReason += " (Walk on Water Patch)"; + break; + case 782: + banReason += " (Collision M2 Special)"; + longBan = true; + break; + case 783: + banReason += " (Collision M2 Regular)"; + longBan = true; + break; + case 784: + banReason += " (Collision WMD)"; + longBan = true; + break; + case 785: + banReason += " (Multi-Jump Patch)"; + break; + case 786: + banReason += " (WPE PRO)"; + longBan = true; + break; + case 787: + banReason += " (rEdoX Packet Editor)"; + break; } switch (action) { - case WARDEN_ACTION_LOG: - return "None"; - break; - case WARDEN_ACTION_KICK: - _session->KickPlayer("WARDEN_ACTION_KICK"); - return "Kick"; - break; - case WARDEN_ACTION_BAN: - { - std::stringstream duration; - duration << sWorld->getIntConfig(CONFIG_WARDEN_CLIENT_BAN_DURATION) << "s"; - std::string accountName; - AccountMgr::GetName(_session->GetAccountId(), accountName); - sBan->BanAccount(accountName, ((longBan && false /*ZOMG!*/) ? "1209600s" : duration.str()), banReason, "Server"); + case WARDEN_ACTION_LOG: + return "None"; + break; + case WARDEN_ACTION_KICK: + _session->KickPlayer("WARDEN_ACTION_KICK"); + return "Kick"; + break; + case WARDEN_ACTION_BAN: + { + std::stringstream duration; + duration << sWorld->getIntConfig(CONFIG_WARDEN_CLIENT_BAN_DURATION) << "s"; + std::string accountName; + AccountMgr::GetName(_session->GetAccountId(), accountName); + sBan->BanAccount(accountName, ((longBan && false /*ZOMG!*/) ? "1209600s" : duration.str()), banReason, "Server"); - return "Ban"; - } - default: - break; + return "Ban"; + } + default: + break; } return "Undefined"; } diff --git a/src/server/game/Warden/Warden.h b/src/server/game/Warden/Warden.h index 2dafd35dc..103301195 100644 --- a/src/server/game/Warden/Warden.h +++ b/src/server/game/Warden/Warden.h @@ -93,43 +93,43 @@ class Warden friend class WardenWin; friend class WardenMac; - public: - Warden(); - virtual ~Warden(); +public: + Warden(); + virtual ~Warden(); - virtual void Init(WorldSession* session, BigNumber* k) = 0; - virtual ClientWardenModule* GetModuleForClient() = 0; - virtual void InitializeModule() = 0; - virtual void RequestHash() = 0; - virtual void HandleHashResult(ByteBuffer &buff) = 0; - virtual void RequestData() = 0; - virtual void HandleData(ByteBuffer &buff) = 0; + virtual void Init(WorldSession* session, BigNumber* k) = 0; + virtual ClientWardenModule* GetModuleForClient() = 0; + virtual void InitializeModule() = 0; + virtual void RequestHash() = 0; + virtual void HandleHashResult(ByteBuffer& buff) = 0; + virtual void RequestData() = 0; + virtual void HandleData(ByteBuffer& buff) = 0; - void SendModuleToClient(); - void RequestModule(); - void Update(); - void DecryptData(uint8* buffer, uint32 length); - void EncryptData(uint8* buffer, uint32 length); + void SendModuleToClient(); + void RequestModule(); + void Update(); + void DecryptData(uint8* buffer, uint32 length); + void EncryptData(uint8* buffer, uint32 length); - static bool IsValidCheckSum(uint32 checksum, const uint8 *data, const uint16 length); - static uint32 BuildChecksum(const uint8 *data, uint32 length); + static bool IsValidCheckSum(uint32 checksum, const uint8* data, const uint16 length); + static uint32 BuildChecksum(const uint8* data, uint32 length); - // If no check is passed, the default action from config is executed - std::string Penalty(WardenCheck* check = NULL, uint16 checkFailed = 0); + // If no check is passed, the default action from config is executed + std::string Penalty(WardenCheck* check = NULL, uint16 checkFailed = 0); - private: - WorldSession* _session; - uint8 _inputKey[16]; - uint8 _outputKey[16]; - uint8 _seed[16]; - ARC4 _inputCrypto; - ARC4 _outputCrypto; - uint32 _checkTimer; // Timer for sending check requests - uint32 _clientResponseTimer; // Timer for client response delay - bool _dataSent; - uint32 _previousTimestamp; - ClientWardenModule* _module; - bool _initialized; +private: + WorldSession* _session; + uint8 _inputKey[16]; + uint8 _outputKey[16]; + uint8 _seed[16]; + ARC4 _inputCrypto; + ARC4 _outputCrypto; + uint32 _checkTimer; // Timer for sending check requests + uint32 _clientResponseTimer; // Timer for client response delay + bool _dataSent; + uint32 _previousTimestamp; + ClientWardenModule* _module; + bool _initialized; }; #endif diff --git a/src/server/game/Warden/WardenCheckMgr.cpp b/src/server/game/Warden/WardenCheckMgr.cpp index b22c60cbe..84beb4e37 100644 --- a/src/server/game/Warden/WardenCheckMgr.cpp +++ b/src/server/game/Warden/WardenCheckMgr.cpp @@ -115,12 +115,12 @@ void WardenCheckMgr::LoadWardenChecks() if (checkType == MPQ_CHECK || checkType == MEM_CHECK) { - WardenCheckResult *wr = new WardenCheckResult(); + WardenCheckResult* wr = new WardenCheckResult(); wr->Result.SetHexStr(checkResult.c_str()); int len = checkResult.size() / 2; if (wr->Result.GetNumBytes() < len) { - uint8 *temp = new uint8[len]; + uint8* temp = new uint8[len]; memset(temp, 0, len); memcpy(temp, wr->Result.AsByteArray().get(), wr->Result.GetNumBytes()); std::reverse(temp, temp + len); @@ -136,8 +136,7 @@ void WardenCheckMgr::LoadWardenChecks() wardenCheck->Comment = comment; ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u warden checks.", count); sLog->outString(); @@ -185,8 +184,7 @@ void WardenCheckMgr::LoadWardenOverrides() CheckStore[checkId]->Action = WardenActions(action); ++count; } - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u warden action overrides.", count); sLog->outString(); diff --git a/src/server/game/Warden/WardenCheckMgr.h b/src/server/game/Warden/WardenCheckMgr.h index 9e1c05e7c..5b55770dd 100644 --- a/src/server/game/Warden/WardenCheckMgr.h +++ b/src/server/game/Warden/WardenCheckMgr.h @@ -39,27 +39,27 @@ class WardenCheckMgr WardenCheckMgr(); ~WardenCheckMgr(); - public: - static WardenCheckMgr* instance(); +public: + static WardenCheckMgr* instance(); - // We have a linear key without any gaps, so we use vector for fast access - typedef std::vector CheckContainer; - typedef std::map CheckResultContainer; + // We have a linear key without any gaps, so we use vector for fast access + typedef std::vector CheckContainer; + typedef std::map CheckResultContainer; - WardenCheck* GetWardenDataById(uint16 Id); - WardenCheckResult* GetWardenResultById(uint16 Id); + WardenCheck* GetWardenDataById(uint16 Id); + WardenCheckResult* GetWardenResultById(uint16 Id); - std::vector MemChecksIdPool; - std::vector OtherChecksIdPool; + std::vector MemChecksIdPool; + std::vector OtherChecksIdPool; - void LoadWardenChecks(); - void LoadWardenOverrides(); + void LoadWardenChecks(); + void LoadWardenOverrides(); - ACE_RW_Mutex _checkStoreLock; + ACE_RW_Mutex _checkStoreLock; - private: - CheckContainer CheckStore; - CheckResultContainer CheckResultStore; +private: + CheckContainer CheckStore; + CheckResultContainer CheckResultStore; }; #define sWardenCheckMgr WardenCheckMgr::instance() diff --git a/src/server/game/Warden/WardenMac.cpp b/src/server/game/Warden/WardenMac.cpp index 588c7d32d..6259baf1a 100644 --- a/src/server/game/Warden/WardenMac.cpp +++ b/src/server/game/Warden/WardenMac.cpp @@ -26,7 +26,7 @@ WardenMac::~WardenMac() { } -void WardenMac::Init(WorldSession *pClient, BigNumber *K) +void WardenMac::Init(WorldSession* pClient, BigNumber* K) { _session = pClient; // Generate Warden Key @@ -65,7 +65,7 @@ void WardenMac::Init(WorldSession *pClient, BigNumber *K) ClientWardenModule* WardenMac::GetModuleForClient() { - ClientWardenModule *mod = new ClientWardenModule; + ClientWardenModule* mod = new ClientWardenModule; uint32 len = sizeof(Module_0DBBF209A27B1E279A9FEC5C168A15F7_Data); @@ -110,7 +110,8 @@ void WardenMac::RequestHash() _session->SendPacket(&pkt); } -struct keyData { +struct keyData +{ union { struct @@ -125,7 +126,7 @@ struct keyData { }; }; -void WardenMac::HandleHashResult(ByteBuffer &buff) +void WardenMac::HandleHashResult(ByteBuffer& buff) { // test @@ -218,7 +219,7 @@ void WardenMac::RequestData() _dataSent = true; } -void WardenMac::HandleData(ByteBuffer &buff) +void WardenMac::HandleData(ByteBuffer& buff) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_WARDEN, "Handle data"); diff --git a/src/server/game/Warden/WardenMac.h b/src/server/game/Warden/WardenMac.h index de6fbecc5..b2b8812fe 100644 --- a/src/server/game/Warden/WardenMac.h +++ b/src/server/game/Warden/WardenMac.h @@ -18,17 +18,17 @@ class Warden; class WardenMac : public Warden { - public: - WardenMac(); - ~WardenMac(); +public: + WardenMac(); + ~WardenMac(); - void Init(WorldSession* session, BigNumber* k); - ClientWardenModule* GetModuleForClient(); - void InitializeModule(); - void RequestHash(); - void HandleHashResult(ByteBuffer& buff); - void RequestData(); - void HandleData(ByteBuffer& buff); + void Init(WorldSession* session, BigNumber* k); + ClientWardenModule* GetModuleForClient(); + void InitializeModule(); + void RequestHash(); + void HandleHashResult(ByteBuffer& buff); + void RequestData(); + void HandleData(ByteBuffer& buff); }; #endif diff --git a/src/server/game/Warden/WardenWin.cpp b/src/server/game/Warden/WardenWin.cpp index 4bf09d262..7f56afa22 100644 --- a/src/server/game/Warden/WardenWin.cpp +++ b/src/server/game/Warden/WardenWin.cpp @@ -41,7 +41,7 @@ WardenWin::~WardenWin() sLog->outDebug(LOG_FILTER_POOLSYS, "IM DESTRUCTING MYSELF QQ, OTHERSIZE: %u, OTHEREM: %u, MEMSIZE: %u, MEMEM: %u, CURSIZE: %u, CUREM: %u!\n", otherSize, otherClear, memSize, memClear, curSize, curClear); } -void WardenWin::Init(WorldSession* session, BigNumber *k) +void WardenWin::Init(WorldSession* session, BigNumber* k) { _session = session; // Generate Warden Key @@ -72,7 +72,7 @@ void WardenWin::Init(WorldSession* session, BigNumber *k) ClientWardenModule* WardenWin::GetModuleForClient() { - ClientWardenModule *mod = new ClientWardenModule; + ClientWardenModule* mod = new ClientWardenModule; uint32 length = sizeof(Module.Module); @@ -156,7 +156,7 @@ void WardenWin::RequestHash() _session->SendPacket(&pkt); } -void WardenWin::HandleHashResult(ByteBuffer &buff) +void WardenWin::HandleHashResult(ByteBuffer& buff) { buff.rpos(buff.wpos()); @@ -221,7 +221,8 @@ void WardenWin::RequestData() if (id != 786 /*WPE PRO*/ && id != 209 /*WoWEmuHacker*/) _currentChecks.push_back(id); } - _currentChecks.push_back(786); _currentChecks.push_back(209); + _currentChecks.push_back(786); + _currentChecks.push_back(209); ByteBuffer buff; buff << uint8(WARDEN_SMSG_CHEAT_CHECKS_REQUEST); @@ -274,42 +275,42 @@ void WardenWin::RequestData() switch (type) { case MEM_CHECK: - { - buff << uint8(0x00); - buff << uint32(wd->Address); - buff << uint8(wd->Length); - break; - } + { + buff << uint8(0x00); + buff << uint32(wd->Address); + buff << uint8(wd->Length); + break; + } case PAGE_CHECK_A: case PAGE_CHECK_B: - { - buff.append(wd->Data.AsByteArray(0, false).get(), wd->Data.GetNumBytes()); - buff << uint32(wd->Address); - buff << uint8(wd->Length); - break; - } + { + buff.append(wd->Data.AsByteArray(0, false).get(), wd->Data.GetNumBytes()); + buff << uint32(wd->Address); + buff << uint8(wd->Length); + break; + } case MPQ_CHECK: case LUA_STR_CHECK: - { - buff << uint8(index++); - break; - } + { + buff << uint8(index++); + break; + } case DRIVER_CHECK: - { - buff.append(wd->Data.AsByteArray(0, false).get(), wd->Data.GetNumBytes()); - buff << uint8(index++); - break; - } + { + buff.append(wd->Data.AsByteArray(0, false).get(), wd->Data.GetNumBytes()); + buff << uint8(index++); + break; + } case MODULE_CHECK: - { - uint32 seed = rand32(); - buff << uint32(seed); - HmacHash hmac(4, (uint8*)&seed); - hmac.UpdateData(wd->Str); - hmac.Finalize(); - buff.append(hmac.GetDigest(), hmac.GetLength()); - break; - } + { + uint32 seed = rand32(); + buff << uint32(seed); + HmacHash hmac(4, (uint8*)&seed); + hmac.UpdateData(wd->Str); + hmac.Finalize(); + buff.append(hmac.GetDigest(), hmac.GetLength()); + break; + } /*case PROC_CHECK: { buff.append(wd->i.AsByteArray(0, false).get(), wd->i.GetNumBytes()); @@ -345,7 +346,7 @@ void WardenWin::RequestData() #endif } -void WardenWin::HandleData(ByteBuffer &buff) +void WardenWin::HandleData(ByteBuffer& buff) { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) sLog->outDebug(LOG_FILTER_WARDEN, "Handle data"); @@ -397,8 +398,8 @@ void WardenWin::HandleData(ByteBuffer &buff) #endif } - WardenCheckResult *rs; - WardenCheck *rd; + WardenCheckResult* rs; + WardenCheck* rd; uint8 type; uint16 checkFailed = 0; @@ -413,133 +414,133 @@ void WardenWin::HandleData(ByteBuffer &buff) switch (type) { case MEM_CHECK: - { - uint8 Mem_Result; - buff >> Mem_Result; - - if (Mem_Result != 0) { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MEM_CHECK not 0x00, CheckId %u account Id %u", *itr, _session->GetAccountId()); -#endif - checkFailed = *itr; - continue; - } + uint8 Mem_Result; + buff >> Mem_Result; - if (memcmp(buff.contents() + buff.rpos(), rs->Result.AsByteArray(0, false).get(), rd->Length) != 0) - { + if (Mem_Result != 0) + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MEM_CHECK fail CheckId %u account Id %u", *itr, _session->GetAccountId()); + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MEM_CHECK not 0x00, CheckId %u account Id %u", *itr, _session->GetAccountId()); #endif - checkFailed = *itr; + checkFailed = *itr; + continue; + } + + if (memcmp(buff.contents() + buff.rpos(), rs->Result.AsByteArray(0, false).get(), rd->Length) != 0) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MEM_CHECK fail CheckId %u account Id %u", *itr, _session->GetAccountId()); +#endif + checkFailed = *itr; + buff.rpos(buff.rpos() + rd->Length); + continue; + } + buff.rpos(buff.rpos() + rd->Length); - continue; - } - - buff.rpos(buff.rpos() + rd->Length); #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MEM_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MEM_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); #endif - break; - } + break; + } case PAGE_CHECK_A: case PAGE_CHECK_B: case DRIVER_CHECK: case MODULE_CHECK: - { - const uint8 byte = 0xE9; - if (memcmp(buff.contents() + buff.rpos(), &byte, sizeof(uint8)) != 0) { + const uint8 byte = 0xE9; + if (memcmp(buff.contents() + buff.rpos(), &byte, sizeof(uint8)) != 0) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + if (type == PAGE_CHECK_A || type == PAGE_CHECK_B) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT PAGE_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + + if (type == MODULE_CHECK) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MODULE_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + + if (type == DRIVER_CHECK) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT DRIVER_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); +#endif + checkFailed = *itr; + buff.rpos(buff.rpos() + 1); + continue; + } + + buff.rpos(buff.rpos() + 1); + #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) if (type == PAGE_CHECK_A || type == PAGE_CHECK_B) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT PAGE_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); - - if (type == MODULE_CHECK) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MODULE_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); - - if (type == DRIVER_CHECK) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT DRIVER_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT PAGE_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); + else if (type == MODULE_CHECK) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MODULE_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); + else if (type == DRIVER_CHECK) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT DRIVER_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); #endif - checkFailed = *itr; - buff.rpos(buff.rpos() + 1); - continue; + break; } - - buff.rpos(buff.rpos() + 1); - -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - if (type == PAGE_CHECK_A || type == PAGE_CHECK_B) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT PAGE_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); - else if (type == MODULE_CHECK) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MODULE_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); - else if (type == DRIVER_CHECK) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT DRIVER_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); -#endif - break; - } case LUA_STR_CHECK: - { - uint8 Lua_Result; - buff >> Lua_Result; - - if (Lua_Result != 0) { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT LUA_STR_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); -#endif - checkFailed = *itr; - continue; - } + uint8 Lua_Result; + buff >> Lua_Result; - uint8 luaStrLen; - buff >> luaStrLen; + if (Lua_Result != 0) + { +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT LUA_STR_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); +#endif + checkFailed = *itr; + continue; + } - if (luaStrLen != 0) - { - char *str = new char[luaStrLen + 1]; - memcpy(str, buff.contents() + buff.rpos(), luaStrLen); - str[luaStrLen] = '\0'; // null terminator + uint8 luaStrLen; + buff >> luaStrLen; + + if (luaStrLen != 0) + { + char* str = new char[luaStrLen + 1]; + memcpy(str, buff.contents() + buff.rpos(), luaStrLen); + str[luaStrLen] = '\0'; // null terminator #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "Lua string: %s", str); + sLog->outDebug(LOG_FILTER_WARDEN, "Lua string: %s", str); #endif - delete[] str; + delete[] str; + } + buff.rpos(buff.rpos() + luaStrLen); // Skip string +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT LUA_STR_CHECK passed, CheckId %u account Id %u", *itr, _session->GetAccountId()); +#endif + break; } - buff.rpos(buff.rpos() + luaStrLen); // Skip string -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT LUA_STR_CHECK passed, CheckId %u account Id %u", *itr, _session->GetAccountId()); -#endif - break; - } case MPQ_CHECK: - { - uint8 Mpq_Result; - buff >> Mpq_Result; - - if (Mpq_Result != 0) { -#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MPQ_CHECK not 0x00 account id %u", _session->GetAccountId()); -#endif - checkFailed = *itr; - continue; - } + uint8 Mpq_Result; + buff >> Mpq_Result; - if (memcmp(buff.contents() + buff.rpos(), rs->Result.AsByteArray(0, false).get(), 20) != 0) // SHA1 - { + if (Mpq_Result != 0) + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MPQ_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MPQ_CHECK not 0x00 account id %u", _session->GetAccountId()); #endif - checkFailed = *itr; - buff.rpos(buff.rpos() + 20); // 20 bytes SHA1 - continue; - } + checkFailed = *itr; + continue; + } - buff.rpos(buff.rpos() + 20); // 20 bytes SHA1 + if (memcmp(buff.contents() + buff.rpos(), rs->Result.AsByteArray(0, false).get(), 20) != 0) // SHA1 + { #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MPQ_CHECK passed, CheckId %u account Id %u", *itr, _session->GetAccountId()); + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MPQ_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); #endif - break; - } + checkFailed = *itr; + buff.rpos(buff.rpos() + 20); // 20 bytes SHA1 + continue; + } + + buff.rpos(buff.rpos() + 20); // 20 bytes SHA1 +#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) + sLog->outDebug(LOG_FILTER_WARDEN, "RESULT MPQ_CHECK passed, CheckId %u account Id %u", *itr, _session->GetAccountId()); +#endif + break; + } default: // Should never happen break; } diff --git a/src/server/game/Warden/WardenWin.h b/src/server/game/Warden/WardenWin.h index da5f84ef9..66bab96be 100644 --- a/src/server/game/Warden/WardenWin.h +++ b/src/server/game/Warden/WardenWin.h @@ -60,23 +60,23 @@ class Warden; class WardenWin : public Warden { - public: - WardenWin(); - ~WardenWin(); +public: + WardenWin(); + ~WardenWin(); - void Init(WorldSession* session, BigNumber* K); - ClientWardenModule* GetModuleForClient(); - void InitializeModule(); - void RequestHash(); - void HandleHashResult(ByteBuffer &buff); - void RequestData(); - void HandleData(ByteBuffer &buff); + void Init(WorldSession* session, BigNumber* K); + ClientWardenModule* GetModuleForClient(); + void InitializeModule(); + void RequestHash(); + void HandleHashResult(ByteBuffer& buff); + void RequestData(); + void HandleData(ByteBuffer& buff); - private: - uint32 _serverTicks; - std::list _otherChecksTodo; - std::list _memChecksTodo; - std::list _currentChecks; +private: + uint32 _serverTicks; + std::list _otherChecksTodo; + std::list _memChecksTodo; + std::list _currentChecks; }; #endif diff --git a/src/server/game/Weather/Weather.cpp b/src/server/game/Weather/Weather.cpp index 819461cfb..0c239e4bb 100644 --- a/src/server/game/Weather/Weather.cpp +++ b/src/server/game/Weather/Weather.cpp @@ -27,7 +27,7 @@ Weather::Weather(uint32 zone, WeatherData const* weatherChances) m_grade = 0; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) - sLog->outDetail("WORLD: Starting weather system for zone %u (change every %u minutes).", m_zone, (uint32)(m_timer.GetInterval() / (MINUTE*IN_MILLISECONDS))); + sLog->outDetail("WORLD: Starting weather system for zone %u (change every %u minutes).", m_zone, (uint32)(m_timer.GetInterval() / (MINUTE * IN_MILLISECONDS))); #endif } @@ -85,7 +85,7 @@ bool Weather::ReGenerate() time_t gtime = sWorld->GetGameTime(); struct tm ltime; localtime_r(>ime, <ime); - uint32 season = ((ltime.tm_yday - 78 + 365)/91)%4; + uint32 season = ((ltime.tm_yday - 78 + 365) / 91) % 4; #if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS) static char const* seasonName[WEATHER_SEASONS] = { "spring", "summer", "fall", "winter" }; @@ -126,7 +126,7 @@ bool Weather::ReGenerate() { if (m_grade > 0.6666667f) { - // Severe change, but how severe? + // Severe change, but how severe? uint32 rnd = urand(0, 99); if (rnd < 50) { @@ -141,8 +141,8 @@ bool Weather::ReGenerate() // At this point, only weather that isn't doing anything remains but that have weather data uint32 chance1 = m_weatherChances->data[season].rainChance; - uint32 chance2 = chance1+ m_weatherChances->data[season].snowChance; - uint32 chance3 = chance2+ m_weatherChances->data[season].stormChance; + uint32 chance2 = chance1 + m_weatherChances->data[season].snowChance; + uint32 chance3 = chance2 + m_weatherChances->data[season].stormChance; uint32 rnd = urand(0, 99); if (rnd <= chance1) @@ -277,29 +277,29 @@ void Weather::SetWeather(WeatherType type, float grade) /// Get the sound number associated with the current weather WeatherState Weather::GetWeatherState() const { - if (m_grade<0.27f) + if (m_grade < 0.27f) return WEATHER_STATE_FINE; switch (m_type) { case WEATHER_TYPE_RAIN: - if (m_grade<0.40f) + if (m_grade < 0.40f) return WEATHER_STATE_LIGHT_RAIN; - else if (m_grade<0.70f) + else if (m_grade < 0.70f) return WEATHER_STATE_MEDIUM_RAIN; else return WEATHER_STATE_HEAVY_RAIN; case WEATHER_TYPE_SNOW: - if (m_grade<0.40f) + if (m_grade < 0.40f) return WEATHER_STATE_LIGHT_SNOW; - else if (m_grade<0.70f) + else if (m_grade < 0.70f) return WEATHER_STATE_MEDIUM_SNOW; else return WEATHER_STATE_HEAVY_SNOW; case WEATHER_TYPE_STORM: - if (m_grade<0.40f) + if (m_grade < 0.40f) return WEATHER_STATE_LIGHT_SANDSTORM; - else if (m_grade<0.70f) + else if (m_grade < 0.70f) return WEATHER_STATE_MEDIUM_SANDSTORM; else return WEATHER_STATE_HEAVY_SANDSTORM; diff --git a/src/server/game/Weather/Weather.h b/src/server/game/Weather/Weather.h index f73b574ef..3c5b5e036 100644 --- a/src/server/game/Weather/Weather.h +++ b/src/server/game/Weather/Weather.h @@ -52,29 +52,29 @@ enum WeatherState /// Weather for one zone class Weather { - public: +public: - Weather(uint32 zone, WeatherData const* weatherChances); - ~Weather() { }; + Weather(uint32 zone, WeatherData const* weatherChances); + ~Weather() { }; - bool Update(uint32 diff); - bool ReGenerate(); - bool UpdateWeather(); + bool Update(uint32 diff); + bool ReGenerate(); + bool UpdateWeather(); - void SendWeatherUpdateToPlayer(Player* player); - void SetWeather(WeatherType type, float grade); + void SendWeatherUpdateToPlayer(Player* player); + void SetWeather(WeatherType type, float grade); - /// For which zone is this weather? - uint32 GetZone() const { return m_zone; }; - uint32 GetScriptId() const { return m_weatherChances->ScriptId; } + /// For which zone is this weather? + uint32 GetZone() const { return m_zone; }; + uint32 GetScriptId() const { return m_weatherChances->ScriptId; } - private: +private: - WeatherState GetWeatherState() const; - uint32 m_zone; - WeatherType m_type; - float m_grade; - IntervalTimer m_timer; - WeatherData const* m_weatherChances; + WeatherState GetWeatherState() const; + uint32 m_zone; + WeatherType m_type; + float m_grade; + IntervalTimer m_timer; + WeatherData const* m_weatherChances; }; #endif diff --git a/src/server/game/Weather/WeatherMgr.cpp b/src/server/game/Weather/WeatherMgr.cpp index f4ebb73bb..3d0863f80 100644 --- a/src/server/game/Weather/WeatherMgr.cpp +++ b/src/server/game/Weather/WeatherMgr.cpp @@ -20,141 +20,140 @@ namespace WeatherMgr { -namespace -{ - typedef std::unordered_map > WeatherMap; - typedef std::unordered_map WeatherZoneMap; - - WeatherMap m_weathers; - WeatherZoneMap mWeatherZoneMap; - - WeatherData const* GetWeatherData(uint32 zone_id) + namespace { - WeatherZoneMap::const_iterator itr = mWeatherZoneMap.find(zone_id); - return (itr != mWeatherZoneMap.end()) ? &itr->second : nullptr; - } -} + typedef std::unordered_map > WeatherMap; + typedef std::unordered_map WeatherZoneMap; -/// Find a Weather object by the given zoneid -Weather* FindWeather(uint32 id) -{ - WeatherMap::const_iterator itr = m_weathers.find(id); - return (itr != m_weathers.end()) ? itr->second.get() : 0; -} + WeatherMap m_weathers; + WeatherZoneMap mWeatherZoneMap; -/// Remove a Weather object for the given zoneid -void RemoveWeather(uint32 id) -{ - // not called at the moment. Kept for completeness - WeatherMap::iterator itr = m_weathers.find(id); - - if (itr != m_weathers.end()) - m_weathers.erase(itr); -} - -/// Add a Weather object to the list -Weather* AddWeather(uint32 zone_id) -{ - WeatherData const* weatherChances = GetWeatherData(zone_id); - - // zone does not have weather, ignore - if (!weatherChances) - return nullptr; - - Weather* w = new Weather(zone_id, weatherChances); - m_weathers[w->GetZone()].reset(w); - w->ReGenerate(); - w->UpdateWeather(); - - return w; -} - -void LoadWeatherData() -{ - uint32 oldMSTime = getMSTime(); - - uint32 count = 0; - - QueryResult result = WorldDatabase.Query("SELECT " - "zone, spring_rain_chance, spring_snow_chance, spring_storm_chance," - "summer_rain_chance, summer_snow_chance, summer_storm_chance," - "fall_rain_chance, fall_snow_chance, fall_storm_chance," - "winter_rain_chance, winter_snow_chance, winter_storm_chance," - "ScriptName FROM game_weather"); - - if (!result) - { - sLog->outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty."); - sLog->outString(); - return; - } - - do - { - Field* fields = result->Fetch(); - - uint32 zone_id = fields[0].GetUInt32(); - - WeatherData& wzc = mWeatherZoneMap[zone_id]; - - for (uint8 season = 0; season < WEATHER_SEASONS; ++season) + WeatherData const* GetWeatherData(uint32 zone_id) { - wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE-1) + 1].GetUInt8(); - wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE-1) + 2].GetUInt8(); - wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE-1) + 3].GetUInt8(); - - if (wzc.data[season].rainChance > 100) - { - wzc.data[season].rainChance = 25; - sLog->outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%", zone_id, season); - } - - if (wzc.data[season].snowChance > 100) - { - wzc.data[season].snowChance = 25; - sLog->outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%", zone_id, season); - } - - if (wzc.data[season].stormChance > 100) - { - wzc.data[season].stormChance = 25; - sLog->outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%", zone_id, season); - } + WeatherZoneMap::const_iterator itr = mWeatherZoneMap.find(zone_id); + return (itr != mWeatherZoneMap.end()) ? &itr->second : nullptr; } - - wzc.ScriptId = sObjectMgr->GetScriptId(fields[13].GetCString()); - - ++count; } - while (result->NextRow()); - sLog->outString(">> Loaded %u weather definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - sLog->outString(); -} - -void SendFineWeatherUpdateToPlayer(Player* player) -{ - WorldPacket data(SMSG_WEATHER, (4 + 4 + 1)); - data << (uint32)WEATHER_STATE_FINE; - data << (float)0.0f; - data << uint8(0); - player->GetSession()->SendPacket(&data); -} - -void Update(uint32 diff) -{ - ///- Send an update signal to Weather objects - WeatherMap::iterator itr, next; - for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next) + /// Find a Weather object by the given zoneid + Weather* FindWeather(uint32 id) { - next = itr; - ++next; + WeatherMap::const_iterator itr = m_weathers.find(id); + return (itr != m_weathers.end()) ? itr->second.get() : 0; + } - ///- and remove Weather objects for zones with no player - // As interval > WorldTick - if (!itr->second->Update(diff)) + /// Remove a Weather object for the given zoneid + void RemoveWeather(uint32 id) + { + // not called at the moment. Kept for completeness + WeatherMap::iterator itr = m_weathers.find(id); + + if (itr != m_weathers.end()) m_weathers.erase(itr); } -} + + /// Add a Weather object to the list + Weather* AddWeather(uint32 zone_id) + { + WeatherData const* weatherChances = GetWeatherData(zone_id); + + // zone does not have weather, ignore + if (!weatherChances) + return nullptr; + + Weather* w = new Weather(zone_id, weatherChances); + m_weathers[w->GetZone()].reset(w); + w->ReGenerate(); + w->UpdateWeather(); + + return w; + } + + void LoadWeatherData() + { + uint32 oldMSTime = getMSTime(); + + uint32 count = 0; + + QueryResult result = WorldDatabase.Query("SELECT " + "zone, spring_rain_chance, spring_snow_chance, spring_storm_chance," + "summer_rain_chance, summer_snow_chance, summer_storm_chance," + "fall_rain_chance, fall_snow_chance, fall_storm_chance," + "winter_rain_chance, winter_snow_chance, winter_storm_chance," + "ScriptName FROM game_weather"); + + if (!result) + { + sLog->outErrorDb(">> Loaded 0 weather definitions. DB table `game_weather` is empty."); + sLog->outString(); + return; + } + + do + { + Field* fields = result->Fetch(); + + uint32 zone_id = fields[0].GetUInt32(); + + WeatherData& wzc = mWeatherZoneMap[zone_id]; + + for (uint8 season = 0; season < WEATHER_SEASONS; ++season) + { + wzc.data[season].rainChance = fields[season * (MAX_WEATHER_TYPE - 1) + 1].GetUInt8(); + wzc.data[season].snowChance = fields[season * (MAX_WEATHER_TYPE - 1) + 2].GetUInt8(); + wzc.data[season].stormChance = fields[season * (MAX_WEATHER_TYPE - 1) + 3].GetUInt8(); + + if (wzc.data[season].rainChance > 100) + { + wzc.data[season].rainChance = 25; + sLog->outErrorDb("Weather for zone %u season %u has wrong rain chance > 100%%", zone_id, season); + } + + if (wzc.data[season].snowChance > 100) + { + wzc.data[season].snowChance = 25; + sLog->outErrorDb("Weather for zone %u season %u has wrong snow chance > 100%%", zone_id, season); + } + + if (wzc.data[season].stormChance > 100) + { + wzc.data[season].stormChance = 25; + sLog->outErrorDb("Weather for zone %u season %u has wrong storm chance > 100%%", zone_id, season); + } + } + + wzc.ScriptId = sObjectMgr->GetScriptId(fields[13].GetCString()); + + ++count; + } while (result->NextRow()); + + sLog->outString(">> Loaded %u weather definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + sLog->outString(); + } + + void SendFineWeatherUpdateToPlayer(Player* player) + { + WorldPacket data(SMSG_WEATHER, (4 + 4 + 1)); + data << (uint32)WEATHER_STATE_FINE; + data << (float)0.0f; + data << uint8(0); + player->GetSession()->SendPacket(&data); + } + + void Update(uint32 diff) + { + ///- Send an update signal to Weather objects + WeatherMap::iterator itr, next; + for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next) + { + next = itr; + ++next; + + ///- and remove Weather objects for zones with no player + // As interval > WorldTick + if (!itr->second->Update(diff)) + m_weathers.erase(itr); + } + } } // namespace diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index c9cf65bef..0be59d9e1 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -334,7 +334,7 @@ bool World::HasRecentlyDisconnected(WorldSession* session) } } return false; - } +} int32 World::GetQueuePos(WorldSession* sess) { @@ -581,7 +581,7 @@ void World::LoadConfigSettings(bool reload) else if (rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > NOMINAL_MELEE_RANGE) { sLog->outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.", - rate_values[RATE_TARGET_POS_RECALCULATION_RANGE], NOMINAL_MELEE_RANGE, NOMINAL_MELEE_RANGE); + rate_values[RATE_TARGET_POS_RECALCULATION_RANGE], NOMINAL_MELEE_RANGE, NOMINAL_MELEE_RANGE); rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = NOMINAL_MELEE_RANGE; } @@ -639,7 +639,7 @@ void World::LoadConfigSettings(bool reload) m_int_configs[CONFIG_CHAT_CHANNEL_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Channel", 1); m_int_configs[CONFIG_CHAT_WHISPER_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Whisper", 1); m_int_configs[CONFIG_CHAT_SAY_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Say", 1); - m_int_configs[CONFIG_PARTY_LEVEL_REQ] = sConfigMgr->GetIntDefault("PartyLevelReq", 1); + m_int_configs[CONFIG_PARTY_LEVEL_REQ] = sConfigMgr->GetIntDefault("PartyLevelReq", 1); m_int_configs[CONFIG_TRADE_LEVEL_REQ] = sConfigMgr->GetIntDefault("LevelReq.Trade", 1); m_int_configs[CONFIG_TICKET_LEVEL_REQ] = sConfigMgr->GetIntDefault("LevelReq.Ticket", 1); m_int_configs[CONFIG_AUCTION_LEVEL_REQ] = sConfigMgr->GetIntDefault("LevelReq.Auction", 1); @@ -822,13 +822,13 @@ void World::LoadConfigSettings(bool reload) if (m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1) { sLog->outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.", - m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL]); + m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL]); m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55; } else if (m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_int_configs[CONFIG_MAX_PLAYER_LEVEL]) { sLog->outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.", - m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL]); + m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL]); m_int_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_int_configs[CONFIG_MAX_PLAYER_LEVEL]; } @@ -836,12 +836,12 @@ void World::LoadConfigSettings(bool reload) if (int32(m_int_configs[CONFIG_START_PLAYER_MONEY]) < 0) { sLog->outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.", m_int_configs[CONFIG_START_PLAYER_MONEY], MAX_MONEY_AMOUNT, 0); - m_int_configs[CONFIG_START_PLAYER_MONEY] = 0; + m_int_configs[CONFIG_START_PLAYER_MONEY] = 0; } else if (m_int_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT) { sLog->outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.", - m_int_configs[CONFIG_START_PLAYER_MONEY], MAX_MONEY_AMOUNT, MAX_MONEY_AMOUNT); + m_int_configs[CONFIG_START_PLAYER_MONEY], MAX_MONEY_AMOUNT, MAX_MONEY_AMOUNT); m_int_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT; } @@ -856,13 +856,13 @@ void World::LoadConfigSettings(bool reload) if (int32(m_int_configs[CONFIG_START_HONOR_POINTS]) < 0) { sLog->outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.", - m_int_configs[CONFIG_START_HONOR_POINTS], m_int_configs[CONFIG_MAX_HONOR_POINTS], 0); + m_int_configs[CONFIG_START_HONOR_POINTS], m_int_configs[CONFIG_MAX_HONOR_POINTS], 0); m_int_configs[CONFIG_START_HONOR_POINTS] = 0; } else if (m_int_configs[CONFIG_START_HONOR_POINTS] > m_int_configs[CONFIG_MAX_HONOR_POINTS]) { sLog->outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.", - m_int_configs[CONFIG_START_HONOR_POINTS], m_int_configs[CONFIG_MAX_HONOR_POINTS], m_int_configs[CONFIG_MAX_HONOR_POINTS]); + m_int_configs[CONFIG_START_HONOR_POINTS], m_int_configs[CONFIG_MAX_HONOR_POINTS], m_int_configs[CONFIG_MAX_HONOR_POINTS]); m_int_configs[CONFIG_START_HONOR_POINTS] = m_int_configs[CONFIG_MAX_HONOR_POINTS]; } @@ -877,21 +877,21 @@ void World::LoadConfigSettings(bool reload) if (int32(m_int_configs[CONFIG_START_ARENA_POINTS]) < 0) { sLog->outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.", - m_int_configs[CONFIG_START_ARENA_POINTS], m_int_configs[CONFIG_MAX_ARENA_POINTS], 0); + m_int_configs[CONFIG_START_ARENA_POINTS], m_int_configs[CONFIG_MAX_ARENA_POINTS], 0); m_int_configs[CONFIG_START_ARENA_POINTS] = 0; } else if (m_int_configs[CONFIG_START_ARENA_POINTS] > m_int_configs[CONFIG_MAX_ARENA_POINTS]) { sLog->outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.", - m_int_configs[CONFIG_START_ARENA_POINTS], m_int_configs[CONFIG_MAX_ARENA_POINTS], m_int_configs[CONFIG_MAX_ARENA_POINTS]); + m_int_configs[CONFIG_START_ARENA_POINTS], m_int_configs[CONFIG_MAX_ARENA_POINTS], m_int_configs[CONFIG_MAX_ARENA_POINTS]); m_int_configs[CONFIG_START_ARENA_POINTS] = m_int_configs[CONFIG_MAX_ARENA_POINTS]; } - m_int_configs[CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL] = sConfigMgr->GetIntDefault("RecruitAFriend.MaxLevel", 60); + m_int_configs[CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL] = sConfigMgr->GetIntDefault("RecruitAFriend.MaxLevel", 60); if (m_int_configs[CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL] > m_int_configs[CONFIG_MAX_PLAYER_LEVEL]) { sLog->outError("RecruitAFriend.MaxLevel (%i) must be in the range 0..MaxLevel(%u). Set to %u.", - m_int_configs[CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL], 60); + m_int_configs[CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL], m_int_configs[CONFIG_MAX_PLAYER_LEVEL], 60); m_int_configs[CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL] = 60; } @@ -928,7 +928,7 @@ void World::LoadConfigSettings(bool reload) if (m_int_configs[CONFIG_START_GM_LEVEL] < m_int_configs[CONFIG_START_PLAYER_LEVEL]) { sLog->outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.", - m_int_configs[CONFIG_START_GM_LEVEL], m_int_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_int_configs[CONFIG_START_PLAYER_LEVEL]); + m_int_configs[CONFIG_START_GM_LEVEL], m_int_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_int_configs[CONFIG_START_PLAYER_LEVEL]); m_int_configs[CONFIG_START_GM_LEVEL] = m_int_configs[CONFIG_START_PLAYER_LEVEL]; } else if (m_int_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL) @@ -954,7 +954,7 @@ void World::LoadConfigSettings(bool reload) if (reload) { - m_timers[WUPDATE_UPTIME].SetInterval(m_int_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILLISECONDS); + m_timers[WUPDATE_UPTIME].SetInterval(m_int_configs[CONFIG_UPTIME_UPDATE]*MINUTE * IN_MILLISECONDS); m_timers[WUPDATE_UPTIME].Reset(); } @@ -972,7 +972,7 @@ void World::LoadConfigSettings(bool reload) } m_int_configs[CONFIG_LOGDB_CLEARTIME] = sConfigMgr->GetIntDefault("LogDB.Opt.ClearTime", 1209600); // 14 days default sLog->outString("Will clear `logs` table of entries older than %i seconds every %u minutes.", - m_int_configs[CONFIG_LOGDB_CLEARTIME], m_int_configs[CONFIG_LOGDB_CLEARINTERVAL]); + m_int_configs[CONFIG_LOGDB_CLEARTIME], m_int_configs[CONFIG_LOGDB_CLEARINTERVAL]); m_int_configs[CONFIG_TELEPORT_TIMEOUT_NEAR] = sConfigMgr->GetIntDefault("TeleportTimeoutNear", 25); // pussywizard m_int_configs[CONFIG_TELEPORT_TIMEOUT_FAR] = sConfigMgr->GetIntDefault("TeleportTimeoutFar", 45); // pussywizard @@ -1116,10 +1116,13 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_BG_XP_FOR_KILL] = sConfigMgr->GetBoolDefault("Battleground.GiveXPForKills", false); m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK_TIMER] = sConfigMgr->GetIntDefault("Battleground.ReportAFK.Timer", 4); m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] = sConfigMgr->GetIntDefault("Battleground.ReportAFK", 3); - if (m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] < 1) { + if (m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] < 1) + { sLog->outError("Battleground.ReportAFK (%d) must be >0. Using 3 instead.", m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK]); m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] = 3; - } else if (m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] > 9) { + } + else if (m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] > 9) + { sLog->outError("Battleground.ReportAFK (%d) must be <10. Using 3 instead.", m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK]); m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] = 3; } @@ -1164,10 +1167,10 @@ void World::LoadConfigSettings(bool reload) //visibility on continents m_MaxVisibleDistanceOnContinents = sConfigMgr->GetFloatDefault("Visibility.Distance.Continents", DEFAULT_VISIBILITY_DISTANCE); - if (m_MaxVisibleDistanceOnContinents < 45*sWorld->getRate(RATE_CREATURE_AGGRO)) + if (m_MaxVisibleDistanceOnContinents < 45 * sWorld->getRate(RATE_CREATURE_AGGRO)) { - sLog->outError("Visibility.Distance.Continents can't be less max aggro radius %f", 45*sWorld->getRate(RATE_CREATURE_AGGRO)); - m_MaxVisibleDistanceOnContinents = 45*sWorld->getRate(RATE_CREATURE_AGGRO); + sLog->outError("Visibility.Distance.Continents can't be less max aggro radius %f", 45 * sWorld->getRate(RATE_CREATURE_AGGRO)); + m_MaxVisibleDistanceOnContinents = 45 * sWorld->getRate(RATE_CREATURE_AGGRO); } else if (m_MaxVisibleDistanceOnContinents > MAX_VISIBILITY_DISTANCE) { @@ -1177,10 +1180,10 @@ void World::LoadConfigSettings(bool reload) //visibility in instances m_MaxVisibleDistanceInInstances = sConfigMgr->GetFloatDefault("Visibility.Distance.Instances", DEFAULT_VISIBILITY_INSTANCE); - if (m_MaxVisibleDistanceInInstances < 45*sWorld->getRate(RATE_CREATURE_AGGRO)) + if (m_MaxVisibleDistanceInInstances < 45 * sWorld->getRate(RATE_CREATURE_AGGRO)) { - sLog->outError("Visibility.Distance.Instances can't be less max aggro radius %f", 45*sWorld->getRate(RATE_CREATURE_AGGRO)); - m_MaxVisibleDistanceInInstances = 45*sWorld->getRate(RATE_CREATURE_AGGRO); + sLog->outError("Visibility.Distance.Instances can't be less max aggro radius %f", 45 * sWorld->getRate(RATE_CREATURE_AGGRO)); + m_MaxVisibleDistanceInInstances = 45 * sWorld->getRate(RATE_CREATURE_AGGRO); } else if (m_MaxVisibleDistanceInInstances > MAX_VISIBILITY_DISTANCE) { @@ -1190,10 +1193,10 @@ void World::LoadConfigSettings(bool reload) //visibility in BG/Arenas m_MaxVisibleDistanceInBGArenas = sConfigMgr->GetFloatDefault("Visibility.Distance.BGArenas", DEFAULT_VISIBILITY_BGARENAS); - if (m_MaxVisibleDistanceInBGArenas < 45*sWorld->getRate(RATE_CREATURE_AGGRO)) + if (m_MaxVisibleDistanceInBGArenas < 45 * sWorld->getRate(RATE_CREATURE_AGGRO)) { - sLog->outError("Visibility.Distance.BGArenas can't be less max aggro radius %f", 45*sWorld->getRate(RATE_CREATURE_AGGRO)); - m_MaxVisibleDistanceInBGArenas = 45*sWorld->getRate(RATE_CREATURE_AGGRO); + sLog->outError("Visibility.Distance.BGArenas can't be less max aggro radius %f", 45 * sWorld->getRate(RATE_CREATURE_AGGRO)); + m_MaxVisibleDistanceInBGArenas = 45 * sWorld->getRate(RATE_CREATURE_AGGRO); } else if (m_MaxVisibleDistanceInBGArenas > MAX_VISIBILITY_DISTANCE) { @@ -1214,7 +1217,7 @@ void World::LoadConfigSettings(bool reload) ///- Read the "Data" directory from the config file std::string dataPath = sConfigMgr->GetStringDefault("DataDir", "./"); - if (dataPath.empty() || (dataPath.at(dataPath.length()-1) != '/' && dataPath.at(dataPath.length()-1) != '\\')) + if (dataPath.empty() || (dataPath.at(dataPath.length() - 1) != '/' && dataPath.at(dataPath.length() - 1) != '\\')) dataPath.push_back('/'); #if AC_PLATFORM == AC_PLATFORM_UNIX || AC_PLATFORM == AC_PLATFORM_APPLE @@ -1419,14 +1422,14 @@ void World::SetInitialWorldSettings() { ///- Check the existence of the map files for all starting areas. if (!MapManager::ExistMapAndVMap(0, -6240.32f, 331.033f) - || !MapManager::ExistMapAndVMap(0, -8949.95f, -132.493f) - || !MapManager::ExistMapAndVMap(1, -618.518f, -4251.67f) - || !MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f) - || !MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f) - || !MapManager::ExistMapAndVMap(1, -2917.58f, -257.98f) - || (m_int_configs[CONFIG_EXPANSION] && ( - !MapManager::ExistMapAndVMap(530, 10349.6f, -6357.29f) || - !MapManager::ExistMapAndVMap(530, -3961.64f, -13931.2f)))) + || !MapManager::ExistMapAndVMap(0, -8949.95f, -132.493f) + || !MapManager::ExistMapAndVMap(1, -618.518f, -4251.67f) + || !MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f) + || !MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f) + || !MapManager::ExistMapAndVMap(1, -2917.58f, -257.98f) + || (m_int_configs[CONFIG_EXPANSION] && ( + !MapManager::ExistMapAndVMap(530, 10349.6f, -6357.29f) || + !MapManager::ExistMapAndVMap(530, -3961.64f, -13931.2f)))) { exit(1); } @@ -1901,28 +1904,28 @@ void World::SetInitialWorldSettings() m_startTime = m_gameTime; LoginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, uptime, revision) VALUES(%u, %u, 0, '%s')", - realmID, uint32(m_startTime), GitRevision::GetFullVersion()); // One-time query + realmID, uint32(m_startTime), GitRevision::GetFullVersion()); // One-time query - m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILLISECONDS); - m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILLISECONDS); - m_timers[WUPDATE_AUCTIONS].SetCurrent(MINUTE*IN_MILLISECONDS); - m_timers[WUPDATE_UPTIME].SetInterval(m_int_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILLISECONDS); - //Update "uptime" table based on configuration entry in minutes. + m_timers[WUPDATE_WEATHERS].SetInterval(1 * IN_MILLISECONDS); + m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE * IN_MILLISECONDS); + m_timers[WUPDATE_AUCTIONS].SetCurrent(MINUTE * IN_MILLISECONDS); + m_timers[WUPDATE_UPTIME].SetInterval(m_int_configs[CONFIG_UPTIME_UPDATE]*MINUTE * IN_MILLISECONDS); + //Update "uptime" table based on configuration entry in minutes. m_timers[WUPDATE_CORPSES].SetInterval(20 * MINUTE * IN_MILLISECONDS); - //erase corpses every 20 minutes - m_timers[WUPDATE_CLEANDB].SetInterval(m_int_configs[CONFIG_LOGDB_CLEARINTERVAL]*MINUTE*IN_MILLISECONDS); - // clean logs table every 14 days by default + //erase corpses every 20 minutes + m_timers[WUPDATE_CLEANDB].SetInterval(m_int_configs[CONFIG_LOGDB_CLEARINTERVAL]*MINUTE * IN_MILLISECONDS); + // clean logs table every 14 days by default m_timers[WUPDATE_AUTOBROADCAST].SetInterval(getIntConfig(CONFIG_AUTOBROADCAST_INTERVAL)); - m_timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*MINUTE*IN_MILLISECONDS); // Mysql ping time in minutes + m_timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*MINUTE * IN_MILLISECONDS); // Mysql ping time in minutes // our speed up - m_timers[WUPDATE_5_SECS].SetInterval(5*IN_MILLISECONDS); + m_timers[WUPDATE_5_SECS].SetInterval(5 * IN_MILLISECONDS); - mail_expire_check_timer = time(nullptr) + 6*3600; + mail_expire_check_timer = time(nullptr) + 6 * 3600; ///- Initilize static helper structures AIRegistry::Initialize(); @@ -2012,7 +2015,7 @@ void World::SetInitialWorldSettings() ///- Run eluna scripts. // in multithread foreach: run scripts sEluna->RunScripts(); - sEluna->OnConfigLoad(false,false); // Must be done after Eluna is initialized and scripts have run. + sEluna->OnConfigLoad(false, false); // Must be done after Eluna is initialized and scripts have run. #endif if (sWorld->getBoolConfig(CONFIG_PRELOAD_ALL_NON_INSTANCED_MAP_GRIDS)) @@ -2048,7 +2051,8 @@ void World::SetInitialWorldSettings() sLog->SetLogDB(true); } - if (sConfigMgr->isDryRun()) { + if (sConfigMgr->isDryRun()) + { sLog->outString("AzerothCore dry run completed, terminating."); exit(0); } @@ -2068,7 +2072,7 @@ void World::DetectDBCLang() std::string availableLocalsStr; uint8 default_locale = TOTAL_LOCALES; - for (uint8 i = default_locale -1; i < TOTAL_LOCALES; --i) // -1 will be 255 due to uint8 + for (uint8 i = default_locale - 1; i < TOTAL_LOCALES; --i) // -1 will be 255 due to uint8 { if (race->name[i][0] != '\0') // check by race names { @@ -2080,7 +2084,7 @@ void World::DetectDBCLang() } if (default_locale != m_lang_confid && m_lang_confid < TOTAL_LOCALES && - (m_availableDbcLocaleMask & (1 << m_lang_confid))) + (m_availableDbcLocaleMask & (1 << m_lang_confid))) { default_locale = m_lang_confid; } @@ -2215,7 +2219,7 @@ void World::Update(uint32 diff) if (m_gameTime > mail_expire_check_timer) { sObjectMgr->ReturnOrDeleteOldMails(true); - mail_expire_check_timer = m_gameTime + 6*3600; + mail_expire_check_timer = m_gameTime + 6 * 3600; } UpdateSessions(diff); @@ -2342,10 +2346,10 @@ void World::SendGlobalMessage(WorldPacket* packet, WorldSession* self, TeamId te for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) { if (itr->second && - itr->second->GetPlayer() && - itr->second->GetPlayer()->IsInWorld() && - itr->second != self && - (teamId == TEAM_NEUTRAL || itr->second->GetPlayer()->GetTeamId() == teamId)) + itr->second->GetPlayer() && + itr->second->GetPlayer()->IsInWorld() && + itr->second != self && + (teamId == TEAM_NEUTRAL || itr->second->GetPlayer()->GetTeamId() == teamId)) { itr->second->SendPacket(packet); } @@ -2359,11 +2363,11 @@ void World::SendGlobalGMMessage(WorldPacket* packet, WorldSession* self, TeamId for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) { if (itr->second && - itr->second->GetPlayer() && - itr->second->GetPlayer()->IsInWorld() && - itr->second != self && - !AccountMgr::IsPlayerAccount(itr->second->GetSecurity()) && - (teamId == TEAM_NEUTRAL || itr->second->GetPlayer()->GetTeamId() == teamId)) + itr->second->GetPlayer() && + itr->second->GetPlayer()->IsInWorld() && + itr->second != self && + !AccountMgr::IsPlayerAccount(itr->second->GetSecurity()) && + (teamId == TEAM_NEUTRAL || itr->second->GetPlayer()->GetTeamId() == teamId)) { itr->second->SendPacket(packet); } @@ -2374,44 +2378,44 @@ namespace acore { class WorldWorldTextBuilder { - public: - typedef std::vector WorldPacketList; - explicit WorldWorldTextBuilder(uint32 textId, va_list* args = nullptr) : i_textId(textId), i_args(args) {} - void operator()(WorldPacketList& data_list, LocaleConstant loc_idx) + public: + typedef std::vector WorldPacketList; + explicit WorldWorldTextBuilder(uint32 textId, va_list* args = nullptr) : i_textId(textId), i_args(args) {} + void operator()(WorldPacketList& data_list, LocaleConstant loc_idx) + { + char const* text = sObjectMgr->GetAcoreString(i_textId, loc_idx); + + if (i_args) { - char const* text = sObjectMgr->GetAcoreString(i_textId, loc_idx); + // we need copy va_list before use or original va_list will corrupted + va_list ap; + va_copy(ap, *i_args); - if (i_args) - { - // we need copy va_list before use or original va_list will corrupted - va_list ap; - va_copy(ap, *i_args); + char str[2048]; + vsnprintf(str, 2048, text, ap); + va_end(ap); - char str[2048]; - vsnprintf(str, 2048, text, ap); - va_end(ap); - - do_helper(data_list, &str[0]); - } - else - do_helper(data_list, (char*)text); + do_helper(data_list, &str[0]); } - private: - char* lineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } - void do_helper(WorldPacketList& data_list, char* text) + else + do_helper(data_list, (char*)text); + } + private: + char* lineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } + void do_helper(WorldPacketList& data_list, char* text) + { + char* pos = text; + while (char* line = lineFromMessage(pos)) { - char* pos = text; - while (char* line = lineFromMessage(pos)) - { - WorldPacket* data = new WorldPacket(); - ChatHandler::BuildChatPacket(*data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); - data_list.push_back(data); - } + WorldPacket* data = new WorldPacket(); + ChatHandler::BuildChatPacket(*data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); + data_list.push_back(data); } + } - uint32 i_textId; - va_list* i_args; + uint32 i_textId; + va_list* i_args; }; } // namespace acore @@ -2483,11 +2487,11 @@ bool World::SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) { if (itr->second && - itr->second->GetPlayer() && - itr->second->GetPlayer()->IsInWorld() && - itr->second->GetPlayer()->GetZoneId() == zone && - itr->second != self && - (teamId == TEAM_NEUTRAL || itr->second->GetPlayer()->GetTeamId() == teamId)) + itr->second->GetPlayer() && + itr->second->GetPlayer()->IsInWorld() && + itr->second->GetPlayer()->GetZoneId() == zone && + itr->second != self && + (teamId == TEAM_NEUTRAL || itr->second->GetPlayer()->GetTeamId() == teamId)) { itr->second->SendPacket(packet); foundPlayerToSend = true; @@ -2595,11 +2599,11 @@ void World::ShutdownMsg(bool show, Player* player) ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds if (show || - (m_ShutdownTimer < 5* MINUTE && (m_ShutdownTimer % 15) == 0) || // < 5 min; every 15 sec - (m_ShutdownTimer < 15 * MINUTE && (m_ShutdownTimer % MINUTE) == 0) || // < 15 min ; every 1 min - (m_ShutdownTimer < 30 * MINUTE && (m_ShutdownTimer % (5 * MINUTE)) == 0) || // < 30 min ; every 5 min - (m_ShutdownTimer < 12 * HOUR && (m_ShutdownTimer % HOUR) == 0) || // < 12 h ; every 1 h - (m_ShutdownTimer > 12 * HOUR && (m_ShutdownTimer % (12 * HOUR)) == 0)) // > 12 h ; every 12 h + (m_ShutdownTimer < 5 * MINUTE && (m_ShutdownTimer % 15) == 0) || // < 5 min; every 15 sec + (m_ShutdownTimer < 15 * MINUTE && (m_ShutdownTimer % MINUTE) == 0) || // < 15 min ; every 1 min + (m_ShutdownTimer < 30 * MINUTE && (m_ShutdownTimer % (5 * MINUTE)) == 0) || // < 30 min ; every 5 min + (m_ShutdownTimer < 12 * HOUR && (m_ShutdownTimer % HOUR) == 0) || // < 12 h ; every 1 h + (m_ShutdownTimer > 12 * HOUR && (m_ShutdownTimer % (12 * HOUR)) == 0)) // > 12 h ; every 12 h { std::string str = secsToTimeString(m_ShutdownTimer).append("."); @@ -2634,7 +2638,7 @@ void World::ShutdownCancel() } /// Send a server message to the user(s) -void World::SendServerMessage(ServerMessageType type, const char *text, Player* player) +void World::SendServerMessage(ServerMessageType type, const char* text, Player* player) { WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size data << uint32(type); @@ -2704,7 +2708,7 @@ void World::UpdateSessions(uint32 diff) next = itr; ++next; WorldSession* pSession = itr->second; - if (!pSession->GetPlayer() || pSession->GetOfflineTime()+60 < currTime || pSession->IsKicked()) + if (!pSession->GetPlayer() || pSession->GetOfflineTime() + 60 < currTime || pSession->IsKicked()) { m_offlineSessions.erase(itr); if (m_sessions.find(pSession->GetAccountId()) != m_sessions.end()) @@ -2778,7 +2782,7 @@ void World::SendAutoBroadcast() else if (abcenter == 1) { - WorldPacket data(SMSG_NOTIFICATION, (msg.size()+1)); + WorldPacket data(SMSG_NOTIFICATION, (msg.size() + 1)); data << msg; sWorld->SendGlobalMessage(&data); } @@ -2787,7 +2791,7 @@ void World::SendAutoBroadcast() { sWorld->SendWorldText(LANG_AUTO_BROADCAST, msg.c_str()); - WorldPacket data(SMSG_NOTIFICATION, (msg.size()+1)); + WorldPacket data(SMSG_NOTIFICATION, (msg.size() + 1)); data << msg; sWorld->SendGlobalMessage(&data); } @@ -2844,7 +2848,7 @@ time_t World::GetNextTimeWithDayAndHour(int8 dayOfWeek, int8 hour) localTm.tm_sec = 0; uint32 add; if (dayOfWeek < 0 || dayOfWeek > 6) - dayOfWeek = (localTm.tm_wday+1)%7; + dayOfWeek = (localTm.tm_wday + 1) % 7; if (localTm.tm_wday >= dayOfWeek) add = (7 - (localTm.tm_wday - dayOfWeek)) * DAY; else @@ -2866,7 +2870,7 @@ time_t World::GetNextTimeWithMonthAndHour(int8 month, int8 hour) localTm.tm_sec = 0; if (month < 0 || month > 11) { - month = (localTm.tm_mon+1)%12; + month = (localTm.tm_mon + 1) % 12; if (month == 0) localTm.tm_year += 1; } @@ -3002,7 +3006,7 @@ void World::ResetMonthlyQuests() void World::ResetEventSeasonalQuests(uint16 event_id) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL); - stmt->setUInt16(0,event_id); + stmt->setUInt16(0, event_id); CharacterDatabase.Execute(stmt); for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) @@ -3048,7 +3052,7 @@ void World::ResetGuildCap() void World::UpdateMaxSessionCounters() { - m_maxActiveSessionCount = std::max(m_maxActiveSessionCount, uint32(m_sessions.size()-m_QueuedPlayer.size())); + m_maxActiveSessionCount = std::max(m_maxActiveSessionCount, uint32(m_sessions.size() - m_QueuedPlayer.size())); m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount, uint32(m_QueuedPlayer.size())); } @@ -3100,8 +3104,7 @@ void World::LoadWorldStates() Field* fields = result->Fetch(); m_worldstates[fields[0].GetUInt32()] = fields[1].GetUInt32(); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %u world states in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); @@ -3181,8 +3184,7 @@ void World::LoadGlobalPlayerDataStore() { Field* fields = mailCountResult->Fetch(); _mailCountMap[fields[0].GetUInt32()] = uint16(fields[1].GetUInt64()); - } - while (mailCountResult->NextRow()); + } while (mailCountResult->NextRow()); } do @@ -3208,8 +3210,7 @@ void World::LoadGlobalPlayerDataStore() 0 /*guild id*/); ++count; - } - while (result->NextRow()); + } while (result->NextRow()); sLog->outString(">> Loaded %d Players data in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index e8a09cd5e..6365586d6 100644 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -484,7 +484,7 @@ enum RealmType REALM_TYPE_RP = 6, REALM_TYPE_RPPVP = 8, REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries - // replaced by REALM_PVP in realm list + // replaced by REALM_PVP in realm list }; enum RealmZone @@ -548,15 +548,15 @@ struct CliCommandHolder typedef void CommandFinished(void*, bool success); void* m_callbackArg; - char *m_command; + char* m_command; Print* m_print; CommandFinished* m_commandFinished; - CliCommandHolder(void* callbackArg, const char *command, Print* zprint, CommandFinished* commandFinished) + CliCommandHolder(void* callbackArg, const char* command, Print* zprint, CommandFinished* commandFinished) : m_callbackArg(callbackArg), m_print(zprint), m_commandFinished(commandFinished) { - size_t len = strlen(command)+1; + size_t len = strlen(command) + 1; m_command = new char[len]; memcpy(m_command, command, len); } @@ -604,339 +604,339 @@ struct PetitionData /// The World class World { - public: - World(); - ~World(); +public: + World(); + ~World(); - static World* instance(); + static World* instance(); - static uint32 m_worldLoopCounter; + static uint32 m_worldLoopCounter; - WorldSession* FindSession(uint32 id) const; - WorldSession* FindOfflineSession(uint32 id) const; - WorldSession* FindOfflineSessionForCharacterGUID(uint32 guidLow) const; - void AddSession(WorldSession* s); - void SendAutoBroadcast(); - bool KickSession(uint32 id); - /// Get the number of current active sessions - void UpdateMaxSessionCounters(); - const SessionMap& GetAllSessions() const { return m_sessions; } - uint32 GetActiveAndQueuedSessionCount() const { return m_sessions.size(); } - uint32 GetActiveSessionCount() const { return m_sessions.size() - m_QueuedPlayer.size(); } - uint32 GetQueuedSessionCount() const { return m_QueuedPlayer.size(); } - /// Get the maximum number of parallel sessions on the server since last reboot - uint32 GetMaxQueuedSessionCount() const { return m_maxQueuedSessionCount; } - uint32 GetMaxActiveSessionCount() const { return m_maxActiveSessionCount; } - /// Get number of players - inline uint32 GetPlayerCount() const { return m_PlayerCount; } - inline uint32 GetMaxPlayerCount() const { return m_MaxPlayerCount; } + WorldSession* FindSession(uint32 id) const; + WorldSession* FindOfflineSession(uint32 id) const; + WorldSession* FindOfflineSessionForCharacterGUID(uint32 guidLow) const; + void AddSession(WorldSession* s); + void SendAutoBroadcast(); + bool KickSession(uint32 id); + /// Get the number of current active sessions + void UpdateMaxSessionCounters(); + const SessionMap& GetAllSessions() const { return m_sessions; } + uint32 GetActiveAndQueuedSessionCount() const { return m_sessions.size(); } + uint32 GetActiveSessionCount() const { return m_sessions.size() - m_QueuedPlayer.size(); } + uint32 GetQueuedSessionCount() const { return m_QueuedPlayer.size(); } + /// Get the maximum number of parallel sessions on the server since last reboot + uint32 GetMaxQueuedSessionCount() const { return m_maxQueuedSessionCount; } + uint32 GetMaxActiveSessionCount() const { return m_maxActiveSessionCount; } + /// Get number of players + inline uint32 GetPlayerCount() const { return m_PlayerCount; } + inline uint32 GetMaxPlayerCount() const { return m_MaxPlayerCount; } - /// Increase/Decrease number of players - inline void IncreasePlayerCount() - { - m_PlayerCount++; - m_MaxPlayerCount = std::max(m_MaxPlayerCount, m_PlayerCount); - } - inline void DecreasePlayerCount() { m_PlayerCount--; } + /// Increase/Decrease number of players + inline void IncreasePlayerCount() + { + m_PlayerCount++; + m_MaxPlayerCount = std::max(m_MaxPlayerCount, m_PlayerCount); + } + inline void DecreasePlayerCount() { m_PlayerCount--; } - Player* FindPlayerInZone(uint32 zone); + Player* FindPlayerInZone(uint32 zone); - /// Deny clients? - bool IsClosed() const; + /// Deny clients? + bool IsClosed() const; - /// Close world - void SetClosed(bool val); + /// Close world + void SetClosed(bool val); - /// Security level limitations - AccountTypes GetPlayerSecurityLimit() const { return m_allowedSecurityLevel; } - void SetPlayerSecurityLimit(AccountTypes sec); - void LoadDBAllowedSecurityLevel(); + /// Security level limitations + AccountTypes GetPlayerSecurityLimit() const { return m_allowedSecurityLevel; } + void SetPlayerSecurityLimit(AccountTypes sec); + void LoadDBAllowedSecurityLevel(); - /// Active session server limit - void SetPlayerAmountLimit(uint32 limit) { m_playerLimit = limit; } - uint32 GetPlayerAmountLimit() const { return m_playerLimit; } + /// Active session server limit + void SetPlayerAmountLimit(uint32 limit) { m_playerLimit = limit; } + uint32 GetPlayerAmountLimit() const { return m_playerLimit; } - //player Queue - typedef std::list Queue; - void AddQueuedPlayer(WorldSession*); - bool RemoveQueuedPlayer(WorldSession* session); - int32 GetQueuePos(WorldSession*); - bool HasRecentlyDisconnected(WorldSession*); + //player Queue + typedef std::list Queue; + void AddQueuedPlayer(WorldSession*); + bool RemoveQueuedPlayer(WorldSession* session); + int32 GetQueuePos(WorldSession*); + bool HasRecentlyDisconnected(WorldSession*); - /// \todo Actions on m_allowMovement still to be implemented - /// Is movement allowed? - bool getAllowMovement() const { return m_allowMovement; } - /// Allow/Disallow object movements - void SetAllowMovement(bool allow) { m_allowMovement = allow; } + /// \todo Actions on m_allowMovement still to be implemented + /// Is movement allowed? + bool getAllowMovement() const { return m_allowMovement; } + /// Allow/Disallow object movements + void SetAllowMovement(bool allow) { m_allowMovement = allow; } - /// Set the string for new characters (first login) - void SetNewCharString(std::string const& str) { m_newCharString = str; } - /// Get the string for new characters (first login) - std::string const& GetNewCharString() const { return m_newCharString; } + /// Set the string for new characters (first login) + void SetNewCharString(std::string const& str) { m_newCharString = str; } + /// Get the string for new characters (first login) + std::string const& GetNewCharString() const { return m_newCharString; } - LocaleConstant GetDefaultDbcLocale() const { return m_defaultDbcLocale; } + LocaleConstant GetDefaultDbcLocale() const { return m_defaultDbcLocale; } - /// Get the path where data (dbc, maps) are stored on disk - std::string const& GetDataPath() const { return m_dataPath; } + /// Get the path where data (dbc, maps) are stored on disk + std::string const& GetDataPath() const { return m_dataPath; } - /// When server started? - time_t const& GetStartTime() const { return m_startTime; } - /// What time is it? - time_t const& GetGameTime() const { return m_gameTime; } - /// What time is it? in ms - static uint32 GetGameTimeMS() { return m_gameMSTime; } - /// Uptime (in secs) - uint32 GetUptime() const { return uint32(m_gameTime - m_startTime); } - /// Update time - uint32 GetUpdateTime() const { return m_updateTime; } - void SetRecordDiffInterval(int32 t) { if (t >= 0) m_int_configs[CONFIG_INTERVAL_LOG_UPDATE] = (uint32)t; } + /// When server started? + time_t const& GetStartTime() const { return m_startTime; } + /// What time is it? + time_t const& GetGameTime() const { return m_gameTime; } + /// What time is it? in ms + static uint32 GetGameTimeMS() { return m_gameMSTime; } + /// Uptime (in secs) + uint32 GetUptime() const { return uint32(m_gameTime - m_startTime); } + /// Update time + uint32 GetUpdateTime() const { return m_updateTime; } + void SetRecordDiffInterval(int32 t) { if (t >= 0) m_int_configs[CONFIG_INTERVAL_LOG_UPDATE] = (uint32)t; } - /// Next daily quests and random bg reset time - time_t GetNextDailyQuestsResetTime() const { return m_NextDailyQuestReset; } - time_t GetNextWeeklyQuestsResetTime() const { return m_NextWeeklyQuestReset; } - time_t GetNextRandomBGResetTime() const { return m_NextRandomBGReset; } + /// Next daily quests and random bg reset time + time_t GetNextDailyQuestsResetTime() const { return m_NextDailyQuestReset; } + time_t GetNextWeeklyQuestsResetTime() const { return m_NextWeeklyQuestReset; } + time_t GetNextRandomBGResetTime() const { return m_NextRandomBGReset; } - /// Get the maximum skill level a player can reach - uint16 GetConfigMaxSkillValue() const - { - uint16 lvl = uint16(getIntConfig(CONFIG_MAX_PLAYER_LEVEL)); - return lvl > 60 ? 300 + ((lvl - 60) * 75) / 10 : lvl * 5; - } + /// Get the maximum skill level a player can reach + uint16 GetConfigMaxSkillValue() const + { + uint16 lvl = uint16(getIntConfig(CONFIG_MAX_PLAYER_LEVEL)); + return lvl > 60 ? 300 + ((lvl - 60) * 75) / 10 : lvl * 5; + } - void SetInitialWorldSettings(); - void LoadConfigSettings(bool reload = false); + void SetInitialWorldSettings(); + void LoadConfigSettings(bool reload = false); - void SendWorldText(uint32 string_id, ...); - void SendGlobalText(const char* text, WorldSession* self); - void SendGMText(uint32 string_id, ...); - void SendGlobalMessage(WorldPacket* packet, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); - void SendGlobalGMMessage(WorldPacket* packet, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); - bool SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); - void SendZoneText(uint32 zone, const char *text, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); - void SendServerMessage(ServerMessageType type, const char *text = "", Player* player = nullptr); + void SendWorldText(uint32 string_id, ...); + void SendGlobalText(const char* text, WorldSession* self); + void SendGMText(uint32 string_id, ...); + void SendGlobalMessage(WorldPacket* packet, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); + void SendGlobalGMMessage(WorldPacket* packet, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); + bool SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); + void SendZoneText(uint32 zone, const char* text, WorldSession* self = 0, TeamId teamId = TEAM_NEUTRAL); + void SendServerMessage(ServerMessageType type, const char* text = "", Player* player = nullptr); - /// Are we in the middle of a shutdown? - bool IsShuttingDown() const { return m_ShutdownTimer > 0; } - uint32 GetShutDownTimeLeft() const { return m_ShutdownTimer; } - void ShutdownServ(uint32 time, uint32 options, uint8 exitcode); - void ShutdownCancel(); - void ShutdownMsg(bool show = false, Player* player = nullptr); - static uint8 GetExitCode() { return m_ExitCode; } - static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; } - static bool IsStopped() { return m_stopEvent; } + /// Are we in the middle of a shutdown? + bool IsShuttingDown() const { return m_ShutdownTimer > 0; } + uint32 GetShutDownTimeLeft() const { return m_ShutdownTimer; } + void ShutdownServ(uint32 time, uint32 options, uint8 exitcode); + void ShutdownCancel(); + void ShutdownMsg(bool show = false, Player* player = nullptr); + static uint8 GetExitCode() { return m_ExitCode; } + static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; } + static bool IsStopped() { return m_stopEvent; } - void Update(uint32 diff); + void Update(uint32 diff); - void UpdateSessions(uint32 diff); - /// Set a server rate (see #Rates) - void setRate(Rates rate, float value) { rate_values[rate]=value; } - /// Get a server rate (see #Rates) - float getRate(Rates rate) const { return rate_values[rate]; } + void UpdateSessions(uint32 diff); + /// Set a server rate (see #Rates) + void setRate(Rates rate, float value) { rate_values[rate] = value; } + /// Get a server rate (see #Rates) + float getRate(Rates rate) const { return rate_values[rate]; } - /// Set a server configuration element (see #WorldConfigs) - void setBoolConfig(WorldBoolConfigs index, bool value) - { - if (index < BOOL_CONFIG_VALUE_COUNT) - m_bool_configs[index] = value; - } + /// Set a server configuration element (see #WorldConfigs) + void setBoolConfig(WorldBoolConfigs index, bool value) + { + if (index < BOOL_CONFIG_VALUE_COUNT) + m_bool_configs[index] = value; + } - /// Get a server configuration element (see #WorldConfigs) - bool getBoolConfig(WorldBoolConfigs index) const - { - return index < BOOL_CONFIG_VALUE_COUNT ? m_bool_configs[index] : 0; - } + /// Get a server configuration element (see #WorldConfigs) + bool getBoolConfig(WorldBoolConfigs index) const + { + return index < BOOL_CONFIG_VALUE_COUNT ? m_bool_configs[index] : 0; + } - /// Set a server configuration element (see #WorldConfigs) - void setFloatConfig(WorldFloatConfigs index, float value) - { - if (index < FLOAT_CONFIG_VALUE_COUNT) - m_float_configs[index] = value; - } + /// Set a server configuration element (see #WorldConfigs) + void setFloatConfig(WorldFloatConfigs index, float value) + { + if (index < FLOAT_CONFIG_VALUE_COUNT) + m_float_configs[index] = value; + } - /// Get a server configuration element (see #WorldConfigs) - float getFloatConfig(WorldFloatConfigs index) const - { - return index < FLOAT_CONFIG_VALUE_COUNT ? m_float_configs[index] : 0; - } + /// Get a server configuration element (see #WorldConfigs) + float getFloatConfig(WorldFloatConfigs index) const + { + return index < FLOAT_CONFIG_VALUE_COUNT ? m_float_configs[index] : 0; + } - /// Set a server configuration element (see #WorldConfigs) - void setIntConfig(WorldIntConfigs index, uint32 value) - { - if (index < INT_CONFIG_VALUE_COUNT) - m_int_configs[index] = value; - } + /// Set a server configuration element (see #WorldConfigs) + void setIntConfig(WorldIntConfigs index, uint32 value) + { + if (index < INT_CONFIG_VALUE_COUNT) + m_int_configs[index] = value; + } - /// Get a server configuration element (see #WorldConfigs) - uint32 getIntConfig(WorldIntConfigs index) const - { - return index < INT_CONFIG_VALUE_COUNT ? m_int_configs[index] : 0; - } + /// Get a server configuration element (see #WorldConfigs) + uint32 getIntConfig(WorldIntConfigs index) const + { + return index < INT_CONFIG_VALUE_COUNT ? m_int_configs[index] : 0; + } - void setWorldState(uint32 index, uint64 value); - uint64 getWorldState(uint32 index) const; - void LoadWorldStates(); + void setWorldState(uint32 index, uint64 value); + uint64 getWorldState(uint32 index) const; + void LoadWorldStates(); - /// Are we on a "Player versus Player" server? - bool IsPvPRealm() const { return (getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP); } - bool IsFFAPvPRealm() const { return getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP; } + /// Are we on a "Player versus Player" server? + bool IsPvPRealm() const { return (getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP); } + bool IsFFAPvPRealm() const { return getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP; } - void KickAll(); - void KickAllLess(AccountTypes sec); + void KickAll(); + void KickAllLess(AccountTypes sec); - // for max speed access - static float GetMaxVisibleDistanceOnContinents() { return m_MaxVisibleDistanceOnContinents; } - static float GetMaxVisibleDistanceInInstances() { return m_MaxVisibleDistanceInInstances; } - static float GetMaxVisibleDistanceInBGArenas() { return m_MaxVisibleDistanceInBGArenas; } + // for max speed access + static float GetMaxVisibleDistanceOnContinents() { return m_MaxVisibleDistanceOnContinents; } + static float GetMaxVisibleDistanceInInstances() { return m_MaxVisibleDistanceInInstances; } + static float GetMaxVisibleDistanceInBGArenas() { return m_MaxVisibleDistanceInBGArenas; } - // our: needed for arena spectator subscriptions - uint32 GetNextWhoListUpdateDelaySecs() - { - if (m_timers[WUPDATE_5_SECS].Passed()) - return 1; - uint32 t = m_timers[WUPDATE_5_SECS].GetInterval() - m_timers[WUPDATE_5_SECS].GetCurrent(); - t = std::min(t, (uint32)m_timers[WUPDATE_5_SECS].GetInterval()); - return uint32(ceil(t/1000.0f)); - } + // our: needed for arena spectator subscriptions + uint32 GetNextWhoListUpdateDelaySecs() + { + if (m_timers[WUPDATE_5_SECS].Passed()) + return 1; + uint32 t = m_timers[WUPDATE_5_SECS].GetInterval() - m_timers[WUPDATE_5_SECS].GetCurrent(); + t = std::min(t, (uint32)m_timers[WUPDATE_5_SECS].GetInterval()); + return uint32(ceil(t / 1000.0f)); + } - // xinef: Global Player Data Storage system - void LoadGlobalPlayerDataStore(); - uint32 GetGlobalPlayerGUID(std::string const& name) const; - GlobalPlayerData const* GetGlobalPlayerData(uint32 guid) const; - void AddGlobalPlayerData(uint32 guid, uint32 accountId, std::string const& name, uint8 gender, uint8 race, uint8 playerClass, uint8 level, uint16 mailCount, uint32 guildId); - void UpdateGlobalPlayerData(uint32 guid, uint8 mask, std::string const& name, uint8 level = 0, uint8 gender = 0, uint8 race = 0, uint8 playerClass = 0); - void UpdateGlobalPlayerMails(uint32 guid, int16 count, bool add = true); - void UpdateGlobalPlayerGuild(uint32 guid, uint32 guildId); - void UpdateGlobalPlayerGroup(uint32 guid, uint32 groupId); - void UpdateGlobalPlayerArenaTeam(uint32 guid, uint8 slot, uint32 arenaTeamId); - void UpdateGlobalNameData(uint32 guidLow, std::string const& oldName, std::string const& newName); - void DeleteGlobalPlayerData(uint32 guid, std::string const& name); + // xinef: Global Player Data Storage system + void LoadGlobalPlayerDataStore(); + uint32 GetGlobalPlayerGUID(std::string const& name) const; + GlobalPlayerData const* GetGlobalPlayerData(uint32 guid) const; + void AddGlobalPlayerData(uint32 guid, uint32 accountId, std::string const& name, uint8 gender, uint8 race, uint8 playerClass, uint8 level, uint16 mailCount, uint32 guildId); + void UpdateGlobalPlayerData(uint32 guid, uint8 mask, std::string const& name, uint8 level = 0, uint8 gender = 0, uint8 race = 0, uint8 playerClass = 0); + void UpdateGlobalPlayerMails(uint32 guid, int16 count, bool add = true); + void UpdateGlobalPlayerGuild(uint32 guid, uint32 guildId); + void UpdateGlobalPlayerGroup(uint32 guid, uint32 groupId); + void UpdateGlobalPlayerArenaTeam(uint32 guid, uint8 slot, uint32 arenaTeamId); + void UpdateGlobalNameData(uint32 guidLow, std::string const& oldName, std::string const& newName); + void DeleteGlobalPlayerData(uint32 guid, std::string const& name); - void ProcessCliCommands(); - void QueueCliCommand(CliCommandHolder* commandHolder) { cliCmdQueue.add(commandHolder); } + void ProcessCliCommands(); + void QueueCliCommand(CliCommandHolder* commandHolder) { cliCmdQueue.add(commandHolder); } - void ForceGameEventUpdate(); + void ForceGameEventUpdate(); - void UpdateRealmCharCount(uint32 accid); + void UpdateRealmCharCount(uint32 accid); - LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if (m_availableDbcLocaleMask & (1 << locale)) return locale; else return m_defaultDbcLocale; } + LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if (m_availableDbcLocaleMask & (1 << locale)) return locale; else return m_defaultDbcLocale; } - // used World DB version - void LoadDBVersion(); - char const* GetDBVersion() const { return m_DBVersion.c_str(); } + // used World DB version + void LoadDBVersion(); + char const* GetDBVersion() const { return m_DBVersion.c_str(); } - void LoadAutobroadcasts(); + void LoadAutobroadcasts(); - void UpdateAreaDependentAuras(); + void UpdateAreaDependentAuras(); - uint32 GetCleaningFlags() const { return m_CleaningFlags; } - void SetCleaningFlags(uint32 flags) { m_CleaningFlags = flags; } - void ResetEventSeasonalQuests(uint16 event_id); + uint32 GetCleaningFlags() const { return m_CleaningFlags; } + void SetCleaningFlags(uint32 flags) { m_CleaningFlags = flags; } + void ResetEventSeasonalQuests(uint16 event_id); - time_t GetNextTimeWithDayAndHour(int8 dayOfWeek, int8 hour); // pussywizard - time_t GetNextTimeWithMonthAndHour(int8 month, int8 hour); // pussywizard + time_t GetNextTimeWithDayAndHour(int8 dayOfWeek, int8 hour); // pussywizard + time_t GetNextTimeWithMonthAndHour(int8 month, int8 hour); // pussywizard - std::string const& GetRealmName() const { return _realmName; } // pussywizard - void SetRealmName(std::string name) { _realmName = name; } // pussywizard + std::string const& GetRealmName() const { return _realmName; } // pussywizard + void SetRealmName(std::string name) { _realmName = name; } // pussywizard - protected: - void _UpdateGameTime(); - // callback for UpdateRealmCharacters - void _UpdateRealmCharCount(PreparedQueryResult resultCharCount); +protected: + void _UpdateGameTime(); + // callback for UpdateRealmCharacters + void _UpdateRealmCharCount(PreparedQueryResult resultCharCount); - void InitDailyQuestResetTime(); - void InitWeeklyQuestResetTime(); - void InitMonthlyQuestResetTime(); - void InitRandomBGResetTime(); - void InitCalendarOldEventsDeletionTime(); - void InitGuildResetTime(); - void ResetDailyQuests(); - void ResetWeeklyQuests(); - void ResetMonthlyQuests(); - void ResetRandomBG(); - void CalendarDeleteOldEvents(); - void ResetGuildCap(); - private: - static std::atomic_long m_stopEvent; - static uint8 m_ExitCode; - uint32 m_ShutdownTimer; - uint32 m_ShutdownMask; + void InitDailyQuestResetTime(); + void InitWeeklyQuestResetTime(); + void InitMonthlyQuestResetTime(); + void InitRandomBGResetTime(); + void InitCalendarOldEventsDeletionTime(); + void InitGuildResetTime(); + void ResetDailyQuests(); + void ResetWeeklyQuests(); + void ResetMonthlyQuests(); + void ResetRandomBG(); + void CalendarDeleteOldEvents(); + void ResetGuildCap(); +private: + static std::atomic_long m_stopEvent; + static uint8 m_ExitCode; + uint32 m_ShutdownTimer; + uint32 m_ShutdownMask; - uint32 m_CleaningFlags; + uint32 m_CleaningFlags; - bool m_isClosed; + bool m_isClosed; - time_t m_startTime; - time_t m_gameTime; - IntervalTimer m_timers[WUPDATE_COUNT]; - time_t mail_expire_check_timer; - uint32 m_updateTime, m_updateTimeSum; - static uint32 m_gameMSTime; + time_t m_startTime; + time_t m_gameTime; + IntervalTimer m_timers[WUPDATE_COUNT]; + time_t mail_expire_check_timer; + uint32 m_updateTime, m_updateTimeSum; + static uint32 m_gameMSTime; - SessionMap m_sessions; - SessionMap m_offlineSessions; - typedef std::unordered_map DisconnectMap; - DisconnectMap m_disconnects; - uint32 m_maxActiveSessionCount; - uint32 m_maxQueuedSessionCount; - uint32 m_PlayerCount; - uint32 m_MaxPlayerCount; + SessionMap m_sessions; + SessionMap m_offlineSessions; + typedef std::unordered_map DisconnectMap; + DisconnectMap m_disconnects; + uint32 m_maxActiveSessionCount; + uint32 m_maxQueuedSessionCount; + uint32 m_PlayerCount; + uint32 m_MaxPlayerCount; - std::string m_newCharString; + std::string m_newCharString; - float rate_values[MAX_RATES]; - uint32 m_int_configs[INT_CONFIG_VALUE_COUNT]; - bool m_bool_configs[BOOL_CONFIG_VALUE_COUNT]; - float m_float_configs[FLOAT_CONFIG_VALUE_COUNT]; - typedef std::map WorldStatesMap; - WorldStatesMap m_worldstates; - uint32 m_playerLimit; - AccountTypes m_allowedSecurityLevel; - LocaleConstant m_defaultDbcLocale; // from config for one from loaded DBC locales - uint32 m_availableDbcLocaleMask; // by loaded DBC - void DetectDBCLang(); - bool m_allowMovement; - std::string m_dataPath; + float rate_values[MAX_RATES]; + uint32 m_int_configs[INT_CONFIG_VALUE_COUNT]; + bool m_bool_configs[BOOL_CONFIG_VALUE_COUNT]; + float m_float_configs[FLOAT_CONFIG_VALUE_COUNT]; + typedef std::map WorldStatesMap; + WorldStatesMap m_worldstates; + uint32 m_playerLimit; + AccountTypes m_allowedSecurityLevel; + LocaleConstant m_defaultDbcLocale; // from config for one from loaded DBC locales + uint32 m_availableDbcLocaleMask; // by loaded DBC + void DetectDBCLang(); + bool m_allowMovement; + std::string m_dataPath; - // for max speed access - static float m_MaxVisibleDistanceOnContinents; - static float m_MaxVisibleDistanceInInstances; - static float m_MaxVisibleDistanceInBGArenas; + // for max speed access + static float m_MaxVisibleDistanceOnContinents; + static float m_MaxVisibleDistanceInInstances; + static float m_MaxVisibleDistanceInBGArenas; - // our speed ups - GlobalPlayerDataMap _globalPlayerDataStore; // xinef - GlobalPlayerNameMap _globalPlayerNameStore; // xinef + // our speed ups + GlobalPlayerDataMap _globalPlayerDataStore; // xinef + GlobalPlayerNameMap _globalPlayerNameStore; // xinef - std::string _realmName; + std::string _realmName; - // CLI command holder to be thread safe - ACE_Based::LockedQueue cliCmdQueue; + // CLI command holder to be thread safe + ACE_Based::LockedQueue cliCmdQueue; - // next daily quests and random bg reset time - time_t m_NextDailyQuestReset; - time_t m_NextWeeklyQuestReset; - time_t m_NextMonthlyQuestReset; - time_t m_NextRandomBGReset; - time_t m_NextCalendarOldEventsDeletionTime; - time_t m_NextGuildReset; + // next daily quests and random bg reset time + time_t m_NextDailyQuestReset; + time_t m_NextWeeklyQuestReset; + time_t m_NextMonthlyQuestReset; + time_t m_NextRandomBGReset; + time_t m_NextCalendarOldEventsDeletionTime; + time_t m_NextGuildReset; - //Player Queue - Queue m_QueuedPlayer; + //Player Queue + Queue m_QueuedPlayer; - // sessions that are added async - void AddSession_(WorldSession* s); - ACE_Based::LockedQueue addSessQueue; + // sessions that are added async + void AddSession_(WorldSession* s); + ACE_Based::LockedQueue addSessQueue; - // used versions - std::string m_DBVersion; + // used versions + std::string m_DBVersion; - typedef std::map AutobroadcastsMap; - AutobroadcastsMap m_Autobroadcasts; + typedef std::map AutobroadcastsMap; + AutobroadcastsMap m_Autobroadcasts; - typedef std::map AutobroadcastsWeightMap; - AutobroadcastsWeightMap m_AutobroadcastsWeights; + typedef std::map AutobroadcastsWeightMap; + AutobroadcastsWeightMap m_AutobroadcastsWeights; - void ProcessQueryCallbacks(); - ACE_Future_Set m_realmCharCallbacks; + void ProcessQueryCallbacks(); + ACE_Future_Set m_realmCharCallbacks; }; #define sWorld World::instance()